问:
Back to top link flashes twice before dissappearing
As per the fiddle below I have a scroll back to top link, but upon clicking the link to scroll back to the top it flashes twice.

I have tried the usual suspects such as the $(body,html), but it still occurs even when I use one of those.

stop() before the fadeIn and fadeOut does help prevent this but causes the fadeIn to be incredibly slow.

Therefore, I was wondering if anyone could explain why this flash of the element is happening and how I could stop it from occurring?

jQuery(function() {
  jQuery(window).scroll(function() {
    if (jQuery(this).scrollTop() > 50) {
      jQuery('#back_top').fadeIn();
    } else {
      jQuery('#back_top').fadeOut();
    }
  });
  jQuery('#back_top').click(function() {
    jQuery('body,html').animate({
      scrollTop: 0
    }, 500);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#back_top {
  background-color: #447282;
  /* button color */
  color: white;
  /* text/arrow color */
  display: none;
  z-index: 999;
  /* float in bottom right corner */
  /* 20 pixels from edge */
  position: fixed;
  right: 10px;
  bottom: 10px;
  /* size of button is 50 pixels*/
  width: 54px;
  height: 54px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  opacity: 0.9;
}

a#back_top {
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 12px;
  text-transform: uppercase;
  text-align: center;
  line-height: 1.6;
  padding-left: 2px;
  padding-top: 8px;
}

a#back_top .arrow:before {
  content: "\e902";
  font-family: 'vishIcon';
  font-style: normal;
  font-weight: 600;
  font-size: 18px;
  line-height: 1;
  speak: none;
  -webkit-font-smoothing: antialiased;
  content: "\e902";
  text-align: center;
  display: block;
  vertical-align: middle;
  cursor: pointer;
  /*     margin-left: -4px; */
}</code>```

What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using
Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default
model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary
to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the
more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
(The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The
standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions
from the 1914 translation by H. Rackham. Where can I get some? There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly
believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this
the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition,
injected humour, or non-characteristic words etc.
Top```

答:
Okay looks like the animation was firing multiple times.

I have an solution with debounce and so I am not running $() inside of scroll listeners, which is a bad idea.

Debouncing will cause the action to not process until after the time threshold of inactivity has passed

jQuery(function($) {
 var $backToTop = $('#back_top');
  var $window = $(window);
  var debounce;

  $window.on('scroll', function() {
   if (debounce) clearTimeout(debounce);

    debounce = setTimeout(function(){
     debounce = null;

   $backToTop.finish();

   if ($window.scrollTop() > 50) {
        $backToTop.fadeIn();
      } else {
        $backToTop.fadeOut();
      }
    }, 100);
  });

 $backToTop.on('click', function() {
    $('html').animate({
      scrollTop: 0
    }, 500);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#back_top {
  background-color: #447282;
  /* button color */
  color: white;
  /* text/arrow color */
  display: none;
  z-index: 999;
  /* float in bottom right corner */
  /* 20 pixels from edge */
  position: fixed;
  right: 10px;
  bottom: 10px;
  /* size of button is 50 pixels*/
  width: 54px;
  height: 54px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  opacity: 0.9;
}

a#back_top {
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 12px;
  text-transform: uppercase;
  text-align: center;
  line-height: 1.6;
  padding-left: 2px;
  padding-top: 8px;
}

a#back_top .arrow:before {
  content: "\e902";
  font-family: 'vishIcon';
  font-style: normal;
  font-weight: 600;
  font-size: 18px;
  line-height: 1;
  speak: none;
  -webkit-font-smoothing: antialiased;
  content: "\e902";
  text-align: center;
  display: block;
  vertical-align: middle;
  cursor: pointer;
  /*     margin-left: -4px; */
}</code>```

What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
Top```

Body:
As per the fiddle below I have a scroll back to top link, but upon clicking the link to scroll back to the top it flashes twice.

I have tried the usual suspects such as the $(body,html), but it still occurs even when I use one of those.

stop() before the fadeIn and fadeOut does help prevent this but causes the fadeIn to be incredibly slow.

Therefore, I was wondering if anyone could explain why this flash of the element is happening and how I could stop it from occurring?

jQuery(function() {
  jQuery(window).scroll(function() {
    if (jQuery(this).scrollTop() > 50) {
      jQuery('#back_top').fadeIn();
    } else {
      jQuery('#back_top').fadeOut();
    }
  });
  jQuery('#back_top').click(function() {
    jQuery('body,html').animate({
      scrollTop: 0
    }, 500);
  });
});

#back_top {
  background-color: #447282;
  /* button color */
  color: white;
  /* text/arrow color */
  display: none;
  z-index: 999;
  /* float in bottom right corner */
  /* 20 pixels from edge */
  position: fixed;
  right: 10px;
  bottom: 10px;
  /* size of button is 50 pixels*/
  width: 54px;
  height: 54px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  opacity: 0.9;
}

a#back_top {
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 12px;
  text-transform: uppercase;
  text-align: center;
  line-height: 1.6;
  padding-left: 2px;
  padding-top: 8px;
}

a#back_top .arrow:before {
  content: "\e902";
  font-family: 'vishIcon';
  font-style: normal;
  font-weight: 600;
  font-size: 18px;
  line-height: 1;
  speak: none;
  -webkit-font-smoothing: antialiased;
  content: "\e902";
  text-align: center;
  display: block;
  vertical-align: middle;
  cursor: pointer;
  /*     margin-left: -4px; */
}

What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using
Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default
model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary
to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the
more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
(The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The
standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions
from the 1914 translation by H. Rackham. Where can I get some? There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly
believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this
the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition,
injected humour, or non-characteristic words etc.
Top

Body:
Okay looks like the animation was firing multiple times.

I have an solution with debounce and so I am not running $() inside of scroll listeners, which is a bad idea.

Debouncing will cause the action to not process until after the time threshold of inactivity has passed

jQuery(function($) {
 var $backToTop = $('#back_top');
  var $window = $(window);
  var debounce;

  $window.on('scroll', function() {
   if (debounce) clearTimeout(debounce);

    debounce = setTimeout(function(){
     debounce = null;

   $backToTop.finish();

   if ($window.scrollTop() > 50) {
        $backToTop.fadeIn();
      } else {
        $backToTop.fadeOut();
      }
    }, 100);
  });

 $backToTop.on('click', function() {
    $('html').animate({
      scrollTop: 0
    }, 500);
  });
});

#back_top {
  background-color: #447282;
  /* button color */
  color: white;
  /* text/arrow color */
  display: none;
  z-index: 999;
  /* float in bottom right corner */
  /* 20 pixels from edge */
  position: fixed;
  right: 10px;
  bottom: 10px;
  /* size of button is 50 pixels*/
  width: 54px;
  height: 54px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  opacity: 0.9;
}

a#back_top {
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 12px;
  text-transform: uppercase;
  text-align: center;
  line-height: 1.6;
  padding-left: 2px;
  padding-top: 8px;
}

a#back_top .arrow:before {
  content: "\e902";
  font-family: 'vishIcon';
  font-style: normal;
  font-weight: 600;
  font-size: 18px;
  line-height: 1;
  speak: none;
  -webkit-font-smoothing: antialiased;
  content: "\e902";
  text-align: center;
  display: block;
  vertical-align: middle;
  cursor: pointer;
  /*     margin-left: -4px; */
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
<a href="#" id="back_top" style="display: none;"><span class="arrow"></span>Top</a>


来源: stackexchange

问:
docker alpine /bin/sh script.sh not found
I'm trying to build a docker image that has the openjdk:8-alpine as base.

The problem is when I try to execute a script.sh, returning me the following message:

```<code>/bin/sh: bin/script.sh: not found
</code>```

The script.sh is in the bin/ folder correctly, that's why I don't know what's the problem.

Anyone have any idea?

Thank you.

答:
Make sure the shebang on the script points to an interpreter that actually exists. Thus, if the script being invoked uses:

```<code>#!/bin/bash
</code>```

...then /bin/bash needs to actually be installed. (Alternately, you might consider trying to port the script to work with POSIX sh, and modifying its shebang to /bin/sh).

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to build a docker image that has the openjdk:8-alpine as base.

The problem is when I try to execute a script.sh, returning me the following message:

/bin/sh: bin/script.sh: not found

The script.sh is in the bin/ folder correctly, that's why I don't know what's the problem.

Anyone have any idea?

Thank you.

Body:
Make sure the shebang on the script points to an interpreter that actually exists. Thus, if the script being invoked uses:

#!/bin/bash

...then /bin/bash needs to actually be installed. (Alternately, you might consider trying to port the script to work with POSIX sh, and modifying its shebang to /bin/sh).


问:
Invalid Column Name when Create trigger using SQL server
I encountered several errors when I tried to create a simple trigger using SQL server. Tables are created using:

```<code>CREATE TABLE person
(
    person_id INT NOT NULL PRIMARY KEY,
    name VARCHAR NOT NULL,
    phone INT,
    birth_date DATE,
    address VARCHAR
);

CREATE TABLE volunteers
(
    person_id INT NOT NULL PRIMARY KEY,
    skill VARCHAR,
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE physicians
(
    person_id INT NOT NULL PRIMARY KEY,
    speciality VARCHAR,
    phone_number INT,
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE patients
(
    person_id INT NOT NULL PRIMARY KEY,
    contact_date DATE,
    physician_id INT,   -- TODO determine whether NULL able
                        -- TODO determine ON DELETE ACTION
    CHECK (person_id <> physician_id),
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    FOREIGN KEY (physician_id) REFERENCES physicians(person_id)
        ON DELETE NO ACTION
        ON UPDATE NO ACTION
);

CREATE TABLE outpatients
(
    person_id INT NOT NULL PRIMARY KEY,
    FOREIGN KEY (person_id) REFERENCES patients(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE visits
(
    person_id INT  NOT NULL,
    date DATE NOT NULL,
    comments VARCHAR,
    PRIMARY KEY (person_id, date),
    FOREIGN KEY (person_id) REFERENCES outpatients(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE employees
(
    person_id INT NOT NULL PRIMARY KEY,
    date_hire DATE,
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE nurses
(
    person_id INT NOT NULL PRIMARY KEY,
    certificate VARCHAR,
    care_center_name VARCHAR,
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    -- FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
    --     ON DELETE CASCADE
    --     ON UPDATE CASCADE
);

CREATE TABLE care_centers
(
    name VARCHAR PRIMARY KEY NOT NULL,
    nurses_in_charge INT NOT NULL,
    location VARCHAR,
    type VARCHAR
    -- FOREIGN KEY (nurses_in_charge) REFERENCES registered_nurse(person_id)
);

CREATE TABLE registered_nurse
(
    person_id INT NOT NULL PRIMARY KEY,
    care_center_name VARCHAR,
    FOREIGN KEY (person_id) REFERENCES nurses(person_id),
        -- ON DELETE CASCADE
        -- ON UPDATE CASCADE,
    FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
        -- ON DELETE CASCADE
        -- ON UPDATE CASCADE
);

ALTER TABLE nurses
    ADD constraint nurses__care_centers_FK
    FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
        ON DELETE CASCADE
        ON UPDATE CASCADE;

ALTER TABLE care_centers
    ADD constraint care_centers__registered_nurse_FK
    FOREIGN KEY (nurses_in_charge) REFERENCES registered_nurse(person_id);

CREATE TABLE beds
(
    bed_number INT NOT NULL,
    room_number INT NOT NULL,
    care_center_name VARCHAR,
    PRIMARY KEY (bed_number,room_number),
    FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE residents
(
    person_id INT NOT NULL PRIMARY KEY,
    date_admitted DATE,
    bed_number INT,
    room_number INT,
    FOREIGN KEY (person_id) REFERENCES patients(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    FOREIGN KEY (bed_number, room_number) REFERENCES beds(bed_number, room_number)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE staffs
(
    person_id INT NOT NULL PRIMARY KEY,
    job_class DATE,
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE technicians
(
    person_id INT NOT NULL PRIMARY KEY,
    skill VARCHAR,
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE laboratories
(
    name VARCHAR NOT NULL PRIMARY KEY,
    location VARCHAR
);

CREATE TABLE assignTechnicianToLab
(
    person_id INT NOT NULL,
    laboratories_name VARCHAR NOT NULL,
    PRIMARY KEY(person_id, laboratories_name),
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    FOREIGN KEY (laboratories_name) REFERENCES laboratories(name)
        ON DELETE CASCADE
        ON UPDATE CASCADE
)
</code>```

And the trigger I am trying to create:

```<code>-- Trigger
/* if nurse has certificate "RN", add to registered_nurse */
CREATE TRIGGER registered_nurse_trigger
ON nurses
FOR INSERT, UPDATE
AS
BEGIN
    IF EXISTS (SELECT * FROM inserted where certificate = "RN")
    BEGIN
        INSERT INTO registered_nurse
        VALUES(inserted.person_id, nurses.care_center_name);
    END
END;
</code>```

And I keep getting errors saying that:

Msg 207, Level 16, State 1, Procedure registered_nurse_trigger, Line 6

  Invalid column name 'RN'.

Msg 4104, Level 16, State 1, Procedure registered_nurse_trigger, Line 8

  The multi-part identifier "inserted.person_id" could not be bound.

Msg 4104, Level 16, State 1, Procedure registered_nurse_trigger, Line 8

  The multi-part identifier "nurses.care_center_name" could not be bound.

I've been hanging over here for several hours and I really appreciate anyone can help me with it. Thank you very much!

答:
You can't use VALUES() like that.  Use INSERT..SELECT instead:

```<code>-- Trigger
/* if nurse has certificate "RN", add to registered_nurse */
CREATE TRIGGER registered_nurse_trigger ON nurses
For INSERT, UPDATE
AS BEGIN
INSERT INTO registered_nurse (person_id, care_center_name)
SELECT person_id, care_center_name
FROM inserted
WHERE certificate = 'RN'
END;
</code>```

I don't think you need to reference nurses or have that EXISTS() either, but maybe I'm overlooking something.

Body:
I encountered several errors when I tried to create a simple trigger using SQL server. Tables are created using:

CREATE TABLE person
(
    person_id INT NOT NULL PRIMARY KEY,
    name VARCHAR NOT NULL,
    phone INT,
    birth_date DATE,
    address VARCHAR
);

