问:
Android make view height 50% of screen width
I wish to make a view with the width to be match_parent, but the height to be 50% of the width.

How do I do it?

Is the only way to do it through java code inside the activity? I'll have to read the screen width and set the height that way.

答:
You can do it programmatically by extending the view class the are you using and override the OnMeasure method like below:

```<code>public class HalfHeightTextView extends AppCompatTextView {

    public HalfHeightTextView(Context context) {
        super(context);
    }

    public HalfHeightTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public HalfHeightTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //We take the measured height and set half of it as height
        setMeasuredDimension(widthMeasureSpec, widthMeasureSpec/2);
    }
}
</code>```

Then you should use it that way in your layout

```<code><FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.example.android.sunshine.utilities.HalfHeightTextView
    android:layout_width="match_parent"
    android:text="This is a test"
    android:background="@color/colorAccent"
    android:layout_height="wrap_content"/>
</code>```

Body:
You can do it programmatically by extending the view class the are you using and override the OnMeasure method like below:

public class HalfHeightTextView extends AppCompatTextView {

    public HalfHeightTextView(Context context) {
        super(context);
    }

    public HalfHeightTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public HalfHeightTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //We take the measured height and set half of it as height
        setMeasuredDimension(widthMeasureSpec, widthMeasureSpec/2);
    }
}

Then you should use it that way in your layout

<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.example.android.sunshine.utilities.HalfHeightTextView
    android:layout_width="match_parent"
    android:text="This is a test"
    android:background="@color/colorAccent"
    android:layout_height="wrap_content"/>


来源: stackexchange

问:
capistrano-template: undefined method `template' for #<SSHKit::Backend::Printer
In order to use erb templates with capistrano (no rails) I followed the instructions given in https://github.com/faber-lotto/capistrano-template, but when running [bundle exec] cap staging define_usermacros -n --trace capistrano tells me that the template method was unknown to SSHKit::Backend::Printer:

```<code>** Invoke staging (first_time)
** Execute staging
** Invoke load:defaults (first_time)
** Execute load:defaults
** Invoke define_usermacros (first_time)
** Execute define_usermacros
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing as    deploy@10.33.66.12: undefined method `template' for #<SSHKit::Backend::Printer:0x007ff383bd4d80>
/usr/local/var/rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/sshkit-1.13.1/lib/sshkit/runners/parallel.rb:15:in `rescue in block (2 levels) in execute'
/usr/local/var/rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/sshkit-1.13.1/lib/sshkit/runners/parallel.rb:11:in `block (2 levels) in execute'
NoMethodError: undefined method `template' for #<SSHKit::Backend::Printer:0x007ff383bd4d80>
config/deploy.rb:42:in `block (2 levels) in <top (required)>'
/usr/local/var/rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/sshkit-1.13.1/lib/sshkit/backends/abstract.rb:29:in `instance_exec'
/usr/local/var/rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/sshkit-1.13.1/lib/sshkit/backends/abstract.rb:29:in `run'
/usr/local/var/rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/sshkit-1.13.1/lib/sshkit/runners/parallel.rb:12:in `block (2 levels) in execute'
Tasks: TOP => define_usermacros
</code>```

I tried to up- and downgrade capistrano, airbrussh, sshkit in the bundle but to no avail, things remain broken.

At the moment cap doctor tells me I'm using the following versions:

Environment

```<code>Ruby     ruby 2.2.5p319 (2016-04-26 revision 54774) [x86_64-darwin15]
Rubygems 2.6.10
Bundler  1.14.3
Command  /usr/local/var/rbenv/versions/2.2.5/bin/cap staging doctor
</code>```

Gems

```<code>capistrano          3.7.2  (update available)
airbrussh           1.2.0
rake                12.0.0
sshkit              1.13.1
net-ssh             4.1.0
capistrano-template 0.0.8
</code>```

And here's the capistrano stuff:

Gemfile:

```<code>source "https://rubygems.org"

group :development do
  gem "capistrano", "~> 3.7.0"
  gem "capistrano-template"
end
</code>```

Capfile:

```<code>require "capistrano/setup"
require "capistrano/deploy"
require "capistrano/scm/git"
install_plugin Capistrano::SCM::Git
require 'capistrano/capistrano_plugin_template'
</code>```

config/deploy.rb:

```<code>[...]
desc 'Upload user macros as rendered erb-template'
task :define_usermacros do
  on roles :all do
    template 'resource.cfg', "#{release_path}/resource_file",
         0o640,
         locals: {
           'user1' => 'blah'
         }
 end
end
</code>```

... and there is of course an erb template in config/deploy/templates/shared/resource.cfg.erb.

Any hints on the solution or how to debug the issue welcome!

答:
http://www.rubydoc.info/github/capistrano/sshkit/SSHKit/Backend/Printer is used for dry-runs (i.e. with -n), so the job works when run without -n.

The dry-run can fixed by adding

SSHKit::Backend::Printer.send(:include, Capistrano::Template::Helpers::DSL)

after

require 'capistrano/capistrano_plugin_template'

in the Capfile.

ContentLicense: CC BY-SA 3.0

Body:
In order to use erb templates with capistrano (no rails) I followed the instructions given in https://github.com/faber-lotto/capistrano-template, but when running [bundle exec] cap staging define_usermacros -n --trace capistrano tells me that the template method was unknown to SSHKit::Backend::Printer:

** Invoke staging (first_time)
** Execute staging
** Invoke load:defaults (first_time)
** Execute load:defaults
** Invoke define_usermacros (first_time)
** Execute define_usermacros
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing as    deploy@10.33.66.12: undefined method `template' for #<SSHKit::Backend::Printer:0x007ff383bd4d80>
/usr/local/var/rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/sshkit-1.13.1/lib/sshkit/runners/parallel.rb:15:in `rescue in block (2 levels) in execute'
/usr/local/var/rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/sshkit-1.13.1/lib/sshkit/runners/parallel.rb:11:in `block (2 levels) in execute'
NoMethodError: undefined method `template' for #<SSHKit::Backend::Printer:0x007ff383bd4d80>
config/deploy.rb:42:in `block (2 levels) in <top (required)>'
/usr/local/var/rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/sshkit-1.13.1/lib/sshkit/backends/abstract.rb:29:in `instance_exec'
/usr/local/var/rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/sshkit-1.13.1/lib/sshkit/backends/abstract.rb:29:in `run'
/usr/local/var/rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/sshkit-1.13.1/lib/sshkit/runners/parallel.rb:12:in `block (2 levels) in execute'
Tasks: TOP => define_usermacros

I tried to up- and downgrade capistrano, airbrussh, sshkit in the bundle but to no avail, things remain broken.

At the moment cap doctor tells me I'm using the following versions:

Environment

Ruby     ruby 2.2.5p319 (2016-04-26 revision 54774) [x86_64-darwin15]
Rubygems 2.6.10
Bundler  1.14.3
Command  /usr/local/var/rbenv/versions/2.2.5/bin/cap staging doctor

Gems

capistrano          3.7.2  (update available)
airbrussh           1.2.0
rake                12.0.0
sshkit              1.13.1
net-ssh             4.1.0
capistrano-template 0.0.8

And here's the capistrano stuff:

Gemfile:

source "https://rubygems.org"

group :development do
  gem "capistrano", "~> 3.7.0"
  gem "capistrano-template"
end

Capfile:

require "capistrano/setup"
require "capistrano/deploy"
require "capistrano/scm/git"
install_plugin Capistrano::SCM::Git
require 'capistrano/capistrano_plugin_template'

config/deploy.rb:

[...]
desc 'Upload user macros as rendered erb-template'
task :define_usermacros do
  on roles :all do
    template 'resource.cfg', "#{release_path}/resource_file",
         0o640,
         locals: {
           'user1' => 'blah'
         }
 end
end

... and there is of course an erb template in config/deploy/templates/shared/resource.cfg.erb.

Any hints on the solution or how to debug the issue welcome!


问:
Inner join or other equal solution
I have good working  sql query but I need to select also atribute from table advert. I tried with inner join but it wasn't successful. So this query is ok but I need to select one atribute from table advert.</p>

```<code>SELECT D.* FROM  details
WHERE (D.name LIKE ?) AND  (D.id_advert IN(
   SELECT A.id
   FROM advert A
   WHERE A.status=1 and duration >= CURDATE()
   ORDER BY duration DESC ))
</code>```

答:
```<code>SELECT *
FROM details D
INNER JOIN advert A ON D.id_advert = A.id
INNER JOIN place P ON A.id_place = P.id
WHERE (D.NAME LIKE ?)
    AND ( D.id_advert IN (
            SELECT A.id
            FROM advert A
            WHERE A.STATUS = 1 AND duration >= CURDATE()
            ORDER BY duration DESC
            )
        )
