问:
Treating numerical variables as text
I was not sure how to title this question, so I'll go straight to the code for you to see what I mean. Really new into this, so bear with me!

I have this code:

```<code>1   #include <cs50.h>
2   #include <stdio.h>
3   #include <string.h>
4
5   int main(int argc, string argv[])
6   {
7
8   if (argc!=2)
9   {
10     printf("error!! Usage: ./caesar k\n");
11     return 1;
12   }
13
14   printf("Plaintext: ");
15   string text=get_string();
16
17   char k=argv[1][0];
18   int n=strlen(text);
19
20
21   for (int i=0; i<n; i++)
22   {
23     if(text[i]>='a' && text[i]<='z')
24     {
25         printf("Cyphertext: %c\n", text[i]+k);
26     }
27   }
28   }
</code>```

What's its purpose?
Well, given a text, it adds k to every character. Which means that, for abc, and k=1, the output would be bcd; for abc and k=3, output would be def.

Now, it is imperative that k is given as a command line argument.

What do I want to do?
Just take k (which is a number), add it to every character of the input string text, and voilà.
Since every letter is a number in ASCII, adding a number can change the character, so... it should work. [I am still trying to figure out how ASCII works, and when do char show up like charcters and not numbers... but anyway].

What is going on?
First, I am having trouble declaring k as an int or char. In line 17, -and although k is a number(!)- the IDE forces me to declare a string or char*: if I declare k as int I receive an error; if I declare char I receive an error too, unless I declare it not only as k=argv[1] but as k=argv[1][0], as shown in the code above.

Second, executing the code above, this is the input/output (the name of the program is caesar):

```<code>$./caesar
error!! Usage: ./caesar k

$./caesar 1
Plaintext: a
Cyphertext: (nothing...)
</code>```

Third, given the error above, I changed the code in line 25 from this:

```<code>printf("Cyphertext: %c\n", text[i]+k);
</code>```

to this:

```<code>printf("Cyphertext: %s\n", text[i]+k);
</code>```

which returned this error message:

```<code>caesar.c:25:38: error: format specifies type 'char *' but the argument has
type 'int' [-Werror,-Wformat]
        printf("Cyphertext: %s", text[i]+k);
                            ~~   ^~~~~~~~~
                            %d`
</code>```

error message I do not understand, given that neither text nor k are int.

Anyway, changing %c to %s did not work, so I tried with %i instead:

```<code>printf("Cyphertext: %i\n", text[i]+k)
</code>```

which at least returned something:

```<code>$./caesar 1
Plaintext: a
Cyphertext: 146

$./caesar 5
Plaintext: a
Cyphertext: 150
</code>```

So, basically, it is adding k to 150 -which is 'û' in ASCII, so...(?).

And, finally, apart from the fact the program returns a number I do not understand, I thought I could make it show up like letters/non-numerical characters adding this:

```<code>printf("Cyphertext: %i\n", (char)text[i]+k);
</code>```

but it actually does not, the program returns exactly the same last output shown above.

So well, this is a much longer question than I expected, but I hope someone in here has the patence and proficency to answer it.

Thank you very much!

答:
The general purpose solution is

```<code>int k = atoi(argv[1]);
</code>```

atoi takes a string and converts it to a number. The subtract solution above only deals with single digits, this will allow k > 9

Title: Treating numerical variables as text

Body:
I was not sure how to title this question, so I'll go straight to the code for you to see what I mean. Really new into this, so bear with me!

I have this code:

1   #include <cs50.h>
2   #include <stdio.h>
3   #include <string.h>
4
5   int main(int argc, string argv[])
6   {
7
8   if (argc!=2)
9   {
10     printf("error!! Usage: ./caesar k\n");
11     return 1;
12   }
13
14   printf("Plaintext: ");
15   string text=get_string();
16
17   char k=argv[1][0];
18   int n=strlen(text);
19
20
21   for (int i=0; i<n; i++)
22   {
23     if(text[i]>='a' && text[i]<='z')
24     {
25         printf("Cyphertext: %c\n", text[i]+k);
26     }
27   }
28   }

What's its purpose?
Well, given a text, it adds k to every character. Which means that, for abc, and k=1, the output would be bcd; for abc and k=3, output would be def.

Now, it is imperative that k is given as a command line argument.

What do I want to do?
Just take k (which is a number), add it to every character of the input string text, and voilà.
Since every letter is a number in ASCII, adding a number can change the character, so... it should work. [I am still trying to figure out how ASCII works, and when do char show up like charcters and not numbers... but anyway].

What is going on?
First, I am having trouble declaring k as an int or char. In line 17, -and although k is a number(!)- the IDE forces me to declare a string or char*: if I declare k as int I receive an error; if I declare char I receive an error too, unless I declare it not only as k=argv[1] but as k=argv[1][0], as shown in the code above.

Second, executing the code above, this is the input/output (the name of the program is caesar):

$./caesar
error!! Usage: ./caesar k

$./caesar 1
Plaintext: a
Cyphertext: (nothing...)

Third, given the error above, I changed the code in line 25 from this:

printf("Cyphertext: %c\n", text[i]+k);

to this:

printf("Cyphertext: %s\n", text[i]+k);

which returned this error message:

caesar.c:25:38: error: format specifies type 'char *' but the argument has
type 'int' [-Werror,-Wformat]
        printf("Cyphertext: %s", text[i]+k);
                            ~~   ^~~~~~~~~
                            %d`

error message I do not understand, given that neither text nor k are int.

Anyway, changing %c to %s did not work, so I tried with %i instead:

printf("Cyphertext: %i\n", text[i]+k)

which at least returned something:

$./caesar 1
Plaintext: a
Cyphertext: 146

$./caesar 5
Plaintext: a
Cyphertext: 150

So, basically, it is adding k to 150 -which is 'û' in ASCII, so...(?).

And, finally, apart from the fact the program returns a number I do not understand, I thought I could make it show up like letters/non-numerical characters adding this:

printf("Cyphertext: %i\n", (char)text[i]+k);

but it actually does not, the program returns exactly the same last output shown above.

So well, this is a much longer question than I expected, but I hope someone in here has the patence and proficency to answer it.

Thank you very much!

Body:
The general purpose solution is

int k = atoi(argv[1]);

atoi takes a string and converts it to a number. The subtract solution above only deals with single digits, this will allow k > 9


来源: stackexchange

问:
SSL Issue - Jenkins slave connection issue with TFS

Upgraded the Jenkins.

Created a slave.

Installed latest JDK on Slave machine and launched the slave.

when tagged a job with slave and ran it, getting above error ..

did search on google and as per search added public cert of my target TFS to the java keystore which is in C:\Program Files (x86)\Java\jre1.8.0_131\lib\security\cacerts.

it worked for 2 jobs, for some purpose i un tagged the job and ran on master , again i tagged it back to slave and ran it.. again the issue came back.

tried to add the cert again, but its prompted cert is already in keystore ..
7 did uninstall and re install of slave and changes JAVA version .. no luck..
rest of the log below5)

Building remotely on

  node1

  in workspace C:\Builds\Jenkins\workspace\Foot_Driver
  Querying for remote changeset at '$/AEXX/' as of 'D2017-06-23T15:26:13Z'...
  FATAL: com.microsoft.tfs.core.exceptions.TECoreException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targe

答:
By adding all the certs in the chain to the cacerts, issue got resolved.

Get all the list of certs in the chain by using (replace your domain with google.com)
openssl s_client -host google.com -port 443 -prexit -showcerts

copy each certs in a seprate .pem file eg - VS_cert1.pem, VS_cert2.pem

import all the certs to the java cacerts

keytool -import -alias VS1 -file "C:\Users\xxxx\Desktop\Temp\VS_cert1.pem" -keystore "C:\Program Files (x86)\Java\jre1.8.0_131\lib\security\cacerts"

keytool -import -alias VS2 -file "C:\Users\xxxx\Desktop\Temp\VS_cert2.pem" -keystore "C:\Program Files (x86)\Java\jre1.8.0_131\lib\security\cacerts"

Bounce the service.

ContentLicense: CC BY-SA 3.0


问:
How to test React PropTypes through Jest?
I'm writing Jest tests for my React code and hoping to make use of/test the PropType checks. I am quite new to the Javascript universe. I'm using npm to install react-0.11.2 and have a simple:

```<code>var React = require('react/addons');
</code>```

In my tests. My test looks quite similar to the jest/react tutorial example with code like:

var eventCell = TestUtils.renderIntoDocument(
  <EventCell
    slot={slot}
    weekId={weekId}
    day={day}
    eventTypes={eventTypes}
    />
);

var time = TestUtils.findRenderedDOMComponentWithClass(eventCell, 'time');
expect(time.getDOMNode().textContent).toEqual('19:00 ');
```

However it seems that the PropType checks in the EventCell component aren't being triggered. I understand that the checks are only run in Development mode but then I also thought that getting react through npm gave you the development version. The checks trigger in my browser when I build the component with watchify.

What am I missing?

答:
Mocking console.error is not suitable for use in unit tests! @AndrewWillems linked to another SO question in a comment above that describes the problems with this approach.

Check out this issue on facebook/prop-types for discussion about the ability for that library to throw instead of logging propType errors (at the time of writing, it's not supported).

I have published a helper library to provide that behaviour in the mean time, check-prop-types. You can use it like this:

```<code>import PropTypes from 'prop-types';
import checkPropTypes from 'check-prop-types';

const HelloComponent = ({ name }) => (
  <h1>Hi, {name}</h1>
);

HelloComponent.propTypes = {
  name: PropTypes.string.isRequired,
};

let result = checkPropTypes(HelloComponent.propTypes, { name: 'Julia' }, 'prop', HelloComponent.name);
assert(`result` === null);

result = checkPropTypes(HelloComponent.propTypes, { name: 123 }, 'prop', HelloComponent.name);
assert(`result` === 'Failed prop type: Invalid prop `name` of type `number` supplied to `HelloComponent`, expected `string`.');
</code>```

Body:
I'm writing Jest tests for my React code and hoping to make use of/test the PropType checks. I am quite new to the Javascript universe. I'm using npm to install react-0.11.2 and have a simple:

var React = require('react/addons');

In my tests. My test looks quite similar to the jest/react tutorial example with code like:

var eventCell = TestUtils.renderIntoDocument(
  <EventCell
    slot={slot}
    weekId={weekId}
    day={day}
    eventTypes={eventTypes}
    />
);

var time = TestUtils.findRenderedDOMComponentWithClass(eventCell, 'time');
expect(time.getDOMNode().textContent).toEqual('19:00 ');

However it seems that the PropType checks in the EventCell component aren't being triggered. I understand that the checks are only run in Development mode but then I also thought that getting react through npm gave you the development version. The checks trigger in my browser when I build the component with watchify.

What am I missing?

Body:
Mocking console.error is not suitable for use in unit tests! @AndrewWillems linked to another SO question in a comment above that describes the problems with this approach.

Check out this issue on facebook/prop-types for discussion about the ability for that library to throw instead of logging propType errors (at the time of writing, it's not supported).

I have published a helper library to provide that behaviour in the mean time, check-prop-types. You can use it like this:

import PropTypes from 'prop-types';
import checkPropTypes from 'check-prop-types';

const HelloComponent = ({ name }) => (
  <h1>Hi, {name}</h1>
);

HelloComponent.propTypes = {
  name: PropTypes.string.isRequired,
};

let result = checkPropTypes(HelloComponent.propTypes, { name: 'Julia' }, 'prop', HelloComponent.name);
assert(`result` === null);

result = checkPropTypes(HelloComponent.propTypes, { name: 123 }, 'prop', HelloComponent.name);
assert(`result` === 'Failed prop type: Invalid prop `name` of type `number` supplied to `HelloComponent`, expected `string`.');


问:
Create a has_many through record
I have a user a movie and a watchlist model in my Ruby project.

movie.rb:

```<code>class Movie < ApplicationRecord
  has_many :watchlists
  has_many :users, through: :watchlists
