问:
Invert interpolation to give the variable associated with a desired interpolation function value
I am trying to invert an interpolated function using scipy's interpolate function. Let's say I create an interpolated function,

```<code>import scipy.interpolate as interpolate
interpolatedfunction = interpolated.interp1d(xvariable,data,kind='cubic')
</code>```

Is there some function that can find x when I specify a:

```<code>interpolatedfunction(x) == a
</code>```

In other words, "I want my interpolated function to equal a; what is the value of xvariable such that my function is equal to a?"

I appreciate I can do this with some numerical scheme, but is there a more straightforward method? What if the interpolated function is multivalued in xvariable?

答:
There are dedicated methods for finding roots of cubic splines. The simplest to use is the .roots() method of InterpolatedUnivariateSpline object:

```<code>spl = InterpolatedUnivariateSpline(x, y)
roots = spl.roots()
</code>```

This finds all of the roots instead of just one, as generic solvers (fsolve, brentq, newton, bisect, etc) do.

```<code>x = np.arange(20)
y = np.cos(np.arange(20))
spl = InterpolatedUnivariateSpline(x, y)
print(spl.roots())
</code>```

outputs array([  1.56669456,   4.71145244,   7.85321627,  10.99554642, 14.13792756,  17.28271674])

However, you want to equate the spline to some arbitrary number a, rather than 0. One option is to rebuild the spline (you can't just subtract a from it):

```<code>solutions = InterpolatedUnivariateSpline(x, y - a).roots()
</code>```

Note that none of this will work with the function returned by interp1d; it does not have roots method. For that function, using generic methods like fsolve is an option, but you will only get one root at a time from it. In any case, why use interp1d for cubic splines when there are more powerful ways to do the same kind of interpolation?

Non-object-oriented way

Instead of rebuilding the spline after subtracting a from data, one can  directly subtract a from spline coefficients. This requires us to drop down to non-object-oriented interpolation methods. Specifically, sproot takes in a tck tuple prepared by splrep, as follows:

```<code>tck = splrep(x, y, k=3, s=0)
tck_mod = (tck[0], tck[1] - a, tck[2])
solutions = sproot(tck_mod)
</code>```

I'm not sure if messing with tck is worth the gain here, as it's possible that the bulk of computation time will be in root-finding anyway. But it's good to have alternatives.

Body:
I am trying to invert an interpolated function using scipy's interpolate function. Let's say I create an interpolated function,

import scipy.interpolate as interpolate
interpolatedfunction = interpolated.interp1d(xvariable,data,kind='cubic')

Is there some function that can find x when I specify a:

interpolatedfunction(x) == a

In other words, "I want my interpolated function to equal a; what is the value of xvariable such that my function is equal to a?"

I appreciate I can do this with some numerical scheme, but is there a more straightforward method? What if the interpolated function is multivalued in xvariable?

Body:
There are dedicated methods for finding roots of cubic splines. The simplest to use is the .roots() method of InterpolatedUnivariateSpline object:

spl = InterpolatedUnivariateSpline(x, y)
roots = spl.roots()

This finds all of the roots instead of just one, as generic solvers (fsolve, brentq, newton, bisect, etc) do.

x = np.arange(20)
y = np.cos(np.arange(20))
spl = InterpolatedUnivariateSpline(x, y)
print(spl.roots())

outputs array([  1.56669456,   4.71145244,   7.85321627,  10.99554642, 14.13792756,  17.28271674])

However, you want to equate the spline to some arbitrary number a, rather than 0. One option is to rebuild the spline (you can't just subtract a from it):

solutions = InterpolatedUnivariateSpline(x, y - a).roots()

Note that none of this will work with the function returned by interp1d; it does not have roots method. For that function, using generic methods like fsolve is an option, but you will only get one root at a time from it. In any case, why use interp1d for cubic splines when there are more powerful ways to do the same kind of interpolation?

Non-object-oriented way

Instead of rebuilding the spline after subtracting a from data, one can  directly subtract a from spline coefficients. This requires us to drop down to non-object-oriented interpolation methods. Specifically, sproot takes in a tck tuple prepared by splrep, as follows:

tck = splrep(x, y, k=3, s=0)
tck_mod = (tck[0], tck[1] - a, tck[2])
solutions = sproot(tck_mod)

I'm not sure if messing with tck is worth the gain here, as it's possible that the bulk of computation time will be in root-finding anyway. But it's good to have alternatives.


来源: stackexchange

问:
Using Bootstrap 4, how to keep a text fixed over an image?
I have a background with a text appearing over it (when hovering the text). When I resize the window my background image shrink while the text doesn't. I want the text to stay at the same position over the picture. How would it be possible to have the text shrinking and staying at the same place when the image is reduce (because of a windows resize)?

Before resize :

After resize :

```<code><div class="row two">
  <div class="col-md-12">
    <a href="{{site.baseurl}}/portfolio.html">
      <img src="http://res.cloudinary.com/lyoon/image/upload/c_scale,h_350,w_500/v1510612416/windows-10-1995434_1280_xtmlea.png" class="img-fluid shadow" alt="My apps/games made" />
      <p class="img_description">Colt Steele Udemy Projects <i class="fa fa-play" aria-hidden="true"></i></p>
    </a>
  </div>
</div>
</code>```

CSS:

```<code>.shadow {
  box-shadow: 0px 3px 10px grey;
  -moz-box-shadow: 0px 3px 10px grey;
  -webkit-box-shadow: 0px 3px 10px grey;
}

.img_description {
  margin: 0 auto;
  width: 500px;
  padding-top: 175px;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  font-size: 20px;
  color: white;
  background-color:
  visibility: hidden;
  opacity: 0;
}

.img_description:hover {
  visibility: visible;
  opacity: 1;
  background-color: rgba(139, 146, 152, 0.65);
}
</code>```

答:
I recommend looking into Media Queries.

You can set a threshold that will trigger separate styles under those conditions. It can be very useful when you want your UI to do something different at different sizes.

```<code>@media only screen
and (*Your threshold criteria goes here* EXAMPLE:  max-width : 1000px) {
  //css goes here with whatever css you want to fire at this threshold
}
</code>```

I would just target your text class and set up a media query or two to make it behave. Let me know if you need further assistance.

ContentLicense: CC BY-SA 3.0

Body:
I have a background with a text appearing over it (when hovering the text). When I resize the window my background image shrink while the text doesn't. I want the text to stay at the same position over the picture. How would it be possible to have the text shrinking and staying at the same place when the image is reduce (because of a windows resize)?

Before resize :

After resize :

Colt Steele Udemy Projects

CSS:

.shadow {
  box-shadow: 0px 3px 10px grey;
  -moz-box-shadow: 0px 3px 10px grey;
  -webkit-box-shadow: 0px 3px 10px grey;
}

.img_description {
  margin: 0 auto;
  width: 500px;
  padding-top: 175px;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  font-size: 20px;
  color: white;
  background-color:
  visibility: hidden;
  opacity: 0;
}

.img_description:hover {
  visibility: visible;
  opacity: 1;
  background-color: rgba(139, 146, 152, 0.65);
}

Body:
I recommend looking into Media Queries.

You can set a threshold that will trigger separate styles under those conditions. It can be very useful when you want your UI to do something different at different sizes.

@media only screen
and (*Your threshold criteria goes here* EXAMPLE:  max-width : 1000px) {
  //css goes here with whatever css you want to fire at this threshold
}

I would just target your text class and set up a media query or two to make it behave. Let me know if you need further assistance.


问:
Association type mismatch in Rails app
```<code>Rails 5.1
</code>```

My migration file:

```<code>class CreateFwExports < ActiveRecord::Migration[5.1]
  def change
    create_table :fw_exports, id: :string do |t|
      t.string :screen_name, index: true, limit: 16
      t.string :full_name, limit: 21
      t.string :location

      t.timestamps
    end

  end
end
</code>```

In my helper file, I have the following method:

```<code>def process_spreadsheet(number_of_rows, spreadsheet)
  for i in 1..number_of_rows do
    fw_export_record = FwExport.new(
        :screen_name => spreadsheet[i][0].to_s,
        :full_name => spreadsheet[i][1].to_s,
        :location => spreadsheet[i][2].to_s,
    )
    fw_export_record.save
  end
end
</code>```

What this method does, is receive a spreadsheet CSV object, and iterates through the data, trying to save each row to the fw_exports table.

The first data row is:

```<code>xxxxxxxx,xxxxxxxxxx,"Nottingham, England"
</code>```

I am getting the following error message:

```<code>ActiveRecord::AssociationTypeMismatch (Location(#38400060) expected, got "Nottingham, England" which is an instance of String(#10657520)):
app/helpers/fw_exports_helper.rb:21:in `block in process_spreadsheet'
app/helpers/fw_exports_helper.rb:20:in `process_spreadsheet'
app/controllers/fw_exports_controller.rb:82:in `process_parsed_spreadsheet'
</code>```

When I looked at the actual MySQL table, here's what I got:

```<code>id Primary  varchar(255)    utf8mb4_unicode_ci      No  None
screen_name  varchar(16)    utf8mb4_unicode_ci      Yes NULL
full_name   varchar(21) utf8mb4_unicode_ci      Yes NULL
location    varchar(255)    utf8mb4_unicode_ci      Yes NULL
</code>```

From the controller:

```<code>def fw_export_params
  params.require(:fw_export).permit(:screen_name, :full_name, :location)
end
</code>```

id is generated through a method defined in the concerns section

Any idea why I'm getting the error message?

Edit:

In my fw_exports.rb model, I had the following:

```<code>has_one :location
</code>```

I have a locations table (and model), with the following fields:

```<code>  t.string :fw_exports_id, index: true
  t.string :city
  t.string :state
  t.string :country
</code>```

When I commented out, the line in the fw_exports.rb model:

```<code># has_one :location
</code>```

I stopped getting the above mentioned error, and instead, I am now getting the following error:

```<code>NoMethodError (undefined method `each' for "0":String):
app/helpers/fw_exports_helper.rb:21:in `block in process_spreadsheet'
app/helpers/fw_exports_helper.rb:20:in `process_spreadsheet'
app/controllers/fw_exports_controller.rb:82:in `process_parsed_spreadsheet'
</code>```

Same spot in code, different message.

答:
Add |i| after the do

```<code>for i in 1..number_of_rows do |i|
</code>```

Edit after response in comment:
You don't show the model but probably you have a relationship called location that is conflicting with the field.

Title: Association type mismatch in Rails app

Body:
Rails 5.1

My migration file:

class CreateFwExports < ActiveRecord::Migration[5.1]
  def change
    create_table :fw_exports, id: :string do |t|
      t.string :screen_name, index: true, limit: 16
      t.string :full_name, limit: 21
      t.string :location

      t.timestamps
    end

  end
end

In my helper file, I have the following method:

def process_spreadsheet(number_of_rows, spreadsheet)
  for i in 1..number_of_rows do
    fw_export_record = FwExport.new(
        :screen_name => spreadsheet[i][0].to_s,
        :full_name => spreadsheet[i][1].to_s,
        :location => spreadsheet[i][2].to_s,
    )
    fw_export_record.save
  end
end

What this method does, is receive a spreadsheet CSV object, and iterates through the data, trying to save each row to the fw_exports table.

The first data row is:

xxxxxxxx,xxxxxxxxxx,"Nottingham, England"

I am getting the following error message:

ActiveRecord::AssociationTypeMismatch (Location(#38400060) expected, got "Nottingham, England" which is an instance of String(#10657520)):
app/helpers/fw_exports_helper.rb:21:in `block in process_spreadsheet'
app/helpers/fw_exports_helper.rb:20:in `process_spreadsheet'
app/controllers/fw_exports_controller.rb:82:in `process_parsed_spreadsheet'

When I looked at the actual MySQL table, here's what I got:

id Primary  varchar(255)    utf8mb4_unicode_ci      No  None
screen_name  varchar(16)    utf8mb4_unicode_ci      Yes NULL
full_name   varchar(21) utf8mb4_unicode_ci      Yes NULL
location    varchar(255)    utf8mb4_unicode_ci      Yes NULL

From the controller:

def fw_export_params
  params.require(:fw_export).permit(:screen_name, :full_name, :location)
end

id is generated through a method defined in the concerns section

Any idea why I'm getting the error message?

Edit:

In my fw_exports.rb model, I had the following:

has_one :location

I have a locations table (and model), with the following fields:

  t.string :fw_exports_id, index: true
  t.string :city
  t.string :state
  t.string :country

When I commented out, the line in the fw_exports.rb model:

# has_one :location

I stopped getting the above mentioned error, and instead, I am now getting the following error:

NoMethodError (undefined method `each' for "0":String):
app/helpers/fw_exports_helper.rb:21:in `block in process_spreadsheet'
app/helpers/fw_exports_helper.rb:20:in `process_spreadsheet'
app/controllers/fw_exports_controller.rb:82:in `process_parsed_spreadsheet'

Same spot in code, different message.

Body:
Add |i| after the do

for i in 1..number_of_rows do |i|

Edit after response in comment:
You don't show the model but probably you have a relationship called location that is conflicting with the field.


问:
How to join nested jsonb array elements?
My question is somewhat similar to this one:

How to join jsonb array elements in Postgres?

But I have some nested arrays I need to fill in. To keep it simple I only have 1 table:

```<code>CREATE table tester(
  id int,
  name text,
  d jsonb
)

INSERT INTO tester(id, name, d) VALUES
  ('1', 'bob',    '[
                     {
                       "employees": [{"id":2},{"id":3},{"id":4}],
                       "coworkers": [{"id":5},{"id":6}]
                     },
                     {
                       "employees": [{"id":3},{"id":4}],
                       "coworkers": [{"id":5}]
                     }
                   ]'::jsonb),
   ('2', 'barb',    '[
                     {
                       "employees": [{"id":3}],
                       "coworkers": []
                     },
                     {
                       "employees": [{"id":3},{"id":4}],
                       "coworkers": [{"id":5, "id":3}]
                     }
                   ]'::jsonb),

   ('3', 'ann',    '[]'::jsonb),
   ('4', 'jeff',   '[]'::jsonb),
   ('5', 'rachel', '[]'::jsonb),
   ('6', 'ryan',   '[]'::jsonb);
</code>```

See: http://sqlfiddle.com/#!17/7c7ef/12/0

I am trying to add simply the name to each of the coworkers and employees so that bob would look like:

```<code>[
  {
    "employees": [{"id":2, "name":"barb"},{"id":3, "name":"ann"},{"id":4, "jeff"}],
    "coworkers": [{"id":5, "name":"rachel"},{"id":6, "name":"ryan"}]
  },
  {
    "employees": [{"id":3, "name":"ann"},{"id":4, "name":"jeff"}],
    "coworkers": [{"id":5, "name":"rachel"}]
  }
]
</code>```

So far, I have:

```<code>SELECT c.person person
FROM tester
LEFT JOIN LATERAL(
    SELECT jsonb_agg(
        jsonb_build_object(
            'employees', c.wrk->'employees',
            'coworkers', c.wrk->'coworkers'
        )
    ) AS person
    FROM jsonb_array_elements(tester.d) AS c(wrk)
) c ON true
</code>```

Which returns everything but the names:

```<code>[{"coworkers": [{"id": 5}, {"id": 6}], "employees": [{"id": 2}, {"id": 3}, {"id": 4}]}, {"coworkers": [{"id": 5}], "employees": [{"id": 3}, {"id": 4}]}]
[{"coworkers": [], "employees": [{"id": 3}]}, {"coworkers": [{"id": 3}], "employees": [{"id": 3}, {"id": 4}]}]
(null)
(null)
(null)
(null)
</code>```

Please take note of the list of objects: they are separate objects and not just one big object.

The "(null)" s/b a blank array "[]".

答:
Using two lateral joins we can create the arrays for coworkers and employees, where we join to the tester table within the lateral query to get the name, then construct the jsonb object & aggregate to get the transformed array.

The resulting query is hairy, though not overly complicated.

```<code>SELECT
    "name"
  , CASE
      WHEN d = '[]'::jsonb THEN NULL
      ELSE coworker.people || employee.people
    END relationships
FROM tester
, LATERAL (
    SELECT
        jsonb_build_object(
             'coworkers'
           , JSON_AGG(json_build_object('id', id, 'name', "name"))
        ) people
    FROM (SELECT DISTINCT
              (jsonb_array_elements(el->'coworkers')->>'id')::int id
          FROM jsonb_array_elements(d) el) coworker
    NATURAL JOIN tester
    ) coworker
, LATERAL (
    SELECT
        jsonb_build_object(
           'employees'
          , JSON_AGG(json_build_object('id', id, 'name', "name"))) people
    FROM (SELECT DISTINCT
              (jsonb_array_elements(el->'employees')->>'id')::int id
          FROM jsonb_array_elements(d) el) employee
    NATURAL JOIN tester
    ) employee
</code>```

alternate solution for list of objects:

```<code>WITH people_separated AS (
  SELECT
    "name"
  , coworkers
  , employees
  FROM tester
  , LATERAL (
    SELECT
      k->'coworkers' coworkers
    , k->'employees' employees
    FROM jsonb_array_elements(d) k
  ) split
)
, people_relationships AS (
SELECT
  name
, JSON_AGG(
    CASE WHEN e.people IS NULL THEN '{}'::jsonb ELSE jsonb_build_object('employees', e.people) END
    ||
    CASE WHEN c.people IS NULL THEN '{}'::jsonb ELSE jsonb_build_object('coworkers', c.people) END
  ) relationships
FROM people_separated
, LATERAL (
    SELECT JSON_AGG(
        c || jsonb_build_object(
                  'name'
                , (SELECT name FROM tester WHERE id = (c->>'id')::int)
             )
    ) people
    FROM jsonb_array_elements(coworkers) c) c
, LATERAL (
    SELECT JSON_AGG(
        e || jsonb_build_object(
                  'name'
                , (SELECT name FROM tester WHERE id = (e->>'id')::int)
             )
    ) people
    FROM jsonb_array_elements(employees) e) e
GROUP BY 1
)
SELECT name, relationships FROM tester LEFT JOIN people_relationships USING (name)
</code>```

Body:
My question is somewhat similar to this one:

How to join jsonb array elements in Postgres?

But I have some nested arrays I need to fill in. To keep it simple I only have 1 table:

CREATE table tester(
  id int,
  name text,
  d jsonb
)

INSERT INTO tester(id, name, d) VALUES
  ('1', 'bob',    '[
                     {
                       "employees": [{"id":2},{"id":3},{"id":4}],
                       "coworkers": [{"id":5},{"id":6}]
                     },
                     {
                       "employees": [{"id":3},{"id":4}],
                       "coworkers": [{"id":5}]
                     }
                   ]'::jsonb),
   ('2', 'barb',    '[
                     {
                       "employees": [{"id":3}],
                       "coworkers": []
                     },
                     {
                       "employees": [{"id":3},{"id":4}],
                       "coworkers": [{"id":5, "id":3}]
                     }
                   ]'::jsonb),

   ('3', 'ann',    '[]'::jsonb),
   ('4', 'jeff',   '[]'::jsonb),
   ('5', 'rachel', '[]'::jsonb),
   ('6', 'ryan',   '[]'::jsonb);

See: http://sqlfiddle.com/#!17/7c7ef/12/0

I am trying to add simply the name to each of the coworkers and employees so that bob would look like:

[
  {
    "employees": [{"id":2, "name":"barb"},{"id":3, "name":"ann"},{"id":4, "jeff"}],
    "coworkers": [{"id":5, "name":"rachel"},{"id":6, "name":"ryan"}]
  },
  {
    "employees": [{"id":3, "name":"ann"},{"id":4, "name":"jeff"}],
    "coworkers": [{"id":5, "name":"rachel"}]
  }
]

So far, I have:

SELECT c.person person
FROM tester
LEFT JOIN LATERAL(
    SELECT jsonb_agg(
        jsonb_build_object(
            'employees', c.wrk->'employees',
            'coworkers', c.wrk->'coworkers'
        )
    ) AS person
    FROM jsonb_array_elements(tester.d) AS c(wrk)
) c ON true

Which returns everything but the names:

[{"coworkers": [{"id": 5}, {"id": 6}], "employees": [{"id": 2}, {"id": 3}, {"id": 4}]}, {"coworkers": [{"id": 5}], "employees": [{"id": 3}, {"id": 4}]}]
[{"coworkers": [], "employees": [{"id": 3}]}, {"coworkers": [{"id": 3}], "employees": [{"id": 3}, {"id": 4}]}]
(null)
(null)
(null)
(null)

Please take note of the list of objects: they are separate objects and not just one big object.

The "(null)" s/b a blank array "[]".

Body:
Using two lateral joins we can create the arrays for coworkers and employees, where we join to the tester table within the lateral query to get the name, then construct the jsonb object & aggregate to get the transformed array.

The resulting query is hairy, though not overly complicated.

SELECT
    "name"
  , CASE
      WHEN d = '[]'::jsonb THEN NULL
      ELSE coworker.people || employee.people
    END relationships
FROM tester
, LATERAL (
    SELECT
        jsonb_build_object(
             'coworkers'
           , JSON_AGG(json_build_object('id', id, 'name', "name"))
        ) people
    FROM (SELECT DISTINCT
              (jsonb_array_elements(el->'coworkers')->>'id')::int id
          FROM jsonb_array_elements(d) el) coworker
    NATURAL JOIN tester
    ) coworker
, LATERAL (
    SELECT
        jsonb_build_object(
           'employees'
          , JSON_AGG(json_build_object('id', id, 'name', "name"))) people
    FROM (SELECT DISTINCT
              (jsonb_array_elements(el->'employees')->>'id')::int id
          FROM jsonb_array_elements(d) el) employee
    NATURAL JOIN tester
    ) employee

alternate solution for list of objects:

WITH people_separated AS (
  SELECT
    "name"
  , coworkers
  , employees
  FROM tester
  , LATERAL (
    SELECT
      k->'coworkers' coworkers
    , k->'employees' employees
    FROM jsonb_array_elements(d) k
  ) split
)
, people_relationships AS (
SELECT
  name
, JSON_AGG(
    CASE WHEN e.people IS NULL THEN '{}'::jsonb ELSE jsonb_build_object('employees', e.people) END
    ||
    CASE WHEN c.people IS NULL THEN '{}'::jsonb ELSE jsonb_build_object('coworkers', c.people) END
  ) relationships
FROM people_separated
, LATERAL (
    SELECT JSON_AGG(
        c || jsonb_build_object(
                  'name'
                , (SELECT name FROM tester WHERE id = (c->>'id')::int)
             )
    ) people
    FROM jsonb_array_elements(coworkers) c) c
, LATERAL (
    SELECT JSON_AGG(
        e || jsonb_build_object(
                  'name'
                , (SELECT name FROM tester WHERE id = (e->>'id')::int)
             )
    ) people
    FROM jsonb_array_elements(employees) e) e
GROUP BY 1
)
SELECT name, relationships FROM tester LEFT JOIN people_relationships USING (name)


问:
Is there a way to see stdout from the Jenkins artifactory release plugin?
The Jenkins artifactory release plugin runs a bunch of git commands when releasing for example:

```<code>[RELEASE] Changing POMs to next development version
[RELEASE] Committing next development version on branch 'master'
[RELEASE] Pushing branch 'master' to ''
 > git --version # timeout=10
using GIT_SSH to set credentials jenkins-mod with full ssh keys
Finished: SUCCESS
</code>```

The git output doesn't get printed to 'stdout' though. In the case above I would expect to see the git version to be printed out. Is there any way to get this output? It's hard to debug what is happening without the git stdout.

答:
Try starting Jenkins with the java option  -Dhudson.plugins.git.GitSCM.verbose=true.

The Artifactory plugin uses the git-client plugin. Options for enabling verbose output in the git client should apply. This option was added to the git-client plugin in this commit 2ca0d09e51810e83ab0d1893ecb87c64f0599210. I have git-client 2.6.0 installed and it works okay.

On my CentOS 7 system with Jenkins 1.651 I enabled the option by editing /etc/sysconfig/jenkins and adding it to the JENKINS_JAVA_OPTIONS variable. After that a restart with "systemctl restart jenkins" was used for it to take effect.

You can see it enabled by looking at the process list:

```<code>[root@jenkins]# ps aux | grep Git
build     3556  166  9.9 3576244 386416 ?      Ssl  15:10   0:18 /etc/alternatives/java -Dcom.sun.akuma.Daemon=daemonized -Djava.awt.headless=true -Dhudson.plugins.git.GitSCM.verbose=true -DJENKINS_HOME=/var/lib/jenkins -jar /usr/lib/jenkins/jenkins.war --logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war --daemon --httpPort=8080 --ajp13Port=8009 --debug=5 --handlerCountMax=100 --handlerCountMaxIdle=20
</code>```

Body:
The Jenkins artifactory release plugin runs a bunch of git commands when releasing for example:

[RELEASE] Changing POMs to next development version
[RELEASE] Committing next development version on branch 'master'
[RELEASE] Pushing branch 'master' to ''
 > git --version # timeout=10
using GIT_SSH to set credentials jenkins-mod with full ssh keys
Finished: SUCCESS

The git output doesn't get printed to 'stdout' though. In the case above I would expect to see the git version to be printed out. Is there any way to get this output? It's hard to debug what is happening without the git stdout.

Body:
Try starting Jenkins with the java option  -Dhudson.plugins.git.GitSCM.verbose=true.

The Artifactory plugin uses the git-client plugin. Options for enabling verbose output in the git client should apply. This option was added to the git-client plugin in this commit 2ca0d09e51810e83ab0d1893ecb87c64f0599210. I have git-client 2.6.0 installed and it works okay.

On my CentOS 7 system with Jenkins 1.651 I enabled the option by editing /etc/sysconfig/jenkins and adding it to the JENKINS_JAVA_OPTIONS variable. After that a restart with "systemctl restart jenkins" was used for it to take effect.

You can see it enabled by looking at the process list:

[root@jenkins]# ps aux | grep Git
build     3556  166  9.9 3576244 386416 ?      Ssl  15:10   0:18 /etc/alternatives/java -Dcom.sun.akuma.Daemon=daemonized -Djava.awt.headless=true -Dhudson.plugins.git.GitSCM.verbose=true -DJENKINS_HOME=/var/lib/jenkins -jar /usr/lib/jenkins/jenkins.war --logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war --daemon --httpPort=8080 --ajp13Port=8009 --debug=5 --handlerCountMax=100 --handlerCountMaxIdle=20


问:
ejs: Only add class 'active' to first image of image gallery
```<code><div class="placeImgCol ">
                <div class="slider-outer">
                  <img src="/images/arrow-left.png" class="prev" alt="Previous">
                  <img src="/images/arrow-right.png" class="next" alt="Next">
                  <div class="slider-inner">
                    <% item.imgNames.forEach(function (img, index) { %>
                    <img src="/uploads/<%=img%>" class=<%if(index === 0){ return "active"} else { return "" } %> value="<%=index%>">
                    <% })%>
                  </div>

                </div>
            </div>
</code>```

Hey guys, I'm working in node.js and now I'm trying to make an image gallery inside of every list item (see uploaded image).

Now, I can link these images so that they show up in devtools, but they have a standard css style of display: none. This is good for every image, except the first one which I want to have a class 'active', this removes the 'display:none'. I tried the following line in EJS:

" class=<% index === 0 ? "active" : "" %>

But this doesn't seem to work since it doesn't add the active class to the first image element. Can someone tell me how to do this properly?

screenshot of the website

答:
If you're not going to do a ternary, the if statement needs to span a couple different sets of tags.  I've only detailed out the tricky part, you'll need to insert it back into your code.

Try something like this:

```<code><% yourArray.forEach(function (img, index) { %>
<img src=<whatever> class=
  <% if (index === 0) {%>
  <%= "active" %>
  <% } %>
... and so on />
</code>```

Hope that helps.

Body:
                    <% item.imgNames.forEach(function (img, index) { %>
                    <img src="/uploads/<%=img%>" class=<%if(index === 0){ return "active"} else { return "" } %> value="<%=index%>">
                    <% })%>

Hey guys, I'm working in node.js and now I'm trying to make an image gallery inside of every list item (see uploaded image).

Now, I can link these images so that they show up in devtools, but they have a standard css style of display: none. This is good for every image, except the first one which I want to have a class 'active', this removes the 'display:none'. I tried the following line in EJS:

" class=<% index === 0 ? "active" : "" %>

But this doesn't seem to work since it doesn't add the active class to the first image element. Can someone tell me how to do this properly?

screenshot of the website

Body:
If you're not going to do a ternary, the if statement needs to span a couple different sets of tags.  I've only detailed out the tricky part, you'll need to insert it back into your code.

Try something like this:

<% yourArray.forEach(function (img, index) { %>
<img src=<whatever> class=
  <% if (index === 0) {%>
  <%= "active" %>
  <% } %>
... and so on />

Hope that helps.


问:
Entity Data Model Connection not Syncing properly over Git
I'm working on an ASP.NET w/ MVC5 project. The project has a small and simple SQL Server Connection hosted in Azure with a single Table. For my interface I generated an EDM object using the Database as the source via "Add ADO.NET Entity Data Model"

It all worked fine until I tried to work on the project on another machine. I synced the project to the other machine via GitHub, and everything was there (including the connection to my Azure hosted SQL Server), but I couldn't get the Solution to Build.

As can be seen in the Screenshot below, the EDM and it's associated files are marked as "checked-in" with a warning icon, and there are build-warning messages telling me the files are missing. However they show up in the Solution Explorer, and I can see them in the folder when I navigate to it manually in Windows File Explorer.

Is there some other configuration step I need to take to get the model to sync properly to other machines?

答: I had an old version of the EDM that had a different name on the new machine, so when it tried to connect it got confused. I wiped the repo and re-cloned it and now it works!</p>


问:
MATLAB, Convert 4049 rows x 50 columns of spectrograph data into 3D plot
```<code>%Sampling Frequency
f=8000;

%Sampling Time
t=5;
%Data imported from microsoft Excel
matrix=Book2S1;

%Size Matrix
s=size(matrix);
h=s(1,1);
w=s(1,2);

%Set Up Rows and Columns
rows=(0:(f/2)/(h-1):f/2);
columns=(0:t/(w-1):t);

%plot
mesh(columns,rows,matrix);
xlabel('Time, s')
ylabel('Frequency, Hz')
zlabel('Power Spectral Density, V^2/Hz')`enter code here
</code>```

This is the code that I type in to attempt to get a 3D plot. The goal is for me to obtain a plot that looks like the image listed below, but I continue getting a mesh error

Error using mesh (line 139)
Data inputs must be numeric, datetime, duration, categorical arrays or objects which can be converted to
double.

Error in Lab_3_1 (line 21)
mesh(columns,rows,matrix);

What my plot is supposed to look like.
The picture didn't want to get saved after being cropped, sorry people.

The following is a link to half of the data being used for this plot.
https://docs.google.com/spreadsheets/d/e/2PACX-1vRMWfmFYDnwMSPzahD8k-aWAXHstbNRdlY4gmOHJoXkLaBb4PY7zF5-41yFkQHR4g0w3LrMFiz3ZqWJ/pubhtml

答:
Try substituting your 4049x50 matrix replacing my random matrix f:

```<code>% t=5;
% fs = 8000;
lower = -60;
upper = 20;
f = (upper-lower).*rand(4049,50) + lower;
% s=size(f);
% h=s(1,1);
% w=s(1,2);
% rows=(0:(fs/2)/(h-1):fs/2);
% columns=(0:t/(w-1):t);
mesh(f);
colormap('jet');
colorbar;
xlabel('Time, s')
ylabel('Frequency, Hz')
zlabel('Power Spectral Density V^2/Hz')
ylim([0 4000])
zlim([-100 40])
</code>```

Using the random data matrix f, I get this:

Body:
%Sampling Frequency
f=8000;

%Sampling Time
t=5;
%Data imported from microsoft Excel
matrix=Book2S1;

%Size Matrix
s=size(matrix);
h=s(1,1);
w=s(1,2);

%Set Up Rows and Columns
rows=(0:(f/2)/(h-1):f/2);
columns=(0:t/(w-1):t);

%plot
mesh(columns,rows,matrix);
xlabel('Time, s')
ylabel('Frequency, Hz')
zlabel('Power Spectral Density, V^2/Hz')`enter code here

This is the code that I type in to attempt to get a 3D plot. The goal is for me to obtain a plot that looks like the image listed below, but I continue getting a mesh error

Error using mesh (line 139)
Data inputs must be numeric, datetime, duration, categorical arrays or objects which can be converted to
double.

Error in Lab_3_1 (line 21)
mesh(columns,rows,matrix);

What my plot is supposed to look like.
The picture didn't want to get saved after being cropped, sorry people.

The following is a link to half of the data being used for this plot.
https://docs.google.com/spreadsheets/d/e/2PACX-1vRMWfmFYDnwMSPzahD8k-aWAXHstbNRdlY4gmOHJoXkLaBb4PY7zF5-41yFkQHR4g0w3LrMFiz3ZqWJ/pubhtml

Body:
Try substituting your 4049x50 matrix replacing my random matrix f:

% t=5;
% fs = 8000;
lower = -60;
upper = 20;
f = (upper-lower).*rand(4049,50) + lower;
% s=size(f);
% h=s(1,1);
% w=s(1,2);
% rows=(0:(fs/2)/(h-1):fs/2);
% columns=(0:t/(w-1):t);
mesh(f);
colormap('jet');
colorbar;
xlabel('Time, s')
ylabel('Frequency, Hz')
zlabel('Power Spectral Density V^2/Hz')
ylim([0 4000])
zlim([-100 40])

Using the random data matrix f, I get this:


问:
Split sequence dataframe in R
I have a dataframe of sequences like this

```<code>dput(df)
structure(list(val = structure(c(3L, 2L, 4L, 1L, 5L, 6L), .Label = c("{36415},{36415}",
                           "{36415},{85610}", "{36415},{9904}", "{85025,36415}", "{85610},{36415}",
                           "{8872},{36415}"), class = "factor")), .Names = "val", row.names = c(NA,
                                                                                -6L), class = "data.frame")

df
              val
1  {36415},{9904}
2 {36415},{85610}
3   {85025,36415}
4 {36415},{36415}
5 {85610},{36415}
6  {8872},{36415}
</code>```

Notice the 3rd row above. The first row says there is a sequence item 1 followed by item 2 in different rows. The 3rd row says item1 and 2 belong to same row in the sequence

I want to break this data frame into columns like this

```<code>col1        col2
36415       9904
36415       85610
85025,36415 NA
36415       36415
...
</code>```

Notice how the 3rd row of the data frame is.

Is there any way to achieve this?

Title: Split sequence dataframe in R

Body:
I have a dataframe of sequences like this

dput(df)
structure(list(val = structure(c(3L, 2L, 4L, 1L, 5L, 6L), .Label = c("{36415},{36415}",
                           "{36415},{85610}", "{36415},{9904}", "{85025,36415}", "{85610},{36415}",
                           "{8872},{36415}"), class = "factor")), .Names = "val", row.names = c(NA,
                                                                                -6L), class = "data.frame")

df
              val
1  {36415},{9904}
2 {36415},{85610}
3   {85025,36415}
4 {36415},{36415}
5 {85610},{36415}
6  {8872},{36415}

Notice the 3rd row above. The first row says there is a sequence item 1 followed by item 2 in different rows. The 3rd row says item1 and 2 belong to same row in the sequence

I want to break this data frame into columns like this

col1        col2
36415       9904
36415       85610
85025,36415 NA
36415       36415
...

Notice how the 3rd row of the data frame is.

Is there any way to achieve this?

Body:
Here's a one-liner with extract from tidyr. This uses capture groups to specify the column patterns:

library(tidyr)

extract(df, "val", c("col1", "col2"), regex = "\\{([\\d,]+)(?:\\},\\{)?([\\d,]+)?\\}")

or with str_match from stringr. This uses the exact same regex:

library(stringr)

data.frame(str_match(df$val, "\\{([\\d,]+)(?:\\},\\{)?([\\d,]+)?\\}")[,-1])

Result:

         col1  col2
1       36415  9904
2       36415 85610
3 85025,36415  <NA>
4       36415 36415
5       85610 36415
6        8872 36415

           X1    X2
1       36415  9904
2       36415 85610
3 85025,36415  <NA>
4       36415 36415
5       85610 36415
6        8872 36415


问:
React 16: Warning: Expected server HTML to contain a matching
 in
Since upgrading to React 16 I get this error message:

warning.js:33 Warning: Expected server HTML to contain a matching
 in .

What is generally causing this error message and how can it be fixed?

答:
If you use ReactDOM.hydrate to start web application, you will see this warning.

If your application does not use server-side rendering (ssr), please use ReactDOM.render to start.

Title: React 16: Warning: Expected server HTML to contain a matching <div> in <body>

ContentLicense: CC BY-SA 4.0


问:
Rails: Param problems with delete button
index.html:

```<code>  <% @partners.each do |j| %>
            <% if j.link == nil %>
                <div class="column_left"><%= j.name %></div>
            <% else %>
                <div class="column_left"><%= image_tag("#{j.link}") %></div>
            <% end %>
            <div class="column_right"><%= j.description %></div>
            <%if logged_in? %>
                <%= button_to "-", j, :method => :destroy , data: { confirm: "Sind Sie sich sicher, dass sie den Partner #{j.name} löschen wollen?" } %>
            <% end %>
</code>```

controller:

```<code>    def delete
        Partner.find(partner_params).destroy_all
        redirect_to partner_path, notice: "#Eintrag wurde gelöscht!"
    end

    def addPartner
        @partner = Partner.new(partner_params)
        if !Partner.exists?(:name => partner_params[:name])
            uploaded_io = params[:partner][:logo]
            File.open(Rails.root.join('app', 'assets', 'images', 'partner', uploaded_io.original_filename), 'wb') do |file|
              file.write(uploaded_io.read)
            @partner[:link] = "partner/#{uploaded_io.original_filename}"
            params[:partner].delete :logo
            @partner.save
            redirect_to partner_path, notice: "#{@partner.name} wurde modifiziert!"

            end
        else
          @partner = Partner.where(:name => partner_params[:name])
          if @partner.update_all(partner_params)
            flash[:notice] = "#{@partner.name} wurde geändert!"
          end
        end
      end

    private
       def partner_params
          params.require(:partner).permit(:name, :link, :description)
       end
</code>```

routes.rb:

```<code>  Rails.application.routes.draw do

  get '/login' => 'sessions#new'
  post '/login' => 'sessions#create'
  delete '/logout' => 'sessions#destroy'

  resources :users
  get '/home' => 'main#home'
  get '/impressum' => 'main#impressum'
  post '/impressum' => 'main#updateImpressumById'
  get '/partner' => 'partner#index'
  post '/partner' => 'partner#addPartner'
  delete '/partner' => 'partner#delete'
  get '/jobs' => 'jobs#index'
  post '/jobs' => 'jobs#index'
  get '/kontakt' => 'contacts#new'
  post '/home' => 'main#updateText'
  get '/referenzen' => 'reference#index'
  post '/referenzen' => 'reference#index'

  resources "contacts", only: [:new, :create]
</code>```

I want to delete an entry from my database by clicking on a button. But there must be a conflict with the "private_params".
I always got this problem:

param is missing or the value is empty: partner

I searched for similiar problems, but nothing seems to fit really.

答:
If you only want delete 1 record, use the method destroy like this :

```<code>Partner.find(params[:id]).destroy
</code>```

Now, if you want delete more than 1, use destroy_all passing a condition as an argument, like this :

```<code> Partner.destroy_all(status: 'inactive')
</code>```

So, replace destroy_all with destroyer, like this:

```<code>Partner.find(params[:id]).destroy
</code>```

I hope that helps you

Destroy_all documentation

Body:
index.html:

  <% @partners.each do |j| %>
            <% if j.link == nil %>

<%= j.name %>

            <% else %>

<%= image_tag("#{j.link}") %>

            <% end %>

<%= j.description %>

            <%if logged_in? %>
                <%= button_to "-", j, :method => :destroy , data: { confirm: "Sind Sie sich sicher, dass sie den Partner #{j.name} löschen wollen?" } %>
            <% end %>

controller:

    def delete
        Partner.find(partner_params).destroy_all
        redirect_to partner_path, notice: "#Eintrag wurde gelöscht!"
    end

    def addPartner
        @partner = Partner.new(partner_params)
        if !Partner.exists?(:name => partner_params[:name])
            uploaded_io = params[:partner][:logo]
            File.open(Rails.root.join('app', 'assets', 'images', 'partner', uploaded_io.original_filename), 'wb') do |file|
              file.write(uploaded_io.read)
            @partner[:link] = "partner/#{uploaded_io.original_filename}"
            params[:partner].delete :logo
            @partner.save
            redirect_to partner_path, notice: "#{@partner.name} wurde modifiziert!"

            end
        else
          @partner = Partner.where(:name => partner_params[:name])
          if @partner.update_all(partner_params)
            flash[:notice] = "#{@partner.name} wurde geändert!"
          end
        end
      end

    private
       def partner_params
          params.require(:partner).permit(:name, :link, :description)
       end

routes.rb:

  Rails.application.routes.draw do

  get '/login' => 'sessions#new'
  post '/login' => 'sessions#create'
  delete '/logout' => 'sessions#destroy'

  resources :users
  get '/home' => 'main#home'
  get '/impressum' => 'main#impressum'
  post '/impressum' => 'main#updateImpressumById'
  get '/partner' => 'partner#index'
  post '/partner' => 'partner#addPartner'
  delete '/partner' => 'partner#delete'
  get '/jobs' => 'jobs#index'
  post '/jobs' => 'jobs#index'
  get '/kontakt' => 'contacts#new'
  post '/home' => 'main#updateText'
  get '/referenzen' => 'reference#index'
  post '/referenzen' => 'reference#index'

  resources "contacts", only: [:new, :create]

I want to delete an entry from my database by clicking on a button. But there must be a conflict with the "private_params".
I always got this problem:

param is missing or the value is empty: partner

I searched for similiar problems, but nothing seems to fit really.

Body:
If you only want delete 1 record, use the method destroy like this :

Partner.find(params[:id]).destroy

Now, if you want delete more than 1, use destroy_all passing a condition as an argument, like this :

 Partner.destroy_all(status: 'inactive')

So, replace destroy_all with destroyer, like this:

Partner.find(params[:id]).destroy

I hope that helps you

Destroy_all documentation


问:
How do I stop a process running in IntelliJ such that it calls the shutdown hooks?
When I run my program in IntelliJ then use the STOP button, it does not call my shutdown hooks that I've created. Is there a way in IntelliJ to have those called on shutdown?</p>

答:
You need to use the Exit button in the Run panel, not the Stop button. Note that it will only work when Running and will not work when Debugging.

Here is the screenshot if you can't find it:

This feature uses platform specific code and currently works on Windows and Linux only. <s>Once IDEA-56273 is fixed, this feature should be also available on Mac.</s> It is fixed in 10.5 version of IDEA.


问:
How to access 'this' in overridden method?
I have an abstract class which exposes a method:

```<code>public abstract class Foo {
    public update(){
        //do some stuff
    }
}
</code>```

Which this class inherits from:

```<code>public class Doo extends Foo {
    public update(){
        super.update();
        const x = this.getValue(); //problem line
    }
}
</code>```

Now, since update() is exposed, it's being executed in a different context, and so that this on the "problem line" is referencing the calling object, a problem I'd normally solve by declaring update() in the abstract parent as an arrow method:

```<code>public class Foo {
    public update = () => {
       //call this all i want
    }
}
</code>```

However, if I do this, I can no longer call super() from the child class. Is there any way to call super.update() and maintain control over this?

答:
Unfortunately the best thing you can do is create two methods--one for overriding and one for public. Put implementation in the overriding method as you have it but expose a separate method using arrow functions that calls this.otherMethod(). that way you're preserving this for the public method and preserving super for the implementation.

This is not really a TypeScript issue but a JavaScript one.

Body:
I have an abstract class which exposes a method:

public abstract class Foo {
    public update(){
        //do some stuff
    }
}

Which this class inherits from:

public class Doo extends Foo {
    public update(){
        super.update();
        const x = this.getValue(); //problem line
    }
}

Now, since update() is exposed, it's being executed in a different context, and so that this on the "problem line" is referencing the calling object, a problem I'd normally solve by declaring update() in the abstract parent as an arrow method:

public class Foo {
    public update = () => {
       //call this all i want
    }
}

However, if I do this, I can no longer call super() from the child class. Is there any way to call super.update() and maintain control over this?


问:
Resharper test runner not outputting Console.WriteLine()?
Why is it that Console.Writeline() will work when executing from a console app main() method; but when I execute the same using resharpers test runner I do not see the Console.Writeline() in the test runner output window?

The best way to explain this is with an example.

I am using: Resharper Ultimate 2017.1.3, Visual Studio 2017 Community, and .Net 4.6.1 framework. Language is C#. I also installed (via nuget) nunit framework 2.6.4.

First create a class library and copy paste the following in to a .cs file.

```<code>using System;
using System.Collections;
using System.Threading;
using NUnit.Framework;

namespace ObserverPatternExample
{
    [TestFixture]
    internal class ObserverTestFixture
    {
        [Test]
        public void DemonstrateObserverPattern()
        {
            var subject = new Subject();
            var a = new Observer(subject, "a");
            var b = new Observer(subject, "b"); // etc. as many observers as you want.

            subject.Go();
        }
    }

    // "subject" is observer pattern lingo. The "subject" will do the broadcasting to the observers.
    public class Subject
    {
        public delegate void CallbackHandler(string s);
        public event CallbackHandler NotifyEvent;
        private const int waitTimeInMilliseconds = 200;
        private readonly Simulator simulator = new Simulator();
        public string FakeSimulatorState { get; set; }

        public void Go()
        {
            new Thread(Run).Start(); // a good thing to notice: events cross thread boundaries!!!
        }

        private void Run()
        {
            foreach (string s in simulator)
            {
                Console.WriteLine("Subject: " + s);
                FakeSimulatorState = s;
                NotifyEvent?.Invoke(s);
                Thread.Sleep(
                    waitTimeInMilliseconds); // we do this to "pretend" that the simulator is actually doing someting.
            }
        }

    }

    public class Observer : IObserverPattern // the "observer" will subscribe to the event being broadcast by the "subject"
    {
        private readonly string _name;
        public Observer(Subject subject, string name)
        {
            _name = name;
            subject.NotifyEvent += Update;
        }
        public void Update(string state)
        {
            Console.WriteLine("Observer {0}: {1}", _name, state);
        }
    }

    internal interface IObserverPattern
    {
        void Update(string state);
    }

    public class Simulator : IEnumerable
    {
        private readonly string[] _stateSequence = { "BEGIN", "CRAWL", "WALK", "JUMP", "END" };

        public IEnumerator GetEnumerator()
        {
            foreach (var s in _stateSequence)
                yield return s;
        }
    }
}
</code>```

And now execute the test. I expect to see the Console.WriteLine() calls display strings in the Resharper test runner output window. But I don't. For example here is a screenshot:

Now let's perform the exact same sequence, but this time we'll call the client code from a new console project main() method. To set this up copy paste the following code and reference the class library you created in the steps above.

```<code>using ObserverPatternExample;

namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var subject = new Subject();
            var a = new Observer(subject, "a");
            var b = new Observer(subject, "b"); // etc. as many observers as you want.

            subject.Go();
        }
    }
}
</code>```

Next execute the console app. You should see the following displayed:

Can anyone please explain how I can configure either my code or the test runner to display the output in the test runner output window?

* UPDATE *
I made partial success. InBetween's suggestion to use a TraceListener made me realize I should be using a ConsoleTraceListener. To faciliate this I modified the unit test to appear like this:

```<code>using System.Threading;
using NUnit.Framework;

namespace ObserverPatternExample.DontUse
{
    [TestFixture]
    internal class ObserverTestFixture
    {
        [SetUp]
        public void Setup()
        {
            Trace.Listeners.Add(new ConsoleTraceListener());
        }

        [TearDown]
        public void TearDown()
        {
            Trace.Flush();
        }

        [Test]
        public void DemonstrateObserverPattern()
        {
            var subject = new Subject();
            var a = new Observer(subject, "a");
            var b = new Observer(subject, "b"); // etc. as many observers as you want.

            subject.Go();
        }
    }
</code>```

And the results are surprising: I do get SOME output; but only the initial BEGIN state. Which appears like this:

Short story: I'm still looking for a solution.

*** SOLUTION ****

```<code>        [Test]
        public void DemonstrateObserverPattern()
        {
            var subject = new Subject();
            var a = new Observer(subject, "a");
            var b = new Observer(subject, "b"); // etc. as many observers as you want.

            subject.Go();

Thread.Sleep(1000); // <--- add this to force test runner to wait for other thread to complete.
        }
</code>```

答:
It looks like Resharper is finishing before your thread completes. Your call to

```<code>Thread(Run).Start();
</code>```

is non-blocking. This means the test thread will complete before the Go thread does, hence you get no results.

See https://msdn.microsoft.com/en-us/library/6x4c42hc(v=vs.110).aspx where is states "Note that the call to Start does not block the calling thread."

Body:
Why is it that Console.Writeline() will work when executing from a console app main() method; but when I execute the same using resharpers test runner I do not see the Console.Writeline() in the test runner output window?

The best way to explain this is with an example.

I am using: Resharper Ultimate 2017.1.3, Visual Studio 2017 Community, and .Net 4.6.1 framework. Language is C#. I also installed (via nuget) nunit framework 2.6.4.

First create a class library and copy paste the following in to a .cs file.

using System;
using System.Collections;
using System.Threading;
using NUnit.Framework;

namespace ObserverPatternExample
{
    [TestFixture]
    internal class ObserverTestFixture
    {
        [Test]
        public void DemonstrateObserverPattern()
        {
            var subject = new Subject();
            var a = new Observer(subject, "a");
            var b = new Observer(subject, "b"); // etc. as many observers as you want.

            subject.Go();
        }
    }

    // "subject" is observer pattern lingo. The "subject" will do the broadcasting to the observers.
    public class Subject
    {
        public delegate void CallbackHandler(string s);
        public event CallbackHandler NotifyEvent;
        private const int waitTimeInMilliseconds = 200;
        private readonly Simulator simulator = new Simulator();
        public string FakeSimulatorState { get; set; }

        public void Go()
        {
            new Thread(Run).Start(); // a good thing to notice: events cross thread boundaries!!!
        }

        private void Run()
        {
            foreach (string s in simulator)
            {
                Console.WriteLine("Subject: " + s);
                FakeSimulatorState = s;
                NotifyEvent?.Invoke(s);
                Thread.Sleep(
                    waitTimeInMilliseconds); // we do this to "pretend" that the simulator is actually doing someting.
            }
        }

    }

    public class Observer : IObserverPattern // the "observer" will subscribe to the event being broadcast by the "subject"
    {
        private readonly string _name;
        public Observer(Subject subject, string name)
        {
            _name = name;
            subject.NotifyEvent += Update;
        }
        public void Update(string state)
        {
            Console.WriteLine("Observer {0}: {1}", _name, state);
        }
    }

    internal interface IObserverPattern
    {
        void Update(string state);
    }

    public class Simulator : IEnumerable
    {
        private readonly string[] _stateSequence = { "BEGIN", "CRAWL", "WALK", "JUMP", "END" };

        public IEnumerator GetEnumerator()
        {
            foreach (var s in _stateSequence)
                yield return s;
        }
    }
}

And now execute the test. I expect to see the Console.WriteLine() calls display strings in the Resharper test runner output window. But I don't. For example here is a screenshot:

Now let's perform the exact same sequence, but this time we'll call the client code from a new console project main() method. To set this up copy paste the following code and reference the class library you created in the steps above.

using ObserverPatternExample;

namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var subject = new Subject();
            var a = new Observer(subject, "a");
            var b = new Observer(subject, "b"); // etc. as many observers as you want.

            subject.Go();
        }
    }
}

Next execute the console app. You should see the following displayed:

Can anyone please explain how I can configure either my code or the test runner to display the output in the test runner output window?

* UPDATE *
I made partial success. InBetween's suggestion to use a TraceListener made me realize I should be using a ConsoleTraceListener. To faciliate this I modified the unit test to appear like this:

using System.Threading;
using NUnit.Framework;

namespace ObserverPatternExample.DontUse
{
    [TestFixture]
    internal class ObserverTestFixture
    {
        [SetUp]
        public void Setup()
        {
            Trace.Listeners.Add(new ConsoleTraceListener());
        }

        [TearDown]
        public void TearDown()
        {
            Trace.Flush();
        }

        [Test]
        public void DemonstrateObserverPattern()
        {
            var subject = new Subject();
            var a = new Observer(subject, "a");
            var b = new Observer(subject, "b"); // etc. as many observers as you want.

            subject.Go();
        }
    }

And the results are surprising: I do get SOME output; but only the initial BEGIN state. Which appears like this:

Short story: I'm still looking for a solution.

*** SOLUTION ****

        [Test]
        public void DemonstrateObserverPattern()
        {
            var subject = new Subject();
            var a = new Observer(subject, "a");
            var b = new Observer(subject, "b"); // etc. as many observers as you want.

            subject.Go();

Thread.Sleep(1000); // <--- add this to force test runner to wait for other thread to complete.
        }

Body:
It looks like Resharper is finishing before your thread completes. Your call to

Thread(Run).Start();

is non-blocking. This means the test thread will complete before the Go thread does, hence you get no results.

See https://msdn.microsoft.com/en-us/library/6x4c42hc(v=vs.110).aspx where is states "Note that the call to Start does not block the calling thread."


答:
If you just want to show the first and hide all the next, a posibility is using 'first-child' css pseudo class:

.slider-inner img {
  display: none; /*all the images are not displayed*/
}

.slider-inner img:first-child {
  display: inline-block; /*just the first image will be displayed*/
}
```

Title: ejs: Only add class 'active' to first image of image gallery


问:
Laravel Testing Increasing Memory Use
```<code>Time: 1.89 minutes, Memory: 526.00MB

OK (487 tests, 2324 assertions)
</code>```

This is my phpunittest result from testing my Laravel API, the memory consumption just keeps increasing and feel like i tried all posts and answers across the internet for what keeps racking up memory when testing. From own debugging the App is trashed every test which it should.

Everything is pretty standard, with the createApplication method that looks like this.

```<code>public function createApplication()
{
    // Ran out of memory
    ini_set('memory_limit', '1024M');

    $app = require __DIR__ . '/../bootstrap/app.php';

    $app->make(Kernel::class)->bootstrap();

    return $app;
}
</code>```

Came to the conclusion that the memory leak is in, which does not get cleaned up properly.

```<code>$app = require __DIR__ . '/../bootstrap/app.php';

$app->make(Kernel::class)->bootstrap();
</code>```

答:
Here is a simple solution. I tested it in Laravel 5.5. Set this as the content of the tests/CreatesApplication.php file:

```<code>namespace Tests;

use Illuminate\Contracts\Console\Kernel;

trait CreatesApplication
{
    /**
     * @var \Illuminate\Foundation\Application
     */
    protected static $application;

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        if (!isset(static::$application)) {
            static::$application = require __DIR__ . '/../bootstrap/app.php';
            static::$application->make(Kernel::class)->bootstrap();
        }

        return static::$application;
    }

    /**
     * {@inheritDoc}
     */
    protected function tearDown()
    {
        // Required if you use HTTP tests
        $this->app['auth']->guard(null)->logout();
        $this->app['auth']->shouldUse(null);
        $this->flushSession();

        // Always required
        $this->app = null;
        parent::tearDown();
    }
}
</code>```

This code makes tests use the same Laravel application instance for all tests instead of creating a new instance for each test. Also this causes a faster testing run.

This solution has disadvantages:

If a test modifies the application, the other tests can fail because they expect an unaltered application.

If a test uses the DatabaseTransactions or the DatabaseMigrations trait, the database is reset when all the test of a PHPUnit test run has finished.

Title: Laravel Testing Increasing Memory Use

Body:
Time: 1.89 minutes, Memory: 526.00MB

OK (487 tests, 2324 assertions)

This is my phpunittest result from testing my Laravel API, the memory consumption just keeps increasing and feel like i tried all posts and answers across the internet for what keeps racking up memory when testing. From own debugging the App is trashed every test which it should.

Everything is pretty standard, with the createApplication method that looks like this.

public function createApplication()
{
    // Ran out of memory
    ini_set('memory_limit', '1024M');

    $app = require __DIR__ . '/../bootstrap/app.php';

    $app->make(Kernel::class)->bootstrap();

    return $app;
}

Came to the conclusion that the memory leak is in, which does not get cleaned up properly.

$app = require __DIR__ . '/../bootstrap/app.php';

$app->make(Kernel::class)->bootstrap();

Body:
Here is a simple solution. I tested it in Laravel 5.5. Set this as the content of the tests/CreatesApplication.php file:

namespace Tests;

use Illuminate\Contracts\Console\Kernel;

trait CreatesApplication
{
    /**
     * @var \Illuminate\Foundation\Application
     */
    protected static $application;

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        if (!isset(static::$application)) {
            static::$application = require __DIR__ . '/../bootstrap/app.php';
            static::$application->make(Kernel::class)->bootstrap();
        }

        return static::$application;
    }

    /**
     * {@inheritDoc}
     */
    protected function tearDown()
    {
        // Required if you use HTTP tests
        $this->app['auth']->guard(null)->logout();
        $this->app['auth']->shouldUse(null);
        $this->flushSession();

        // Always required
        $this->app = null;
        parent::tearDown();
    }
}

This code makes tests use the same Laravel application instance for all tests instead of creating a new instance for each test. Also this causes a faster testing run.

This solution has disadvantages:

If a test modifies the application, the other tests can fail because they expect an unaltered application.

If a test uses the DatabaseTransactions or the DatabaseMigrations trait, the database is reset when all the test of a PHPUnit test run has finished.


问:
Convert hyperlink
I am trying to write a python function and convert markdown format link like: [text] (link), into  tags in HTML. For example:

link(line)

```<code>link("Here is the link [Social Science Illustrated](https://en.wikipedia.org/wiki/Social_Science_Illustrated) I gave you yesterday.")

"Here is the link <a href="https://en.wikipedia.org/wiki/Social_Science_Illustrated">Social Science Illustrated</a> I gave you yesterday."
</code>```

And my code for now is:

```<code>def link(line):
  import re
  urls = re.compile(r"((https?):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)")
  line = urls.sub(r'<a href="\1"></a>', line)
  return line
</code>```

Output:

```<code>=> 'Here is the link [Social Science Illustrated] ( <a href="https://en.wikipedia.org/wiki/Social_Science_Illustrated"></a> ) I gave you yesterday.'
</code>```

So I was wondering how to convert [text] part into correct position?

答:
If you just need to convert based on the [text](link) syntax:

```<code>def link(line):
  import re
  urls = re.compile(r'\[([^\]]*)]\(([^\)]*)\)')
  line = urls.sub(r'<a href="\2">\1</a>', line)
  return line
</code>```

You don't have to validate the link. Any decent browser will not render it as a link.

Title: Convert hyperlink

Body:
I am trying to write a python function and convert markdown format link like: [text] (link), into  tags in HTML. For example:

link(line)

link("Here is the link [Social Science Illustrated](https://en.wikipedia.org/wiki/Social_Science_Illustrated) I gave you yesterday.")

"Here is the link Social Science Illustrated I gave you yesterday."

And my code for now is:

def link(line):
  import re
  urls = re.compile(r"((https?):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)")
  line = urls.sub(r'', line)
  return line

Output:

=> 'Here is the link [Social Science Illustrated] (  ) I gave you yesterday.'

So I was wondering how to convert [text] part into correct position?

Body:
If you just need to convert based on the [text](link) syntax:

def link(line):
  import re
  urls = re.compile(r'\[([^\]]*)]\(([^\)]*)\)')
  line = urls.sub(r'<a href="\2">\1</a>', line)
  return line

You don't have to validate the link. Any decent browser will not render it as a link.


问:
animate jquery working only once
I am trying to use a simple animation feature of jquery. In my application, I have two button " Slide Right" and "Slide Left". When we click on these buttons, these move the box to left or right respectively. My move right button is working perfectly but my move right button is working only once. What's wrong with my code? Here's my code:

$(document).ready(function() {

  $("#slideRightButton").click(function() {
    $("#boxToBeMoved").animate({
      left: '+=10%'
    });
  });

  $("#slideLeftButton").click(function() {
    $("#boxToBeMoved").animate({
      right: '+=10%'
    });
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<button id="slideRightButton">Slide Right</button>
<button id="slideLeftButton">Slide Left</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>

<div id="boxToBeMoved" style="background:#98bf21;height:100px;width:100px;position:absolute;"></div></code>```

The above code is just an extension of the jquery tutorial by W3Schools which can be found here

答:
You are changing the left and right property of the box, It looks like the right property is taking precedence and preventing the left from doing anything.

If you make both use the same property, one adding to it and the other subtracting, it should work.

```<code>$("#slideRightButton").click(function(){
    $("div").animate({left: '+=10%'});
});
$("#slideLeftButton").click(function(){
    $("#boxToBeMoved").animate({left: '-=10%'});
});
</code>```

Title: animate jquery working only once

Body:
I am trying to use a simple animation feature of jquery. In my application, I have two button " Slide Right" and "Slide Left". When we click on these buttons, these move the box to left or right respectively. My move right button is working perfectly but my move right button is working only once. What's wrong with my code? Here's my code:

$(document).ready(function() {

  $("#slideRightButton").click(function() {
    $("#boxToBeMoved").animate({
      left: '+=10%'
    });
  });

  $("#slideLeftButton").click(function() {
    $("#boxToBeMoved").animate({
      right: '+=10%'
    });
  });

});

<button id="slideRightButton">Slide Right</button>
<button id="slideLeftButton">Slide Left</button>

By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!

The above code is just an extension of the jquery tutorial by W3Schools which can be found here

Body:
You are changing the left and right property of the box, It looks like the right property is taking precedence and preventing the left from doing anything.

If you make both use the same property, one adding to it and the other subtracting, it should work.

$("#slideRightButton").click(function(){
    $("div").animate({left: '+=10%'});
});
$("#slideLeftButton").click(function(){
    $("#boxToBeMoved").animate({left: '-=10%'});
});


问:
Read boolean values from DB?
In C#, using SqlDataReader, is there a way to read a boolean value from the DB?

```<code>while (reader.Read())
{
    destPath = reader["destination_path"].ToString();
    destFile = reader["destination_file"].ToString();
    createDir = reader["create_directory"].ToString();
    deleteExisting = Convert.ToBoolean(reader["delete_existing"]);
    skipIFolderDate = reader["skipifolderdate"].ToString();
    useTempFile = reader["useTempFile"].ToString();
    password = reader["password"].ToString();
}
</code>```

In the code above, delete_existing is always a 1 or 0 in the DB. I read on MSDN that Convert.ToBoolean() does not accept a 1 or 0 as valid input. It only accepts true or false. Is there an alternative way to convert a DB value to a bool? Or do I need to do this outside of the SqlDataReader?

Also, I can not change the DB values, so please no answers saying, "Change the DB values from 1's and 0's to true's and false's."

Thanks!

答:
If you are using CASE in SELECT and want to use GetBoolean then use CAST to change the column to bit before reading.

For eg:

```<code>SELECT CAST((CASE WHEN [Condition] THEN 1 ELSE 0 END) as bit) FROM Table_Name
</code>```

then you can use

```<code>reader.GetBoolean(0)
</code>```

Title: Read boolean values from DB?

Body:
In C#, using SqlDataReader, is there a way to read a boolean value from the DB?

while (reader.Read())
{
    destPath = reader["destination_path"].ToString();
    destFile = reader["destination_file"].ToString();
    createDir = reader["create_directory"].ToString();
    deleteExisting = Convert.ToBoolean(reader["delete_existing"]);
    skipIFolderDate = reader["skipifolderdate"].ToString();
    useTempFile = reader["useTempFile"].ToString();
    password = reader["password"].ToString();
}

In the code above, delete_existing is always a 1 or 0 in the DB. I read on MSDN that Convert.ToBoolean() does not accept a 1 or 0 as valid input. It only accepts true or false. Is there an alternative way to convert a DB value to a bool? Or do I need to do this outside of the SqlDataReader?

Also, I can not change the DB values, so please no answers saying, "Change the DB values from 1's and 0's to true's and false's."

Thanks!

Body:
If you are using CASE in SELECT and want to use GetBoolean then use CAST to change the column to bit before reading.

For eg:

SELECT CAST((CASE WHEN [Condition] THEN 1 ELSE 0 END) as bit) FROM Table_Name

then you can use

reader.GetBoolean(0)


问:
Android Studio 3 does not run tests in Spock
I updated Android Studio to version 3 and since then all my spock tests, when in a java module, do not run when trying to run them from inside the application (right click on groovy folder -> Run 'Tests in groovy'). I get a:

Class not found: "package.name.classname"Empty test suite."

Same if I try to run a single test.

If I run the test task from the gradle panel I get this:
error. Cause: unknown.

On the other hand:

Any spock tests in android modules run fine.

All my java tests in all my modules run fine.

All my tests (spock and java) run fine when running them from outside AS using gradle (gradlew clean test).

My setup:

gradle v4.1

android gradle plugin v3.0.0

java version compatibility v1.8

in my java modules i use the gradle groovy plugin

in my android modules i use the groovy android gradle plugin

A few things I tried after searching in both google and here:

changing the android gradle plugin back to v2.3.3 and gradle to v3.3

trying to copy all groovy classes to build/classes/java/test

答:
So this is more of a workaround than an actual solution but it should give you your debugger back which is probably 90% of the value anyway:

You can run your test suite like:

```<code>./gradlew <module>:test --debug-jvm
</code>```

And the jvm running your tests will suspend until a debugger attaches.

From Android Studio bring up the action chooser by pressing ctrl + shift + a (on linux anyway, check the equivalent for your OS) and select:

Attach to local process...

Once Android Studio attaches the tests will begin running.

The --debug-jvm flag can be used together with --tests to debug an individual test:

```<code>./gradlew <module>:test --tests fully.qualified.test.Test --debug-jvm
</code>```

Body:
So this is more of a workaround than an actual solution but it should give you your debugger back which is probably 90% of the value anyway:

You can run your test suite like:

./gradlew <module>:test --debug-jvm

And the jvm running your tests will suspend until a debugger attaches.

From Android Studio bring up the action chooser by pressing ctrl + shift + a (on linux anyway, check the equivalent for your OS) and select:

Attach to local process...

Once Android Studio attaches the tests will begin running.

The --debug-jvm flag can be used together with --tests to debug an individual test:

./gradlew <module>:test --tests fully.qualified.test.Test --debug-jvm


问:
I need help figuring out how this program from my proffesor works
I've gotten assigned a program that we need to edit parts of, but for the life of me I cant get it to work in the first place. I know it's me just being dumb, so I was hoping someone could help me out. </p>

<p>I know it works through a web browser but I just cant figure out how to work it, cause I dont see any inputs or things like that. </p>

```<code>    # -------------------------------------------------------------------------------
# Name:        Hello World Server
# Purpose:     ¯\_(ツ)_/¯
#
# Author:      JaredRand
#
# Created:     11/1/17
# Copyright:
# Licence:
# -------------------------------------------------------------------------------

from socket import *

def main():
    serverPort = 8080
    serverSocket = socket(AF_INET, SOCK_STREAM)
    serverSocket.bind(('localhost', serverPort))
    serverSocket.listen(0)  # number of backlogged connections
    print('server ready')
    while 1:

        try:
            connectionSocket, addr = serverSocket.accept()  # make everything after this a function?
            print('passed try 1')
        except IOError:
            print("Server Socket Accept Error")

        try:
            request = connectionSocket.recv(1024).decode('utf-8')
            print('passed try 2')
            print(request)
        except IOError:
            print("Server Socket Recv Error")

        if request:
            # https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html
            try:

                [Method, Request_URI, HHTP_Version] = request.split(' ', 2)
                print('passed try 3')
                print(Method)
                print(Request_URI)
                print(HHTP_Version)
            except ValueError:
                print("Request Parse Error:" + request)

            try:
                # https://www.ietf.org/rfc/rfc2396.txt
                [scheme, hier_part] = Request_URI.split(":", 1)
                print('passed try 4')
                print(scheme)
                print(hier_part)
            except ValueError:
                print("No Scheme")
                scheme = None
                hier_part = Request_URI

            # more parsing is required but assuming the Request_URI is a path
            print("Request URI is: " + hier_part)

            # see if the file is present
            if hier_part != "/":
                try:
                    print("Request File is: " + hier_part)
                    fo = open('.' + hier_part, "rb")
                except IOError:
                    # here need to send a 404 error
                    http_status = 'HTTP/1.1 404 Not Found\n'
                    http_content = 'Content-Type: text/html charset=utf-8\n\n'
                    outputdata = 'Bad File'
                else:
                    # right now only file we have is the icon
                    outputdata = fo.read()
                    fo.close()
                    http_status = 'HTTP/1.1 200 OK\n'
                    http_content = 'Content-Type: image/x-icon\n\n'
            else:
                # here we would the contents of index.html
                outputdata = '<!DOCTYPE html><head><meta charset="utf-8">' \
                             + '<title> test </title></head><body><h1>Index File</h1><p>Should be index</p></body></html>'
                http_status = 'HTTP/1.1 200 OK\n'
                http_content = 'Content-Type: text/html charset=utf-8\n\n'

            # send the response header

            connectionSocket.send(http_status.encode('utf-8'))
            connectionSocket.send('Connection: close\n'.encode('utf-8'))
            # https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html Should
            LengthString = 'Content-Length: ' + str(len(outputdata)) + '\n'
            # connectionSocket.send('Transfer-Encoding: identity\n')
            connectionSocket.send(LengthString.encode('utf-8'))
            connectionSocket.send(http_content.encode('utf-8'))

            print(type(outputdata))
            try:
                outputdatae = outputdata.encode('utf-8')
            except AttributeError:
                outputdatae = outputdata

            connectionSocket.send(outputdatae)

            connectionSocket.shutdown(SHUT_RDWR)
            connectionSocket.close()
        else:
            print("No Request")

    pass

if __name__ == '__main__':
    main()
</code>```

答:
This is a Python script that starts a web server.

Install Python for your operating system (if needed)

Save the file as webserver.py

Run the Python script python webserver.py

Open a web browser and go to http://localhost:8080/

Body:
I've gotten assigned a program that we need to edit parts of, but for the life of me I cant get it to work in the first place. I know it's me just being dumb, so I was hoping someone could help me out.

I know it works through a web browser but I just cant figure out how to work it, cause I dont see any inputs or things like that.

    # -------------------------------------------------------------------------------
# Name:        Hello World Server
# Purpose:     ¯\_(ツ)_/¯
#
# Author:      JaredRand
#
# Created:     11/1/17
# Copyright:
# Licence:
# -------------------------------------------------------------------------------

from socket import *

def main():
    serverPort = 8080
    serverSocket = socket(AF_INET, SOCK_STREAM)
    serverSocket.bind(('localhost', serverPort))
    serverSocket.listen(0)  # number of backlogged connections
    print('server ready')
    while 1:

        try:
            connectionSocket, addr = serverSocket.accept()  # make everything after this a function?
            print('passed try 1')
        except IOError:
            print("Server Socket Accept Error")

        try:
            request = connectionSocket.recv(1024).decode('utf-8')
            print('passed try 2')
            print(request)
        except IOError:
            print("Server Socket Recv Error")

        if request:
            # https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html
            try:

                [Method, Request_URI, HHTP_Version] = request.split(' ', 2)
                print('passed try 3')
                print(Method)
                print(Request_URI)
                print(HHTP_Version)
            except ValueError:
                print("Request Parse Error:" + request)

            try:
                # https://www.ietf.org/rfc/rfc2396.txt
                [scheme, hier_part] = Request_URI.split(":", 1)
                print('passed try 4')
                print(scheme)
                print(hier_part)
            except ValueError:
                print("No Scheme")
                scheme = None
                hier_part = Request_URI

            # more parsing is required but assuming the Request_URI is a path
            print("Request URI is: " + hier_part)

            # see if the file is present
            if hier_part != "/":
                try:
                    print("Request File is: " + hier_part)
                    fo = open('.' + hier_part, "rb")
                except IOError:
                    # here need to send a 404 error
                    http_status = 'HTTP/1.1 404 Not Found\n'
                    http_content = 'Content-Type: text/html charset=utf-8\n\n'
                    outputdata = 'Bad File'
                else:
                    # right now only file we have is the icon
                    outputdata = fo.read()
                    fo.close()
                    http_status = 'HTTP/1.1 200 OK\n'
                    http_content = 'Content-Type: image/x-icon\n\n'
            else:
                # here we would the contents of index.html
                outputdata = '<!DOCTYPE html><meta charset="utf-8">' \
                             + '<title> test </title>
Index File

Should be index
'
                http_status = 'HTTP/1.1 200 OK\n'
                http_content = 'Content-Type: text/html charset=utf-8\n\n'

            # send the response header

            connectionSocket.send(http_status.encode('utf-8'))
            connectionSocket.send('Connection: close\n'.encode('utf-8'))
            # https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html Should
            LengthString = 'Content-Length: ' + str(len(outputdata)) + '\n'
            # connectionSocket.send('Transfer-Encoding: identity\n')
            connectionSocket.send(LengthString.encode('utf-8'))
            connectionSocket.send(http_content.encode('utf-8'))

            print(type(outputdata))
            try:
                outputdatae = outputdata.encode('utf-8')
            except AttributeError:
                outputdatae = outputdata

            connectionSocket.send(outputdatae)

            connectionSocket.shutdown(SHUT_RDWR)
            connectionSocket.close()
        else:
            print("No Request")

    pass

if __name__ == '__main__':
    main()


问:
map array of objects into map grouped by object key js immutable
i want to map an array of object to output Immutable Map that is grouped by specific object key.

```<code>array looks like
[
 {id:1, time:19072016},
 {id:2, time:19072016},
 {id:3, time:19072015},
]
output im seeking is
[
 byId: {
  1:{id:1, time:19072016},
  2:{id:2, time:19072016},
  3:{id:3, time:19072015},
 },
 byTime: {
  19072016:[1,2],
  19072015:[3],
 }
]
</code>```

what is most effective way to do it using immutablejs or seamless-immutable ?

currently im using reduce as :

```<code>array.reduce( (final,row) =>final.setIn(['byId',row.id],row) ,
              Immutable.Map({byId:{},byTime:{}});
</code>```

this output byIds as i want it, but problem with byTime is that i need to merge not overwrite.

i tried with seamless-immutable i did:

```<code>Seamless(arr).toObject(i=>[i.id,i]) //this will return byId as i want it
Seamless(arr).toObject(i=>[i.time,[i.id]]) //this will not merge [1,2] :(
</code>```

答:
You can get what you want by using .groupBy() and .map().

const data = Immutable.fromJS([
  {id:1, time:19072016},
  {id:2, time:19072016},
  {id:3, time:19072015},
]);

const byId = data
  .groupBy(item => item.get('id'))
  .map(items => items.first());
console.log(byId);

const byTime = data
  .groupBy(item => item.get('time'))
  .map(items => items.map(item => item.get('id')));
console.log(byTime);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script></code>```

Body:
i want to map an array of object to output Immutable Map that is grouped by specific object key.

array looks like
[
 {id:1, time:19072016},
 {id:2, time:19072016},
 {id:3, time:19072015},
]
output im seeking is
[
 byId: {
  1:{id:1, time:19072016},
  2:{id:2, time:19072016},
  3:{id:3, time:19072015},
 },
 byTime: {
  19072016:[1,2],
  19072015:[3],
 }
]

what is most effective way to do it using immutablejs or seamless-immutable ?

currently im using reduce as :

array.reduce( (final,row) =>final.setIn(['byId',row.id],row) ,
              Immutable.Map({byId:{},byTime:{}});

this output byIds as i want it, but problem with byTime is that i need to merge not overwrite.

i tried with seamless-immutable i did:

Seamless(arr).toObject(i=>[i.id,i]) //this will return byId as i want it
Seamless(arr).toObject(i=>[i.time,[i.id]]) //this will not merge [1,2] :(

Body:
You can get what you want by using .groupBy() and .map().

const data = Immutable.fromJS([
  {id:1, time:19072016},
  {id:2, time:19072016},
  {id:3, time:19072015},
]);

const byId = data
  .groupBy(item => item.get('id'))
  .map(items => items.first());
console.log(byId);

const byTime = data
  .groupBy(item => item.get('time'))
  .map(items => items.map(item => item.get('id')));
console.log(byTime);

<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>


问:
How can Greasemonkey copy the contents of a certain div, to the clipboard?
I am trying to make a script that copies the contents of a certain div, and put it into the clipboard (ready to paste). This div is within a site (Shopify), which I cannot modify.

```<code><ul class="next-list next-list--plain-divided" id="line-item-properties" refresh="line-item-properties">
<li class="type--breakall">
    <div class="next-grid next-grid--compact next-grid--no-outside-padding next-grid--vertically-centered">

        <div class="next-grid__cell">
            <div class="wrappable wrappable--no-spacing">
                <div class="wrappable__item wrappable__item--no-flex">
                    <p class="type--subdued">Custom Text:</p>
                </div>
                <div class="wrappable__item">
                    IWANTTHISTEXT
                </div>
            </div>
        </div>

        <div class="next-grid__cell next-grid__cell--no-flex hide-when-printing">
            <a href="/admin/orders/170903371809/delete_property?line_item_id=332788334625&property_key=Custom+Text"
              class="btn btn--link" data-tg-remote="delete" data-refresh-on-success="line-item-properties"
            >
                <svg class="next-icon next-icon--color-ink-lighter next-icon--size-20">
                    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#delete-minor"></use>
                </svg>
            </a>
        </div>

    </div>
</li>
</code>```

So I want the area of text that says "IWANTTHISTEXT".

So far I have attempted multiple strategies and come up with nothing! Any help would be appreciated.

答:
You would use GM_setClipboard().

For a static page:

```<code>// ==UserScript==
// @name     _AutoClipboard, get item text
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant    GM_setClipboard
// ==/UserScript==

var targText = $(".wrappable__item").text ().trim ();

console.log ("Copied to clipboard: ", targText);
GM_setClipboard (targText);
</code>```

Note that if there is more than one wrappable__item node, it will mash their text all together and return one long string to the clipboard.

For a dynamic (AJAX-driven) page:

```<code>// ==UserScript==
// @name     _AutoClipboard, get item text
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_setClipboard
// ==/UserScript==

waitForKeyElements (".wrappable__item", getNodeText);

function getNodeText (jNode) {
    var targText = jNode.text ().trim ();

    console.log ("Copied to clipboard: ", targText);
    GM_setClipboard (targText);
}
</code>```

For this, if there is more than one wrappable__item node, the clipboard will only end up with the text for the last one.

Body:
I am trying to make a script that copies the contents of a certain div, and put it into the clipboard (ready to paste). This div is within a site (Shopify), which I cannot modify.

Custom Text:

                    IWANTTHISTEXT

                <svg class="next-icon next-icon--color-ink-lighter next-icon--size-20">
                    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#delete-minor"></use>
                </svg>

So I want the area of text that says "IWANTTHISTEXT".

So far I have attempted multiple strategies and come up with nothing! Any help would be appreciated.

Body:
You would use GM_setClipboard().

For a static page:

// ==UserScript==
// @name     _AutoClipboard, get item text
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant    GM_setClipboard
// ==/UserScript==

var targText = $(".wrappable__item").text ().trim ();

console.log ("Copied to clipboard: ", targText);
GM_setClipboard (targText);

Note that if there is more than one wrappable__item node, it will mash their text all together and return one long string to the clipboard.

For a dynamic (AJAX-driven) page:

// ==UserScript==
// @name     _AutoClipboard, get item text
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_setClipboard
// ==/UserScript==

waitForKeyElements (".wrappable__item", getNodeText);

function getNodeText (jNode) {
    var targText = jNode.text ().trim ();

    console.log ("Copied to clipboard: ", targText);
    GM_setClipboard (targText);
}

For this, if there is more than one wrappable__item node, the clipboard will only end up with the text for the last one.


答: It works fine, run the program then go to the port and you should see

Title: I need help figuring out how this program from my proffesor works


问:
How to cast array<int> to string in hive?
I have a column of type array<bigint> (say of value [1,2,3,4]), and I want to convert it to string (say "1,2,3,4"), how can I do that?

I tried concat_ws(',' arr), but it complains

```<code>Argument 2 of function CONCAT_WS must be "string or array<string>", but "array<bigint>" was found."
</code>```

Is there a way to cast array<bigint> to array<string>?

答:
Try this:</p>

```<code>select xx,concat_ws(',',collect_set(cast(element as string))) as arrystr
from table
lateral view explode(arr) b as element
group by xx
</code>```

Body:
I have a column of type array<bigint> (say of value [1,2,3,4]), and I want to convert it to string (say "1,2,3,4"), how can I do that?

I tried concat_ws(',' arr), but it complains

Argument 2 of function CONCAT_WS must be "string or array<string>", but "array<bigint>" was found."

Is there a way to cast array<bigint> to array<string>?

Body:
Try this:

select xx,concat_ws(',',collect_set(cast(element as string))) as arrystr
from table
lateral view explode(arr) b as element
group by xx


问:
Making ajax call and showing contents in qtip
I am writing code for a dropdown list. The dropdown list is being populated from the data from the database. So I am making 2 ajax calls one is on event onmouseover to populate the contents of dropdown list and the other on selection of specific option making ajax call to bring related contents on the screen.

Now I want to make another ajax call to get the contents which can be populated on hovering over the specific option. The contents got from ajax call can be displayed in the small dialog box. For achieving this I have installed the qtip libraries.

Problem

I am not getting how the ajax call be made. Which even will be appropriate for achieving this? I know the qtip is loaded onload of the page. But since I want to make ajax call to get the contents of the message to be shown on hovering over the option. Any suggestions?

I have also read somewhere that you can't make more than 2 ajax calls at a time.

** The contents for the 3 ajax calls are different. And I have separate JSP files for each of them.

答:
When you make your AJAX call to get the dropdown list content, you can also return the descriptions you want to display for each list item and affect them to the corresponding qtip.

The qtip will show onmouseover, and with the description you have set when populating your dropdown list.

ContentLicense: CC BY-SA 2.5


答:
Updated to include author's request to not exceed the maximum width.

To accomplish this, I included a wrapper div with a fixed width.

When sliding to the right, it checks if the value will be bigger than parent's width and, if positive, returns.

Same when sliding to the left, but it returns if the value is negative, preventing the box to slide outside the limits of the parent div.

$(document).ready(function() {

  const slideVal = 30; // slide value (in pixels)

  $("#slideRightButton").click(function() {
    var box = $("#boxToBeMoved");
    if (parseInt(box.css("left")) + slideVal > parseInt(box.parent().width())) return;
    box.animate({
      left: '+=' + slideVal
    });
  });

  $("#slideLeftButton").click(function() {
    var box = $("#boxToBeMoved");
    if (parseInt(box.css("left")) - slideVal < 0) return;
    box.animate({
      left: '-=' + slideVal
    });
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<button id="slideRightButton">Slide Right</button>
<button id="slideLeftButton">Slide Left</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>

<div id="wrapper" style="width: 200px">
  <div id="boxToBeMoved" style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</div></code>```

Title: animate jquery working only once

Body:
Updated to include author's request to not exceed the maximum width.

To accomplish this, I included a wrapper div with a fixed width.

When sliding to the right, it checks if the value will be bigger than parent's width and, if positive, returns.

Same when sliding to the left, but it returns if the value is negative, preventing the box to slide outside the limits of the parent div.

$(document).ready(function() {

  const slideVal = 30; // slide value (in pixels)

  $("#slideRightButton").click(function() {
    var box = $("#boxToBeMoved");
    if (parseInt(box.css("left")) + slideVal > parseInt(box.parent().width())) return;
    box.animate({
      left: '+=' + slideVal
    });
  });

  $("#slideLeftButton").click(function() {
    var box = $("#boxToBeMoved");
    if (parseInt(box.css("left")) - slideVal < 0) return;
    box.animate({
      left: '-=' + slideVal
    });
  });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<button id="slideRightButton">Slide Right</button>
<button id="slideLeftButton">Slide Left</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>

<div id="wrapper" style="width: 200px">
  <div id="boxToBeMoved" style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</div>


问:
Angular 4 | how to format date using pipe?
Good day,

how can i format my date using pipe in angular? im having trouble on it since it always return wrong date.

Below is how i format my date.

Actual value
20170901

```<code><span>{{apidata.DeliveryDate | date: 'yyyy-MM-dd'}}</span>
</code>```

it returns (1970-01-01)

how can i fix this?

答:
DatePipe converts a Date object or date saved in ISO string. What you are trying to format is a number (that's a real backend design issue)... You can convert your date into real format, e.g. by using moment library:

```<code>apidata.deliveryDate = moment(apidata.DeliveryDate, 'YYYYMMDD').toISOString();
</code>```

And then it will work. You can also create custom pipe that will convert and format the "date" for you. Example code for in-component solution:

```<code>// regular imports
import * as moment from 'moment';

@Component({
  template: `<span>{{apidata.deliveryDate | date: 'yyyy-MM-dd'}}</span>`
})
export class SomeComponent {
  apidata: any;

  constructor(someService: SomeService) { // <-- this is a service you get your data from
    this.someService.getApiData().subscribe((apidata) => {
      this.apidata = apidata;
      this.apidata.deliveryDate = moment(apidata.DeliveryDate, 'YYYYMMDD').toISOString();
    }
  }
}
</code>```

Body:
Good day,

how can i format my date using pipe in angular? im having trouble on it since it always return wrong date.

Below is how i format my date.

Actual value
20170901

{{apidata.DeliveryDate | date: 'yyyy-MM-dd'}}

it returns (1970-01-01)

how can i fix this?

Body:
DatePipe converts a Date object or date saved in ISO string. What you are trying to format is a number (that's a real backend design issue)... You can convert your date into real format, e.g. by using moment library:

apidata.deliveryDate = moment(apidata.DeliveryDate, 'YYYYMMDD').toISOString();

And then it will work. You can also create custom pipe that will convert and format the "date" for you. Example code for in-component solution:

// regular imports
import * as moment from 'moment';

@Component({
  template: `<span>{{apidata.deliveryDate | date: 'yyyy-MM-dd'}}</span>`
})
export class SomeComponent {
  apidata: any;

  constructor(someService: SomeService) { // <-- this is a service you get your data from
    this.someService.getApiData().subscribe((apidata) => {
      this.apidata = apidata;
      this.apidata.deliveryDate = moment(apidata.DeliveryDate, 'YYYYMMDD').toISOString();
    }
  }
}