CREATE TABLE volunteers
(
    person_id INT NOT NULL PRIMARY KEY,
    skill VARCHAR,
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE physicians
(
    person_id INT NOT NULL PRIMARY KEY,
    speciality VARCHAR,
    phone_number INT,
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE patients
(
    person_id INT NOT NULL PRIMARY KEY,
    contact_date DATE,
    physician_id INT,   -- TODO determine whether NULL able
                        -- TODO determine ON DELETE ACTION
    CHECK (person_id <> physician_id),
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    FOREIGN KEY (physician_id) REFERENCES physicians(person_id)
        ON DELETE NO ACTION
        ON UPDATE NO ACTION
);

CREATE TABLE outpatients
(
    person_id INT NOT NULL PRIMARY KEY,
    FOREIGN KEY (person_id) REFERENCES patients(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE visits
(
    person_id INT  NOT NULL,
    date DATE NOT NULL,
    comments VARCHAR,
    PRIMARY KEY (person_id, date),
    FOREIGN KEY (person_id) REFERENCES outpatients(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE employees
(
    person_id INT NOT NULL PRIMARY KEY,
    date_hire DATE,
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE nurses
(
    person_id INT NOT NULL PRIMARY KEY,
    certificate VARCHAR,
    care_center_name VARCHAR,
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    -- FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
    --     ON DELETE CASCADE
    --     ON UPDATE CASCADE
);

CREATE TABLE care_centers
(
    name VARCHAR PRIMARY KEY NOT NULL,
    nurses_in_charge INT NOT NULL,
    location VARCHAR,
    type VARCHAR
    -- FOREIGN KEY (nurses_in_charge) REFERENCES registered_nurse(person_id)
);

CREATE TABLE registered_nurse
(
    person_id INT NOT NULL PRIMARY KEY,
    care_center_name VARCHAR,
    FOREIGN KEY (person_id) REFERENCES nurses(person_id),
        -- ON DELETE CASCADE
        -- ON UPDATE CASCADE,
    FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
        -- ON DELETE CASCADE
        -- ON UPDATE CASCADE
);

ALTER TABLE nurses
    ADD constraint nurses__care_centers_FK
    FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
        ON DELETE CASCADE
        ON UPDATE CASCADE;

ALTER TABLE care_centers
    ADD constraint care_centers__registered_nurse_FK
    FOREIGN KEY (nurses_in_charge) REFERENCES registered_nurse(person_id);

CREATE TABLE beds
(
    bed_number INT NOT NULL,
    room_number INT NOT NULL,
    care_center_name VARCHAR,
    PRIMARY KEY (bed_number,room_number),
    FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE residents
(
    person_id INT NOT NULL PRIMARY KEY,
    date_admitted DATE,
    bed_number INT,
    room_number INT,
    FOREIGN KEY (person_id) REFERENCES patients(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    FOREIGN KEY (bed_number, room_number) REFERENCES beds(bed_number, room_number)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE staffs
(
    person_id INT NOT NULL PRIMARY KEY,
    job_class DATE,
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE technicians
(
    person_id INT NOT NULL PRIMARY KEY,
    skill VARCHAR,
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE laboratories
(
    name VARCHAR NOT NULL PRIMARY KEY,
    location VARCHAR
);

CREATE TABLE assignTechnicianToLab
(
    person_id INT NOT NULL,
    laboratories_name VARCHAR NOT NULL,
    PRIMARY KEY(person_id, laboratories_name),
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    FOREIGN KEY (laboratories_name) REFERENCES laboratories(name)
        ON DELETE CASCADE
        ON UPDATE CASCADE
)

And the trigger I am trying to create:

-- Trigger
/* if nurse has certificate "RN", add to registered_nurse */
CREATE TRIGGER registered_nurse_trigger
ON nurses
FOR INSERT, UPDATE
AS
BEGIN
    IF EXISTS (SELECT * FROM inserted where certificate = "RN")
    BEGIN
        INSERT INTO registered_nurse
        VALUES(inserted.person_id, nurses.care_center_name);
    END
END;

And I keep getting errors saying that:

Msg 207, Level 16, State 1, Procedure registered_nurse_trigger, Line 6

  Invalid column name 'RN'.

Msg 4104, Level 16, State 1, Procedure registered_nurse_trigger, Line 8

  The multi-part identifier "inserted.person_id" could not be bound.

Msg 4104, Level 16, State 1, Procedure registered_nurse_trigger, Line 8

  The multi-part identifier "nurses.care_center_name" could not be bound.

I've been hanging over here for several hours and I really appreciate anyone can help me with it. Thank you very much!

Body:
You can't use VALUES() like that.  Use INSERT..SELECT instead:

-- Trigger
/* if nurse has certificate "RN", add to registered_nurse */
CREATE TRIGGER registered_nurse_trigger ON nurses
For INSERT, UPDATE
AS BEGIN
INSERT INTO registered_nurse (person_id, care_center_name)
SELECT person_id, care_center_name
FROM inserted
WHERE certificate = 'RN'
END;

I don't think you need to reference nurses or have that EXISTS() either, but maybe I'm overlooking something.


问:
HTML email table stretching horizontally when lots of text
I am trying to create a responsive HTML email. The two columns should be equal height and they currently stack on mobile. Everything works properly until there is a lot of text as the Billing Information or Shipping Information. It's an unlikely case that the text will ever look like this, but I must handle all possibilities without the email breaking. How can I make my td stretch vertically instead of horizontally? I cannot use a fixed width as it will break the responsiveness of my table.

                                                                        Billing Information

                                                                        {{ receipt.order.get_billing_html|safe }}

                                                                        Shipping Information

                                                                            Shipping Address

Shipping speed description
                                                                        {% endif %}
                                                                        {% if receipt.order.shipper_tracking_number %}

Tracking: Shipper Name

```

答:
Found the answer in post: HTML CSS How to stop a table cell from expanding

Using style="overflow-wrap: break-word;" on the  solved my problem. It is compatible across Gmail, Apple Mail, Yahoo, latest Outlook.

Body:
Found the answer in post: HTML CSS How to stop a table cell from expanding

Using style="overflow-wrap: break-word;" on the <td> solved my problem. It is compatible across Gmail, Apple Mail, Yahoo, latest Outlook.


问:
making a constant heading - css issue
I have an AJAX application which has used CSS divs to create panels on the screen, which are loaded separately and in succession, depending on what was loaded before it. The bottom "panel" is a table showing a list or records from a database. At the top of the database is the name of the table, and I would like a way to have it be always above the list of records. I am unsure of how to do this, if it is with Javascript, or PHP, or css and html.

edit: I tried wrapping the table header in a div and setting the css for this purpose, but the table header does not seem to be in its own header and does not stay on screen separate from the records.

```<code>.tableheader {
    position: absolute;
}
</code>```

and

```<code>$table = 'AUCTIONS';

$rows = getRowsByArticleSearch($query, $table);

echo '<div id="tableheader" class="tableheader">';

echo "<h1>{$query} Auctions</h1>" . "\n";
echo "</div>";
</code>```

Have I missed something fundamental here?

答:
Do you want the table name to be inside the panel with the table?  If so, I think it should be pretty straightforward, but maybe I am missing something.

If you want the table name to be positioned outside the panel it comes from, perhaps you could use the CSS property position: absolute (along with a top and left property) to put it at the top of the page.

Alternatively, you may want to use javascript to re-parent the div.  For example, if you create an empty div at the top of the page, where you want the title to go, and give it an id titleParent and put the title in a div with id parent, the following javascript snippet should move the title div from the bottom panel to the top div:

```<code>var title = document.getElementById('title');
document.getElementById('titleParent').appendChild(title);
</code>```

Just put that snippet in a

Title: making a constant heading - css issue

Body:
I have an AJAX application which has used CSS divs to create panels on the screen, which are loaded separately and in succession, depending on what was loaded before it. The bottom "panel" is a table showing a list or records from a database. At the top of the database is the name of the table, and I would like a way to have it be always above the list of records. I am unsure of how to do this, if it is with Javascript, or PHP, or css and html.

edit: I tried wrapping the table header in a div and setting the css for this purpose, but the table header does not seem to be in its own header and does not stay on screen separate from the records.

.tableheader {
    position: absolute;
}

and

$table = 'AUCTIONS';

$rows = getRowsByArticleSearch($query, $table);

echo '
';

echo "
{$query} Auctions
" . "\n";
echo "
";

Have I missed something fundamental here?

Body:
Do you want the table name to be inside the panel with the table?  If so, I think it should be pretty straightforward, but maybe I am missing something.

If you want the table name to be positioned outside the panel it comes from, perhaps you could use the CSS property position: absolute (along with a top and left property) to put it at the top of the page.

Alternatively, you may want to use javascript to re-parent the div.  For example, if you create an empty div at the top of the page, where you want the title to go, and give it an id titleParent and put the title in a div with id parent, the following javascript snippet should move the title div from the bottom panel to the top div:

var title = document.getElementById('title');
document.getElementById('titleParent').appendChild(title);

Just put that snippet in a <script> block after the bottom panel.

OwnerDisplayName: pkaeding

ContentLicense: CC BY-SA 2.5


问:
How to add objects to a pointer
I'm trying to figure out how does a vector adds more objects after it has already "Created" some:

```<code>int *ptr;
ptr = new int;
</code>```

How after using that, can you add more objects to that pointer? (make it an array). Thanks!

答:
As with most STL containers it uses an external allocator to actually allocate the memory. This is the second template parameter to vector.

It uses placement-new to create the objects into the memory.

For adding more objects when it has run out of memory it must allocate a bigger amount. If the underlying type is POD it can just realloc, but if not it must move them with the object's operator=.

ContentLicense: CC BY-SA 4.0

Title: How to add objects to a pointer

Body:
I'm trying to figure out how does a vector adds more objects after it has already "Created" some:

int *ptr;
ptr = new int;

How after using that, can you add more objects to that pointer? (make it an array). Thanks!


问:
How to redirect output in multiple columns in bash?
I am running a test multiple times on terminal and redirecting output to a file. While redirecting I want each run as a separate column. Currently, I am able to get the following:

```<code>Run1
1
2
3
4
Run2
1
2
3
4
</code>```

How to redirect it as follow:

```<code>Run1  Run2
1      1
2      2
3      3
4      4
</code>```

答:
With pr:

```<code>pr -2 -t -s file
</code>```

or from stdin:

```<code>cat file | pr -2 -t -s
</code>```

Output:

```
Run1    Run2
1       1
2       2
3       3
4       4
```

See: man pr

Body:
I am running a test multiple times on terminal and redirecting output to a file. While redirecting I want each run as a separate column. Currently, I am able to get the following:

Run1
1
2
3
4
Run2
1
2
3
4

How to redirect it as follow:

Run1  Run2
1      1
2      2
3      3
4      4

Body:
With pr:

pr -2 -t -s file

or from stdin:

cat file | pr -2 -t -s

Output:

Run1    Run2
1       1
2       2
3       3
4       4

See: man pr


问:
Typescript and IDB library for using indexedDB. Guidance needed
Question from a newbie.
I'm trying to follow the walk through Working with IndexedDB tutorial which uses Jake Archibald's IDB library but using Typescript instead of plain Javascript. I'm not having much of a success so far.

My code looks like this.

```<code>import * as idb from "./idb";

const dbPromise: Promise<idb.DB> = idb.default.open('test-db2', 1, (upgradeDb: idb.UpgradeDB) => {
    console.log('making a new object store');
    if (!upgradeDb.objectStoreNames.contains('firstOS')) {
        upgradeDb.createObjectStore('firstOS');
    }
});
</code>```

The definition file loads well since the compiler doesn't throw any errors and intellisense works fine in VS Code.

I manage to load my module using require.js on my html page, but the console shows the following error:

```<code>Uncaught TypeError: Cannot read property 'default' of undefined
at Object.<anonymous> (main.ts:8)
at Object.execCb (require.min.js:5)
at b.check (require.min.js:5)
at b.<anonymous> (require.min.js:5)
at require.min.js:5
at require.min.js:5
at each (require.min.js:5)
at b.emit (require.min.js:5)
at b.check (require.min.js:5)
at b.enable (require.min.js:5)
</code>```

Now, if I remove defaultfrom the call to idb.default.open(...), the compiler tells me that 'open' does not exist on type '.../idb'.
The library exports idb as its default.

I'm missing some sort of initialization but I cannot really see what or where.

Can anyone help?

WORK AROUND

This is how I finally made this work.

```<code>import * as idxdb from "./idb";
import "./js/idb.js";

let dbPromise: Promise<idxdb.DB> = idb.open('test-db2', 1, (upgradeDb: idxdb.UpgradeDB) => {
    console.log('making a new object store');
    if (!upgradeDb.objectStoreNames.contains('firstOS')) {
        upgradeDb.createObjectStore('firstOS');
    }
});
</code>```

The first import statement brings the types in so it compiles and it provides hinting. The second statement brings the idb object to the mix.

Thanks very much to @Josh for pointing me in the right direction.

答:
Hmm, not a typescript expert, but after learning some module syntax, it looks like an a module problem. Looking at the code of https://github.com/jakearchibald/idb/blob/master/lib/idb.js, you see see that in the browser context the variable idb is defined at the end with self.idb = exp;.

So you are trying to import a module using ES6 module syntax, but the file you are importing is not a module, in the sense that it has no exports, and no default export.

(1) You can downoad the idb.js file and insert an export default in there at the end, and proceed with importing the default exported value.

(2) You can learn how to import a script file as a module when it does not export anything.

Under 2, because self is window in the browser, you probably can just directly access the variable idb, because by including the file it becomes defined in global scope.

So, first you want to import the file, ignoring what it exports, using import "./idb.js".  This style of import syntax ignores whatever is exported. Since we know idb.js doesn't export anything, this is great because it is the minimal amount of work needed to import a file without exports.  And the result of the import is that it is evaluated, so that means the imported will declare idb in global scope of window as an implied side effect of the module (defining globals is normally frowned upon in modules but this is ok because this is a non-module).

So ... try the following, if you are working in a browser context:

```<code>import "./idb.js";

// This should print out information about the idb object declared in
// global scope of the browser (e.g. under window.idb)
console.log(idb);

// Because the variable idb is basically just a global, just access
// here as it comes from the global
const dbPromise: Promise<idb.DB> = idb.open(...);
</code>```

Body:
Question from a newbie.
I'm trying to follow the walk through Working with IndexedDB tutorial which uses Jake Archibald's IDB library but using Typescript instead of plain Javascript. I'm not having much of a success so far.

My code looks like this.

import * as idb from "./idb";

const dbPromise: Promise<idb.DB> = idb.default.open('test-db2', 1, (upgradeDb: idb.UpgradeDB) => {
    console.log('making a new object store');
    if (!upgradeDb.objectStoreNames.contains('firstOS')) {
        upgradeDb.createObjectStore('firstOS');
    }
});

The definition file loads well since the compiler doesn't throw any errors and intellisense works fine in VS Code.

I manage to load my module using require.js on my html page, but the console shows the following error:

Uncaught TypeError: Cannot read property 'default' of undefined
at Object.<anonymous> (main.ts:8)
at Object.execCb (require.min.js:5)
at b.check (require.min.js:5)
at b.<anonymous> (require.min.js:5)
at require.min.js:5
at require.min.js:5
at each (require.min.js:5)
at b.emit (require.min.js:5)
at b.check (require.min.js:5)
at b.enable (require.min.js:5)

Now, if I remove defaultfrom the call to idb.default.open(...), the compiler tells me that 'open' does not exist on type '.../idb'.
The library exports idb as its default.

I'm missing some sort of initialization but I cannot really see what or where.

Can anyone help?

WORK AROUND

This is how I finally made this work.

import * as idxdb from "./idb";
import "./js/idb.js";

let dbPromise: Promise<idxdb.DB> = idb.open('test-db2', 1, (upgradeDb: idxdb.UpgradeDB) => {
    console.log('making a new object store');
    if (!upgradeDb.objectStoreNames.contains('firstOS')) {
        upgradeDb.createObjectStore('firstOS');
    }
});

The first import statement brings the types in so it compiles and it provides hinting. The second statement brings the idb object to the mix.

Thanks very much to @Josh for pointing me in the right direction.

Body:
Hmm, not a typescript expert, but after learning some module syntax, it looks like an a module problem. Looking at the code of https://github.com/jakearchibald/idb/blob/master/lib/idb.js, you see see that in the browser context the variable idb is defined at the end with self.idb = exp;.

So you are trying to import a module using ES6 module syntax, but the file you are importing is not a module, in the sense that it has no exports, and no default export.

(1) You can downoad the idb.js file and insert an export default in there at the end, and proceed with importing the default exported value.

(2) You can learn how to import a script file as a module when it does not export anything.

Under 2, because self is window in the browser, you probably can just directly access the variable idb, because by including the file it becomes defined in global scope.

So, first you want to import the file, ignoring what it exports, using import "./idb.js".  This style of import syntax ignores whatever is exported. Since we know idb.js doesn't export anything, this is great because it is the minimal amount of work needed to import a file without exports.  And the result of the import is that it is evaluated, so that means the imported will declare idb in global scope of window as an implied side effect of the module (defining globals is normally frowned upon in modules but this is ok because this is a non-module).

So ... try the following, if you are working in a browser context:

import "./idb.js";

// This should print out information about the idb object declared in
// global scope of the browser (e.g. under window.idb)
console.log(idb);

// Because the variable idb is basically just a global, just access
// here as it comes from the global
const dbPromise: Promise<idb.DB> = idb.open(...);


问:
Effective scraping from web into (pandas) DataFrame that preserves the intended format
Goal: Scraping a page and convert it to DataFrame preserving the intended format (python 3).

The data seems to be in csv format and is located here:
'https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data'. I tried three approaches, but they all fail.

Approach 1: pandas.read_csv(url) --> the dataframe format is all garbled.
E.g.:

```<code>import pandas as pd
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data'
df = pd.read_csv(url, sep=',')
df.head()
</code>```

Output:

```<code>    18.0 8 307.0 130.0 3504. 12.0 70 1  "chevrolet chevelle malibu"
0   15.0 8 350.0 165.0 3693. 11...
1   18.0 8 318.0 150.0 3436. 11...
2   16.0 8 304.0 150.0 3433. 12...
3   17.0 8 302.0 140.0 3449. 10...
4   15.0 8 429.0 198.0 4341. 10...
</code>```

Approach 2: pandas.read_html --> ValueError: No tables found.

Full trace:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-44-07c4c7f7c45c> in <module>()
----> 1 df = pd.read_html(url)
      2 df.head(10)

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pandas/io/html.py in read_html(io, match, flavor, header, index_col, skiprows, attrs, parse_dates, tupleize_cols, thousands, encoding, decimal, converters, na_values, keep_default_na)
    904                   thousands=thousands, attrs=attrs, encoding=encoding,
    905                   decimal=decimal, converters=converters, na_values=na_values,
--> 906                   keep_default_na=keep_default_na)

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pandas/io/html.py in _parse(flavor, io, match, attrs, encoding, **kwargs)
    741             break
    742     else:
--> 743         raise_with_traceback(retained)
    744
    745     ret = []

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pandas/compat/__init__.py in raise_with_traceback(exc, traceback)
    342         if traceback == Ellipsis:
    343             _, _, traceback = sys.exc_info()
--> 344         raise exc.with_traceback(traceback)
    345 else:
    346     # this version of raise is a syntax error in Python 3

ValueError: No tables found
</code>```

Approach 3: BeatifulSoup to pandas --> KeyError: 0

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup
page = urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
</code>```

Full trace:

```<code>---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-45-a2a52b487623> in <module>()
      3 page = urlopen(url)
      4 soup = BeautifulSoup(page, 'html.parser')
----> 5 df = pd.DataFrame(soup)

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
    335         else:
    336             try:
--> 337                 arr = np.array(data, dtype=dtype, copy=copy)
    338             except (ValueError, TypeError) as e:
    339                 exc = TypeError('DataFrame constructor called with '

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/bs4/element.py in __getitem__(self, key)
   1009         """tag[key] returns the value of the 'key' attribute for the tag,
   1010         and throws an exception if it's not there."""
-> 1011         return self.attrs[key]
   1012
   1013     def __iter__(self):

KeyError: 0
</code>```

Body:
Goal: Scraping a page and convert it to DataFrame preserving the intended format (python 3).

The data seems to be in csv format and is located here:
'https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data'. I tried three approaches, but they all fail.

Approach 1: pandas.read_csv(url) --> the dataframe format is all garbled.
E.g.:

import pandas as pd
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data'
df = pd.read_csv(url, sep=',')
df.head()

Output:

    18.0 8 307.0 130.0 3504. 12.0 70 1  "chevrolet chevelle malibu"
0   15.0 8 350.0 165.0 3693. 11...
1   18.0 8 318.0 150.0 3436. 11...
2   16.0 8 304.0 150.0 3433. 12...
3   17.0 8 302.0 140.0 3449. 10...
4   15.0 8 429.0 198.0 4341. 10...

Approach 2: pandas.read_html --> ValueError: No tables found.

Full trace:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-44-07c4c7f7c45c> in <module>()
----> 1 df = pd.read_html(url)
      2 df.head(10)

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pandas/io/html.py in read_html(io, match, flavor, header, index_col, skiprows, attrs, parse_dates, tupleize_cols, thousands, encoding, decimal, converters, na_values, keep_default_na)
    904                   thousands=thousands, attrs=attrs, encoding=encoding,
    905                   decimal=decimal, converters=converters, na_values=na_values,
--> 906                   keep_default_na=keep_default_na)

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pandas/io/html.py in _parse(flavor, io, match, attrs, encoding, **kwargs)
    741             break
    742     else:
--> 743         raise_with_traceback(retained)
    744
    745     ret = []

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pandas/compat/__init__.py in raise_with_traceback(exc, traceback)
    342         if traceback == Ellipsis:
    343             _, _, traceback = sys.exc_info()
--> 344         raise exc.with_traceback(traceback)
    345 else:
    346     # this version of raise is a syntax error in Python 3

ValueError: No tables found

Approach 3: BeatifulSoup to pandas --> KeyError: 0

from urllib.request import urlopen
from bs4 import BeautifulSoup
page = urlopen(url)
soup = BeautifulSoup(page, 'html.parser')

Full trace:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-45-a2a52b487623> in <module>()
      3 page = urlopen(url)
      4 soup = BeautifulSoup(page, 'html.parser')
----> 5 df = pd.DataFrame(soup)

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
    335         else:
    336             try:
--> 337                 arr = np.array(data, dtype=dtype, copy=copy)
    338             except (ValueError, TypeError) as e:
    339                 exc = TypeError('DataFrame constructor called with '

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/bs4/element.py in __getitem__(self, key)
   1009         """tag[key] returns the value of the 'key' attribute for the tag,
   1010         and throws an exception if it's not there."""
-> 1011         return self.attrs[key]
   1012
   1013     def __iter__(self):

KeyError: 0

Body:
In [33]: url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data'

In [34]: df = pd.read_fwf(url, header=None)

In [35]: df
Out[35]:
        0  1      2      3       4     5   6  7                            8
0    18.0  8  307.0  130.0  3504.0  12.0  70  1  "chevrolet chevelle malibu"
1    15.0  8  350.0  165.0  3693.0  11.5  70  1          "buick skylark 320"
2    18.0  8  318.0  150.0  3436.0  11.0  70  1         "plymouth satellite"
3    16.0  8  304.0  150.0  3433.0  12.0  70  1              "amc rebel sst"
4    17.0  8  302.0  140.0  3449.0  10.5  70  1                "ford torino"
5    15.0  8  429.0  198.0  4341.0  10.0  70  1           "ford galaxie 500"
6    14.0  8  454.0  220.0  4354.0   9.0  70  1           "chevrolet impala"
..    ... ..    ...    ...     ...   ...  .. ..                          ...
391  36.0  4  135.0  84.00  2370.0  13.0  82  1          "dodge charger 2.2"
392  27.0  4  151.0  90.00  2950.0  17.3  82  1           "chevrolet camaro"
393  27.0  4  140.0  86.00  2790.0  15.6  82  1            "ford mustang gl"
394  44.0  4   97.0  52.00  2130.0  24.6  82  2                  "vw pickup"
395  32.0  4  135.0  84.00  2295.0  11.6  82  1              "dodge rampage"
396  28.0  4  120.0  79.00  2625.0  18.6  82  1                "ford ranger"
397  31.0  4  119.0  82.00  2720.0  19.4  82  1                 "chevy s-10"

[398 rows x 9 columns]


问:
Angular ng-repeat for Bootstrap Carousel
I have an issue where my carousel shows the correct amount of uib-slides based on the list (3 items per page so if there are 7 total items there are 3 pages 3/3/1) but instead of the proper 3/3/1 it is showing all 7 items on each page 7/7/7.

HTML

```<code><div uib-carousel active="active" class="carousel-inner" role="listbox">
    <div uib-slide ng-repeat="slide in testCtrl.carouselSlides track by $index" index="$index" ng-class="{active : $first}">
        <div ng-repeat="fav in testCtrl.carouselList">
            <div class="col-sm-4" ng-repeat="f in fav">
                <widget-chart="widget" style="margin:auto;"></widget-chart>
            </div>
        </div>
    </div>
</div>
</code>```

carouselSlides is just an empty array that is calculated to show how many pages is needed. So if there are 8 items it needs 3 pages (3/3/2) so carouselSlides just equals [ , , ]

carouselList is the data which is a formatted to look something like

```<code>carouselList = [
    [a, b, c],
    [d, f, g],
    [h, i, j],
    [k, l]
];
</code>```

But can be any length it's just put into arrays of 3.

I have tried adding a limitTo but it didn't seem to have any effect.

```<code><div class="col-sm-4" ng-repeat="f in fav | limitTo:3">
</code>```

I tried doing something similar to bluescreen's answer to Filter results 6 through 10 of 100 with ng-repeat in AngularJS where I have two limitTo's but it didn't work either.

```<code><div class="col-sm-4" ng-repeat="f in fav | limitTo:6 | limitTo:-3" >
</code>```

Is there something wrong with what I am doing? Is this even possible with ui-bootstrap's carousel?

=====UPDATE=====

I tried modifying my code to see if @NTP's solution would work. Here is my attempt.

I reformatted the data in carouselList to look like

```<code>carouselList = [a, b, c, d, f, g h, i, j, k, l];
</code>```

and changed my HTML to be

```<code><div uib-carousel active="active" class="carousel-inner" role="listbox">
    <div uib-slide ng-repeat="slide in testCtrl.carouselSlides track by $index" index="testCtrl.carouselList[$index]">
        <div class="col-sm-4">
            <widget-chart="testCtrl.carouselList[$index * 3]" style="margin:auto;"></widget-chart>
        </div>
        <div class="col-sm-4" ng-if="testCtrl.carouselList[$index * 3 + 1] != undefined">
            <widget-chart="testCtrl.carouselList[$index * 3 + 1]" style="margin:auto;"></widget-chart>
        </div>
        <div class="col-sm-4" ng-if="testCtrl.carouselList[$index * 3 + 2] != undefined">
            <widget-chart="testCtrl.carouselList[$index * 3 + 2]" style="margin:auto;"></widget-chart>
        </div>
    </div>
</div>
</code>```

However, this did not work.

Note: I am not sure if this matters or not but I am not repeating images I am repeating a widget panel object I have.

答:
first calculate number of iterations for ng-repeat

```<code>  $scope.getNumber = function() {
    if($scope.slides.length % 3 == 0)
      return new Array($scope.slides.length / 3);
    else
      return new Array(Math.floor($scope.slides.length/3) + 1);
  }
</code>```

then use the following code to display 3 items per slide

```<code><div uib-carousel active="active" interval="myInterval" no-wrap="noWrapSlides">
  <div uib-slide ng-repeat="slide in getNumber() track by $index" index="slides[$index].id">
    <img ng-src="{{slides[$index * 3].image}}" style="width:33%">
    <img ng-show="slides[$index * 3 + 1] != undefined" ng-src="{{slides[$index * 3 + 1].image}}" style="width:33%">
    <img ng-show="slides[$index * 3 + 2] != undefined" ng-src="{{slides[$index * 3 + 2].image}}" style="width:33%">
  </div>
</div>
</code>```

Plunker

Body:
I have an issue where my carousel shows the correct amount of uib-slides based on the list (3 items per page so if there are 7 total items there are 3 pages 3/3/1) but instead of the proper 3/3/1 it is showing all 7 items on each page 7/7/7.

HTML

                <widget-chart="widget" style="margin:auto;"></widget-chart>

carouselSlides is just an empty array that is calculated to show how many pages is needed. So if there are 8 items it needs 3 pages (3/3/2) so carouselSlides just equals [ , , ]

carouselList is the data which is a formatted to look something like

carouselList = [
    [a, b, c],
    [d, f, g],
    [h, i, j],
    [k, l]
];

But can be any length it's just put into arrays of 3.

I have tried adding a limitTo but it didn't seem to have any effect.

I tried doing something similar to bluescreen's answer to Filter results 6 through 10 of 100 with ng-repeat in AngularJS where I have two limitTo's but it didn't work either.

Is there something wrong with what I am doing? Is this even possible with ui-bootstrap's carousel?

=====UPDATE=====

I tried modifying my code to see if @NTP's solution would work. Here is my attempt.

I reformatted the data in carouselList to look like

carouselList = [a, b, c, d, f, g h, i, j, k, l];

and changed my HTML to be

            <widget-chart="testCtrl.carouselList[$index * 3]" style="margin:auto;"></widget-chart>

            <widget-chart="testCtrl.carouselList[$index * 3 + 1]" style="margin:auto;"></widget-chart>

            <widget-chart="testCtrl.carouselList[$index * 3 + 2]" style="margin:auto;"></widget-chart>

However, this did not work.

Note: I am not sure if this matters or not but I am not repeating images I am repeating a widget panel object I have.

Body:
first calculate number of iterations for ng-repeat

  $scope.getNumber = function() {
    if($scope.slides.length % 3 == 0)
      return new Array($scope.slides.length / 3);
    else
      return new Array(Math.floor($scope.slides.length/3) + 1);
  }

then use the following code to display 3 items per slide

<div uib-carousel active="active" interval="myInterval" no-wrap="noWrapSlides">
  <div uib-slide ng-repeat="slide in getNumber() track by $index" index="slides[$index].id">
    <img ng-src="{{slides[$index * 3].image}}" style="width:33%">
    <img ng-show="slides[$index * 3 + 1] != undefined" ng-src="{{slides[$index * 3 + 1].image}}" style="width:33%">
    <img ng-show="slides[$index * 3 + 2] != undefined" ng-src="{{slides[$index * 3 + 2].image}}" style="width:33%">
  </div>
</div>

Plunker


问:
Bizzare behavior with a button on the click event
Hello i have this bizzare behavior when i click a button the response happens 2 times, and i don't understand what is going on???

This is the code of the javascript:

```<code>function main(){
//Creating the function that will be executed by the showhid.
$("#showhid").click(function(event){
    if ($('#btcreator').is(":visible") === true){

        $(this).button({
            icons:{secondary:'ui-icon-arrowthick-1-w'},
            text:false});

        $(this).animate({left:'97%'}, 'fast');

        $('#btcreator').animate({width:'hide'}, 'fast');

        return;
    }else if($('#btcreator').is(":visible") === false){

        $(this).button({
            icons:{secondary:'ui-icon-arrowthick-1-e'},
            text:false});

        $(this).animate({left:'522px'}, 'fast');

        $('#btcreator').animate({width:'show'}, 'fast');

        return;
    }
});

//Executing the button function on the createBt Button.
$("#createBt").button();
//Creating the function that will create the batute.
$("#createBt").click(function(event){
    if (getData('fatherbt') == 'none'){
        window.fileLoc="modules/appgen/devBt/"+$('#body').attr('key').substring(0, 5);
        elMnt = window.operation.createElement('element');
        elMnt.setAttribute('name', 'attr');
        elMnt.setAttribute('id', 'idEl');
        elMnt.setAttribute('attrname', 'id');
        elMnt.setAttribute('vtype', 'str');
        elMnt.setAttribute('value', getData('fncnm'));
        window.data_lst = [elMnt];
        elAttr = window.operation.createElement('element');
        elAttr.setAttribute('name', 'attr');
        elAttr.setAttribute('id', 'nameEl');
        elAttr.setAttribute('attrname', 'name');
        elAttr.setAttribute('vtype', 'str');
        elAttr.setAttribute('value', getData('fncName'));
        window.data_lst.push(elAttr);
        window.addEl = 'function';
        catcher('crtBt');
        alert(event.data);
    }
});
}}
</code>```

This is the code of the page...

```<code><HTML><HEAD><LINK href="http://dev.karinapp.com/modules/appgen/css/batute.css" id="css_batute_4" rel="stylesheet" type="text/css"/><LINK href="http://dev.karinapp.com/modules/batute/css/main.css" id="css_batute_22" rel="stylesheet" type="text/css"/><SCRIPT id="script0" src="http://dev.karinapp.com/modules/general/scripts/jQuery.js" type="text/javascript"><!--empty--></SCRIPT><SCRIPT id="script1" src="http://dev.karinapp.com/modules/general/scripts/ui/jquery.ui.core.js" type="text/javascript"><!--empty--></SCRIPT><SCRIPT id="script2" src="http://dev.karinapp.com/modules/general/scripts/ui/jquery.ui.widget.js" type="text/javascript"><!--empty--></SCRIPT><SCRIPT id="script3" src="http://dev.karinapp.com/modules/general/scripts/ui/jquery.ui.button.js" type="text/javascript"><!--empty--></SCRIPT><SCRIPT id="script4" src="/modules/general/scripts/general.js" type="text/javascript"><!--empty--></SCRIPT><LINK href="http://dev.karinapp.com/modules/general/css/karinapp-style/jquery-ui-1.8.4.custom.css" id="link4" rel="stylesheet" type="text/css"/><SCRIPT id="script5" src="/modules/appgen/scripts/batute.js" type="text/javascript"><!--empty--></SCRIPT><SCRIPT id="script6">function __init__(){

main();

}</SCRIPT><SCRIPT id="pdloadScr" src="/modules/general/scripts/loadPage.js" type="text/javascript"><!--empty--></SCRIPT><SCRIPT id="pdLoader" type="text/javascript">window.onload = function(){postLoad();
__init__();}</SCRIPT><SCRIPT id="script9" src="/modules/general/scripts/Catcher.js" type="text/javascript"><!--empty--></SCRIPT></HEAD><BODY id="body" key="fb4d1c88bad8893b8ca3ee30b19bf4190d378552"><DIV father="body" id="btcreator">
            <!--Comment-->

            <LABEL father="@btcreator" id="fncNm_lbl"><!--empty-->              Name:
            </LABEL>

            <LABEL father="@btcreator" id="fatherlbl"><!--empty-->Father:
            </LABEL>
            <INPUT father="@btcreator" id="fncnm" type="text"/>
            <SELECT father="@btcreator" id="fatherbt"><!--Comment--><OPTION father="@fatherbt" id="fatherbt_Opt0" name="fatherbt_Opt0" value="none">No father</OPTION></SELECT>

            <BUTTON father="@btcreator" id="createBt"><!--empty-->Create</BUTTON><SELECT father="@btcreator" id="fncName"><OPTION father="@fncName" id="fncName_Opt0" name="fncName_Opt0" value="default">Select one...</OPTION><OPTION father="@fncName" id="fncName_Opt1" name="fncName_Opt1" value="oper">Operation</OPTION><OPTION father="@fncName" id="fncName_Opt2" name="fncName_Opt2" value="dirls">List of directories</OPTION><OPTION father="@fncName" id="fncName_Opt3" name="fncName_Opt3" value="opnfl">Open File</OPTION><OPTION father="@fncName" id="fncName_Opt4" name="fncName_Opt4" value="delete">Delete File</OPTION><OPTION father="@fncName" id="fncName_Opt5" name="fncName_Opt5" value="compare">Compare</OPTION><OPTION father="@fncName" id="fncName_Opt6" name="fncName_Opt6" value="cp">Copy</OPTION><OPTION father="@fncName" id="fncName_Opt7" name="fncName_Opt7" value="get">Get</OPTION><OPTION father="@fncName" id="fncName_Opt8" name="fncName_Opt8" value="switch">Switch(If-Else)</OPTION><OPTION father="@fncName" id="fncName_Opt9" name="fncName_Opt9" value="upload">Upload</OPTION><OPTION father="@fncName" id="fncName_Opt10" name="fncName_Opt10" value="modify">Modify(Elements)</OPTION><OPTION father="@fncName" id="fncName_Opt11" name="fncName_Opt11" value="create">Create(Elements)</OPTION><OPTION father="@fncName" id="fncName_Opt12" name="fncName_Opt12" value="find">Select(SQL)</OPTION><OPTION father="@fncName" id="fncName_Opt13" name="fncName_Opt13" value="insert">Insert(SQL)</OPTION><OPTION father="@fncName" id="fncName_Opt14" name="fncName_Opt14" value="update">Update(SQL)</OPTION></SELECT><BUTTON father="@btcreator" id="addRpl" value="Add Reply"><!--empty-->Add Reply</BUTTON><LABEL father="@btcreator" id="fncNameLbl"><!--empty-->Function:</LABEL>

            <DIV father="@btcreator" id="rplCrt">
                <!--Comment-->
                <BUTTON father="@rplCrt" id="crtMdl" value="Create Model"><!--empty-->Create model</BUTTON>
                <BUTTON father="@rplCrt" id="stcRpl" value="Add Static Reply"><!--empty-->Add static Reply</BUTTON>
                <BUTTON father="@rplCrt" id="addMdl"><!--empty--></BUTTON><TEXTAREA cols="45" father="@rplCrt" id="insertStc" rows="15"><!--Comment--></TEXTAREA><TABLE father="@rplCrt" id="mdlLst" width="90%"><THEAD father="@mdlLst" id="thead0"><TR>
<TH width="50%">Function name:</TH>
<TH>Select</TH>

</TR></THEAD><TBODY father="@mdlLst" id="tbody0"/></TABLE><LABEL father="@rplCrt" id="insertMdlLbl"><!--empty-->Insert model on:</LABEL><INPUT father="@rplCrt" id="mdIns"/>
            </DIV>
        <LABEL father="@btcreator" for="dtype" id="dTypelbl">Data-Type:</LABEL><SELECT father="@btcreator" id="dtype"><!--Comment--><OPTION father="@dtype" id="dtype_Opt0" name="dtype_Opt0" value="data">Data</OPTION><OPTION father="@dtype" id="dtype_Opt1" name="dtype_Opt1" value="int">Integer</OPTION><OPTION father="@dtype" id="dtype_Opt2" name="dtype_Opt2" value="float">Float</OPTION><OPTION father="@dtype" id="dtype_Opt3" name="dtype_Opt3" value="str">String</OPTION><OPTION father="@dtype" id="dtype_Opt4" name="dtype_Opt4" value="list">Array/List</OPTION></SELECT></DIV><BUTTON father="body" id="showhid">
                <!--Comment-->
            </BUTTON></BODY></HTML>
</code>```

Thanks.

答:
If you unbind the events before you bind them, it prevents them accidentally being bound twice. So if before the line:

$("#showhid").click(function(event){

You put this:

$('#showhid').unbind('click');

And before this line:

$("#createBt").click(function(event){

You put this:

$('#createBt').unbind('click');

This should solve your issue.

Body:
Hello i have this bizzare behavior when i click a button the response happens 2 times, and i don't understand what is going on???

This is the code of the javascript:

function main(){
//Creating the function that will be executed by the showhid.
$("#showhid").click(function(event){
    if ($('#btcreator').is(":visible") === true){

        $(this).button({
            icons:{secondary:'ui-icon-arrowthick-1-w'},
            text:false});

        $(this).animate({left:'97%'}, 'fast');

        $('#btcreator').animate({width:'hide'}, 'fast');

        return;
    }else if($('#btcreator').is(":visible") === false){

        $(this).button({
            icons:{secondary:'ui-icon-arrowthick-1-e'},
            text:false});

        $(this).animate({left:'522px'}, 'fast');

        $('#btcreator').animate({width:'show'}, 'fast');

        return;
    }
});

//Executing the button function on the createBt Button.
$("#createBt").button();
//Creating the function that will create the batute.
$("#createBt").click(function(event){
    if (getData('fatherbt') == 'none'){
        window.fileLoc="modules/appgen/devBt/"+$('#body').attr('key').substring(0, 5);
        elMnt = window.operation.createElement('element');
        elMnt.setAttribute('name', 'attr');
        elMnt.setAttribute('id', 'idEl');
        elMnt.setAttribute('attrname', 'id');
        elMnt.setAttribute('vtype', 'str');
        elMnt.setAttribute('value', getData('fncnm'));
        window.data_lst = [elMnt];
        elAttr = window.operation.createElement('element');
        elAttr.setAttribute('name', 'attr');
        elAttr.setAttribute('id', 'nameEl');
        elAttr.setAttribute('attrname', 'name');
        elAttr.setAttribute('vtype', 'str');
        elAttr.setAttribute('value', getData('fncName'));
        window.data_lst.push(elAttr);
        window.addEl = 'function';
        catcher('crtBt');
        alert(event.data);
    }
});
}}

This is the code of the page...

<LINK href="http://dev.karinapp.com/modules/appgen/css/batute.css" id="css_batute_4" rel="stylesheet" type="text/css"/><LINK href="http://dev.karinapp.com/modules/batute/css/main.css" id="css_batute_22" rel="stylesheet" type="text/css"/><LINK href="http://dev.karinapp.com/modules/general/css/karinapp-style/jquery-ui-1.8.4.custom.css" id="link4" rel="stylesheet" type="text/css"/>

                          Name:

            Father:

            <INPUT father="@btcreator" id="fncnm" type="text"/>
            <SELECT father="@btcreator" id="fatherbt"><OPTION father="@fatherbt" id="fatherbt_Opt0" name="fatherbt_Opt0" value="none">No father</OPTION></SELECT>

            <BUTTON father="@btcreator" id="createBt">Create</BUTTON><SELECT father="@btcreator" id="fncName"><OPTION father="@fncName" id="fncName_Opt0" name="fncName_Opt0" value="default">Select one...</OPTION><OPTION father="@fncName" id="fncName_Opt1" name="fncName_Opt1" value="oper">Operation</OPTION><OPTION father="@fncName" id="fncName_Opt2" name="fncName_Opt2" value="dirls">List of directories</OPTION><OPTION father="@fncName" id="fncName_Opt3" name="fncName_Opt3" value="opnfl">Open File</OPTION><OPTION father="@fncName" id="fncName_Opt4" name="fncName_Opt4" value="delete">Delete File</OPTION><OPTION father="@fncName" id="fncName_Opt5" name="fncName_Opt5" value="compare">Compare</OPTION><OPTION father="@fncName" id="fncName_Opt6" name="fncName_Opt6" value="cp">Copy</OPTION><OPTION father="@fncName" id="fncName_Opt7" name="fncName_Opt7" value="get">Get</OPTION><OPTION father="@fncName" id="fncName_Opt8" name="fncName_Opt8" value="switch">Switch(If-Else)</OPTION><OPTION father="@fncName" id="fncName_Opt9" name="fncName_Opt9" value="upload">Upload</OPTION><OPTION father="@fncName" id="fncName_Opt10" name="fncName_Opt10" value="modify">Modify(Elements)</OPTION><OPTION father="@fncName" id="fncName_Opt11" name="fncName_Opt11" value="create">Create(Elements)</OPTION><OPTION father="@fncName" id="fncName_Opt12" name="fncName_Opt12" value="find">Select(SQL)</OPTION><OPTION father="@fncName" id="fncName_Opt13" name="fncName_Opt13" value="insert">Insert(SQL)</OPTION><OPTION father="@fncName" id="fncName_Opt14" name="fncName_Opt14" value="update">Update(SQL)</OPTION></SELECT><BUTTON father="@btcreator" id="addRpl" value="Add Reply">Add Reply</BUTTON>Function:

                <BUTTON father="@rplCrt" id="crtMdl" value="Create Model">Create model</BUTTON>
                <BUTTON father="@rplCrt" id="stcRpl" value="Add Static Reply">Add static Reply</BUTTON>
                <BUTTON father="@rplCrt" id="addMdl"></BUTTON><TEXTAREA cols="45" father="@rplCrt" id="insertStc" rows="15"></TEXTAREA>

Function name:
Select

Insert model on:<INPUT father="@rplCrt" id="mdIns"/>

        Data-Type:<SELECT father="@btcreator" id="dtype"><OPTION father="@dtype" id="dtype_Opt0" name="dtype_Opt0" value="data">Data</OPTION><OPTION father="@dtype" id="dtype_Opt1" name="dtype_Opt1" value="int">Integer</OPTION><OPTION father="@dtype" id="dtype_Opt2" name="dtype_Opt2" value="float">Float</OPTION><OPTION father="@dtype" id="dtype_Opt3" name="dtype_Opt3" value="str">String</OPTION><OPTION father="@dtype" id="dtype_Opt4" name="dtype_Opt4" value="list">Array/List</OPTION></SELECT>
<BUTTON father="body" id="showhid">

            </BUTTON>

Thanks.


问:
How to update a GemFire Region based on changes in some other Region
My retail application has various contexts like receive, transfer etc. The requests to these contexts are handled by RESTful microservices developed using Spring Boot. The persistence layer is Cassandra. This is shared by all services as we couldn't do a vertical scaling for microservices at DB level as the services are tightly coupled conceptually.

We want vertical scaling at GemFire end by creating different Regions for different contexts.

For example, a BOX table in Cassandra will be updated by Region Box-Receive(receive context) and Region Box-Transfer(transfer context) via CacheWriter.

Our problem is how to maintain data sync between these two Regions?
Please suggest any other approach also for separation at GemFire end.

gemfire version-

```<code><dependency>
        <groupId>com.gemstone.gemfire</groupId>
        <artifactId>gemfire</artifactId>
        <version>8.2.6</version>
</dependency>
</code>```

答:
One alternative approach, since you are using Spring Boot would be to do the following:

First annotation your @SpringBootApplication class with @EnableGemfireCacheTransactions...

Example:

```<code>@SpringBootApplication
@EnableGemfireCacheTransactions
@EnableGemfireRepositories
class YourSpringBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(YourSpringBootApplication.class, args);
    }

    ...
}
</code>```

The @EnableGemfireCacheTransactions annotation enables Spring Data GemFire's GemfireTransactionManager, which integrates GemFire's CacheTransactionManager with Spring Transaction Management infrastructure which then allows you to do this...

Now, just annotate your @Service application component transactional service methods with core Spring's @Transactional annotation, like so...

@Service
class YourBoxReceiverTransferService {

```<code>@Transactional
public <return-type> update(ReceiveContext receiveContext,
        TransferContext transferContext {

    ...
    receiveContextRepository.save(receiveContext);
    transferContextRepository.save(transferContext);
    ...
}
</code>```

}

As you can see here, I also used Spring Data (GemFire's) Repository infrastructure to manage the persistence operations (e.g. CRUD), which will be used appropriately in the transactional scoped-context setup by Spring.

2 advantages with the Spring approach, over using GemFire's public API, which unnecessarily couples you to GemFire (a definite code smell, particularly in a Spring context), is...

You don't have to place a bunch of boilerplate, crap code in to your application components, which does not belong there!

Using Spring's Transaction Management infrastructure, it is extremely easy to change your Transaction Management Strategy, such as by switching from GemFire's local-only cache transactions, to say, Global, JTA-based Transactions if the need every arises (such as, oh, well, now I need to send a message over a JMS message queue after the GemFire Region's and Cassandra BOX Table are updated to notify some downstream process that the Receiver/Transfer context has been updated).  With Spring's Transaction Management infrastructure, you do not need to change a single line of application code to change transaction management strategies (such as local to global, or global to local, etc).

Hope this helps!

-John

Body:
My retail application has various contexts like receive, transfer etc. The requests to these contexts are handled by RESTful microservices developed using Spring Boot. The persistence layer is Cassandra. This is shared by all services as we couldn't do a vertical scaling for microservices at DB level as the services are tightly coupled conceptually.

We want vertical scaling at GemFire end by creating different Regions for different contexts.

For example, a BOX table in Cassandra will be updated by Region Box-Receive(receive context) and Region Box-Transfer(transfer context) via CacheWriter.

Our problem is how to maintain data sync between these two Regions?
Please suggest any other approach also for separation at GemFire end.

gemfire version-

<dependency>
        <groupId>com.gemstone.gemfire</groupId>
        <artifactId>gemfire</artifactId>
        <version>8.2.6</version>
</dependency>

Body:
One alternative approach, since you are using Spring Boot would be to do the following:

First annotation your @SpringBootApplication class with @EnableGemfireCacheTransactions...

Example:

@SpringBootApplication
@EnableGemfireCacheTransactions
@EnableGemfireRepositories
class YourSpringBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(YourSpringBootApplication.class, args);
    }

    ...
}

The @EnableGemfireCacheTransactions annotation enables Spring Data GemFire's GemfireTransactionManager, which integrates GemFire's CacheTransactionManager with Spring Transaction Management infrastructure which then allows you to do this...

Now, just annotate your @Service application component transactional service methods with core Spring's @Transactional annotation, like so...

@Service
class YourBoxReceiverTransferService {

@Transactional
public <return-type> update(ReceiveContext receiveContext,
        TransferContext transferContext {

    ...
    receiveContextRepository.save(receiveContext);
    transferContextRepository.save(transferContext);
    ...
}

}

As you can see here, I also used Spring Data (GemFire's) Repository infrastructure to manage the persistence operations (e.g. CRUD), which will be used appropriately in the transactional scoped-context setup by Spring.

2 advantages with the Spring approach, over using GemFire's public API, which unnecessarily couples you to GemFire (a definite code smell, particularly in a Spring context), is...

You don't have to place a bunch of boilerplate, crap code in to your application components, which does not belong there!

Using Spring's Transaction Management infrastructure, it is extremely easy to change your Transaction Management Strategy, such as by switching from GemFire's local-only cache transactions, to say, Global, JTA-based Transactions if the need every arises (such as, oh, well, now I need to send a message over a JMS message queue after the GemFire Region's and Cassandra BOX Table are updated to notify some downstream process that the Receiver/Transfer context has been updated).  With Spring's Transaction Management infrastructure, you do not need to change a single line of application code to change transaction management strategies (such as local to global, or global to local, etc).

Hope this helps!

-John


答:
Vector can resize because it a class. It hides data inside an object and you cannot see its internal structure directly. You just work with its public interface. It can allocate a new larger array a copy data to it without you seeing it.

You cannot do this with int*, because you have no class here, no place to hide real implementation from user.

Title: How to add objects to a pointer


问:
Issues about C# connecting to EC2
I am currently using Amazon EC2 (AMI linux) + MySQL, and now I am working on C# stuff.

I wrote code like this:

```<code>        MySqlConnection DBConn = new MySqlConnection();
        DBConn.ConnectionString = "Server=ec2-**.compute-1.amazonaws.com;Database=****;uid=root;password=****;port=3306;charset=utf8";

        try
        {
            DBConn.Open();
        }
        catch (Exception ex)
        {
            MessageBox.Show("connecting fail");
        }
</code>```

But for some reason, when I run this, it generates a 'connecting fail' error.

I googled and figured out that I need to set "grant all privileges *.* to root@'localhost' "

So, I did that!

But it still doesn't work. I think I followed all of the steps though.

I am working on Visual studio 2008 & Windows7 at the moment.

I Checked the error and it seems like it's a timeout error. I think it's a firewall thing but don't know what I should do. I set my security group so the TCP ports are opened to all (incl. Mysql). It's still not working. Isn't that the way to solve this problem?;(
However, the thing that I am curious about is that I could access to the database using MySQL workbench before I set the security group.

Sorry that I am totally new to EC2.

答: You should turn on VPC Flow Logs on that ENI to see if the connection is getting accepted on that interface, or rejected. High chance that your security groups are no correct, as gandil mentioned.</p>

Title: Issues about C# connecting to EC2

Body:
I am currently using Amazon EC2 (AMI linux) + MySQL, and now I am working on C# stuff.

I wrote code like this:

        MySqlConnection DBConn = new MySqlConnection();
        DBConn.ConnectionString = "Server=ec2-**.compute-1.amazonaws.com;Database=****;uid=root;password=****;port=3306;charset=utf8";

        try
        {
            DBConn.Open();
        }
        catch (Exception ex)
        {
            MessageBox.Show("connecting fail");
        }

But for some reason, when I run this, it generates a 'connecting fail' error.

I googled and figured out that I need to set "grant all privileges *.* to root@'localhost' "

So, I did that!

But it still doesn't work. I think I followed all of the steps though.

I am working on Visual studio 2008 & Windows7 at the moment.

I Checked the error and it seems like it's a timeout error. I think it's a firewall thing but don't know what I should do. I set my security group so the TCP ports are opened to all (incl. Mysql). It's still not working. Isn't that the way to solve this problem?;(
However, the thing that I am curious about is that I could access to the database using MySQL workbench before I set the security group.

Sorry that I am totally new to EC2.


问:
iOS 11, Cordova app sidebar disappears on scroll
we published several apps based on Cordova for iOS. The graphical interface framework we used was AdminLTE, derived from Bootstrap.
In all the apps, we have a sidebar, whose position is fixed in CSS. Beside it, we have a scrollable content (a series of LI inside an UL list). Everything was fine until iOS 10, but now we have a strange behaviour. Scrolling the content, the sidebar simply disappears.
I have read many suggestions (especially this Overflow scrolling not working on position fixed element iOS).
None of the solutions really work. But the strangest thing is that this behaviour only started in betas of iOS11 (while the proposed solutions are from iOS 5 and later).

When I say it does not work, I mean that this fix:

```<code>.main-sidebar * {
    transform: translate3d(0,0,0); }
</code>```

applies correctly to the first inner element of .main-sidebar, while the other sub-elements still disappear.

So, anybody has faced this particular situation?

Thanks
Fabio

答:
Try giving an actual value to the z axis. ie: transform: translate3d(0,0,1px).

I've found that I have better luck engaging hardware acceleration with that, rather than an empty zero value.

But I doubt it'll fix the problem entirely. I'm having all sorts of disappearing content issues with iOS 11 and can't fix them. Strangely, I can't reproduce them in the normal mobile Safari browser. They only show in the headless web view.

Body:
we published several apps based on Cordova for iOS. The graphical interface framework we used was AdminLTE, derived from Bootstrap.
In all the apps, we have a sidebar, whose position is fixed in CSS. Beside it, we have a scrollable content (a series of LI inside an UL list). Everything was fine until iOS 10, but now we have a strange behaviour. Scrolling the content, the sidebar simply disappears.
I have read many suggestions (especially this Overflow scrolling not working on position fixed element iOS).
None of the solutions really work. But the strangest thing is that this behaviour only started in betas of iOS11 (while the proposed solutions are from iOS 5 and later).

When I say it does not work, I mean that this fix:

.main-sidebar * {
    transform: translate3d(0,0,0); }

applies correctly to the first inner element of .main-sidebar, while the other sub-elements still disappear.

So, anybody has faced this particular situation?

Thanks
Fabio


问:
RabbitMQ separate listeners by type
I have POJO which represents a message to Rabbit MQ. There is an integer which is responsible for the type of the message(whether it's update, remove, add and so on):

public class Message {
    private String field1;
    private String field2;

    private Integer type;
    ...
    <some other fields>
}
```

I have a consumer which accepts such messages in my spring boot app. So in order to handle each type separately, I have to add some switch/case construction in my code.

Are there any more clear solutions for such case?

答:
You can use Spring Integration with a router...

```<code>Rabbit Inbound channel adapter -> router ->
</code>```

Where the router routes to a different service activator (method) based on the type.

EDIT

Here's an example:

```<code>@SpringBootApplication
public class So47272336Application {

    public static void main(String[] args) {
        SpringApplication.run(So47272336Application.class, args);
    }

    @Bean
    public ApplicationRunner runner(RabbitTemplate rabbitTemplate) {
        return args -> {
            rabbitTemplate.convertAndSend("my.queue", new Domain(1, "foo"));
            rabbitTemplate.convertAndSend("my.queue", new Domain(2, "bar"));
            rabbitTemplate.convertAndSend("my.queue", new Domain(3, "baz"));
        };
    }

    @Bean
    public Queue queue() {
        return new Queue("my.queue");
    }

    @Bean
    public IntegrationFlow flow(ConnectionFactory connectionFactory) {
        return IntegrationFlows.from(Amqp.inboundAdapter(connectionFactory, "my.queue"))
                .route("payload.type", r -> r
                        .subFlowMapping("1", f -> f.handle("bean", "add"))
                        .subFlowMapping("2", f -> f.handle("bean", "remove"))
                        .subFlowMapping("3", f -> f.handle("bean", "update")))
                .get();
    }

    @Bean
    public MyBean bean() {
        return new MyBean();
    }

    public static class MyBean {

        public void add(Domain object) {
            System.out.println("Adding " + object);
        }

        public void remove(Domain object) {
            System.out.println("Removing " + object);
        }

        public void update(Domain object) {
            System.out.println("Updating " + object);
        }

    }

    public static class Domain implements Serializable {

        private final Integer type;

        private final String info;

        public Domain(Integer type, String info) {
            this.type = type;
            this.info = info;
        }

        public Integer getType() {
            return this.type;
        }

        public String getInfo() {
            return this.info;
        }

        @Override
        public String toString() {
            return "Domain [type=" + this.type + ", info=" + this.info + "]";
        }

    }

}
</code>```

Title: RabbitMQ separate listeners by type

Body:
I have POJO which represents a message to Rabbit MQ. There is an integer which is responsible for the type of the message(whether it's update, remove, add and so on):

public class Message {
    private String field1;
    private String field2;

    private Integer type;
    ...
    <some other fields>
}

I have a consumer which accepts such messages in my spring boot app. So in order to handle each type separately, I have to add some switch/case construction in my code.

Are there any more clear solutions for such case?

Body:
You can use Spring Integration with a router...

Rabbit Inbound channel adapter -> router ->

Where the router routes to a different service activator (method) based on the type.

EDIT

Here's an example:

@SpringBootApplication
public class So47272336Application {

    public static void main(String[] args) {
        SpringApplication.run(So47272336Application.class, args);
    }

    @Bean
    public ApplicationRunner runner(RabbitTemplate rabbitTemplate) {
        return args -> {
            rabbitTemplate.convertAndSend("my.queue", new Domain(1, "foo"));
            rabbitTemplate.convertAndSend("my.queue", new Domain(2, "bar"));
            rabbitTemplate.convertAndSend("my.queue", new Domain(3, "baz"));
        };
    }

    @Bean
    public Queue queue() {
        return new Queue("my.queue");
    }

    @Bean
    public IntegrationFlow flow(ConnectionFactory connectionFactory) {
        return IntegrationFlows.from(Amqp.inboundAdapter(connectionFactory, "my.queue"))
                .route("payload.type", r -> r
                        .subFlowMapping("1", f -> f.handle("bean", "add"))
                        .subFlowMapping("2", f -> f.handle("bean", "remove"))
                        .subFlowMapping("3", f -> f.handle("bean", "update")))
                .get();
    }

    @Bean
    public MyBean bean() {
        return new MyBean();
    }

    public static class MyBean {

        public void add(Domain object) {
            System.out.println("Adding " + object);
        }

        public void remove(Domain object) {
            System.out.println("Removing " + object);
        }

        public void update(Domain object) {
            System.out.println("Updating " + object);
        }

    }

    public static class Domain implements Serializable {

        private final Integer type;

        private final String info;

        public Domain(Integer type, String info) {
            this.type = type;
            this.info = info;
        }

        public Integer getType() {
            return this.type;
        }

        public String getInfo() {
            return this.info;
        }

        @Override
        public String toString() {
            return "Domain [type=" + this.type + ", info=" + this.info + "]";
        }

    }

}


问:
Trouble with retrieving 'ISO-8859-5'-encoded string from file in JavaScript
In my project I'm using third-party library which reads DICOM file and displays some data from it. When it comes to read properties with cyrillic symbols, I get broken string as output. By using encoding/decoding tool I determined that cyrillic symbols were encoded with ISO-8859-5 and then dispalyed as ISO-8859-1.

So my specific question: having a string variable with value:

Á°ÀÁµ¼±°µ²°

how can I convert it to:

САРСЕМБАЕВА

by using JavaScript?

答:
Here is a library which allows to solve the problem like:</p>

```<code>var repairedString
        = cptable.utils.decode(28595, brokenString);
</code>```

Body:
Here is a library which allows to solve the problem like:

var repairedString
        = cptable.utils.decode(28595, brokenString);