end
</code>```

user.rb

```<code>class User < ActiveRecord::Base
  has_many :watchlists
  has_many :movies, through: :watchlists
  # Include default devise modules.
  devise :database_authenticatable,
         :registerable,
         :recoverable,
         :rememberable,
         :trackable,
         :validatable,
         # :confirmable,
         :omniauthable
  include DeviseTokenAuth::Concerns::User
end
</code>```

watchlist.rb

```<code>class Watchlist < ApplicationRecord
  belongs_to :movie
  belongs_to :user
end
</code>```

And this is the MoviesController:

```<code>class MoviesController < ApplicationController

  before_action :set_movie, only: [:show, :update, :destroy]

  # POST /movies
  def create
    if Movie.exists?(title: movie_params[:title])
      render json: { body: 'Movie already exists', status: 400 }
    else

      @movie = Movie.create!(movie_params)
      render json: { body: @movie, status: 200 }
    end

  end

  def movie_params
    # whitelist params
    params.permit(:title, :created_by, :id)
  end

end
</code>```

Currently I only store the movie in the movie table. How do I create a record in the watchlist that has a movie id and a user id?

答:
If you <s>are using Devise</s> have current_user, just do

```<code>@movie = current_user.movies.create!(movie_params)
</code>```

instead of

```<code>@movie = Movie.create!(movie_params)
</code>```

If you <s>are not using Devise</s> don't have current_user, fetch the logged in user, say @user and do

```<code>@movie = @user.movies.create!(movie_params)
</code>```

Title: Create a has_many through record

Body:
I have a user a movie and a watchlist model in my Ruby project.

movie.rb:

class Movie < ApplicationRecord
  has_many :watchlists
  has_many :users, through: :watchlists
end

user.rb

class User < ActiveRecord::Base
  has_many :watchlists
  has_many :movies, through: :watchlists
  # Include default devise modules.
  devise :database_authenticatable,
         :registerable,
         :recoverable,
         :rememberable,
         :trackable,
         :validatable,
         # :confirmable,
         :omniauthable
  include DeviseTokenAuth::Concerns::User
end

watchlist.rb

class Watchlist < ApplicationRecord
  belongs_to :movie
  belongs_to :user
end

And this is the MoviesController:

class MoviesController < ApplicationController

  before_action :set_movie, only: [:show, :update, :destroy]

  # POST /movies
  def create
    if Movie.exists?(title: movie_params[:title])
      render json: { body: 'Movie already exists', status: 400 }
    else

      @movie = Movie.create!(movie_params)
      render json: { body: @movie, status: 200 }
    end

  end

  def movie_params
    # whitelist params
    params.permit(:title, :created_by, :id)
  end

end

Currently I only store the movie in the movie table. How do I create a record in the watchlist that has a movie id and a user id?

Body:
If you <s>are using Devise</s> have current_user, just do

@movie = current_user.movies.create!(movie_params)

instead of

@movie = Movie.create!(movie_params)

If you <s>are not using Devise</s> don't have current_user, fetch the logged in user, say @user and do

@movie = @user.movies.create!(movie_params)


问:
How can I partially read a huge CSV file?
I have a very big csv file so that I can not read them all into the memory. I only want to read and process a few lines in it. So I am seeking a function in Pandas which could handle this task, which the basic python can handle this well:

```<code>with open('abc.csv') as f:
    line = f.readline()
    # pass until it reaches a particular line number....
</code>```

However, if I do this in pandas, I always read the first line:

```<code>datainput1 = pd.read_csv('matrix.txt',sep=',', header = None, nrows = 1 )
datainput2 = pd.read_csv('matrix.txt',sep=',', header = None, nrows = 1 )
</code>```

I am looking for some easier way to handle this task in pandas. For example, if I want to read rows from 1000 to 2000. How can I do this quickly?

I want to use pandas because I want to read data into the dataframe.

答:
In addition to EdChums answer I find the nrows argument useful which simply defines the number of rows you want to import with pandas' read_csv().

Thereby you don't get an iterator but rather can just import a part of the whole file of size nrows. It works with skiprows too.

```<code>df = pd.read_csv('matrix.txt', sep=',', header=None, skiprows=1000, nrows=1000)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a very big csv file so that I can not read them all into the memory. I only want to read and process a few lines in it. So I am seeking a function in Pandas which could handle this task, which the basic python can handle this well:

with open('abc.csv') as f:
    line = f.readline()
    # pass until it reaches a particular line number....

However, if I do this in pandas, I always read the first line:

datainput1 = pd.read_csv('matrix.txt',sep=',', header = None, nrows = 1 )
datainput2 = pd.read_csv('matrix.txt',sep=',', header = None, nrows = 1 )

I am looking for some easier way to handle this task in pandas. For example, if I want to read rows from 1000 to 2000. How can I do this quickly?

I want to use pandas because I want to read data into the dataframe.

Body:
In addition to EdChums answer I find the nrows argument useful which simply defines the number of rows you want to import with pandas' read_csv().

Thereby you don't get an iterator but rather can just import a part of the whole file of size nrows. It works with skiprows too.

df = pd.read_csv('matrix.txt', sep=',', header=None, skiprows=1000, nrows=1000)


问:
Invisible google Recaptcha and ajax form
I have an ajax form:

```<code>  <form id="my_form">
    <input type="text" id="field1" />
    <input type="submit" value="submit" />
  </form>
</code>```

And js code:

```<code>document.getElementById("my_form").onsubmit = function(e) {
  e.preventDefault();

  var xhr = new XMLHttpRequest();
  //.............. send request to a server
</code>```

In the documentation it assumes that a form is a normal form, not ajax. How exactly should I integrate invisible reCaptcha to my ajax forms? For example:

```<code>  <form id="my_form">
    <input type="text" id="field1" />
    <div class="g-recaptcha" data-sitekey="12345" data-callback="????></div>
    <input type="submit" value="submit" />
  </form>
</code>```

And, in particular, what should I specify for "data-callback" handler? Again, in the documentation it  data-callback submits a form, but a normal form, whereas mine is ajax. Do I need "data-callback" at all? Shouldn't I instead call recaptcha inside my handler? How?

There're "render", "getResponse" and "execute". Which one should I use? It's not clear from the documentation.

答:
You can easily validate google recaptcha's using jquery

```<code><?php
$remoteip = $_SERVER['REMOTE_ADDR'];
?>
<script type="text/javascript">
    function reloadRecaptcha() {
        var publicKey = "your_public_key";
        var div = "recap";
        Recaptcha.create(publicKey,div,{theme: "white"});
        return false;
    }
    function validate() {

        var challenge = Recaptcha.get_challenge();
        var response = Recaptcha.get_response();
        var remoteip = "<?php echo $remoteip; ?>";
        $.ajax({
          type: "POST",
          url: "validateRecaptcha.php",
          async: false,
          data: {
            remoteip: remoteip,
            challenge: challenge,
            response: response
          },
          success: function(resp) {
                if(resp == "true") {
                    document.getElementById("message").innerHTML = "Perfect!";
                }
                else {
                    document.getElementById("message").innerHTML = "Incorrect Recaptcha! Please try again!";
                    reloadRecaptcha();
                }
          }
        });
        return false;
    }
</code>```

Body:
I have an ajax form:

  <form id="my_form">
    <input type="text" id="field1" />
    <input type="submit" value="submit" />
  </form>

And js code:

document.getElementById("my_form").onsubmit = function(e) {
  e.preventDefault();

  var xhr = new XMLHttpRequest();
  //.............. send request to a server

In the documentation it assumes that a form is a normal form, not ajax. How exactly should I integrate invisible reCaptcha to my ajax forms? For example:

  <form id="my_form">
    <input type="text" id="field1" />

    <input type="submit" value="submit" />
  </form>

And, in particular, what should I specify for "data-callback" handler? Again, in the documentation it  data-callback submits a form, but a normal form, whereas mine is ajax. Do I need "data-callback" at all? Shouldn't I instead call recaptcha inside my handler? How?

There're "render", "getResponse" and "execute". Which one should I use? It's not clear from the documentation.

Body:
You can easily validate google recaptcha's using jquery

<?php
$remoteip = $_SERVER['REMOTE_ADDR'];
?>
<script type="text/javascript">
    function reloadRecaptcha() {
        var publicKey = "your_public_key";
        var div = "recap";
        Recaptcha.create(publicKey,div,{theme: "white"});
        return false;
    }
    function validate() {

        var challenge = Recaptcha.get_challenge();
        var response = Recaptcha.get_response();
        var remoteip = "<?php echo $remoteip; ?>";
        $.ajax({
          type: "POST",
          url: "validateRecaptcha.php",
          async: false,
          data: {
            remoteip: remoteip,
            challenge: challenge,
            response: response
          },
          success: function(resp) {
                if(resp == "true") {
                    document.getElementById("message").innerHTML = "Perfect!";
                }
                else {
                    document.getElementById("message").innerHTML = "Incorrect Recaptcha! Please try again!";
                    reloadRecaptcha();
                }
          }
        });
        return false;
    }


问:
How do I remove the margin when drawing a rectangle inside a panel in a Windows Form?
Firstly, for context, I'm a beginner in C# and I'm playing around with forms.

I have attempted to draw a rectangle to a panel ("myPanel") on a form ("Form1") but there is a margin or some sort of padding which I cannot remove.

I have set the "padding" and "margin" properties of "myPanel" to 0 with no success.

The code is:

```<code>namespace Forms___Playing_with_Graphics
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void myPanel_Paint(object sender, PaintEventArgs e)
        {

            // rectangle, slightly smaller than size of panel
            int topLeftx = myPanel.Location.X;
            int topLefty = myPanel.Location.Y;
            int width = myPanel.Size.Width - 5;
            int height = myPanel.Size.Height - 5;

            Graphics g = e.Graphics;

            Rectangle r = new Rectangle(topLeftx, topLefty, width, height);
            Pen p = new Pen(Color.Black, 5F);

            g.DrawRectangle(p, r);
        }
    }
}
</code>```

A screenshot of the result:

How do I remove this padding between the rectangle and the inside left and top edges?  My naive expectation was for the rectangle to start in the very top-left corner.

Any help would be greatly appreciated.

答:
Top left corner has coordinates x = 0, y = 0. But you should also keep in mind width of rectangle border. If you want rectangle border to fit exactly to the panel which contains it, then you should step inside half of border width:

```<code>private void myPanel_Paint(object sender, PaintEventArgs e)
{
    float borderWidth = 5f;
    float topLeftx = borderWidth / 2;
    float topLefty = borderWidth / 2;
    float width = panel2.ClientSize.Width - borderWidth;
    float height = panel2.ClientSize.Height - borderWidth;

    Graphics g = e.Graphics;
    Pen pen = new Pen(Color.Black, borderWidth);
    g.DrawRectangle(pen, topLeftx, topLefty, width, height);
}
</code>```

Result:

Body:
Firstly, for context, I'm a beginner in C# and I'm playing around with forms.

I have attempted to draw a rectangle to a panel ("myPanel") on a form ("Form1") but there is a margin or some sort of padding which I cannot remove.

I have set the "padding" and "margin" properties of "myPanel" to 0 with no success.

The code is:

namespace Forms___Playing_with_Graphics
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void myPanel_Paint(object sender, PaintEventArgs e)
        {

            // rectangle, slightly smaller than size of panel
            int topLeftx = myPanel.Location.X;
            int topLefty = myPanel.Location.Y;
            int width = myPanel.Size.Width - 5;
            int height = myPanel.Size.Height - 5;

            Graphics g = e.Graphics;

            Rectangle r = new Rectangle(topLeftx, topLefty, width, height);
            Pen p = new Pen(Color.Black, 5F);

            g.DrawRectangle(p, r);
        }
    }
}