</code>```

Here "?" is for search key. This query work perfect.

Title: Inner join or other equal solution

Body:
I have good working  sql query but I need to select also atribute from table advert. I tried with inner join but it wasn't successful. So this query is ok but I need to select one atribute from table advert.

SELECT D.* FROM  details
WHERE (D.name LIKE ?) AND  (D.id_advert IN(
   SELECT A.id
   FROM advert A
   WHERE A.status=1 and duration >= CURDATE()
   ORDER BY duration DESC ))

Body:
SELECT *
FROM details D
INNER JOIN advert A ON D.id_advert = A.id
INNER JOIN place P ON A.id_place = P.id
WHERE (D.NAME LIKE ?)
    AND ( D.id_advert IN (
            SELECT A.id
            FROM advert A
            WHERE A.STATUS = 1 AND duration >= CURDATE()
            ORDER BY duration DESC
            )
        )

Here "?" is for search key. This query work perfect.


问:
Create matrix in R whose elements are associated to a pair of numbers
I am quite new to coding R..so I really appreciate your patience and time (thank you!).

I need to create a matrix in R like the one I attach: each element of this matrix 5x9 is the maximum between the number of row and the sum of the two numbers in parenthesis (that are clearly combinations of the number 0,1,2 in groups of two).
I already know how to construct matrix in R.In this case the problem relates to the fact that each element of the matrix depends on an associated pair of numbers.
I am aware that this request can sounds strange, but any kind of help would be really appreciated.
Thank you!

```<code>|   |(0,0)|(1,0)|(2,0)|(0,1)|(1,1)|(2,1)|(0,2)|(1,2)|(2,2)|
----------------------------------------------------------
| 1 |  1     1     2     1     2     3     2     3     4
| 2 |  2     2     2     2     2     3     2     3     4
| 3 |  3     3     3     3     3     3     3     3     4
| 4 |  4     4     4     4     4     4     4     4     4
| 5 |  5     5     5     5     5     5     5     5     5
</code>```

Body:
I am quite new to coding R..so I really appreciate your patience and time (thank you!).

I need to create a matrix in R like the one I attach: each element of this matrix 5x9 is the maximum between the number of row and the sum of the two numbers in parenthesis (that are clearly combinations of the number 0,1,2 in groups of two).
I already know how to construct matrix in R.In this case the problem relates to the fact that each element of the matrix depends on an associated pair of numbers.
I am aware that this request can sounds strange, but any kind of help would be really appreciated.
Thank you!

|   |(0,0)|(1,0)|(2,0)|(0,1)|(1,1)|(2,1)|(0,2)|(1,2)|(2,2)|
----------------------------------------------------------
| 1 |  1     1     2     1     2     3     2     3     4
| 2 |  2     2     2     2     2     3     2     3     4
| 3 |  3     3     3     3     3     3     3     3     4
| 4 |  4     4     4     4     4     4     4     4     4
| 5 |  5     5     5     5     5     5     5     5     5

Body:
Try this one:

vals <- rowSums(expand.grid(0:2, 0:2))
x <- rep(1:5, 9)
m <- matrix(pmax(x, vals[rep(1:9, each = 5)]), nrow = 5)

#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
# [1,]    1    1    2    1    2    3    2    3    4
# [2,]    2    2    2    2    2    3    2    3    4
# [3,]    3    3    3    3    3    3    3    3    4
# [4,]    4    4    4    4    4    4    4    4    4
# [5,]    5    5    5    5    5    5    5    5    5


问:
JRE not found by eclipse
I am having issues starting up my java neon, and it keeps saying saying "A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run eclipse. no java virtual machine was found after searching the following locations C:/Program Files/Java/jre1.8.0_45/bin" but i installed the jre1.8.0_131, as i dont know how to either downgrade mine or update eclipse's. I feel so silly for not even knowing how to do this but thanks for any help you guys have!</p>

答:
Your JAVA_HOME and or JRE_HOME variables are probably pointing to a wrong installation.

Update those environmental variables and you should be good.

Title: JRE not found by eclipse


问:
pointer targets in initialization differ in signedness
I am running some code on an embedded board that uses an ARM processor. I have declared this array of strings.

```<code>const int8_t *test_str[][3] = {
{"pa4",  "3", "A0"},
{"pa5",  "3", "A1"},
{"pa6",  "3", "A1"},};
</code>```

I am testing the code on another ARM processor from a different manufacturer and got no compile warnings. But if I compile it with the board that I am going to use I get the following warning

pointer targets in initialization differ in signedness

The board is an ST32F0 ARM device. Have I actually missed something out of the declaration?

Thanks

答:
A string literal in C has type char[len], where len represents the number of characters in the literal plus one for null termination.

Since char could be either signed or unsigned, you cannot make a portable code that forces pointers produced from string literals into either int8_t or uint8_t without an additional cast.

Changing const int8_t to const char will make pointer types match, but the type of the elements would no longer be int8_t.

Body:
I am running some code on an embedded board that uses an ARM processor. I have declared this array of strings.

const int8_t *test_str[][3] = {
{"pa4",  "3", "A0"},
{"pa5",  "3", "A1"},
{"pa6",  "3", "A1"},};

I am testing the code on another ARM processor from a different manufacturer and got no compile warnings. But if I compile it with the board that I am going to use I get the following warning

pointer targets in initialization differ in signedness

The board is an ST32F0 ARM device. Have I actually missed something out of the declaration?

Thanks


问:
Rotate canvas arc on its centre
I have a canvas with an arc and some labels inside it.

Here is the fiddle link - Fiddle and below is the code:

    var canvas = document.getElementById("myCanvas"),
    ctx = canvas.getContext("2d"),
    x = canvas.width / 2,
    y = canvas.height / 2,
    radius = 100;

ctx.lineWidth = 2;

var numberofArcs = 10,
    sengmentWidth = 1.5 * Math.PI / numberofArcs,
    pieAngle = 1.5 * Math.PI / numberofArcs;

console.log(pieAngle);

var labeltext = '',
    font = 16,
    hightlight = 1;

drawSegments(radius, font, hightlight);

ctx.translate(x, y);
ctx.rotate(135 * Math.PI);
ctx.translate(-x, -y);

function drawSegments(radius, font, highlight) {
    var offset = 0;

    for (var i = 0; i < numberofArcs; i++) {
        (i<=8) ? offset = 3 : offset = 8;

        ctx.save();
        ctx.beginPath();
        ctx.moveTo(x, y);

        ctx.arc(x, y, radius, i * pieAngle, (i + 1) * pieAngle);

        var hueValue = i * 15;

        ctx.fillStyle = 'hsl(' + hueValue + ',70%, 60%)';
        ctx.fill();
        ctx.lineTo(x, y);
        ctx.lineWidth = 3;
        ctx.strokeStyle = '#f3f5f6';
        ctx.stroke();

        ctx.beginPath();
        ctx.moveTo(x, y);
        ctx.arc(x, y, radius - 10, i * pieAngle, (i + 1) * pieAngle);
        ctx.fillStyle = '#f3f5f6';
        ctx.fill();
        ctx.lineTo(x, y);
        ctx.lineWidth = 0;
        labeltext = i + 1;
        ctx.font = '16px bold white';

        var width = ctx.measureText(labeltext).width;
        ctx.fillStyle = '#CCC';

        if ((i + 1) == highlight) {
            ctx.textBaseline = 'middle';

            console.log(offset);

            ctx.beginPath();
            ctx.moveTo(x + offset +(radius + 30) * Math.cos(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2), y + (radius + 30) * Math.sin(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2));
            ctx.arc(x + offset + (radius + 30) * Math.cos(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2), y + (radius + 30) * Math.sin(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2), 10, 0,  2 * Math.PI);
            ctx.fillStyle = 'red';
            ctx.fill();

            ctx.fillStyle = "#000";

            ctx.fillText(labeltext, x + (radius + 30) * Math.cos(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2), y + (radius + 30) * Math.sin(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2));
        } else {
            ctx.fillStyle = "black";
            ctx.fillText(labeltext, x + (radius + 30) * Math.cos(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2), y + (radius + 30) * Math.sin(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2));
        }
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
    border: 1px dotted black;
    color: black;
}</code>```

<canvas id="myCanvas" width="400" height="400" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>```
</div>
</div>
</p>

<p>What I want to achieve is rotate the whole arc along with labels by 135 degrees.
I tried this code but it did not work : </p>

```ctx.translate(x, y);
ctx.rotate(135 * Math.PI/180);
ctx.translate(-x, -y);
```

Where x and y are canvas center points.
Any help would be appreciated.
PS: I'm new to canvas !

答:
As this is symetrical as you rotate it is easy to just add to the angle we draw segments at by the amount we want to rotate the circle by.

There was a lot of code doing nothing so have cut you code down to be a little more manageable.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2;
const radius = 100;
const numberofArcs = 10;
const sengmentWidth = 1.5 * Math.PI / numberofArcs;
const pieAngle = 1.5 * Math.PI / numberofArcs;
const spacePixels = 4;
const spaceRadians = spacePixels / radius;
const fontHeight = 16;
const textOffset = 30;
var hightlight = 1;
var angle = 135 * (Math.PI / 180);

drawSegments(x, y, radius, hightlight, angle);

function drawSegments(x, y, radius, highlight, angle) {
    ctx.textBaseline = 'middle';
    ctx.textAlign = "center";
    ctx.font = fontHeight + 'px bold white';
    // move center to x,y pos
    ctx.setTransform(1,0,0,1,x,y);
    x = y = 0;
    // draw the light gray pie and border
    var offset = 0;
    ctx.beginPath();
    ctx.moveTo(0,0);
    ctx.arc(0,0,radius + spacePixels, angle, angle + numberofArcs * pieAngle);
    ctx.lineTo(0,0); // or could use closePath
    ctx.fillStyle = '#f3f5f6';
    ctx.strokeStyle = '#e3e5e6';
    ctx.lineWidth = 4;
    ctx.stroke();
    ctx.fill();

    // for each segment draw coloured arc and text
    for (var i = 0; i < numberofArcs; i++) {
        var pA = pieAngle * i; // angle of start of pie pA;
        var tDir  = (i + 0.5) * pieAngle;  // angle of text
        pA += angle;  // add the rotated angle
        tDir += angle;
        var dist = radius + textOffset; // text distance from center
        var sR = spaceRadians; // the spacnig between segments

        ctx.strokeStyle = '#d3d5d6';  // for adding outline to coloured arcs
        ctx.lineWidth = 4;  // outline width is half this amount
        ctx.fillStyle = 'hsl(' + (i*15) + ',70%, 60%)';
        ctx.beginPath();
        ctx.arc(x, y, radius, pA + sR, pA + pieAngle -sR);  // outside CW
        ctx.arc(x, y, radius - 10,pA + pieAngle -sR, pA + sR,true);  // then inside CCW
        ctx.stroke();
        ctx.fill();
        if ((i + 1) === highlight) {

            ctx.fillStyle = 'red';
            ctx.beginPath();
            ctx.arc(dist * Math.cos(tDir), dist  * Math.sin(tDir), 10, 0,  2 * Math.PI);
            ctx.fill();
        }
        ctx.fillStyle = "black";
        ctx.fillText(""+(i + 1), Math.cos(tDir) * dist, Math.sin(tDir) * dist);

    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
    border: 1px dotted black;
    color: black;
}</code>```