A screenshot of the result:

How do I remove this padding between the rectangle and the inside left and top edges?  My naive expectation was for the rectangle to start in the very top-left corner.

Any help would be greatly appreciated.

Body:
Top left corner has coordinates x = 0, y = 0. But you should also keep in mind width of rectangle border. If you want rectangle border to fit exactly to the panel which contains it, then you should step inside half of border width:

private void myPanel_Paint(object sender, PaintEventArgs e)
{
    float borderWidth = 5f;
    float topLeftx = borderWidth / 2;
    float topLefty = borderWidth / 2;
    float width = panel2.ClientSize.Width - borderWidth;
    float height = panel2.ClientSize.Height - borderWidth;

    Graphics g = e.Graphics;
    Pen pen = new Pen(Color.Black, borderWidth);
    g.DrawRectangle(pen, topLeftx, topLefty, width, height);
}

Result:


问:
How to suppress Jenkins groovy Logs
I am trying to execute Jenkins checkout command to checkout source files from subversion repository. When I execute command on a new workspace, it will display complete logs of checkedout files. Is there a option to disable logs and enable only when it is required?</p>

答:
Seems like a quiet checkout improvement is in the works, but not yet released.

https://issues.jenkins-ci.org/browse/JENKINS-14541

Title: How to suppress Jenkins groovy Logs


问:
Unity obtaining Vector of click event
I'm utilizing Unity's Vector3 method, ScreenToWorldPoint.

In short, I can click anywhere on a GameObject and obtain the Vector3 of where the click was in the game. However the result I'm obtaining is the Vector3 directly in front of the camera, rather then where I'm truly clicking on the surface of a given GameObject in the scene.

I want the coordinates of exactly where I click on the surface of a GameObject.

答:
To obtain the Vector3 of exactly where you click on the surface of a GameObject utilize the following code:

```<code>    RaycastHit hit;
    Ray ray;
    Camera c = Camera.main;
    Vector3 hitPoint;

    Rect screenRect = new Rect(0, 0, Screen.width, Screen.height);
    if (screenRect.Contains(Input.mousePosition))
    {
        if (c != null)
        {
            ray = c.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit))
            {
                // If the raycast hit a GameObject...
                hitPoint = hit.point; //this is the point we want
            }

        }
    }
</code>```

We create a ray from our mouse on screen and cast it into the world to calculate the exact position of where the mouse is in the scene.

Title: Unity obtaining Vector of click event

Body:
To obtain the Vector3 of exactly where you click on the surface of a GameObject utilize the following code:

    RaycastHit hit;
    Ray ray;
    Camera c = Camera.main;
    Vector3 hitPoint;

    Rect screenRect = new Rect(0, 0, Screen.width, Screen.height);
    if (screenRect.Contains(Input.mousePosition))
    {
        if (c != null)
        {
            ray = c.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit))
            {
                // If the raycast hit a GameObject...
                hitPoint = hit.point; //this is the point we want
            }

        }
    }

We create a ray from our mouse on screen and cast it into the world to calculate the exact position of where the mouse is in the scene.


问:
Laravel Query Builder - how to format the query using joins
I know this is a poorly written query. How can I re-write this using the Laravel Query builder?</p>

```<code>SELECT tgi.rate, tgi.tax_types_id, tt.name, tt.sales_chart_master_id, tt.purchase_chart_master_id
FROM tax_group_items tgi, tax_types tt
WHERE tgi.tax_groups_id = (SELECT tax_groups_id FROM customers WHERE id=2)
AND tt.id = tgi.tax_types_id
AND tt.id NOT IN (SELECT tax_types_id FROM item_tax_type_exemptions WHERE item_tax_types_id = (SELECT item_tax_types_id FROM products WHERE id = 1))
</code>```

答:
The answer would be more easier and clearer to you if you post your relationships in the model class. If you dont know how to define relations, go to query builder section of official doc.
If you don't want to define relations or don't want to use them then use this</p>

```<code>$query = DB::select('your query');
</code>```

Body:
I know this is a poorly written query. How can I re-write this using the Laravel Query builder?

SELECT tgi.rate, tgi.tax_types_id, tt.name, tt.sales_chart_master_id, tt.purchase_chart_master_id
FROM tax_group_items tgi, tax_types tt
WHERE tgi.tax_groups_id = (SELECT tax_groups_id FROM customers WHERE id=2)
AND tt.id = tgi.tax_types_id
AND tt.id NOT IN (SELECT tax_types_id FROM item_tax_type_exemptions WHERE item_tax_types_id = (SELECT item_tax_types_id FROM products WHERE id = 1))

Body:
The answer would be more easier and clearer to you if you post your relationships in the model class. If you dont know how to define relations, go to query builder section of official doc.
If you don't want to define relations or don't want to use them then use this

$query = DB::select('your query');


问:
JS/ReactJS: How to get all input values of a table?
This is an example table data:

```<code>const tableData = [
    ['one', 'two', 'three'],
    ['uno', 'dos', 'tres'],
    ['ichi', 'ni', 'san']
]
</code>```

The data will be rendered like this:

```<code>render() {
    <Table>
        <Table.Body>
            {
                tableData.map((row, rowIndex) => {
                    return (
                        <Table.Row key={ rowIndex }>
                            {
                                row.map((cell, cellIndex) => {
                                    return (
                                        <Table.Cell key={ cellIndex }>
                                            <Input
                                                defaultValue={ cell }
                                                onChange={ this.tableChange }
                                            />
                                        </Table.Cell>
                                    )
                                })
                            }
                        </Table.Row>
                    )
                })
            }
        </Table.Body>
    </Table>
}
</code>```

Now I need to get an updated dataset on onChange of an Input element.

```<code>tableChange(event) {
    console.log(event.target.value)
}
</code>```

This is how I get the updated current element value. But I need to get the complete updated array - like the input array.

I would think of using the key values, but maybe I need some data-attributes?

答:
This is just an example to cover your case, so let say we have the Table
component which will just render all the code above

 Table

```<code>class Table extends React.Component {
  constructor() {
    super();

    this.onChange = this.onChange.bind(this);
    this.state = {
      tableData: [
        ['one', 'two', 'three'],
        ['uno', 'dos', 'tres'],
        ['ichi', 'ni', 'san']
      ]
    };
  }

  renderRows() {
    const { tableData } = this.state;

    return tableData.map((cells, rowIndex) => (
      <tr key={ rowIndex }>
        {this.renderCells(cells, rowIndex)}
      </tr>
    ));
  }

  renderCells(cells, rowIndex) {
    return cells.map((cell, cellIndex) => (
      <td key={ cellIndex }>
        <Input
          cellIndex={cellIndex}
          rowIndex={rowIndex}
          defaultValue={cell}
          onChange={this.onChange}
        />
      </td>
    ));
  }

  onChange(event, cellIndex, rowIndex) {
    this.state.tableData[rowIndex][cellIndex] = event.target.value;
    const tableData = this.state.tableData;

    console.log('values:', event.target.value, cellIndex, rowIndex);
    console.log('tableData:', tableData);

    this.setState({ tableData });
  }

  render() {
    return (
      <table>
        <tbody>
          {this.renderRows()}
        </tbody>
      </table>
    );
  }
}
</code>```

Input

```<code>function Input({ onChange, cellIndex, rowIndex, defaultValue }) {
  const onInputChange = event => {
    onChange(event, cellIndex, rowIndex);
  };

  return (
    <input
      type="text"
      value={defaultValue}
      onChange={onInputChange}
    />
  );
}
</code>```

There is nothing wrong with passing the index of the elements.

As you can see in the <Input /> component you can pass the reference of rowIndex and cellIndex so you the component knows which element of the array is being updated and then notify it to the parent when the onChange event is triggered.

Here is a working example of this, check it out: https://codepen.io/anon/pen/awjgKb?editors=0010

Body:
This is an example table data:

const tableData = [
    ['one', 'two', 'three'],
    ['uno', 'dos', 'tres'],
    ['ichi', 'ni', 'san']
]

The data will be rendered like this:

render() {

            {
                tableData.map((row, rowIndex) => {
                    return (

                            {
                                row.map((cell, cellIndex) => {
                                    return (

                                            <Input
                                                defaultValue={ cell }
                                                onChange={ this.tableChange }
                                            />

                                    )
                                })
                            }

                    )
                })
            }

}

Now I need to get an updated dataset on onChange of an Input element.

tableChange(event) {
    console.log(event.target.value)
}

This is how I get the updated current element value. But I need to get the complete updated array - like the input array.

I would think of using the key values, but maybe I need some data-attributes?

Body:
This is just an example to cover your case, so let say we have the Table
component which will just render all the code above

 Table

class Table extends React.Component {
  constructor() {
    super();

    this.onChange = this.onChange.bind(this);
    this.state = {
      tableData: [
        ['one', 'two', 'three'],
        ['uno', 'dos', 'tres'],
        ['ichi', 'ni', 'san']
      ]
    };
  }

  renderRows() {
    const { tableData } = this.state;

    return tableData.map((cells, rowIndex) => (
      <tr key={ rowIndex }>
        {this.renderCells(cells, rowIndex)}
      </tr>
    ));
  }