<canvas id="myCanvas" width="400" height="400" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>```

Title: Rotate canvas arc on its centre

Body:
I have a canvas with an arc and some labels inside it.

Here is the fiddle link - Fiddle and below is the code:

    var canvas = document.getElementById("myCanvas"),
    ctx = canvas.getContext("2d"),
    x = canvas.width / 2,
    y = canvas.height / 2,
    radius = 100;

ctx.lineWidth = 2;

var numberofArcs = 10,
    sengmentWidth = 1.5 * Math.PI / numberofArcs,
    pieAngle = 1.5 * Math.PI / numberofArcs;

console.log(pieAngle);

var labeltext = '',
    font = 16,
    hightlight = 1;

drawSegments(radius, font, hightlight);

ctx.translate(x, y);
ctx.rotate(135 * Math.PI);
ctx.translate(-x, -y);

function drawSegments(radius, font, highlight) {
    var offset = 0;

    for (var i = 0; i < numberofArcs; i++) {
        (i<=8) ? offset = 3 : offset = 8;

        ctx.save();
        ctx.beginPath();
        ctx.moveTo(x, y);

        ctx.arc(x, y, radius, i * pieAngle, (i + 1) * pieAngle);

        var hueValue = i * 15;

        ctx.fillStyle = 'hsl(' + hueValue + ',70%, 60%)';
        ctx.fill();
        ctx.lineTo(x, y);
        ctx.lineWidth = 3;
        ctx.strokeStyle = '#f3f5f6';
        ctx.stroke();

        ctx.beginPath();
        ctx.moveTo(x, y);
        ctx.arc(x, y, radius - 10, i * pieAngle, (i + 1) * pieAngle);
        ctx.fillStyle = '#f3f5f6';
        ctx.fill();
        ctx.lineTo(x, y);
        ctx.lineWidth = 0;
        labeltext = i + 1;
        ctx.font = '16px bold white';

        var width = ctx.measureText(labeltext).width;
        ctx.fillStyle = '#CCC';

        if ((i + 1) == highlight) {
            ctx.textBaseline = 'middle';

            console.log(offset);

            ctx.beginPath();
            ctx.moveTo(x + offset +(radius + 30) * Math.cos(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2), y + (radius + 30) * Math.sin(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2));
            ctx.arc(x + offset + (radius + 30) * Math.cos(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2), y + (radius + 30) * Math.sin(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2), 10, 0,  2 * Math.PI);
            ctx.fillStyle = 'red';
            ctx.fill();

            ctx.fillStyle = "#000";

            ctx.fillText(labeltext, x + (radius + 30) * Math.cos(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2), y + (radius + 30) * Math.sin(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2));
        } else {
            ctx.fillStyle = "black";
            ctx.fillText(labeltext, x + (radius + 30) * Math.cos(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2), y + (radius + 30) * Math.sin(i * pieAngle + ((i + 1) * pieAngle - i * pieAngle) / 2));
        }
    }
}

canvas {
    border: 1px dotted black;
    color: black;
}

<canvas id="myCanvas" width="400" height="400" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

What I want to achieve is rotate the whole arc along with labels by 135 degrees.
I tried this code but it did not work :

ctx.translate(x, y);
ctx.rotate(135 * Math.PI/180);
ctx.translate(-x, -y);

Where x and y are canvas center points.
Any help would be appreciated.
PS: I'm new to canvas !

Body:
As this is symetrical as you rotate it is easy to just add to the angle we draw segments at by the amount we want to rotate the circle by.

There was a lot of code doing nothing so have cut you code down to be a little more manageable.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2;
const radius = 100;
const numberofArcs = 10;
const sengmentWidth = 1.5 * Math.PI / numberofArcs;
const pieAngle = 1.5 * Math.PI / numberofArcs;
const spacePixels = 4;
const spaceRadians = spacePixels / radius;
const fontHeight = 16;
const textOffset = 30;
var hightlight = 1;
var angle = 135 * (Math.PI / 180);

drawSegments(x, y, radius, hightlight, angle);

function drawSegments(x, y, radius, highlight, angle) {
    ctx.textBaseline = 'middle';
    ctx.textAlign = "center";
    ctx.font = fontHeight + 'px bold white';
    // move center to x,y pos
    ctx.setTransform(1,0,0,1,x,y);
    x = y = 0;
    // draw the light gray pie and border
    var offset = 0;
    ctx.beginPath();
    ctx.moveTo(0,0);
    ctx.arc(0,0,radius + spacePixels, angle, angle + numberofArcs * pieAngle);
    ctx.lineTo(0,0); // or could use closePath
    ctx.fillStyle = '#f3f5f6';
    ctx.strokeStyle = '#e3e5e6';
    ctx.lineWidth = 4;
    ctx.stroke();
    ctx.fill();

    // for each segment draw coloured arc and text
    for (var i = 0; i < numberofArcs; i++) {
        var pA = pieAngle * i; // angle of start of pie pA;
        var tDir  = (i + 0.5) * pieAngle;  // angle of text
        pA += angle;  // add the rotated angle
        tDir += angle;
        var dist = radius + textOffset; // text distance from center
        var sR = spaceRadians; // the spacnig between segments

        ctx.strokeStyle = '#d3d5d6';  // for adding outline to coloured arcs
        ctx.lineWidth = 4;  // outline width is half this amount
        ctx.fillStyle = 'hsl(' + (i*15) + ',70%, 60%)';
        ctx.beginPath();
        ctx.arc(x, y, radius, pA + sR, pA + pieAngle -sR);  // outside CW
        ctx.arc(x, y, radius - 10,pA + pieAngle -sR, pA + sR,true);  // then inside CCW
        ctx.stroke();
        ctx.fill();
        if ((i + 1) === highlight) {

            ctx.fillStyle = 'red';
            ctx.beginPath();
            ctx.arc(dist * Math.cos(tDir), dist  * Math.sin(tDir), 10, 0,  2 * Math.PI);
            ctx.fill();
        }
        ctx.fillStyle = "black";
        ctx.fillText(""+(i + 1), Math.cos(tDir) * dist, Math.sin(tDir) * dist);

    }
}

canvas {
    border: 1px dotted black;
    color: black;
}

<canvas id="myCanvas" width="400" height="400" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>


问:
Xampp refused connection
I've put a PHP Laravel project in my xampp folder, and I configured it a bit :

```<code><VirtualHost myproject.dev:80>
  DocumentRoot "C:\xampp\htdocs\myproject\public"
  ServerAdmin myproject.dev
<Directory "C:\xampp\htdocs\myproject">
      Options Indexes FollowSymLinks
      AllowOverride All
      Require all granted
</Directory>
</VirtualHost>
</code>```

And this in my system32/drivers/etc

```<code> 127.0.0.1  myproject.dev
</code>```

The problem I have is that it doesn't show my google map ( I heard it's a problem with the port number) , so I tried changing it to a different port. I've went and changed Listen 80 to Listen newport,(changed the above port aswell) however I get connection refused with my new port. If I switch it back to 80 it works fine. Any idea why ?

答: Are you using a private browser ? Sometimes when I use incognito mode it stops me receiving data from outside sources. Such as weather updates and google maps. Or if I pull in JSON data from my web server. </p>

Title: Xampp refused connection

Body:
I've put a PHP Laravel project in my xampp folder, and I configured it a bit :

<VirtualHost myproject.dev:80>
  DocumentRoot "C:\xampp\htdocs\myproject\public"
  ServerAdmin myproject.dev
<Directory "C:\xampp\htdocs\myproject">
      Options Indexes FollowSymLinks
      AllowOverride All
      Require all granted
</Directory>
</VirtualHost>

And this in my system32/drivers/etc

 127.0.0.1  myproject.dev

The problem I have is that it doesn't show my google map ( I heard it's a problem with the port number) , so I tried changing it to a different port. I've went and changed Listen 80 to Listen newport,(changed the above port aswell) however I get connection refused with my new port. If I switch it back to 80 it works fine. Any idea why ?


问:
Common code in React component constructor and componentWillReceiveProps
I often come to this sort of situation when using statefull React components.

I need to do some operation on props - either do some processing which I do now want to have in render() or set state according the values in props.

As I want to do this when component is initially mounted as well as when the props are updated, I end up with a boilerplate code like this:

```<code>constructor(){
    super(props)
    const modifiedProps = doSomethingWithProps(props)
        ...
    this.state = {initialState}
}

componentWillReceiveProps(nextProps) {
    const modifiedProps = doSomethingWithProps(nextProps)
         ...
    this.setState({newState})
}

doSomethingWithProps(props){
        ...
}
</code>```

Is there a better way how to do this ?

答:
Why not pass the props to the component after they are transformed?

This can be achieved in a couple of ways:

Use a simple stateless container, which transforms the props and passes them to this component.

```<code>export const Container = (props) =>
    <YourComponent modifiedProp={doSomethingWithProps(props)} />
</code>```

Use a connected component and do the transformation inside the mapStateToProps method:

```<code>const mapStateToProps = (state, ownProps) => ({
    modifiedProp: doSomethingWithProps(ownProps)
});

export const ConnectedComponent = connect(mapStateToProps)(YourComponent);
</code>```

The first option is really a stripped-down version of the second.

You may also be interested in using selectors to compute the derived props that you pass to your component.

Body:
I often come to this sort of situation when using statefull React components.

I need to do some operation on props - either do some processing which I do now want to have in render() or set state according the values in props.

As I want to do this when component is initially mounted as well as when the props are updated, I end up with a boilerplate code like this:

constructor(){
    super(props)
    const modifiedProps = doSomethingWithProps(props)
        ...
    this.state = {initialState}
}

componentWillReceiveProps(nextProps) {
    const modifiedProps = doSomethingWithProps(nextProps)
         ...
    this.setState({newState})
}

doSomethingWithProps(props){
        ...
}

Is there a better way how to do this ?

Body:
Why not pass the props to the component after they are transformed?

This can be achieved in a couple of ways:

Use a simple stateless container, which transforms the props and passes them to this component.

export const Container = (props) =>
    <YourComponent modifiedProp={doSomethingWithProps(props)} />

Use a connected component and do the transformation inside the mapStateToProps method:

const mapStateToProps = (state, ownProps) => ({
    modifiedProp: doSomethingWithProps(ownProps)
});

export const ConnectedComponent = connect(mapStateToProps)(YourComponent);

The first option is really a stripped-down version of the second.

You may also be interested in using selectors to compute the derived props that you pass to your component.


问:
Rails - Using jquery to get page view from controller
I am trying to use a select_tag to find a customer id and then send it to the controller to render the show page.

```<code><%= select_tag( "cust_id", options_from_collection_for_select(@customers.by_last_name, :id, :last_name, (@customers_id.nil?) ? nil : @customers_id), {:class => 'custTag'}) %>
</code>```

jquery code

```<code>$(document).ready
$(document).on('change', '.custTag', function(){

    var custId = $(this).val();
    alert (custId);
    $.get('/customers/custId');

});
</code>```

I am having two problems:

While the alert shows the customer id(custId) associated with the record, the server is responding with the message - ActiveRecord::RecordNotFound (Couldn't find Customer with 'id'=custId).

If I put the id directly in the code ($.get('/customers/6559');) The controller responds with Processing by CustomersController#show as '*/*'.

And nothing is rendered - the server does receive the entered id and appears to be processing the request as if I have entered the request directly in the browser address bar

I apologize in advance for my ignorance - I am very new to this process.

答:
Two problems merit two answers.

1) Rails routing has URL params, meaning /customers/:id where :id is the param. You're select and JQuery code is fine, as you've confirmed yourself, but you need to add the custId to the string in your $.get to send the actual id.

Currently you're request is /customers/custId so it's trying to find id = custId...

```<code>$.get('/customers/' + custId);
</code>```

2) AJAX need to be handled otherwise nothing happens. You're request is sent, response sent back to your JS, then nothing because nothing is defined.

What do you want to have happen exactly? Did you try doing this via HTML instead of JS?

I'd say what you want is to have the page re-rendered to show, so...

```<code>$.get('/customers/' + custId).done(function(data){
  $(document).html(data) // something like this to replace the content
})
</code>```

The rule of thumb with these things is, do it with HTML FIRST! Then use AJAX to if you feel it's appropriate.

Good luck!

Body:
I am trying to use a select_tag to find a customer id and then send it to the controller to render the show page.

<%= select_tag( "cust_id", options_from_collection_for_select(@customers.by_last_name, :id, :last_name, (@customers_id.nil?) ? nil : @customers_id), {:class => 'custTag'}) %>

jquery code

$(document).ready
$(document).on('change', '.custTag', function(){

    var custId = $(this).val();
    alert (custId);
    $.get('/customers/custId');

});

I am having two problems:

While the alert shows the customer id(custId) associated with the record, the server is responding with the message - ActiveRecord::RecordNotFound (Couldn't find Customer with 'id'=custId).

If I put the id directly in the code ($.get('/customers/6559');) The controller responds with Processing by CustomersController#show as '*/*'.

And nothing is rendered - the server does receive the entered id and appears to be processing the request as if I have entered the request directly in the browser address bar

I apologize in advance for my ignorance - I am very new to this process.

Body:
Two problems merit two answers.

1) Rails routing has URL params, meaning /customers/:id where :id is the param. You're select and JQuery code is fine, as you've confirmed yourself, but you need to add the custId to the string in your $.get to send the actual id.

Currently you're request is /customers/custId so it's trying to find id = custId...

$.get('/customers/' + custId);

2) AJAX need to be handled otherwise nothing happens. You're request is sent, response sent back to your JS, then nothing because nothing is defined.

What do you want to have happen exactly? Did you try doing this via HTML instead of JS?

I'd say what you want is to have the page re-rendered to show, so...

$.get('/customers/' + custId).done(function(data){
  $(document).html(data) // something like this to replace the content
})

The rule of thumb with these things is, do it with HTML FIRST! Then use AJAX to if you feel it's appropriate.

Good luck!


问:
DllImport C Sharp const char*
Hy all,

I want to make from a unmanaged dll to a managed dll in C#.

in the documentation it is:

```<code>typedef void*    AP_HANDLE
typedef uint32_t ap_u32

AP_HANDLE ap_CreateVirtual(const char *szFilename)

void ap_SetState(AP_HANDLE apbase, const char *szState, int nValue)

unsigned char *ap_ColorPipe(AP_HANDLE      apbase,
                            unsigned char *pInBuffer,
                            ap_u32         nInBufferSize,
                            ap_u32        *rgbWidth,
                            ap_u32        *rgbHeight,
                            ap_u32        *rgbBitDepth)
</code>```

In C++ works fine, but in C# the syntax is the problem
It seems I can't make not evan the first function work

```<code>public unsafe class appbase
{
    [DllImport("D:\\apbase.dll", EntryPoint = "ap_CreateVirtual")]
    //, CharSet = UnicodeEncoding
    //, CallingConvention = CallingConvention.StdCall

    public static extern void* ap_CreateVirtual(char* szFilename);
}
</code>```

and

```<code>    public static void Main()
    {
        unsafe
        {
            void* ap_handle = null;

            appbase APPbase = new appbase();

            string s = "D:\\ASX.xsdat";

            fixed (char* p = s)
            {
                ap_handle = APPbase.ap_CreateVirtual(p);
            }

            return;
        }
    }
</code>```

tried with argument for ap_CreateVirtual string, String*, char*, char[] and put a break point on return; the ap_handle was always with value 0x0000

what is the proper way to import these functions ?

答:
char* is the default marshaling for a .NET string.

```<code>[DllImport("D:\\apbase.dll", EntryPoint = "ap_CreateVirtual", CharSet = CharSet.Ansi)]
//, CallingConvention = CallingConvention.StdCall
public static extern System.IntPtr ap_CreateVirtual(string szFilename);
</code>```

Your original attempt was wrong because char in C# is C++'s wchar_t, not C++ char.

If you need a C++ char in C#, it's either byte or sbyte.  But p/invoke will simply do the right thing with System.String.

Title: DllImport C Sharp const char*

Body:
Hy all,

I want to make from a unmanaged dll to a managed dll in C#.

in the documentation it is:

typedef void*    AP_HANDLE
typedef uint32_t ap_u32

AP_HANDLE ap_CreateVirtual(const char *szFilename)

void ap_SetState(AP_HANDLE apbase, const char *szState, int nValue)

unsigned char *ap_ColorPipe(AP_HANDLE      apbase,
                            unsigned char *pInBuffer,
                            ap_u32         nInBufferSize,
                            ap_u32        *rgbWidth,
                            ap_u32        *rgbHeight,
                            ap_u32        *rgbBitDepth)

In C++ works fine, but in C# the syntax is the problem
It seems I can't make not evan the first function work

public unsafe class appbase
{
    [DllImport("D:\\apbase.dll", EntryPoint = "ap_CreateVirtual")]
    //, CharSet = UnicodeEncoding
    //, CallingConvention = CallingConvention.StdCall

    public static extern void* ap_CreateVirtual(char* szFilename);
}

and

    public static void Main()
    {
        unsafe
        {
            void* ap_handle = null;

            appbase APPbase = new appbase();

            string s = "D:\\ASX.xsdat";

            fixed (char* p = s)
            {
                ap_handle = APPbase.ap_CreateVirtual(p);
            }

            return;
        }
    }

tried with argument for ap_CreateVirtual string, String*, char*, char[] and put a break point on return; the ap_handle was always with value 0x0000

what is the proper way to import these functions ?

Body:
char* is the default marshaling for a .NET string.

[DllImport("D:\\apbase.dll", EntryPoint = "ap_CreateVirtual", CharSet = CharSet.Ansi)]
//, CallingConvention = CallingConvention.StdCall
public static extern System.IntPtr ap_CreateVirtual(string szFilename);

Your original attempt was wrong because char in C# is C++'s wchar_t, not C++ char.

If you need a C++ char in C#, it's either byte or sbyte.  But p/invoke will simply do the right thing with System.String.


问:
how to figure image size to fit below header and above footer
I want to center an image in the available space below the page header and above the page footer.
It needs to be responsive, so I want the picture to be as large as possible but not overlap the header and footer.

The ID of the image is #nMapImg.

I have these values:

```<code>var dh=$(document).height();
var dw=$(document).width();
var hh=$("#header").height();
var fh=$("#footer").height();
var w=$("#nMapImg").width();
var availHeight=h-hh-fh;
</code>```

I think this is just math to figure the max size I can have and then I'll center it. I just can't wrap my head around it.

答:
Using flexbox and setting a height on a div where the image lies

*{margin: 0;}
header{
  background: green;
  height: 100px;
}

footer{
  background: green;
  height: 100px;
}

.main{
  height: 1000px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.main img{
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <h1>HEADER</h1>
</header>
<div class="main">
<img src="https://placehold.it//900x500" alt="" />
</div>
<footer>
  <h1>FOOTER</h1>
</footer></code>```

Body:
I want to center an image in the available space below the page header and above the page footer.
It needs to be responsive, so I want the picture to be as large as possible but not overlap the header and footer.

The ID of the image is #nMapImg.

I have these values:

var dh=$(document).height();
var dw=$(document).width();
var hh=$("#header").height();
var fh=$("#footer").height();
var w=$("#nMapImg").width();
var availHeight=h-hh-fh;

I think this is just math to figure the max size I can have and then I'll center it. I just can't wrap my head around it.

Body:
Using flexbox and setting a height on a div where the image lies

*{margin: 0;}
header{
  background: green;
  height: 100px;
}

footer{
  background: green;
  height: 100px;
}

.main{
  height: 1000px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.main img{
  width: 100%;
}

<header>
  <h1>HEADER</h1>
</header>
<div class="main">
<img src="https://placehold.it//900x500" alt="" />
</div>
<footer>
  <h1>FOOTER</h1>
</footer>


问:
get child elements of a dictonairy
I have a network with different hosts and different networks and I want to use ansible to ping each host in each network.

In my host_vars directory all informations about every host and its network are stored in its own file. A hostfile looks like this:

bond:
  - conn_name: net1
    ip4: '10.10.44.21'
    gw4: '10.10.44.1'
  - conn_name: net2
    ip4: '10.10.47.21'
    gw4: '10.10.47.1'
  - conn_name: net3
    ip4: '10.10.46.21'
    gw4: '10.10.46.1'
bond_slave:
  - conn_name: eno1
    ifname: eno1
    master: net1
  - conn_name: eno2
    ifname: eno2
    master: net2
  - conn_name: ens2f1
    ifname: ens2f1
    master: net2
  - conn_name: ens2f0
    ifname: ens2f0
    master: net2
  - conn_name: ens4f1
    ifname: ens4f1
    master: net3
  - conn_name: ens4f0
    ifname: ens4f0
    master: net3
```

<p>My purpose is to get every ip4-value and ping it from every host. what i can do is include all files from host_vars directory and ping the ip-adress of the first bond item of each file.</p>

<pre class="lang-yaml prettyprint-override"><code>---
- hosts: all

- name: Include information about all hosts
  include_vars: ../../host_vars/{{ item }}.yaml
  with_items: hosts
  register: "r"

- name: execute ping
  command: ping {{ bond[0].ip4 }} -c 3
  with_items: "{{ r.results }}"
</code>```

But the bond can have from 2 to 4 networks. How do i loop through each bond to access all ip-address?

Solution

Even though the snippet of Konstantin Suvorov wasn't working for me, it helped me to find the right solution:

- name: execute ping
  command: ping {{ item.ip4 }} -c 3
  with_items: "{{ r.results | map(attribute='ansible_facts.bond') | list }}"
```

答:
If you have bond var defined for each host via host_vars, you can use hostvars magic variable (no need to do this ugly include task):

```<code>- name: ping everything
  command: ping {{ item }} -c 3
  with_items: "{{ play_hosts | map('extract',hostvars,'bond') | list }}"
</code>```

Actually this Jinja2 expression will return a list of lists, but with_items flattends them, so you end up with long list all elements from every bond of every host in current play.

Title: get child elements of a dictonairy

Body:
I have a network with different hosts and different networks and I want to use ansible to ping each host in each network.

In my host_vars directory all informations about every host and its network are stored in its own file. A hostfile looks like this:

bond:
  - conn_name: net1
    ip4: '10.10.44.21'
    gw4: '10.10.44.1'
  - conn_name: net2
    ip4: '10.10.47.21'
    gw4: '10.10.47.1'
  - conn_name: net3
    ip4: '10.10.46.21'
    gw4: '10.10.46.1'
bond_slave:
  - conn_name: eno1
    ifname: eno1
    master: net1
  - conn_name: eno2
    ifname: eno2
    master: net2
  - conn_name: ens2f1
    ifname: ens2f1
    master: net2
  - conn_name: ens2f0
    ifname: ens2f0
    master: net2
  - conn_name: ens4f1
    ifname: ens4f1
    master: net3
  - conn_name: ens4f0
    ifname: ens4f0
    master: net3

My purpose is to get every ip4-value and ping it from every host. what i can do is include all files from host_vars directory and ping the ip-adress of the first bond item of each file.

---
- hosts: all

- name: Include information about all hosts
  include_vars: ../../host_vars/{{ item }}.yaml
  with_items: hosts
  register: "r"

- name: execute ping
  command: ping {{ bond[0].ip4 }} -c 3
  with_items: "{{ r.results }}"

But the bond can have from 2 to 4 networks. How do i loop through each bond to access all ip-address?

Solution

Even though the snippet of Konstantin Suvorov wasn't working for me, it helped me to find the right solution:

- name: execute ping
  command: ping {{ item.ip4 }} -c 3
  with_items: "{{ r.results | map(attribute='ansible_facts.bond') | list }}"

Body:
If you have bond var defined for each host via host_vars, you can use hostvars magic variable (no need to do this ugly include task):

- name: ping everything
  command: ping {{ item }} -c 3
  with_items: "{{ play_hosts | map('extract',hostvars,'bond') | list }}"

Actually this Jinja2 expression will return a list of lists, but with_items flattends them, so you end up with long list all elements from every bond of every host in current play.


问:
Export queries from SSMS to files - not the results but the query
I want to export all my queries as individual files for purposes of putting them into mercurial source control, but I don't know how to export the individual queries as individual files without having to open each one, then save to the folder, then add into the project, or some equally convoluted process.

I wouldn't mind having to add each one individually, but how do I get them out of the database as individual files without opening them all and doing each one save as? Ostensibly I would like them named with the name they have in the database right now.

I could easily dump the whole lot into one long file using database tasks, but that's not really super helpful is it?

I have SSMS 2k5 and 2k8 (and VS 2k5, 2k8, 2010 to boot) to work with, any thoughts?

答:
It is rather easy to write stored procedures which fetches the definition into the result as text. sp_helptext could be used as start.
Than you can use PowerShell to write the Output to the file system.

It sounds as if this would fit rather good into the Really Simple Data Dictionary codeplex project. link text

ContentLicense: CC BY-SA 2.5


答:
It's better if you uninstall current java version and install newest jdk from here. This jdk also contains jre inside.

After installation in Eclipse go to Preferences -> Java -> Installed JREs and point to your jdk installation folder, for example C:\Java\jdk1.8.0_131. After that it should be fine.

Title: JRE not found by eclipse

Body: I am having issues starting up my java neon, and it keeps saying saying "A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run eclipse. no java virtual machine was found after searching the following locations C:/Program Files/Java/jre1.8.0_45/bin" but i installed the jre1.8.0_131, as i dont know how to either downgrade mine or update eclipse's. I feel so silly for not even knowing how to do this but thanks for any help you guys have!


问:
How to get tfs to notify affected developers of changes?
I'm on a small team and we are emailing each other when we make changes telling each other to get latest; pretty inefficient. And error prone.

How can we set up TFS to do this notify via email, perhaps with a change summary including the affected files?

答: You can use alerts in TFS to setup those notifications.</p>


问:
Jenkins pipeline build stuck forever if node doesn't exist
I have a Jenkins pipeline like:

```<code>node("slave1"){
  echo "Building very very complicated things"
}
</code>```

If the node "slave1" does not exist in my Jenkins setup, the build is stuck forever.

I know I could use timeout keyword and wrap the node command. However, this is not good since timeout can happen because of inexistent node or long-taking build. That's not really a solution.

Any calls that I can do to check if a node exists or not?

I use Jenkins 2.32.2 and pipeline plugin version 2.1.

答: You could use timeout like you say, only having the node do something trivial to test the water. If that succeeds you'll know "slave1" exists and can call node again to do the actual build.

Body:
I have a Jenkins pipeline like:

node("slave1"){
  echo "Building very very complicated things"
}

If the node "slave1" does not exist in my Jenkins setup, the build is stuck forever.

I know I could use timeout keyword and wrap the node command. However, this is not good since timeout can happen because of inexistent node or long-taking build. That's not really a solution.

Any calls that I can do to check if a node exists or not?

I use Jenkins 2.32.2 and pipeline plugin version 2.1.


问:
JPanel - Error changing background color of a JPanel
I have written the following code:

```<code>import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JFrame{

    public Test() {
        this.setTitle("Test");
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        JPanel jPanel = new JPanel() {
            public void paint(Graphics g) {
                g.setColor(Color.GREEN);
                g.fillOval(100, 100, 100, 100);
                g.setColor(Color.BLACK);
                g.drawLine(0, 0, 100, 100);
            }
        };
        jPanel.setSize(500, 500);
        jPanel.setBackground(Color.RED);
        this.add(jPanel);
        this.setVisible(true);
        this.setSize(500, 500);
    }

    public static void main(String[] args) {
        Test test = new Test();
    }
}
</code>```

I want to draw a circle, the line, and change the background color of the screen to red, but when I run the program the screen looks as follows:

Where is the error in the code?. Tank you

答:
First, don't override paint, but paintComponent.

Then, the javadoc of setBackground says :

Direct subclasses of JComponent must override paintComponent to honor
  this property.

So calling this method will do nothing by itself in your case, unless you call the paintComponent of the parent class (or paint the background yourself, but that would be overkill).

In any case it is advised to call super.paintComponent, because the parent implementation may perform some cleaning or other useful operations.

Here is a modified version of your code that takes all of this into account :

```<code>import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JFrame {

    public Test() {
        this.setTitle("Test");
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(final WindowEvent e) {
                System.exit(0);
            }
        });

        JPanel jPanel = new JPanel() {
            @Override
            public void paintComponent(final Graphics g) {
                // call parent method
                super.paintComponent(g);

                // OR paint background yourself :
                // g.setColor(getBackground());
                // g.fillRect(0, 0, getWidth(), getHeight());

                // paint other things
                g.setColor(Color.GREEN);
                g.fillOval(100, 100, 100, 100);
                g.setColor(Color.BLACK);
                g.drawLine(0, 0, 100, 100);
            }
        };
        jPanel.setSize(500, 500);
        jPanel.setBackground(Color.RED);
        this.add(jPanel);
        this.setVisible(true);
        this.setSize(500, 500);
    }

    public static void main(final String[] args) {
        Test test = new Test();
    }
}
</code>```

Body:
I have written the following code:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JFrame{

    public Test() {
        this.setTitle("Test");
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        JPanel jPanel = new JPanel() {
            public void paint(Graphics g) {
                g.setColor(Color.GREEN);
                g.fillOval(100, 100, 100, 100);
                g.setColor(Color.BLACK);
                g.drawLine(0, 0, 100, 100);
            }
        };
        jPanel.setSize(500, 500);
        jPanel.setBackground(Color.RED);
        this.add(jPanel);
        this.setVisible(true);
        this.setSize(500, 500);
    }

    public static void main(String[] args) {
        Test test = new Test();
    }
}

I want to draw a circle, the line, and change the background color of the screen to red, but when I run the program the screen looks as follows:

Where is the error in the code?. Tank you

Body:
First, don't override paint, but paintComponent.

Then, the javadoc of setBackground says :

Direct subclasses of JComponent must override paintComponent to honor
  this property.

So calling this method will do nothing by itself in your case, unless you call the paintComponent of the parent class (or paint the background yourself, but that would be overkill).

In any case it is advised to call super.paintComponent, because the parent implementation may perform some cleaning or other useful operations.

Here is a modified version of your code that takes all of this into account :

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JFrame {

    public Test() {
        this.setTitle("Test");
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(final WindowEvent e) {
                System.exit(0);
            }
        });

        JPanel jPanel = new JPanel() {
            @Override
            public void paintComponent(final Graphics g) {
                // call parent method
                super.paintComponent(g);

                // OR paint background yourself :
                // g.setColor(getBackground());
                // g.fillRect(0, 0, getWidth(), getHeight());

                // paint other things
                g.setColor(Color.GREEN);
                g.fillOval(100, 100, 100, 100);
                g.setColor(Color.BLACK);
                g.drawLine(0, 0, 100, 100);
            }
        };
        jPanel.setSize(500, 500);
        jPanel.setBackground(Color.RED);
        this.add(jPanel);
        this.setVisible(true);
        this.setSize(500, 500);
    }

    public static void main(final String[] args) {
        Test test = new Test();
    }
}


问:
Cost of calling str() on a string?
What is the cost (if any) of calling the str function on an object that is already a string? The use case here is to normalize an array of objects of different types and convert them into string, naively it can be implemented like so:

```<code>def arr_2_strarr(arr):
    return [str(val) for val in arr]