  renderCells(cells, rowIndex) {
    return cells.map((cell, cellIndex) => (
      <td key={ cellIndex }>
        <Input
          cellIndex={cellIndex}
          rowIndex={rowIndex}
          defaultValue={cell}
          onChange={this.onChange}
        />
      </td>
    ));
  }

  onChange(event, cellIndex, rowIndex) {
    this.state.tableData[rowIndex][cellIndex] = event.target.value;
    const tableData = this.state.tableData;

    console.log('values:', event.target.value, cellIndex, rowIndex);
    console.log('tableData:', tableData);

    this.setState({ tableData });
  }

  render() {
    return (
      <table>
        <tbody>
          {this.renderRows()}
        </tbody>
      </table>
    );
  }
}

Input

function Input({ onChange, cellIndex, rowIndex, defaultValue }) {
  const onInputChange = event => {
    onChange(event, cellIndex, rowIndex);
  };

  return (
    <input
      type="text"
      value={defaultValue}
      onChange={onInputChange}
    />
  );
}

There is nothing wrong with passing the index of the elements.

As you can see in the <Input /> component you can pass the reference of rowIndex and cellIndex so you the component knows which element of the array is being updated and then notify it to the parent when the onChange event is triggered.

Here is a working example of this, check it out: https://codepen.io/anon/pen/awjgKb?editors=0010


问:
Static Control Background Color with C++
I am creating a basic GUI with the Windows API and I have run into an issue.  It starts with a main window that opens with a custom background color I set (RGB(230,230,230)).  It then displays text in the upper left corner with the static control.

```<code>settingstext = CreateWindow("STATIC",
                             "SETTINGS",
                             SS_LEFT | WS_CHILD,
                             12,
                             20,
                             100,
                             20,
                             hwnd,
                             NULL,
                             proginstance,
                             NULL);
ShowWindow(settingstext, 1);
</code>```

This works, but when the text is displayed I need a way to change the background of it to match the main window or else it just looks like it doesn't blend in.

My question is, how do I do this?  I currently use the method below and it works, but I wanted to know, is there a way to permanently set the background color somehow, right after the CreateWindow function for the static control without changing system colors, and just have it apply to that one control and not anything that sends the WM_CTLCOLORSTATIC message.  I have experimented around with using the GetDC function and SetBkColor function outside of the message loop but nothing works.

```<code>    case WM_CTLCOLORSTATIC:
    {
    HDC hdcStatic = (HDC) wParam;
    SetTextColor(hdcStatic, RGB(0,0,0));
    SetBkColor(hdcStatic, RGB(230,230,230));
    return (INT_PTR)CreateSolidBrush(RGB(230,230,230));
    }
</code>```

I want to do this because...

I don't want to fill up my message loop with functions that need to be called every time the window repaints.

Have the changes apply to only this static control.

I would be very thankful for any help that could be provided, at least pointing me in the right direction, thanks.

答:
For static text controls there's no permanent way to set the text color or their background. Even if you want to apply the changes to a single static control; you would still have to handle WM_CTLCOLORSTATIC notification message in parent dlgproc just when the control is about to be drawn.

This is due to the DefWindowProc overwriting your changes to the device context each time it handles WM_CTLCOLORSTATIC as stated in the MSDN:

By default, the DefWindowProc function selects the default system colors for the static control.

```<code>static HBRUSH hBrush = CreateSolidBrush(RGB(230,230,230));

case WM_CTLCOLORSTATIC:
{
    if (settingstext == (HWND)lParam)

              //OR if the handle is unavailable to you, get ctrl ID

    DWORD CtrlID = GetDlgCtrlID((HWND)lParam); //Window Control ID
    if (CtrlID == IDC_STATIC1) //If desired control
    {
       HDC hdcStatic = (HDC) wParam;
       SetTextColor(hdcStatic, RGB(0,0,0));
       SetBkColor(hdcStatic, RGB(230,230,230));
       return (INT_PTR)hBrush;
    }
}
</code>```

If you're looking to make the control's background transparent over a parent dialog you could use SetBkMode(hdcStatic, TRANSPARENT).

Body:
I am creating a basic GUI with the Windows API and I have run into an issue.  It starts with a main window that opens with a custom background color I set (RGB(230,230,230)).  It then displays text in the upper left corner with the static control.

settingstext = CreateWindow("STATIC",
                             "SETTINGS",
                             SS_LEFT | WS_CHILD,
                             12,
                             20,
                             100,
                             20,
                             hwnd,
                             NULL,
                             proginstance,
                             NULL);
ShowWindow(settingstext, 1);

This works, but when the text is displayed I need a way to change the background of it to match the main window or else it just looks like it doesn't blend in.

My question is, how do I do this?  I currently use the method below and it works, but I wanted to know, is there a way to permanently set the background color somehow, right after the CreateWindow function for the static control without changing system colors, and just have it apply to that one control and not anything that sends the WM_CTLCOLORSTATIC message.  I have experimented around with using the GetDC function and SetBkColor function outside of the message loop but nothing works.

    case WM_CTLCOLORSTATIC:
    {
    HDC hdcStatic = (HDC) wParam;
    SetTextColor(hdcStatic, RGB(0,0,0));
    SetBkColor(hdcStatic, RGB(230,230,230));
    return (INT_PTR)CreateSolidBrush(RGB(230,230,230));
    }

I want to do this because...

I don't want to fill up my message loop with functions that need to be called every time the window repaints.

Have the changes apply to only this static control.

I would be very thankful for any help that could be provided, at least pointing me in the right direction, thanks.

Body:
For static text controls there's no permanent way to set the text color or their background. Even if you want to apply the changes to a single static control; you would still have to handle WM_CTLCOLORSTATIC notification message in parent dlgproc just when the control is about to be drawn.

This is due to the DefWindowProc overwriting your changes to the device context each time it handles WM_CTLCOLORSTATIC as stated in the MSDN:

By default, the DefWindowProc function selects the default system colors for the static control.

static HBRUSH hBrush = CreateSolidBrush(RGB(230,230,230));

case WM_CTLCOLORSTATIC:
{
    if (settingstext == (HWND)lParam)

              //OR if the handle is unavailable to you, get ctrl ID

    DWORD CtrlID = GetDlgCtrlID((HWND)lParam); //Window Control ID
    if (CtrlID == IDC_STATIC1) //If desired control
    {
       HDC hdcStatic = (HDC) wParam;
       SetTextColor(hdcStatic, RGB(0,0,0));
       SetBkColor(hdcStatic, RGB(230,230,230));
       return (INT_PTR)hBrush;
    }
}

If you're looking to make the control's background transparent over a parent dialog you could use SetBkMode(hdcStatic, TRANSPARENT).


问:
Loop Through Cells & Return Regex Search in Message Box
Question with a possibly very simple answer, but I'm still potty training with VBA. I'm looping through an excel array and searching a very long string for the regex pattern "\.\w*?_\w*?_Tag_\w*?". There is a similar example of this in this post under the accepted answer "Example 3: Loop Through Range."