</code>```

But if the str() causes too much overhead, and my arr contains primarily strings, I may consider using:

```<code>def arr_2_strarr2(arr):
    return [str(val) if not isinstance(val, basestring) else val for val in arr]
</code>```

Any suggestions?

答:
```<code>    import time
    string = 'string'
    start_time = time.time()

    for i in range (100000):
        if isinstance(string,basestring):
            continue

    end_time = time.time()
    print (end_time - start_time)
    start_time = time.time()
    for i in range (100000):
        str(string)

    end_time = time.time()
    print (end_time - start_time)

    start_time = time.time()
    int = 9
    for i in range (1000000):
        str(int)

    end_time = time.time()
    print (end_time - start_time)
    #0.031
    #0.016
    #0.27999
</code>```

In these test cases it was twice as fast to just perform str(string) as opposed to using the conditional statement.

Title: Cost of calling str() on a string?

Body:
What is the cost (if any) of calling the str function on an object that is already a string? The use case here is to normalize an array of objects of different types and convert them into string, naively it can be implemented like so:

def arr_2_strarr(arr):
    return [str(val) for val in arr]

But if the str() causes too much overhead, and my arr contains primarily strings, I may consider using:

def arr_2_strarr2(arr):
    return [str(val) if not isinstance(val, basestring) else val for val in arr]

Any suggestions?

Body:
    import time
    string = 'string'
    start_time = time.time()

    for i in range (100000):
        if isinstance(string,basestring):
            continue

    end_time = time.time()
    print (end_time - start_time)
    start_time = time.time()
    for i in range (100000):
        str(string)

    end_time = time.time()
    print (end_time - start_time)

    start_time = time.time()
    int = 9
    for i in range (1000000):
        str(int)

    end_time = time.time()
    print (end_time - start_time)
    #0.031
    #0.016
    #0.27999

In these test cases it was twice as fast to just perform str(string) as opposed to using the conditional statement.


问:
Configurable custom code
Our customer provided source code has portions of code that will be executed based on tool type. A sample code portion is given below. The function has common portions and tool specific(hardware platform) portions. The code is written in C and runs in VxWorks. Addition or deletion of new tool type has code modification. The customer wants addition or deletion new tool type with minimal code change and testing effort

```<code>int vsp_recv(char *const recv_text)
{
    int rc  = 0;
    const int       type =  get_tool_type();
    // Common Code

    if (MODEL_CR == type)
    {
        rc = beamoff(recv_text);
    }
    else
    {
        rc = vsp_set(recv_text);
    }

    return(rc);
}
</code>```

Is it the right technique to separate the code to two methods as given below, keep them in separate source files and define separate make files to generate tool specific binary? Is there any better ways to do this?

Tool type MODEL_CR code

```<code>int vsp_recv_tool_speccific(char *const recv_text)
{
    return beamoff(recv_text);
}
</code>```

Tool type MODEL_CV code

```<code>int vsp_recv_tool_speccific(char *const recv_text)
{
    return vsp_set(recv_text);
}
</code>```

Refactored method

```<code>int vsp_recv(char *const recv_text)
{
    int rc  = 0;
    const int       type =  get_tool_type();
    // Common Code

    rc = vsp_recv_tool_speccific(recv_text);
}
</code>```

答:
the OPs question (and posted code) says that 3 places will need to be modified.

the function: get_tool_type()

the header file with the definitions of MODEL_CV, MODEL_CR, etc

the if-then-else list.

were it me, I would implement a table of function pointers, have get_tool_type() return an index into that table.  Then all the if/then/else code would become a single statement that invokes a function from the table.

Then any updates would be additions to the table, modifications to 'get_too_type(), and the additional functions likebeam_off()`

The loss of a tool type would not require any code change.

the addition of a tool type would require appending an entry to the table, mod to get_tool_type() to recognize the new tool, and the new function to process the new tool type.

Of course, this could result in code that is never executed.

Title: Configurable custom code

Body:
Our customer provided source code has portions of code that will be executed based on tool type. A sample code portion is given below. The function has common portions and tool specific(hardware platform) portions. The code is written in C and runs in VxWorks. Addition or deletion of new tool type has code modification. The customer wants addition or deletion new tool type with minimal code change and testing effort

int vsp_recv(char *const recv_text)
{
    int rc  = 0;
    const int       type =  get_tool_type();
    // Common Code

    if (MODEL_CR == type)
    {
        rc = beamoff(recv_text);
    }
    else
    {
        rc = vsp_set(recv_text);
    }

    return(rc);
}

Is it the right technique to separate the code to two methods as given below, keep them in separate source files and define separate make files to generate tool specific binary? Is there any better ways to do this?

Tool type MODEL_CR code

int vsp_recv_tool_speccific(char *const recv_text)
{
    return beamoff(recv_text);
}

Tool type MODEL_CV code

int vsp_recv_tool_speccific(char *const recv_text)
{
    return vsp_set(recv_text);
}

Refactored method

int vsp_recv(char *const recv_text)
{
    int rc  = 0;
    const int       type =  get_tool_type();
    // Common Code

    rc = vsp_recv_tool_speccific(recv_text);
}


问:
How can I show a message box on a web page before redirect to another web page in asp.net?
I have a page with two text-boxes and a button. After the user fills the text-boxes and clicks on the button, the data of text-boxes are written to the database. Then a message box should be shown to user expressing that the data was written in the database. When the user clicks the OK button on the message box, another asp.net page is shown. I have added the following code in button click and the page redirect without showing the message box.

```<code>    protected void ButtonSubmit_Click(object sender, EventArgs e)
{
    ...
    ...
    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "The data was written!" + "');", true);
    Response.Redirect("Login.aspx");
}
</code>```

How can I show a message box on a web page before redirect to another web page in asp.net?

答:
You'll want to do the redirect on the client side after the alert:</p>

```<code>protected void ButtonSubmit_Click(object sender, EventArgs e)
{
    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('The data was written!'); window.location.replace('Login.aspx');", true);
}
</code>```

Body:
I have a page with two text-boxes and a button. After the user fills the text-boxes and clicks on the button, the data of text-boxes are written to the database. Then a message box should be shown to user expressing that the data was written in the database. When the user clicks the OK button on the message box, another asp.net page is shown. I have added the following code in button click and the page redirect without showing the message box.

    protected void ButtonSubmit_Click(object sender, EventArgs e)
{
    ...
    ...
    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "The data was written!" + "');", true);
    Response.Redirect("Login.aspx");
}

How can I show a message box on a web page before redirect to another web page in asp.net?

Body:
You'll want to do the redirect on the client side after the alert:

protected void ButtonSubmit_Click(object sender, EventArgs e)
{
    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('The data was written!'); window.location.replace('Login.aspx');", true);
}


问:
Thread 1: signal SIGABRT AppDelegate.swift
I tried to compile my first iOS Hello app.

I have

ViewController.swift

```<code>//
//  ViewController.swift
//  My First Project

import UIKit

class ViewController: UIViewController {

    // Declare components
    @IBOutlet weak var inputLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    }

    @IBAction func submitBtn(_ sender: Any) {
        inputLabel.text = "Hello World"

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

I Kept

getting Build Succeeded

But after about 5 seconds, I got this

Console Error

```<code>         0x0000000103915f69 -[UIApplication workspaceDidEndTransaction:] + 188
    18  FrontBoardServices                  0x000000010770f723 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
    19  FrontBoardServices                  0x000000010770f59c -[FBSSerialQueue _performNext] + 189
    20  FrontBoardServices                  0x000000010770f925 -[FBSSerialQueue _performNextFromRunLoopSource] + 45
    21  CoreFoundation                      0x0000000105ff0311 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    22  CoreFoundation                      0x0000000105fd559c __CFRunLoopDoSources0 + 556
    23  CoreFoundation                      0x0000000105fd4a86 __CFRunLoopRun + 918
    24  CoreFoundation                      0x0000000105fd4494 CFRunLoopRunSpecific + 420
    25  UIKit                               0x00000001039147e6 -[UIApplication _run] + 434
    26  UIKit                               0x000000010391a964 UIApplicationMain + 159
    27  My First Project                    0x0000000102e6db3f main + 111
    28  libdyld.dylib                       0x0000000106f7868d start + 1
    29  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