Instead of finding and replacing text though, I want to display the matched search pattern from each cell of the array in a single message box. I've been searching for several hours but most of the VBA Regex examples I've found use built in functions (which don't loop through an array), but since this will be used by other folks I need to use a macro.

Here's what I have so far. I'm thinking I need another loop outside of my For Each loop but not sure how to start executing on this.

```<code>Sub TagNameList()
    Dim strPattern As String: strPattern = "\.\w*?_\w*?_Tag_\w*?"
    Dim Regx As New RegExp
    Dim StrInput As String
    Dim Rng As range
    Dim LastRow As Long: LastRow = ActiveSheet.UsedRange.Rows.Count

'    Set Rng = ActiveSheet.range(Cells(2, 16), Cells(LastRow, 16))
'    Set RegxMatch = Regx.Execute(StrInput)

    For Each cell In Rng
        StrInput = cell.Value

        With Regx
            .Global = True
            .MultiLine = True
            .IgnoreCase = True
            .Pattern = strPattern
        End With

'        If Regx.Test(StrInput) Then
'             MsgBox (Regx.Replace(StrInput, strReplace))
'        Else
'             MsgBox ("Not matched")
'        End If

    Next
End Sub
</code>```

答:
I'm not clear if you mean a message box for the whole range or one for each cell, but you need to use the matches collection, e.g.</p>

```<code>    Sub TagNameList()

    Dim strPattern As String: strPattern = "\.\w*?_\w*?_Tag_\w*?"
    Dim Regx As New RegExp
    Dim StrInput As String
    Dim Rng As Range
    Dim LastRow As Long: LastRow = ActiveSheet.UsedRange.Rows.Count
    Dim oMatches As Object, s As String

    Set Rng = ActiveSheet.Range(Cells(2, 16), Cells(LastRow, 16))
    Set RegxMatch = Regx.Execute(StrInput)

    For Each cell In Rng
        StrInput = cell.Value

        With Regx
            .Global = True
            .MultiLine = True
            .IgnoreCase = True
            .Pattern = strPattern

            If .Test(cell) Then
                Set oMatches = .Execute(cell)
                s = s & "," & oMatches(0).Value
            End If

        End With
    Next
    MsgBox Mid(s, 2)

End Sub
</code>```

Body:
Question with a possibly very simple answer, but I'm still potty training with VBA. I'm looping through an excel array and searching a very long string for the regex pattern "\.\w*?_\w*?_Tag_\w*?". There is a similar example of this in this post under the accepted answer "Example 3: Loop Through Range."

Instead of finding and replacing text though, I want to display the matched search pattern from each cell of the array in a single message box. I've been searching for several hours but most of the VBA Regex examples I've found use built in functions (which don't loop through an array), but since this will be used by other folks I need to use a macro.

Here's what I have so far. I'm thinking I need another loop outside of my For Each loop but not sure how to start executing on this.

Sub TagNameList()
    Dim strPattern As String: strPattern = "\.\w*?_\w*?_Tag_\w*?"
    Dim Regx As New RegExp
    Dim StrInput As String
    Dim Rng As range
    Dim LastRow As Long: LastRow = ActiveSheet.UsedRange.Rows.Count

'    Set Rng = ActiveSheet.range(Cells(2, 16), Cells(LastRow, 16))
'    Set RegxMatch = Regx.Execute(StrInput)

    For Each cell In Rng
        StrInput = cell.Value

        With Regx
            .Global = True
            .MultiLine = True
            .IgnoreCase = True
            .Pattern = strPattern
        End With

'        If Regx.Test(StrInput) Then
'             MsgBox (Regx.Replace(StrInput, strReplace))
'        Else
'             MsgBox ("Not matched")
'        End If

    Next
End Sub

Body:
I'm not clear if you mean a message box for the whole range or one for each cell, but you need to use the matches collection, e.g.

    Sub TagNameList()

    Dim strPattern As String: strPattern = "\.\w*?_\w*?_Tag_\w*?"
    Dim Regx As New RegExp
    Dim StrInput As String
    Dim Rng As Range
    Dim LastRow As Long: LastRow = ActiveSheet.UsedRange.Rows.Count
    Dim oMatches As Object, s As String

    Set Rng = ActiveSheet.Range(Cells(2, 16), Cells(LastRow, 16))
    Set RegxMatch = Regx.Execute(StrInput)

    For Each cell In Rng
        StrInput = cell.Value

        With Regx
            .Global = True
            .MultiLine = True
            .IgnoreCase = True
            .Pattern = strPattern

            If .Test(cell) Then
                Set oMatches = .Execute(cell)
                s = s & "," & oMatches(0).Value
            End If

        End With
    Next
    MsgBox Mid(s, 2)

End Sub


问:
MySQL: Limiting result for WHERE IN list
Let's say there are millions of records in my_table.

Here is my query to extract rows with a specific name from list:

```<code>SELECT * FROM my_table WHERE Name IN ('name1','name2','name3','name4')
</code>```

How do I limit the returned result per name1, name2, etc?
The following query would limit the whole result (to 100).

```<code>SELECT * FROM my_table WHERE Name IN ('name1','name2','name3','name4') LIMIT 100
</code>```

I need to limit to 100 for each name.

答:
This is a bit of a pain in MySQL, but the best method is probably variables:

```<code>select t.*
from (select t.*,
             (@rn := if(@n = name, @rn + 1,
                        if(@n := name, 1, 1)
                       )
             ) as rn
      from my_table t cross join
           (select @n := '', @rn := 0) params
      order by name
     ) t
where rn <= 100;
</code>```

If you want to limit this to a subset of the names, then add the where clause to the subquery.

Note:  If you want to pick certain rows -- such as the oldest or newest or biggest or tallest -- just add a second key to the order by in the subquery.

Body:
Let's say there are millions of records in my_table.

Here is my query to extract rows with a specific name from list:

SELECT * FROM my_table WHERE Name IN ('name1','name2','name3','name4')

How do I limit the returned result per name1, name2, etc?
The following query would limit the whole result (to 100).

SELECT * FROM my_table WHERE Name IN ('name1','name2','name3','name4') LIMIT 100

I need to limit to 100 for each name.

Body:
This is a bit of a pain in MySQL, but the best method is probably variables:

select t.*
from (select t.*,
             (@rn := if(@n = name, @rn + 1,
                        if(@n := name, 1, 1)
                       )
             ) as rn
      from my_table t cross join
           (select @n := '', @rn := 0) params
      order by name
     ) t
where rn <= 100;

If you want to limit this to a subset of the names, then add the where clause to the subquery.

Note:  If you want to pick certain rows -- such as the oldest or newest or biggest or tallest -- just add a second key to the order by in the subquery.


问:
Laravel, first() vs loop
I have an object on which I can run first() but I don't know how to loop through it.

```<code>$types = $biz->types()->first();
echo $types->name; //works great and gives me the name
</code>```

This works fine but if I try:

```<code>    $types = $biz->types(); //returns a BelongsToMany object
    foreach($types as $type){
        echo $type->name; //doesn't enter the loop at all
    }
</code>```

Edit: the following wouldn't work:

```<code> $biz->types; //returns an empty collection
</code>```

This one doesn't give me anything and loop wouldn't initiate.

My question: How do I loop through $types and not just the first one?

PS: I wanted to focus on the loop and first so I didn't bring all the details.

答:
You should access it as a property, which gives you access to the Collection of models. Accessing it as a method gives you QueryBuilder as a result.

```<code>foreach($biz->types as $type) {
   ...
}
</code>```

Title: Laravel, first() vs loop

Body:
I have an object on which I can run first() but I don't know how to loop through it.

$types = $biz->types()->first();
echo $types->name; //works great and gives me the name

This works fine but if I try:

    $types = $biz->types(); //returns a BelongsToMany object
    foreach($types as $type){
        echo $type->name; //doesn't enter the loop at all
    }

Edit: the following wouldn't work:

 $biz->types; //returns an empty collection

This one doesn't give me anything and loop wouldn't initiate.

My question: How do I loop through $types and not just the first one?

PS: I wanted to focus on the loop and first so I didn't bring all the details.

Body:
You should access it as a property, which gives you access to the Collection of models. Accessing it as a method gives you QueryBuilder as a result.

foreach($biz->types as $type) {
   ...
}


问:
How to store extensible metadata in an ORM-friendly way in .NET?
It seems I am unable to find any answers to "how to use EAV approach with ORM tools" question, so I'll try my luck here.

Suppose I have an Entities Table:

```<code>ID -> int
Name -> nvarchar(50)
</code>```

An Images Table:

```<code>EntityID -> int
Width -> int
Height -> int
</code>```

And a Songs Table:

```<code>EntityID -> int
Duration -> decimal(12,3)
</code>```

I need to add extensible metadata to the entities (unknown key-value pairs with type info), so that I'm able to issue queries like:

Find me all the Songs that have a Duration longer than 3 minutes, with a Name starting with 'The', with metadata fulfilling these criteria:

HasGuitarSolo is set to true

GuitarSoloDuration is greater than 30 seconds

And sort the results on GuitarSoloDuration in descending order.

I don't want to create HasGuitarSolo, GuitarSoloDuration, etc. columns in the database, Ideally I would like to store them in an EAV-like schema, or an alternative schema that doesn't require a knowledge of the keys up front.

答:
Add a column to the tables called 'metadata' and put XML in it. SQL server allows you to look at a blob full of XML as if it were additional columns (with limitations).

For ORM, it depends on how your object is structured.

Infinitely Customizable metadata items: you put the name-value pairs from the XML in a collection. If your ORM won't allow this, put it straight into a string property, the setter could parse it into an XML doc (or faster object if you need speed). Getter would return the string. Then a separate property 'MetaDataItem(ItemName->string)' that is not ORM'd would read values from the metadata list and update/add them with its setter.

Metadeta is hardcoded properties - map them using a query that pulls them from the XML.

Hybrid of the two - hardcoded properties for some items - have their setters/getters call MetaDataItem.

Reverse hybrid if certain properties need to be directly stored (esp if you are sorting large lists on them): you have to hardcode properties for that metadata with their own private members, but don't ORM those properties. Hardcoded the saving/loading of those values into the string property that is ORM'd, and if you want to be able to update those hardcoded metadata items from the MetaDataItem property as well, hardcode them it that spot, too!

If you have a whole bunch of hardcoded metadata properties, in addition to the infinite amount, you can easy the crud in the XML property and MetaDataItem property with lists and reflection. If all are hardcoded you can still use the XML text property to load/save them, map that one property, not the others.

Sort them with a LINQ query on the object.

I did this with great success and with each bullet coded, stuff worked better and better! 2005/.Net 1.1 so no ORM, LINQ, my first VB.net program etc. But other developers did use SQL server's XML querying to read my XML. Of course I forgot about this, changed it, and tripped them up :-(

Here are snippets. Key of this all is: ORM friendly = ORM some properties, not others; Allow consumers to use other properties, but not some. If your ORM doesn't allow such ala-carte property selection, you might be able to use inheritance or composition to trick it. Sorry I don't have time to post full example for your purpose.

Well I don't have the code sample here, at home. I will edit and paste it in tommorrow.

EDIT as promised, here's the code snippet:

```<code>   Public Property ItemType(ByVal stTagName As String) As String
        Get
            Dim obj As Object
            obj = Me.lstMemberList.Item(stTagName)
            If Not obj Is Nothing Then
                Return CType(obj, foDataItem).Type
            End If
        End Get
        Set(ByVal Value As String)
            Dim obj As Object
            obj = Me.lstMemberList.Item(stTagName)
            If Not obj Is Nothing Then
                CType(obj, foDataItem).Type = Value
            End If
        End Set
    End Property

    Public Function ItemExists(ByVal stTagName As String) As Boolean
        Return Me.lstMemberList.ContainsKey(stTagName)
    End Function

    Public Property ItemValue(ByVal stTagName As String, Optional ByVal Type4NewItem As String = "") As String
        Get
            Dim obj As Object
            obj = Me.lstMemberList.Item(stTagName)
            If obj Is Nothing Then
                Dim stInternalKey As String = ""
                Try
                    stInternalKey = Me.InternalKey.ToString
                Catch
                End Try
                If stTagName <> "InternalKey" Then '' // avoid deadlock if internalkey errs!
                    Throw New ApplicationException("Tag '" & stTagName & _
                      "' does not exist in FO w/ internal key of " & stInternalKey)
                End If
            Else
                Return CType(obj, foDataItem).Value
            End If
        End Get
        Set(ByVal Value As String)
            '' // if child variation form...
            If bLocked4ChildVariation Then
                '' // protect properties not in the list of allowed updatable items
                If Not Me.GetChildVariationDifferentFields.Contains(stTagName) Then
                    Exit Property
                End If
            End If
            '' // WARNING - DON'T FORGET TO UPDATE THIS LIST OR YOU WILL NEVER FIND THE BUG!
            Select Case stTagName
                Case "PageNum"
                    _PageNum = CInt(Value)
                Case "Left"
                    _Left = CInt(Value)
                Case "Top"
                    _Top = CInt(Value)
                Case "Width"
                    _Width = CInt(Value)
                Case "Height"
                    _Height = CInt(Value)
                Case "Type"
                    _Type = String2Type(Value)
                Case "InternalKey"
                    _InternalKey = CInt(Value)
                Case "UniqueID"
                    _UniqueID = Value
            End Select
            Static MyError As frmErrorMessage
            Dim obj As Object
            If Me.lstMemberList.ContainsKey(stTagName) Then
                Dim foi As foDataItem = CType(Me.lstMemberList.Item(stTagName), foDataItem)
                If foi.Type = "Number" Then
                    Value = CStr(Val(Value))
                End If
                If foi.Value <> Value Then
                    If bMonitorRefreshChanges Then
                        LogObject.LoggIt("Gonna Send Update for Change " & stTagName & " from " & _
                          foi.Value & " to " & Value)
                        If Not Me.FormObjectChanged_Address Is Nothing Then
                            FormObjectChanged_Address(Me, stTagName)
                        End If
                    End If
                End If
                foi.Value = Value
            Else
                Me.lstMemberList.Add(stTagName, New foDataItem(Value, Type4NewItem))
                Me.alOrderAdded.Add(stTagName)
            End If
        End Set
    End Property

  Public Function StringVal(ByVal st As String, Optional ByVal stDefault As String = "") As String
        Try
            StringVal = stDefault
            Return CType(Me.ItemValue(st), String)
        Catch ex As Exception
            Dim bThrowError As Boolean = True
            RaiseEvent ConversionError(ex, "String=" & Me.ItemValue(st), Me, st, bThrowError)
            If bThrowError Then
                LogObject.LoggIt("Error setting tag value in fo.StringVal: " & st)
                Throw New Exception("Rethrown Exception getting value of " & Me.ID & "." & st, ex)
            End If
        End Try
    End Function
    Public Function IntVal(ByVal st As String, Optional ByVal iDefault As Integer = 0) As Integer

    ...

 '' // 'native' values - are normal properties instead of XML properties, which
    '' // actually makes it harder to deal with b/c of extra updates to sync them, BUT,
    '' // worth it - as they are read much more than written (sorts, wizard builds,
    '' // screen redraws, etc) I can afford to be slow when writing to them, PLUS
    '' // retain the benefits of referencing everything else via ItemValue, PLUS
    '' // these are just the more 'popular' items.
    Private _Top As Integer
    Private _Left As Integer
    Private _Width As Integer
    Private _Height As Integer
    Private _PageNum As Integer
    Private _Type As pfoType
    Private _InternalKey As Integer
    Private _UniqueID As String

    Public Sub SetNativeValuesFromMyXML()
        _Top = CInt(CType(Me.lstMemberList("Top"), foDataItem).Value)
        _Left = CInt(CType(Me.lstMemberList("Left"), foDataItem).Value)
        _Width = CInt(CType(Me.lstMemberList("Width"), foDataItem).Value)
        _Height = CInt(CType(Me.lstMemberList("Height"), foDataItem).Value)
        _PageNum = CInt(CType(Me.lstMemberList("PageNum"), foDataItem).Value)
        _Type = String2Type(CType(Me.lstMemberList("Type"), foDataItem).Value)
        _InternalKey = CInt(CType(Me.lstMemberList("InternalKey"), foDataItem).Value)
        _UniqueID = CType(Me.lstMemberList("UniqueID"), foDataItem).Value
    End Sub

    Public Property Top() As Integer
        Get
            Return _Top '' // CInt(ItemValue("Top"))
        End Get
        Set(ByVal Value As Integer)
            ItemValue("Top") = Value.ToString
        End Set
    End Property

    Public Property Left() As Integer
        Get
            Return _Left '' //CInt(ItemValue("Left"))
        End Get

    ...
</code>```

ContentLicense: CC BY-SA 2.5

Body:
It seems I am unable to find any answers to "how to use EAV approach with ORM tools" question, so I'll try my luck here.

Suppose I have an Entities Table:

ID -> int
Name -> nvarchar(50)

An Images Table:

EntityID -> int
Width -> int
Height -> int

And a Songs Table:

EntityID -> int
Duration -> decimal(12,3)

I need to add extensible metadata to the entities (unknown key-value pairs with type info), so that I'm able to issue queries like:

Find me all the Songs that have a Duration longer than 3 minutes, with a Name starting with 'The', with metadata fulfilling these criteria:

HasGuitarSolo is set to true

GuitarSoloDuration is greater than 30 seconds

And sort the results on GuitarSoloDuration in descending order.

I don't want to create HasGuitarSolo, GuitarSoloDuration, etc. columns in the database, Ideally I would like to store them in an EAV-like schema, or an alternative schema that doesn't require a knowledge of the keys up front.

Body:
Add a column to the tables called 'metadata' and put XML in it. SQL server allows you to look at a blob full of XML as if it were additional columns (with limitations).

For ORM, it depends on how your object is structured.

Infinitely Customizable metadata items: you put the name-value pairs from the XML in a collection. If your ORM won't allow this, put it straight into a string property, the setter could parse it into an XML doc (or faster object if you need speed). Getter would return the string. Then a separate property 'MetaDataItem(ItemName->string)' that is not ORM'd would read values from the metadata list and update/add them with its setter.

Metadeta is hardcoded properties - map them using a query that pulls them from the XML.

Hybrid of the two - hardcoded properties for some items - have their setters/getters call MetaDataItem.

Reverse hybrid if certain properties need to be directly stored (esp if you are sorting large lists on them): you have to hardcode properties for that metadata with their own private members, but don't ORM those properties. Hardcoded the saving/loading of those values into the string property that is ORM'd, and if you want to be able to update those hardcoded metadata items from the MetaDataItem property as well, hardcode them it that spot, too!

If you have a whole bunch of hardcoded metadata properties, in addition to the infinite amount, you can easy the crud in the XML property and MetaDataItem property with lists and reflection. If all are hardcoded you can still use the XML text property to load/save them, map that one property, not the others.

Sort them with a LINQ query on the object.

I did this with great success and with each bullet coded, stuff worked better and better! 2005/.Net 1.1 so no ORM, LINQ, my first VB.net program etc. But other developers did use SQL server's XML querying to read my XML. Of course I forgot about this, changed it, and tripped them up :-(

Here are snippets. Key of this all is: ORM friendly = ORM some properties, not others; Allow consumers to use other properties, but not some. If your ORM doesn't allow such ala-carte property selection, you might be able to use inheritance or composition to trick it. Sorry I don't have time to post full example for your purpose.

Well I don't have the code sample here, at home. I will edit and paste it in tommorrow.

EDIT as promised, here's the code snippet:

   Public Property ItemType(ByVal stTagName As String) As String
        Get
            Dim obj As Object
            obj = Me.lstMemberList.Item(stTagName)
            If Not obj Is Nothing Then
                Return CType(obj, foDataItem).Type
            End If
        End Get
        Set(ByVal Value As String)
            Dim obj As Object
            obj = Me.lstMemberList.Item(stTagName)
            If Not obj Is Nothing Then
                CType(obj, foDataItem).Type = Value
            End If
        End Set
    End Property

    Public Function ItemExists(ByVal stTagName As String) As Boolean
        Return Me.lstMemberList.ContainsKey(stTagName)
    End Function

    Public Property ItemValue(ByVal stTagName As String, Optional ByVal Type4NewItem As String = "") As String
        Get
            Dim obj As Object
            obj = Me.lstMemberList.Item(stTagName)
            If obj Is Nothing Then
                Dim stInternalKey As String = ""
                Try
                    stInternalKey = Me.InternalKey.ToString
                Catch
                End Try
                If stTagName <> "InternalKey" Then '' // avoid deadlock if internalkey errs!
                    Throw New ApplicationException("Tag '" & stTagName & _
                      "' does not exist in FO w/ internal key of " & stInternalKey)
                End If
            Else
                Return CType(obj, foDataItem).Value
            End If
        End Get
        Set(ByVal Value As String)
            '' // if child variation form...
            If bLocked4ChildVariation Then
                '' // protect properties not in the list of allowed updatable items
                If Not Me.GetChildVariationDifferentFields.Contains(stTagName) Then
                    Exit Property
                End If
            End If
            '' // WARNING - DON'T FORGET TO UPDATE THIS LIST OR YOU WILL NEVER FIND THE BUG!
            Select Case stTagName
                Case "PageNum"
                    _PageNum = CInt(Value)
                Case "Left"
                    _Left = CInt(Value)
                Case "Top"
                    _Top = CInt(Value)
                Case "Width"
                    _Width = CInt(Value)
                Case "Height"
                    _Height = CInt(Value)
                Case "Type"
                    _Type = String2Type(Value)
                Case "InternalKey"
                    _InternalKey = CInt(Value)
                Case "UniqueID"
                    _UniqueID = Value
            End Select
            Static MyError As frmErrorMessage
            Dim obj As Object
            If Me.lstMemberList.ContainsKey(stTagName) Then
                Dim foi As foDataItem = CType(Me.lstMemberList.Item(stTagName), foDataItem)
                If foi.Type = "Number" Then
                    Value = CStr(Val(Value))
                End If
                If foi.Value <> Value Then
                    If bMonitorRefreshChanges Then
                        LogObject.LoggIt("Gonna Send Update for Change " & stTagName & " from " & _
                          foi.Value & " to " & Value)
                        If Not Me.FormObjectChanged_Address Is Nothing Then
                            FormObjectChanged_Address(Me, stTagName)
                        End If
                    End If
                End If
                foi.Value = Value
            Else
                Me.lstMemberList.Add(stTagName, New foDataItem(Value, Type4NewItem))
                Me.alOrderAdded.Add(stTagName)
            End If
        End Set
    End Property

  Public Function StringVal(ByVal st As String, Optional ByVal stDefault As String = "") As String
        Try
            StringVal = stDefault
            Return CType(Me.ItemValue(st), String)
        Catch ex As Exception
            Dim bThrowError As Boolean = True
            RaiseEvent ConversionError(ex, "String=" & Me.ItemValue(st), Me, st, bThrowError)
            If bThrowError Then
                LogObject.LoggIt("Error setting tag value in fo.StringVal: " & st)
                Throw New Exception("Rethrown Exception getting value of " & Me.ID & "." & st, ex)
            End If
        End Try
    End Function
    Public Function IntVal(ByVal st As String, Optional ByVal iDefault As Integer = 0) As Integer

    ...

 '' // 'native' values - are normal properties instead of XML properties, which
    '' // actually makes it harder to deal with b/c of extra updates to sync them, BUT,
    '' // worth it - as they are read much more than written (sorts, wizard builds,
    '' // screen redraws, etc) I can afford to be slow when writing to them, PLUS
    '' // retain the benefits of referencing everything else via ItemValue, PLUS
    '' // these are just the more 'popular' items.
    Private _Top As Integer
    Private _Left As Integer
    Private _Width As Integer
    Private _Height As Integer
    Private _PageNum As Integer
    Private _Type As pfoType
    Private _InternalKey As Integer
    Private _UniqueID As String

    Public Sub SetNativeValuesFromMyXML()
        _Top = CInt(CType(Me.lstMemberList("Top"), foDataItem).Value)
        _Left = CInt(CType(Me.lstMemberList("Left"), foDataItem).Value)
        _Width = CInt(CType(Me.lstMemberList("Width"), foDataItem).Value)
        _Height = CInt(CType(Me.lstMemberList("Height"), foDataItem).Value)
        _PageNum = CInt(CType(Me.lstMemberList("PageNum"), foDataItem).Value)
        _Type = String2Type(CType(Me.lstMemberList("Type"), foDataItem).Value)
        _InternalKey = CInt(CType(Me.lstMemberList("InternalKey"), foDataItem).Value)
        _UniqueID = CType(Me.lstMemberList("UniqueID"), foDataItem).Value
    End Sub

    Public Property Top() As Integer
        Get
            Return _Top '' // CInt(ItemValue("Top"))
        End Get
        Set(ByVal Value As Integer)
            ItemValue("Top") = Value.ToString
        End Set
    End Property

    Public Property Left() As Integer
        Get
            Return _Left '' //CInt(ItemValue("Left"))
        End Get

    ...


问:
Conda cannot find some package (pyspark) for environment from YML
I have a .yml file that was saved by a colleague. I cannot recreate an environment with conda env create -f file.yml (both with anaconda and miniconda on Ubuntu, and with the official docker images of both)

I tried to add - conda-forge to the channels but that doesn't change anything, I still get:

```<code>Collecting pyspark==2.1.1
  Could not find a version that satisfies the requirement pyspark==2.1.1 (from versions: )
No matching distribution found for pyspark==2.1.1

CondaValueError: pip returned an error.```
```

Whereas installing manually this package with pip or conda works.
Here are the yaml file contents:

name: stuff
channels:
- defaults
dependencies:
- pip=9.0.1=py36_1
- python=3.6.1=0
- setuptools=27.2.0=py36_0
- pip:
  - pyspark==2.1.1

答:
I think for now the guys from Continuum don't actively develop "conda env" anymore. So the recommendation is to use "conda create" directly instead. To share an environment with the exact package version you can simply export the active environment with:

```<code>conda list --explicit > my_environment.txt
</code>```

and pipe the output of that to a file (in the example to "my_environment.txt"). Afterwards you can import the environment by giving it a name (in the example below "MyEnvironment") and the --file option with the exported environment:

```<code>conda create --name MyEnvironment --file my_environment.txt
</code>```

Body:
I have a .yml file that was saved by a colleague. I cannot recreate an environment with conda env create -f file.yml (both with anaconda and miniconda on Ubuntu, and with the official docker images of both)

I tried to add - conda-forge to the channels but that doesn't change anything, I still get:

Collecting pyspark==2.1.1
  Could not find a version that satisfies the requirement pyspark==2.1.1 (from versions: )
No matching distribution found for pyspark==2.1.1

CondaValueError: pip returned an error.```

Whereas installing manually this package with pip or conda works.
Here are the yaml file contents:

name: stuff
channels:
- defaults
dependencies:
- pip=9.0.1=py36_1
- python=3.6.1=0
- setuptools=27.2.0=py36_0
- pip:
  - pyspark==2.1.1

Body:
I think for now the guys from Continuum don't actively develop "conda env" anymore. So the recommendation is to use "conda create" directly instead. To share an environment with the exact package version you can simply export the active environment with:

conda list --explicit > my_environment.txt

and pipe the output of that to a file (in the example to "my_environment.txt"). Afterwards you can import the environment by giving it a name (in the example below "MyEnvironment") and the --file option with the exported environment:

conda create --name MyEnvironment --file my_environment.txt


问:
Android - Issue on removing node from Firebase database
The following function is called from an addChildEventListener to remove a specific node from my Firebase database when it's needed.
The issue here is that the function launches the "Item removed." toast, indicating the task was successfully executed, but the node keeps existing on the database.

Can someone tell me what is wrong?

private void showData(DataSnapshot ds) {
    String keyValue = null;

    if(ds.hasChildren()) {
        keyValue = ds.getKey();

        Toast.makeText(getActivity().getApplicationContext(), "Removing item...", Toast.LENGTH_SHORT).show();
        ds.getRef().child(keyValue).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Toast.makeText(getActivity().getApplicationContext(), "Item removed.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity().getApplicationContext(), "Something bad happened while removing item.", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}```
</div>
</div>
</p>

<p><strong>EDIT</strong>
If it helps, my query is the following:</p>

```orderItemsByTime = db.getInstance().getReference().child("items").orderByChild("time");
```

答:
A likely explanation is that ds.getRef().child(keyValue) is not pointing to the location you intend.  When remove() is performed on a non-existent location, it's not an error.  task.isSuccessful() returns true.

Add some debug logging (or toasting) to show the path for ds.getRef().child(keyValue):

```<code>Toast.makeText(getActivity().getApplicationContext(), "Removing item at " +
        ds.getRef().child(keyValue), Toast.LENGTH_SHORT).show();
</code>```

or

```<code>Log.d(TAG, "Removing item at " + ds.getRef().child(keyValue));
</code>```

Body:
The following function is called from an addChildEventListener to remove a specific node from my Firebase database when it's needed.
The issue here is that the function launches the "Item removed." toast, indicating the task was successfully executed, but the node keeps existing on the database.

Can someone tell me what is wrong?

private void showData(DataSnapshot ds) {
    String keyValue = null;

    if(ds.hasChildren()) {
        keyValue = ds.getKey();

        Toast.makeText(getActivity().getApplicationContext(), "Removing item...", Toast.LENGTH_SHORT).show();
        ds.getRef().child(keyValue).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Toast.makeText(getActivity().getApplicationContext(), "Item removed.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity().getApplicationContext(), "Something bad happened while removing item.", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

EDIT
If it helps, my query is the following:

orderItemsByTime = db.getInstance().getReference().child("items").orderByChild("time");

Body:
A likely explanation is that ds.getRef().child(keyValue) is not pointing to the location you intend.  When remove() is performed on a non-existent location, it's not an error.  task.isSuccessful() returns true.

Add some debug logging (or toasting) to show the path for ds.getRef().child(keyValue):

Toast.makeText(getActivity().getApplicationContext(), "Removing item at " +
        ds.getRef().child(keyValue), Toast.LENGTH_SHORT).show();

or

Log.d(TAG, "Removing item at " + ds.getRef().child(keyValue));


问:
Angular2 modules: best practices
I have always been working with one main module called AppModule but I am yet to divide any of my small apps in several modules. What are the best practises regarding Modules ? In other terms, when should I refactor my code to encapsulate some functionalities in a Module ?

Any examples that could help are very welcome.

Cheers

答:
The main use case for modules is ... well ... modularity. It is the chief way for Angular to implement SRP and SOC. It creates good designs for our Angular apps by increasing cohesion and reduces coupling.

There are other reasons which John Papa lists here:

It makes sense that some of these features have functionality that is not intended to be exposed outside of the feature. We also may want to add a feature to the app as a whole unit at a later time. Or maybe the feature is there and we want to lazy load it when the user decides it is time to visit the feature.

These are all valuable, but the main purpose for modules is good design.

Title: Angular2 modules: best practices


问:
How to assign "cut" range midpoints in R?
I am using cut to divide my data into bins, which gives the resulting bin as something like (x1,x2]. Can anyone tell me how I might make a new column that expresses these bins as the midpoint of the bin? For example, with the following dataframe:

```<code>structure(list(x = c(1L, 4L, 6L, 7L, 8L, 9L, 12L, 18L, 19L),
    y = 1:9), .Names = c("x", "y"), class = "data.frame", row.names = c(NA,
-9L))
</code>```

I can use

```<code>test$xRange <- cut(test$x, breaks=seq(0, 20, 5))
</code>```

to give

```<code>    x   y   xRange
1   1   1   (0,5]
2   4   2   (0,5]
3   6   3   (5,10]
4   7   4   (5,10]
5   8   5   (5,10]
6   9   6   (5,10]
7   12  7   (10,15]
8   18  8   (15,20]
9   19  9   (15,20]
</code>```

But the result I need should instead look like:

```<code>    x   y   xRange        xMidpoint
1   1   1   (0,5]         2.5
2   4   2   (0,5]         2.5
3   6   3   (5,10]        7.5
4   7   4   (5,10]        7.5
5   8   5   (5,10]        7.5
6   9   6   (5,10]        7.5
7   12  7   (10,15]       12.5
8   18  8   (15,20]       17.5
9   19  9   (15,20]       17.5
</code>```

I've done some searching, and came upon a similar question at divide a range of values in bins of equal length: cut vs cut2, which gives a solution as

```<code>cut2 <- function(x, breaks) {
  r <- range(x)
  b <- seq(r[1], r[2], length=2*breaks+1)
  brk <- b[0:breaks*2+1]
  mid <- b[1:breaks*2]
  brk[1] <- brk[1]-0.01
  k <- cut(x, breaks=brk, labels=FALSE)
  mid[k]
}
</code>```

But when I try this on my case, using

```<code>test$xMidpoint <- cut2(test$x, 5)
</code>```

it does not return the correct midpoint. Perhaps I am entering the breaks incorrectly in cut2? Can anyone tell me what I'm doing incorrectly?

答:
I know this is a really old question, but this may help future googlers.  I wrote a function that I called midcut that cuts the data and provides me with the midpoint of the bin.

```<code>midcut<-function(x,from,to,by){
   ## cut the data into bins...
   x=cut(x,seq(from,to,by),include.lowest=T)
   ## make a named vector of the midpoints, names=binnames
   vec=seq(from+by/2,to-by/2,by)
   names(vec)=levels(x)
   ## use the vector to map the names of the bins to the midpoint values
   unname(vec[x])
}
</code>```

example

```<code>test$midpoint=midcut(test$x,0,20,5)
> test
   x y  xRange midpoint
1  1 1   (0,5]      2.5
2  4 2   (0,5]      2.5
3  6 3  (5,10]      7.5
4  7 4  (5,10]      7.5
5  8 5  (5,10]      7.5
6  9 6  (5,10]      7.5
7 12 7 (10,15]     12.5
8 18 8 (15,20]     17.5
9 19 9 (15,20]     17.5
</code>```

Body:
I am using cut to divide my data into bins, which gives the resulting bin as something like (x1,x2]. Can anyone tell me how I might make a new column that expresses these bins as the midpoint of the bin? For example, with the following dataframe:

structure(list(x = c(1L, 4L, 6L, 7L, 8L, 9L, 12L, 18L, 19L),
    y = 1:9), .Names = c("x", "y"), class = "data.frame", row.names = c(NA,
-9L))

I can use

test$xRange <- cut(test$x, breaks=seq(0, 20, 5))

to give

    x   y   xRange
1   1   1   (0,5]
2   4   2   (0,5]
3   6   3   (5,10]
4   7   4   (5,10]
5   8   5   (5,10]
6   9   6   (5,10]
7   12  7   (10,15]
8   18  8   (15,20]
9   19  9   (15,20]

But the result I need should instead look like:

    x   y   xRange        xMidpoint
1   1   1   (0,5]         2.5
2   4   2   (0,5]         2.5
3   6   3   (5,10]        7.5
4   7   4   (5,10]        7.5
5   8   5   (5,10]        7.5
6   9   6   (5,10]        7.5
7   12  7   (10,15]       12.5
8   18  8   (15,20]       17.5
9   19  9   (15,20]       17.5

I've done some searching, and came upon a similar question at divide a range of values in bins of equal length: cut vs cut2, which gives a solution as

cut2 <- function(x, breaks) {
  r <- range(x)
  b <- seq(r[1], r[2], length=2*breaks+1)
  brk <- b[0:breaks*2+1]
  mid <- b[1:breaks*2]
  brk[1] <- brk[1]-0.01
  k <- cut(x, breaks=brk, labels=FALSE)
  mid[k]
}

But when I try this on my case, using

test$xMidpoint <- cut2(test$x, 5)

it does not return the correct midpoint. Perhaps I am entering the breaks incorrectly in cut2? Can anyone tell me what I'm doing incorrectly?

Body:
I know this is a really old question, but this may help future googlers.  I wrote a function that I called midcut that cuts the data and provides me with the midpoint of the bin.

midcut<-function(x,from,to,by){
   ## cut the data into bins...
   x=cut(x,seq(from,to,by),include.lowest=T)
   ## make a named vector of the midpoints, names=binnames
   vec=seq(from+by/2,to-by/2,by)
   names(vec)=levels(x)
   ## use the vector to map the names of the bins to the midpoint values
   unname(vec[x])
}

example

test$midpoint=midcut(test$x,0,20,5)
> test
   x y  xRange midpoint
1  1 1   (0,5]      2.5
2  4 2   (0,5]      2.5
3  6 3  (5,10]      7.5
4  7 4  (5,10]      7.5
5  8 5  (5,10]      7.5
6  9 6  (5,10]      7.5
7 12 7 (10,15]     12.5
8 18 8 (15,20]     17.5
9 19 9 (15,20]     17.5


问:
Angular 2 - Getting length of Pipe in calling component
I have a simple custom pipe in Angular2 to filter an array based on type ID and year arrays, I define it as such:

```<code>@Pipe({name: 'highlightedWorksFilter', pure: false})
export class HighlightedWorksFilterPipe implements PipeTransform {
transform(works: IHighlightedWork[], activityTypeIds: any[], activityYears: any[]){
    if (works && works.length) {
        return works.filter(work => {
            if(activityTypeIds.findIndex(i => i.id === work.activityTypeId && i.checked) === -1) {
                return false;
            }
            if (activityYears.findIndex(i => i.year === work.activityYear && i.checked) === -1) {
                return false;
            }
            return true;
        });
    }
    else {
        return works;
    }
}
}
</code>```

Here's where it's used from a calling component:

```<code><div>FILTERED COUNT / {{highlightedWorks.length}}</div>
<div *ngFor="let work of highlightedWorks | highlightedWorksFilter: myActivityTypeIds:myActivityYears">
 {{work.Title}}
</div>
</code>```

The filter works perfectly and gets updated based on the 2 checkbox list arrays for type and year (using arrays to filter, hence the the "pure: false" on the pipe).

My question is, how can I get that FILTERED COUNT outside of the ngFor to display the pipe's filtered results count?  I have the highlightedWorks.length as the total results count, but want to also display how many results I currently have filtered with the pipes.

答:
You can use a simple index on *ngFor which last value is the index of last filtered element. You add 1 to that value and you have the length of your filtered list.

```<code><div *ngFor="let work of highlightedWorks | highlightedWorksFilter: myActivityTypeIds:myActivityYears; let i=index" [i]="i">
 {{work.Title}} Index: {{i+1}}
</div>
</code>```

You also have to input the value into your component for this to work:

```<code>@Input() i: number;
</code>```

Body:
I have a simple custom pipe in Angular2 to filter an array based on type ID and year arrays, I define it as such:

@Pipe({name: 'highlightedWorksFilter', pure: false})
export class HighlightedWorksFilterPipe implements PipeTransform {
transform(works: IHighlightedWork[], activityTypeIds: any[], activityYears: any[]){
    if (works && works.length) {
        return works.filter(work => {
            if(activityTypeIds.findIndex(i => i.id === work.activityTypeId && i.checked) === -1) {
                return false;
            }
            if (activityYears.findIndex(i => i.year === work.activityYear && i.checked) === -1) {
                return false;
            }
            return true;
        });
    }
    else {
        return works;
    }
}
}

Here's where it's used from a calling component:

FILTERED COUNT / {{highlightedWorks.length}}

 {{work.Title}}

The filter works perfectly and gets updated based on the 2 checkbox list arrays for type and year (using arrays to filter, hence the the "pure: false" on the pipe).

My question is, how can I get that FILTERED COUNT outside of the ngFor to display the pipe's filtered results count?  I have the highlightedWorks.length as the total results count, but want to also display how many results I currently have filtered with the pipes.

Body:
You can use a simple index on *ngFor which last value is the index of last filtered element. You add 1 to that value and you have the length of your filtered list.

<div *ngFor="let work of highlightedWorks | highlightedWorksFilter: myActivityTypeIds:myActivityYears; let i=index" [i]="i">
 {{work.Title}} Index: {{i+1}}
</div>

You also have to input the value into your component for this to work:

@Input() i: number;


问:
Exporting each variable value in loop
I am trying to capture the changing variable '$server' everytime the parameters go through a foreach loop. To summarize, the $sever value is always changing, and I want to capture it and add it into a collective csv file

Thank you!

Here is the code main part of the code that I have.

```<code> function Convert-QueryToObjects
 {
   [CmdletBinding()]
   [Alias('QueryToObject')]
   [OutputType([PSCustomObject])]
   param
   (
    [Parameter(Mandatory = $false,
               ValueFromPipeline = $true,
               ValueFromPipelineByPropertyName = $true,
               Position = 0)]
    [Alias('ComputerName', 'Computer')]
    [string]
    $Name = $env:COMPUTERNAME
)

Process
{
    Write-Verbose "Running query.exe against $Name."
    $Users = query user /server:$Name 2>&1

    if ($Users -like "*No User exists*")
    {
        # Handle no user's found returned from query.
        # Returned: 'No User exists for *'
        Write-Error "There were no users found on $Name : $Users"
        Write-Verbose "There were no users found on $Name."
    }
    elseif ($Users -like "*Error*")
    {
        # Handle errored returned by query.
        # Returned: 'Error ...<message>...'
        Write-Error "There was an error running query against $Name : $Users"
        Write-Verbose "There was an error running query against $Name."
    }
    elseif ($Users -eq $null -and $ErrorActionPreference -eq 'SilentlyContinue')
    {
        # Handdle null output called by -ErrorAction.
        Write-Verbose "Error action has supressed output from query.exe. Results were null."
    }
    else
    {
        Write-Verbose "Users found on $Name. Converting output from text."

        # Conversion logic. Handles the fact that the sessionname column may be populated or not.
        $Users = $Users | ForEach-Object {
            (($_.trim() -replace ">" -replace "(?m)^([A-Za-z0-9]{3,})\s+(\d{1,2}\s+\w+)", '$1  none  $2' -replace "\s{2,}", "," -replace "none", $null))
        } | ConvertFrom-Csv

        Write-Verbose "Generating output for $($Users.Count) users connected to $Name."

        # Output objects.
        foreach ($User in $Users)
        {
            Write-Verbose $User
            if ($VerbosePreference -eq 'Continue')
            {
                # Add '| Out-Host' if -Verbose is tripped.
                [PSCustomObject]@{
                    ComputerName = $Name
                    Username = $User.USERNAME
                    SessionState = $User.STATE.Replace("Disc", "Disconnected")
                    SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")

                } | Out-Host
            }
            else
            {
                # Standard output.
                [PSCustomObject]@{
                    ComputerName = $Name
                    Username = $User.USERNAME
                    SessionState = $User.STATE.Replace("Disc", "Disconnected")
                    SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")

                }
            }
        }
    }
}
}

$Servers = Get-Content 'H:\demo\computernames.txt'

foreach ($Server in $Servers)
{
if (-not( Test-Connection $Server -Count 1 -Quiet )) { continue }

if (-not( Convert-QueryToObjects $Server -ErrorAction SilentlyContinue)) {

      $server | Out-File 'H:\demo\session\run1.csv' -Append

    }
else
{
   Convert-QueryToObjects -Name $Server | select ComputerName, Username, Sessionstate, IdleTime, ID | Export-Csv 'H:\demo\session\run.csv' -NoTypeInformation
}
}
</code>```

答: Create an array outside of your foreach loop and add the $server variable value to the array during your foreach. At the end export the array to a csv.</p>

Title: Exporting each variable value in loop

Body:
I am trying to capture the changing variable '$server' everytime the parameters go through a foreach loop. To summarize, the $sever value is always changing, and I want to capture it and add it into a collective csv file

Thank you!

Here is the code main part of the code that I have.

 function Convert-QueryToObjects
 {
   [CmdletBinding()]
   [Alias('QueryToObject')]
   [OutputType([PSCustomObject])]
   param
   (
    [Parameter(Mandatory = $false,
               ValueFromPipeline = $true,
               ValueFromPipelineByPropertyName = $true,
               Position = 0)]
    [Alias('ComputerName', 'Computer')]
    [string]
    $Name = $env:COMPUTERNAME
)

Process
{
    Write-Verbose "Running query.exe against $Name."
    $Users = query user /server:$Name 2>&1

    if ($Users -like "*No User exists*")
    {
        # Handle no user's found returned from query.
        # Returned: 'No User exists for *'
        Write-Error "There were no users found on $Name : $Users"
        Write-Verbose "There were no users found on $Name."
    }
    elseif ($Users -like "*Error*")
    {
        # Handle errored returned by query.
        # Returned: 'Error ...<message>...'
        Write-Error "There was an error running query against $Name : $Users"
        Write-Verbose "There was an error running query against $Name."
    }
    elseif ($Users -eq $null -and $ErrorActionPreference -eq 'SilentlyContinue')
    {
        # Handdle null output called by -ErrorAction.
        Write-Verbose "Error action has supressed output from query.exe. Results were null."
    }
    else
    {
        Write-Verbose "Users found on $Name. Converting output from text."

        # Conversion logic. Handles the fact that the sessionname column may be populated or not.
        $Users = $Users | ForEach-Object {
            (($_.trim() -replace ">" -replace "(?m)^([A-Za-z0-9]{3,})\s+(\d{1,2}\s+\w+)", '$1  none  $2' -replace "\s{2,}", "," -replace "none", $null))
        } | ConvertFrom-Csv

        Write-Verbose "Generating output for $($Users.Count) users connected to $Name."

        # Output objects.
        foreach ($User in $Users)
        {
            Write-Verbose $User
            if ($VerbosePreference -eq 'Continue')
            {
                # Add '| Out-Host' if -Verbose is tripped.
                [PSCustomObject]@{
                    ComputerName = $Name
                    Username = $User.USERNAME
                    SessionState = $User.STATE.Replace("Disc", "Disconnected")
                    SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")

                } | Out-Host
            }
            else
            {
                # Standard output.
                [PSCustomObject]@{
                    ComputerName = $Name
                    Username = $User.USERNAME
                    SessionState = $User.STATE.Replace("Disc", "Disconnected")
                    SessionType = $($User.SESSIONNAME -Replace '#', '' -Replace "[0-9]+", "")

                }
            }
        }
    }
}
}

$Servers = Get-Content 'H:\demo\computernames.txt'

foreach ($Server in $Servers)
{
if (-not( Test-Connection $Server -Count 1 -Quiet )) { continue }

if (-not( Convert-QueryToObjects $Server -ErrorAction SilentlyContinue)) {

      $server | Out-File 'H:\demo\session\run1.csv' -Append

    }
else
{
   Convert-QueryToObjects -Name $Server | select ComputerName, Username, Sessionstate, IdleTime, ID | Export-Csv 'H:\demo\session\run.csv' -NoTypeInformation
}
}


问:
Managing browser cache
I'm building a web application. I'm linking to separate css and js files and I want to manage cache.
If the script js or the style css file have been updated then force reload and replace that file, else get the file from cache.
Is that possible? How to do that?</p>

答:
As a default css and javascript file cashed in client browser. when you update your css or javascript file only need update and increase version in HTML header like this:</p>

```<code>foo.css?ver=002
foo.js?ver=002
</code>```

Title: Managing browser cache

Body:
As a default css and javascript file cashed in client browser. when you update your css or javascript file only need update and increase version in HTML header like this:

foo.css?ver=002
foo.js?ver=002