</code>```

Try #1

Connection Inspector

I used to have this

I updated to this

Re-run and still happening ...

Try #2

Clean project

Re-run and still happening ...

答:
Make sure the storyboard elements are connected to the outlets in your code. Try to delete all the connections in the connections inspector and reconnect the elements

When you go to main.storyboard, on the right you have a panel, the most right one os the connections inspector. In there you have to delete al the connection by pressing the little 'x' in the connections.

It should look somewhat familiar like this, but different names
in this screenshot

delete all of them

also in your viewController.swift file, remove all the @IBOutlet lines.

Then connect your outlets again to your ViewController.swift file, which you did before

For just changing a label in code it finally should look like this final screenshot

mind the outlet on the right

I hope this will help you!

Body:
I tried to compile my first iOS Hello app.

I have

ViewController.swift

//
//  ViewController.swift
//  My First Project

import UIKit

class ViewController: UIViewController {

    // Declare components
    @IBOutlet weak var inputLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    }

    @IBAction func submitBtn(_ sender: Any) {
        inputLabel.text = "Hello World"

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

I Kept

getting Build Succeeded

But after about 5 seconds, I got this

Console Error

         0x0000000103915f69 -[UIApplication workspaceDidEndTransaction:] + 188
    18  FrontBoardServices                  0x000000010770f723 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
    19  FrontBoardServices                  0x000000010770f59c -[FBSSerialQueue _performNext] + 189
    20  FrontBoardServices                  0x000000010770f925 -[FBSSerialQueue _performNextFromRunLoopSource] + 45
    21  CoreFoundation                      0x0000000105ff0311 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    22  CoreFoundation                      0x0000000105fd559c __CFRunLoopDoSources0 + 556
    23  CoreFoundation                      0x0000000105fd4a86 __CFRunLoopRun + 918
    24  CoreFoundation                      0x0000000105fd4494 CFRunLoopRunSpecific + 420
    25  UIKit                               0x00000001039147e6 -[UIApplication _run] + 434
    26  UIKit                               0x000000010391a964 UIApplicationMain + 159
    27  My First Project                    0x0000000102e6db3f main + 111
    28  libdyld.dylib                       0x0000000106f7868d start + 1
    29  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

Try #1

Connection Inspector

I used to have this

I updated to this

Re-run and still happening ...

Try #2

Clean project

Re-run and still happening ...


问:
Adding an inherited entity to the DBContext
I've this entity

```<code>public class FooEntity
{
   public int ID {get; set;}
   public string Name {get; set;}
}
</code>```

I need to extend FooEntity with new fields like this

```<code>public class FooExtended : FooEntity
{
  public int Age {get; set;}
}
</code>```

but I don't want to persist the Age value in the database, it's used only temporarily in the model of the view.

When I try to add an instance of FooExtended to the DBContext

```<code>context.FooEntity.Add(xxx);
</code>```

I get the following exception

"Mapping and metadata information could not be found for EntityType
  'FooExtended'."

I tried adding the attribute [NotMapped] to the field Age but I get the same exception.

Is it possible to achieve what I'm trying to do with Entity Framework 6.1.3?

答:
```<code>context.FooEntity.Add(xxx as FooEntity);
</code>```

Body:
I've this entity

public class FooEntity
{
   public int ID {get; set;}
   public string Name {get; set;}
}

I need to extend FooEntity with new fields like this

public class FooExtended : FooEntity
{
  public int Age {get; set;}
}

but I don't want to persist the Age value in the database, it's used only temporarily in the model of the view.

When I try to add an instance of FooExtended to the DBContext

context.FooEntity.Add(xxx);

I get the following exception

"Mapping and metadata information could not be found for EntityType
  'FooExtended'."

I tried adding the attribute [NotMapped] to the field Age but I get the same exception.

Is it possible to achieve what I'm trying to do with Entity Framework 6.1.3?


问:
Converting data type nvarchar with decimal place
I have a Job Costing report that I am building for a client of mine. Their Chart of Accounts contains a decimal to the tenth place (i.e. 1001.55). I am running into an issue where no matter what I do I can't get the nvarchar to convert to either floating, int or numeric. If I take out the last Where clause where I try to filter by COA 5310 then it runs without issue. What glaring obvious issue am I overlooking? Any help would be appreciated!

```<code>--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), STR(COA.Number)
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And STR(COA.Number) = 5310
</code>```

--OR--

```<code>--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), CONVERT(varchar(10), COA.Number)
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And CONVERT(varchar(10), COA.Number) = 5310
</code>```

--OR--

```<code>--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), CONVERT(DECIMAL(18,2), COA.Number)
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And CONVERT(DECIMAL(18,2), COA.Number) = 5310
</code>```

--OR--

```<code>--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), CAST([COA.Number] AS NVARCHAR(25))
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And CAST([COA.Number] AS NVARCHAR(25)) = 5310
</code>```

答:
Your problem likely happens because some of the rows in COA.Number are not numeric. You can verify this with the following query:

```<code>select * from COA where ISNUMERIC(COA.Number) <> 1
</code>```

Now you can either fix those rows, or you can filter them out while creating your new table with the opposite:

```<code>WHERE ISNUMERIC(COA.Number) = 1
</code>```

Body:
I have a Job Costing report that I am building for a client of mine. Their Chart of Accounts contains a decimal to the tenth place (i.e. 1001.55). I am running into an issue where no matter what I do I can't get the nvarchar to convert to either floating, int or numeric. If I take out the last Where clause where I try to filter by COA 5310 then it runs without issue. What glaring obvious issue am I overlooking? Any help would be appreciated!

--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), STR(COA.Number)
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And STR(COA.Number) = 5310

--OR--

--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), CONVERT(varchar(10), COA.Number)
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And CONVERT(varchar(10), COA.Number) = 5310

--OR--

--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), CONVERT(DECIMAL(18,2), COA.Number)
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And CONVERT(DECIMAL(18,2), COA.Number) = 5310

--OR--

--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), CAST([COA.Number] AS NVARCHAR(25))
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And CAST([COA.Number] AS NVARCHAR(25)) = 5310

Body:
Your problem likely happens because some of the rows in COA.Number are not numeric. You can verify this with the following query:

select * from COA where ISNUMERIC(COA.Number) <> 1

Now you can either fix those rows, or you can filter them out while creating your new table with the opposite:

WHERE ISNUMERIC(COA.Number) = 1


问:
(Beginner) SQLite Query won't enter if-loop with MoveToNext
I have been on StackOverflow all morning trying to teach myself how to do a query into my uploaded SQLite database on an Android Application. I have tried raw and direct queries, but neither have worked so far. Here is the code:

```<code>public Product getProduct(int id) {
    db = this.getReadableDatabase();

//        new String[] { COLUMN_ID, COLUMN_PRODUCT_NAME, COLUMN_SIZE, COLUMN_HP,
//        COLUMN_CATEGORY, COLUMN_POWER_TYPE, COLUMN_EXP_PROOF, COLUMN_RPM,
//                COLUMN_PSI, COLUMN_GPM, COLUMN_PRICE},

//        Cursor cursor = db.query(
//                TABLE_NAME,
//                null,
//                COLUMN_ID + " = ?",
//                new String[] { Integer.toString(id)},
//                null, null, null, null);

    String strquery = "SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + "=" + id;
    Cursor cursor = db.rawQuery(strquery, null);

    Product product = new Product();

    if (cursor.moveToFirst()) {
        product.setID(cursor.getInt(0));
        product.setName(cursor.getString(1));
        product.setSize(cursor.getDouble(2));
        product.setHp(cursor.getDouble(3));
        product.setCategory(cursor.getString(4));
        product.setPowerType(cursor.getString(5));
        product.setExplosionProof(cursor.getInt(6));
        product.setRPM(cursor.getInt(7));
        product.setBypassPSI(cursor.getInt(8));
        product.setGPM(cursor.getInt(9));
        product.setPrice(cursor.getDouble(10));
        cursor.close();
    }

    db.close();
    return product;
}
</code>```

The commented out fields are previous queries I tried, neither working.

And here are my constants:

```<code>private static final String TABLE_NAME = "Products";
private static final String COLUMN_ID = "'_id'";
</code>```

https://i.stack.imgur.com/5YiZr.png
^ that is a link to a screenshot of the database I am using.

The issue when I debug it is it never enters the if loop, and mCount is always -1. I have done a lot of research, but I am still being frustrated with this. Thank you

[EDIT}

Here is my code to the database

```<code>public class SQLiteHelper extends SQLiteOpenHelper {

private SQLiteHelper sInstance;

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ProductList.db";
private SQLiteDatabase db;
private final Context myContext;
private String databasePath = "";

public SQLiteHelper(Context context){
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.myContext = context;
    databasePath = context.getDatabasePath(DATABASE_NAME).getPath();
}

private static final String TABLE_NAME = "Products";
private static final String COLUMN_ID = "'_id'";
private static final String COLUMN_PRODUCT_NAME = "'Name'";
private static final String COLUMN_SIZE = "'Size'";
private static final String COLUMN_HP = "'HP'";
private static final String COLUMN_CATEGORY = "'Category'";
private static final String COLUMN_POWER_TYPE = "'PowerType'";
private static final String COLUMN_EXP_PROOF = "'ExpProof'";
private static final String COLUMN_RPM = "'RPM'";
private static final String COLUMN_PSI = "'PSI'";
private static final String COLUMN_GPM = "'GPM'";
private static final String COLUMN_PRICE = "'Price'";

public void createDataBase() throws IOException {
    boolean dbExists = checkDataBase();
    if (dbExists) {
    } else {
        this.getReadableDatabase();
        try {
            copyDataBase();
        } catch (IOException e) {
            throw new Error("Error making database");
        }
    }
}

private boolean checkDataBase() {
    SQLiteDatabase check = null;
    try {
        String path = databasePath + DATABASE_NAME;
        check = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
    } catch (SQLiteException e) {
        // database doesn't exist
    }

    if (check != null) {
        check.close();
    }

    return check != null;
}

private void copyDataBase() throws IOException{
    InputStream myInput = myContext.getAssets().open(DATABASE_NAME);

    String outFileName = databasePath + DATABASE_NAME;

    OutputStream myOutput = new FileOutputStream(outFileName);

    byte[] buffer = new byte[1024];
    int length;
    while ((length=myInput.read(buffer))>0) {
        myOutput.write(buffer, 0, length);
    }

    // close streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
}

public void openDataBase() throws SQLException {

    //Open the database
    String myPath = databasePath;
    db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}

@Override
public synchronized void close() {

    if(db != null)
        db.close();
    super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {
</code>```

}

答:
Please review this part of your code.

```<code>public void openDataBase() throws SQLException {
    //Open the database
    String myPath = databasePath;
    db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
</code>```

Here you're just using databasePath and I see that you've set this to the value you've got from context.getDabasePath in the constructor but looking at the other methods you have they look like they're creating a new db path instead:

```<code>private void copyDataBase() throws IOException{
    InputStream myInput = myContext.getAssets().open(DATABASE_NAME);

    String outFileName = databasePath + DATABASE_NAME;

    OutputStream myOutput = new FileOutputStream(outFileName);

    byte[] buffer = new byte[1024];
    int length;
    while ((length=myInput.read(buffer))>0) {
        myOutput.write(buffer, 0, length);
    }

    // close streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
}
</code>```

Not sure if this is because of copy/paste from your source code but this looks like what is causing the missing data that you have.

Body:
I have been on StackOverflow all morning trying to teach myself how to do a query into my uploaded SQLite database on an Android Application. I have tried raw and direct queries, but neither have worked so far. Here is the code:

public Product getProduct(int id) {
    db = this.getReadableDatabase();

//        new String[] { COLUMN_ID, COLUMN_PRODUCT_NAME, COLUMN_SIZE, COLUMN_HP,
//        COLUMN_CATEGORY, COLUMN_POWER_TYPE, COLUMN_EXP_PROOF, COLUMN_RPM,
//                COLUMN_PSI, COLUMN_GPM, COLUMN_PRICE},

//        Cursor cursor = db.query(
//                TABLE_NAME,
//                null,
//                COLUMN_ID + " = ?",
//                new String[] { Integer.toString(id)},
//                null, null, null, null);

    String strquery = "SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + "=" + id;
    Cursor cursor = db.rawQuery(strquery, null);

    Product product = new Product();

    if (cursor.moveToFirst()) {
        product.setID(cursor.getInt(0));
        product.setName(cursor.getString(1));
        product.setSize(cursor.getDouble(2));
        product.setHp(cursor.getDouble(3));
        product.setCategory(cursor.getString(4));
        product.setPowerType(cursor.getString(5));
        product.setExplosionProof(cursor.getInt(6));
        product.setRPM(cursor.getInt(7));
        product.setBypassPSI(cursor.getInt(8));
        product.setGPM(cursor.getInt(9));
        product.setPrice(cursor.getDouble(10));
        cursor.close();
    }

    db.close();
    return product;
}

The commented out fields are previous queries I tried, neither working.

And here are my constants:

private static final String TABLE_NAME = "Products";
private static final String COLUMN_ID = "'_id'";

https://i.stack.imgur.com/5YiZr.png
^ that is a link to a screenshot of the database I am using.

The issue when I debug it is it never enters the if loop, and mCount is always -1. I have done a lot of research, but I am still being frustrated with this. Thank you

[EDIT}

Here is my code to the database

public class SQLiteHelper extends SQLiteOpenHelper {

private SQLiteHelper sInstance;

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ProductList.db";
private SQLiteDatabase db;
private final Context myContext;
private String databasePath = "";

public SQLiteHelper(Context context){
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.myContext = context;
    databasePath = context.getDatabasePath(DATABASE_NAME).getPath();
}

private static final String TABLE_NAME = "Products";
private static final String COLUMN_ID = "'_id'";
private static final String COLUMN_PRODUCT_NAME = "'Name'";
private static final String COLUMN_SIZE = "'Size'";
private static final String COLUMN_HP = "'HP'";
private static final String COLUMN_CATEGORY = "'Category'";
private static final String COLUMN_POWER_TYPE = "'PowerType'";
private static final String COLUMN_EXP_PROOF = "'ExpProof'";
private static final String COLUMN_RPM = "'RPM'";
private static final String COLUMN_PSI = "'PSI'";
private static final String COLUMN_GPM = "'GPM'";
private static final String COLUMN_PRICE = "'Price'";

public void createDataBase() throws IOException {
    boolean dbExists = checkDataBase();
    if (dbExists) {
    } else {
        this.getReadableDatabase();
        try {
            copyDataBase();
        } catch (IOException e) {
            throw new Error("Error making database");
        }
    }
}

private boolean checkDataBase() {
    SQLiteDatabase check = null;
    try {
        String path = databasePath + DATABASE_NAME;
        check = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
    } catch (SQLiteException e) {
        // database doesn't exist
    }

    if (check != null) {
        check.close();
    }

    return check != null;
}

private void copyDataBase() throws IOException{
    InputStream myInput = myContext.getAssets().open(DATABASE_NAME);

    String outFileName = databasePath + DATABASE_NAME;

    OutputStream myOutput = new FileOutputStream(outFileName);

    byte[] buffer = new byte[1024];
    int length;
    while ((length=myInput.read(buffer))>0) {
        myOutput.write(buffer, 0, length);
    }

    // close streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
}

public void openDataBase() throws SQLException {

    //Open the database
    String myPath = databasePath;
    db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}

@Override
public synchronized void close() {

    if(db != null)
        db.close();
    super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {

}

Body:
Please review this part of your code.

public void openDataBase() throws SQLException {
    //Open the database
    String myPath = databasePath;
    db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}

Here you're just using databasePath and I see that you've set this to the value you've got from context.getDabasePath in the constructor but looking at the other methods you have they look like they're creating a new db path instead:

private void copyDataBase() throws IOException{
    InputStream myInput = myContext.getAssets().open(DATABASE_NAME);

    String outFileName = databasePath + DATABASE_NAME;

    OutputStream myOutput = new FileOutputStream(outFileName);

    byte[] buffer = new byte[1024];
    int length;
    while ((length=myInput.read(buffer))>0) {
        myOutput.write(buffer, 0, length);
    }

    // close streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
}

Not sure if this is because of copy/paste from your source code but this looks like what is causing the missing data that you have.


问:
Does a foreign key reduce redundancy if all the columns are referenced?
I've read that one of the benefits of normalization is to reduce redundancy in the DB. But I'm wondering, if you end up referencing all the columns in the target table?

For example, if I have a Video table that references a Genre table, the Genre table might very likely have a single column with a dozen fairly static values like 'Horror' 'Sci-Fi' 'Romance' etc.

In a case like this, does it save any space to separate the two, or is the only benefit making it so you can update all referencing rows from one place?

答:
I would use surrogate keys (Autonumber, Identity, etc) and use that for the foreign key join instead of the actual value.

The idea is more about data quality than reducing space.

In most db's an INT will be smaller than Varchar2 (20)


问:
git clone by https does not work on other machine
On my local machine(Linux), I clone the repo with

```<code>git clone https://rcffc@dev.kom.e-technik.tu-darmstadt.de/gitlab/WaelKH/KM_2_2017_Feature_Selection.git
</code>```

and it asks me for my password. After typing the password I can clone the repository, fine.

On the server(Windows), the command leads to

```<code>remote: Not Found
fatal: repository 'git clone https://rcffc@dev.kom.e-technik.tu-darmstadt.de/gitlab/WaelKH/KM_2_2017_Feature_Selection.git/' not found
</code>```

Please help me.

UPDATE: It is a private repository.
UPDATE 2&3: Made question clearer.
UPDATE 4: Included OS info
UPDATE 5: Included actual commands.

答:
The command to clone a repository stored in http://www.example.com/foo/bar.git is</p>

```<code>git clone https://www.example.com/foo/bar.git
</code>```

Body:
On my local machine(Linux), I clone the repo with

git clone https://rcffc@dev.kom.e-technik.tu-darmstadt.de/gitlab/WaelKH/KM_2_2017_Feature_Selection.git

and it asks me for my password. After typing the password I can clone the repository, fine.

On the server(Windows), the command leads to

remote: Not Found
fatal: repository 'git clone https://rcffc@dev.kom.e-technik.tu-darmstadt.de/gitlab/WaelKH/KM_2_2017_Feature_Selection.git/' not found

Please help me.

UPDATE: It is a private repository.
UPDATE 2&3: Made question clearer.
UPDATE 4: Included OS info
UPDATE 5: Included actual commands.

Body:
The command to clone a repository stored in http://www.example.com/foo/bar.git is

git clone https://www.example.com/foo/bar.git