问:
Run jQuery function on initial page load and scroll
I'm working on a design and I would like make a few blocks "slide in" from the sides when they're in-view of the window. I have it working after following some tutorials online, but it will only work if the elements are not in-view and you scroll down the page to see them. What I would like to do is have the elements also "slide" when the page loads initially. I feel this might be too much code to just post here, so I added everything to a fiddle.

/*Interactivity to determine when an animated element in in view. In view elements trigger our animation*/
$(document).ready(function() {

  //window and animation items
  var animation_elements = $.find('.animation-element');
  var web_window = $(window);

  //check to see if any animation containers are currently in view
  function check_if_in_view() {
    //get current window information
    var window_height = web_window.height();
    var window_top_position = web_window.scrollTop();
    var window_bottom_position = (window_top_position + window_height);

    //iterate through elements to see if its in view
    $.each(animation_elements, function() {

      //get the elements information
      var element = $(this);
      var element_height = $(element).outerHeight();
      var element_top_position = $(element).offset().top;
      var element_bottom_position = (element_top_position + element_height);

      //check to see if this current container is visible (its viewable if it exists between the viewable space of the viewport)
      if ((element_bottom_position >= window_top_position) && (element_top_position <= window_bottom_position)) {
        element.addClass('in-view');
      } else {
        element.removeClass('in-view');
      }
    });

  }

  //on or scroll, detect elements in view
  $(window).on('scroll resize', function() {
    check_if_in_view()
  })
  //trigger our scroll event on initial load
  $(document).ready('scroll');

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  margin-left: auto;
  margin-right: auto;
  width: 80%;
}

.row {
  border-bottom: solid 1px transparent;
  margin-bottom: 2em;
}

.row>* {
  float: left;
}

.row:after,
.row:before {
  content: '';
  display: block;
  clear: both;
  height: 0;
}

.row.uniform>*> :first-child {
  margin-top: 0;
}

.row.uniform>*> :last-child {
  margin-bottom: 0;
}

.wrapper {
  padding: 1em 0em 4em;
}

.profiles {
  margin-bottom: 4em;
  padding-top: 4em;
  background-color: #fff;
  height: 200px;
}

.profile {
  width: 24%;
  height: 100px;
  margin-bottom: 2em;
  margin-right: 2px;
  text-align: center;
  background-color: #666;
  border: 1px solid #000;
  color: black;
}

.animation-element {
  opacity: 0;
  position: relative;
}

.animation-element.slide-left {
  opacity: 0;
  -moz-transition: all 500ms linear;
  -webkit-transition: all 500ms linear;
  -o-transition: all 500ms linear;
  transition: all 500ms linear;
  -moz-transform: translate3d(-150px, 0px, 0px);
  -webkit-transform: translate3d(-150px, 0px, 0px);
  -o-transform: translate(-150px, 0px);
  -ms-transform: translate(-150px, 0px);
  transform: translate3d(-150px, 0px, 0px);
}

.animation-element.slide-left.in-view {
  opacity: 1;
  -moz-transform: translate3d(0px, 0px, 0px);
  -webkit-transform: translate3d(0px, 0px, 0px);
  -o-transform: translate(0px, 0px);
  -ms-transform: translate(0px, 0px);
  transform: translate3d(0px, 0px, 0px);
}

/*animation element sliding right*/

.animation-element.slide-right {
  opacity: 0;
  -moz-transition: all 500ms linear;
  -webkit-transition: all 500ms linear;
  -o-transition: all 500ms linear;
  transition: all 500ms linear;
  -moz-transform: translate3d(150px, 0px, 0px);
  -webkit-transform: translate3d(150px, 0px, 0px);
  -o-transform: translate(150px, 0px);
  -ms-transform: translate(150px, 0px);
  transform: translate3d(150px, 0px, 0px);
}

.animation-element.slide-right.in-view {
  opacity: 1;
  -moz-transform: translate3d(0px, 0px, 0px);
  -webkit-transform: translate3d(0px, 0px, 0px);
  -o-transform: translate(0px, 0px);
  -ms-transform: translate(0px, 0px);
  transform: translate3d(0px, 0px, 0px);
}</code>```

```
</div>
</div>
</p>

<p>The bit of code that I've been playing with is at the bottom of the jquery bit, but nothing I change seems to effect anything.</p>

``` //trigger our scroll event on initial load
$(document).ready('scroll');
```

But I will admit I have very little knowledge of this, and I'm just following tutorials and examples online. On the fiddle, if you scroll down and back up, you'll see the boxes slide into view. What I'm wanting to do is make them slide in on the initial page load and also as you scroll down the page (i'm using the same code on other elements further down the page on the full version).

Thank you to anyone who can help me!

答:
https://api.jquery.com/ready/

Description: Specify a function to execute when the DOM is fully loaded.

You can't just pass in "scroll", as that is not a function.  What you can do is call $(window).trigger('scroll') at the end, or do $(document).ready(check_if_in_view), as check_if_in_view is a function.

/*Interactivity to determine when an animated element in in view. In view elements trigger our animation*/
$(document).ready(function() {

  //window and animation items
  var animation_elements = $.find('.animation-element');
  var web_window = $(window);

  //check to see if any animation containers are currently in view
  function check_if_in_view() {
    //get current window information
    var window_height = web_window.height();
    var window_top_position = web_window.scrollTop();
    var window_bottom_position = (window_top_position + window_height);

    //iterate through elements to see if its in view
    $.each(animation_elements, function() {

      //get the elements information
      var element = $(this);
      var element_height = $(element).outerHeight();
      var element_top_position = $(element).offset().top;
      var element_bottom_position = (element_top_position + element_height);

      //check to see if this current container is visible (its viewable if it exists between the viewable space of the viewport)
      if ((element_bottom_position >= window_top_position) && (element_top_position <= window_bottom_position)) {
        element.addClass('in-view');
      } else {
        element.removeClass('in-view');
      }
    });

  }

  //on or scroll, detect elements in view
  $(window).on('scroll resize', function() {
    check_if_in_view()
  })
  //trigger our scroll event on initial load
  $(window).trigger('scroll');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  margin-left: auto;
  margin-right: auto;
  width: 80%;
}

.row {
  border-bottom: solid 1px transparent;
  margin-bottom: 2em;
}

.row>* {
  float: left;
}

.row:after,
.row:before {
  content: '';
  display: block;
  clear: both;
  height: 0;
}

.row.uniform>*> :first-child {
  margin-top: 0;
}

.row.uniform>*> :last-child {
  margin-bottom: 0;
}

.wrapper {
  padding: 1em 0em 4em;
}

.profiles {
  margin-bottom: 4em;
  padding-top: 4em;
  background-color: #fff;
  height: 200px;
}

.profile {
  width: 24%;
  height: 100px;
  margin-bottom: 2em;
  margin-right: 2px;
  text-align: center;
  background-color: #666;
  border: 1px solid #000;
  color: black;
}

.animation-element {
  opacity: 0;
  position: relative;
}

.animation-element.slide-left {
  opacity: 0;
  -moz-transition: all 500ms linear;
  -webkit-transition: all 500ms linear;
  -o-transition: all 500ms linear;
  transition: all 500ms linear;
  -moz-transform: translate3d(-150px, 0px, 0px);
  -webkit-transform: translate3d(-150px, 0px, 0px);
  -o-transform: translate(-150px, 0px);
  -ms-transform: translate(-150px, 0px);
  transform: translate3d(-150px, 0px, 0px);
}

.animation-element.slide-left.in-view {
  opacity: 1;
  -moz-transform: translate3d(0px, 0px, 0px);
  -webkit-transform: translate3d(0px, 0px, 0px);
  -o-transform: translate(0px, 0px);
  -ms-transform: translate(0px, 0px);
  transform: translate3d(0px, 0px, 0px);
}

/*animation element sliding right*/

.animation-element.slide-right {
  opacity: 0;
  -moz-transition: all 500ms linear;
  -webkit-transition: all 500ms linear;
  -o-transition: all 500ms linear;
  transition: all 500ms linear;
  -moz-transform: translate3d(150px, 0px, 0px);
  -webkit-transform: translate3d(150px, 0px, 0px);
  -o-transform: translate(150px, 0px);
  -ms-transform: translate(150px, 0px);
  transform: translate3d(150px, 0px, 0px);
}

.animation-element.slide-right.in-view {
  opacity: 1;
  -moz-transform: translate3d(0px, 0px, 0px);
  -webkit-transform: translate3d(0px, 0px, 0px);
  -o-transform: translate(0px, 0px);
  -ms-transform: translate(0px, 0px);
  transform: translate3d(0px, 0px, 0px);
}</code>```

```

Body:
I'm working on a design and I would like make a few blocks "slide in" from the sides when they're in-view of the window. I have it working after following some tutorials online, but it will only work if the elements are not in-view and you scroll down the page to see them. What I would like to do is have the elements also "slide" when the page loads initially. I feel this might be too much code to just post here, so I added everything to a fiddle.

/*Interactivity to determine when an animated element in in view. In view elements trigger our animation*/
$(document).ready(function() {

  //window and animation items
  var animation_elements = $.find('.animation-element');
  var web_window = $(window);

  //check to see if any animation containers are currently in view
  function check_if_in_view() {
    //get current window information
    var window_height = web_window.height();
    var window_top_position = web_window.scrollTop();
    var window_bottom_position = (window_top_position + window_height);

    //iterate through elements to see if its in view
    $.each(animation_elements, function() {

      //get the elements information
      var element = $(this);
      var element_height = $(element).outerHeight();
      var element_top_position = $(element).offset().top;
      var element_bottom_position = (element_top_position + element_height);

      //check to see if this current container is visible (its viewable if it exists between the viewable space of the viewport)
      if ((element_bottom_position >= window_top_position) && (element_top_position <= window_bottom_position)) {
        element.addClass('in-view');
      } else {
        element.removeClass('in-view');
      }
    });

  }

  //on or scroll, detect elements in view
  $(window).on('scroll resize', function() {
    check_if_in_view()
  })
  //trigger our scroll event on initial load
  $(document).ready('scroll');

});

.container {
  margin-left: auto;
  margin-right: auto;
  width: 80%;
}

.row {
  border-bottom: solid 1px transparent;
  margin-bottom: 2em;
}

.row>* {
  float: left;
}

.row:after,
.row:before {
  content: '';
  display: block;
  clear: both;
  height: 0;
}

.row.uniform>*> :first-child {
  margin-top: 0;
}

.row.uniform>*> :last-child {
  margin-bottom: 0;
}

.wrapper {
  padding: 1em 0em 4em;
}

.profiles {
  margin-bottom: 4em;
  padding-top: 4em;
  background-color: #fff;
  height: 200px;
}

.profile {
  width: 24%;
  height: 100px;
  margin-bottom: 2em;
  margin-right: 2px;
  text-align: center;
  background-color: #666;
  border: 1px solid #000;
  color: black;
}

.animation-element {
  opacity: 0;
  position: relative;
}

.animation-element.slide-left {
  opacity: 0;
  -moz-transition: all 500ms linear;
  -webkit-transition: all 500ms linear;
  -o-transition: all 500ms linear;
  transition: all 500ms linear;
  -moz-transform: translate3d(-150px, 0px, 0px);
  -webkit-transform: translate3d(-150px, 0px, 0px);
  -o-transform: translate(-150px, 0px);
  -ms-transform: translate(-150px, 0px);
  transform: translate3d(-150px, 0px, 0px);
}

.animation-element.slide-left.in-view {
  opacity: 1;
  -moz-transform: translate3d(0px, 0px, 0px);
  -webkit-transform: translate3d(0px, 0px, 0px);
  -o-transform: translate(0px, 0px);
  -ms-transform: translate(0px, 0px);
  transform: translate3d(0px, 0px, 0px);
}

/*animation element sliding right*/

.animation-element.slide-right {
  opacity: 0;
  -moz-transition: all 500ms linear;
  -webkit-transition: all 500ms linear;
  -o-transition: all 500ms linear;
  transition: all 500ms linear;
  -moz-transform: translate3d(150px, 0px, 0px);
  -webkit-transform: translate3d(150px, 0px, 0px);
  -o-transform: translate(150px, 0px);
  -ms-transform: translate(150px, 0px);
  transform: translate3d(150px, 0px, 0px);
}

.animation-element.slide-right.in-view {
  opacity: 1;
  -moz-transform: translate3d(0px, 0px, 0px);
  -webkit-transform: translate3d(0px, 0px, 0px);
  -o-transform: translate(0px, 0px);
  -ms-transform: translate(0px, 0px);
  transform: translate3d(0px, 0px, 0px);
}

The bit of code that I've been playing with is at the bottom of the jquery bit, but nothing I change seems to effect anything.

 //trigger our scroll event on initial load
$(document).ready('scroll');

But I will admit I have very little knowledge of this, and I'm just following tutorials and examples online. On the fiddle, if you scroll down and back up, you'll see the boxes slide into view. What I'm wanting to do is make them slide in on the initial page load and also as you scroll down the page (i'm using the same code on other elements further down the page on the full version).

Thank you to anyone who can help me!

Body:
https://api.jquery.com/ready/

Description: Specify a function to execute when the DOM is fully loaded.

You can't just pass in "scroll", as that is not a function.  What you can do is call $(window).trigger('scroll') at the end, or do $(document).ready(check_if_in_view), as check_if_in_view is a function.

/*Interactivity to determine when an animated element in in view. In view elements trigger our animation*/
$(document).ready(function() {

  //window and animation items
  var animation_elements = $.find('.animation-element');
  var web_window = $(window);

  //check to see if any animation containers are currently in view
  function check_if_in_view() {
    //get current window information
    var window_height = web_window.height();
    var window_top_position = web_window.scrollTop();
    var window_bottom_position = (window_top_position + window_height);

    //iterate through elements to see if its in view
    $.each(animation_elements, function() {

      //get the elements information
      var element = $(this);
      var element_height = $(element).outerHeight();
      var element_top_position = $(element).offset().top;
      var element_bottom_position = (element_top_position + element_height);

      //check to see if this current container is visible (its viewable if it exists between the viewable space of the viewport)
      if ((element_bottom_position >= window_top_position) && (element_top_position <= window_bottom_position)) {
        element.addClass('in-view');
      } else {
        element.removeClass('in-view');
      }
    });

  }

  //on or scroll, detect elements in view
  $(window).on('scroll resize', function() {
    check_if_in_view()
  })
  //trigger our scroll event on initial load
  $(window).trigger('scroll');
});

.container {
  margin-left: auto;
  margin-right: auto;
  width: 80%;
}

.row {
  border-bottom: solid 1px transparent;
  margin-bottom: 2em;
}

.row>* {
  float: left;
}

.row:after,
.row:before {
  content: '';
  display: block;
  clear: both;
  height: 0;
}

.row.uniform>*> :first-child {
  margin-top: 0;
}

.row.uniform>*> :last-child {
  margin-bottom: 0;
}

.wrapper {
  padding: 1em 0em 4em;
}

.profiles {
  margin-bottom: 4em;
  padding-top: 4em;
  background-color: #fff;
  height: 200px;
}

.profile {
  width: 24%;
  height: 100px;
  margin-bottom: 2em;
  margin-right: 2px;
  text-align: center;
  background-color: #666;
  border: 1px solid #000;
  color: black;
}

.animation-element {
  opacity: 0;
  position: relative;
}

.animation-element.slide-left {
  opacity: 0;
  -moz-transition: all 500ms linear;
  -webkit-transition: all 500ms linear;
  -o-transition: all 500ms linear;
  transition: all 500ms linear;
  -moz-transform: translate3d(-150px, 0px, 0px);
  -webkit-transform: translate3d(-150px, 0px, 0px);
  -o-transform: translate(-150px, 0px);
  -ms-transform: translate(-150px, 0px);
  transform: translate3d(-150px, 0px, 0px);
}

.animation-element.slide-left.in-view {
  opacity: 1;
  -moz-transform: translate3d(0px, 0px, 0px);
  -webkit-transform: translate3d(0px, 0px, 0px);
  -o-transform: translate(0px, 0px);
  -ms-transform: translate(0px, 0px);
  transform: translate3d(0px, 0px, 0px);
}

/*animation element sliding right*/

.animation-element.slide-right {
  opacity: 0;
  -moz-transition: all 500ms linear;
  -webkit-transition: all 500ms linear;
  -o-transition: all 500ms linear;
  transition: all 500ms linear;
  -moz-transform: translate3d(150px, 0px, 0px);
  -webkit-transform: translate3d(150px, 0px, 0px);
  -o-transform: translate(150px, 0px);
  -ms-transform: translate(150px, 0px);
  transform: translate3d(150px, 0px, 0px);
}

.animation-element.slide-right.in-view {
  opacity: 1;
  -moz-transform: translate3d(0px, 0px, 0px);
  -webkit-transform: translate3d(0px, 0px, 0px);
  -o-transform: translate(0px, 0px);
  -ms-transform: translate(0px, 0px);
  transform: translate3d(0px, 0px, 0px);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="wrapper">
  <div class="container">
    <section class="profiles">
      <div class="row">
        <section class="profile animation-element slide-left">
        </section>
        <section class="profile animation-element slide-left">
        </section>
        <section class="profile animation-element slide-right">
        </section>
        <section class="profile animation-element slide-right">
        </section>
      </div>
    </section>
  </div>
</section>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>


来源: stackexchange

问:
Is it possible to translate secrets in Azure Key Vault?
I'm receiving a secret encrypted with Key A, and need to send it somewhere else encrypted under Key B.

Both keys can be symmetric or asymmetric - but I'd like to achieve this within the vault itself (first prize) - (avoiding a decrypt, having the secret in the clear, then an encrypt).

Is this possible with Azure Key Vault?  If not, any workarounds?

Thanks.

答:
As far as I am aware, at this point in time, it is not possible with the current Key Vault API's. The way I think of Key Vault at this point in time is it's just a tailored service for storing and gaining access to Keys, Secrets, Certificates and managing applications and users that can access them (with some fancy bits on top).

You will need to decrypt and re-encrypt somewhere outside of Key Vault.

One possible workaround though given you are in Azure is to create an Azure Function to do this work. At least then the process of the translation happens inside an isolated Function context (in Azure). The beauty of using an Azure Function is that you could do this with minimal code and without a full application, but you would need to ensure that Function can only be utilised by you.

A possible workflow could be:

1) If Key A is not in Key Vault, upload it.

2) If Key B is not in Key Vault, upload it.

3) Run Azure Function with inputs for Key Vault identifiers for Key A, Key B and A(Secret). Do the conversion and then the Function could store B(Secret) in Key Vault (or another Key Vault if you have access to one).

Alternatively it could just output the new encrypted secret.

C# Key Vault Client:

https://learn.microsoft.com/en-us/azure/key-vault/key-vault-use-from-web-application

An example of Azure Function and Key Vault in C# for reference: http://www.rahulpnath.com/blog/azure-key-vault-from-azure-functions/

ContentLicense: CC BY-SA 3.0


答:
Pass your function as a reference to both the event listener and ready()

```<code>$(window).on('scroll resize', check_if_in_view);

$(document).ready(check_if_in_view);
</code>```

Title: Run jQuery function on initial page load and scroll

Body:
Pass your function as a reference to both the event listener and ready()

$(window).on('scroll resize', check_if_in_view);

$(document).ready(check_if_in_view);


问:
ModelState.IsValid returning FALSE because of Auto-Increment Field Not Included
I have two structurally identical tables that each have simple Create New, and Update forms. One of the tables works perfect when both updating and adding new rows... The other table works fine for updating, but can't make it past ModelState.IsValid when creating a new row.

I'm given an error message that says the 'ID' field must be included even though that is an auto-incrementing primary key. I also tried submitting a null value but that doesn't work either.

As far as I can tell both of my primary keys are set up the same way and have they both use a LINQ to Entities Model.

```<code> [HttpPost]
    public ActionResult CreateProduct(Product product)
    {
        if (ModelState.IsValid)
        {
            productrepository.Add(product);
            productrepository.Save();

            return RedirectToAction("ProductList");
        }
        return View();
    }
</code>```

Any suggestions?

Thanks!

答:
I changed my auto-incrementing column name from 'ID' to 'AutoID' and now it seems to work.

This was the only difference I could find between the two tables so I'm guessing either my model needed to be updated or using 'ID' was implying something unintentional.

I'm still not sure why it didn't work, I'm just glad I got it working!

ContentLicense: CC BY-SA 2.5

Body:
I have two structurally identical tables that each have simple Create New, and Update forms. One of the tables works perfect when both updating and adding new rows... The other table works fine for updating, but can't make it past ModelState.IsValid when creating a new row.

I'm given an error message that says the 'ID' field must be included even though that is an auto-incrementing primary key. I also tried submitting a null value but that doesn't work either.

As far as I can tell both of my primary keys are set up the same way and have they both use a LINQ to Entities Model.

 [HttpPost]
    public ActionResult CreateProduct(Product product)
    {
        if (ModelState.IsValid)
        {
            productrepository.Add(product);
            productrepository.Save();

            return RedirectToAction("ProductList");
        }
        return View();
    }

Any suggestions?

Thanks!


问:
Angular-ui-router: ui-sref-active and nested states
I am using angular-ui-router and nested states in my application, and I also have a navigation bar. The nav bar is hand written, and uses ui-sref-active to highlight the current state. It is a two-level navigation bar.

Now, when I am in, say Products / Categories I would like both Products (in level 1) and Categories (in level 2) to be highlighted. However, using ui-sref-active, if I am in state Products.Categories then only that state is highlighted, not Products.

Is there some way to make Products highlight in that state?

答:
My code navigated from /productGroups to /productPartitions, which is the only way to access "productPartitions" view.

So I added a hidden anchor with ui-sref also set to "productPartitions" within the same list item that has ui-sref-active

```<code><li ui-sref-active="active">
     <a ui-sref="productGroups">
     <i class="fa fa-magic"></i> Product groups </a>
     <a ui-sref="productPartitions" style="display:none;"></a>
</li>
</code>```

Now the productGroups navigation button remains active when accessing either view

Body:
My code navigated from /productGroups to /productPartitions, which is the only way to access "productPartitions" view.

So I added a hidden anchor with ui-sref also set to "productPartitions" within the same list item that has ui-sref-active

<li ui-sref-active="active">
     <a ui-sref="productGroups">
     <i class="fa fa-magic"></i> Product groups </a>
     <a ui-sref="productPartitions" style="display:none;"></a>
</li>

Now the productGroups navigation button remains active when accessing either view


问:
Pig latin Limit operator applied to each group attribute
I am trying to return only the five largest places based on population in each state.  I am also trying to sort the result by state name, with places in each state listed in declining order of population.  What I have currently gives me only the first five places with states and not the five largest places for each state.

```<code>-- Groups places by state name.
group_by_state_name_populated_place_name =
    GROUP project_using_state_name
    BY (state::name, place::name);

-- Counts population for each place in every state.
count_population_for_each_place_in_every_state =
    FOREACH group_by_state_name_populated_place_name
    GENERATE group.state::name AS state_name,
             group.place::name AS name,
             COUNT(project_using_state_name.population) AS population;

-- Orders population in each group found above to enable the use of limit.
order_groups_of_states_and_population =
    ORDER count_population_for_each_place_in_every_state
    BY state_name ASC, population DESC, name ASC;

-- Limit the top 5 population for each state BUT currently returning just the first 5 tuples of the previous one and not 5 of each state.
limit_population =
    LIMIT order_groups_of_states_and_population 5;
</code>```

答:
Below code snippet may help</p>

```<code>inp_data = load 'input_data.csv' using PigStorage(',') AS (state:chararray,place:chararray,population:long);

req_stats = FOREACH(GROUP inp_data BY state) {
    ordered = ORDER inp_data BY population DESC;
    required = LIMIT ordered 5;
    GENERATE FLATTEN(required);
};

req_stats_ordered = ORDER req_stats BY state, population DESC;

DUMP req_stats_ordered;
</code>```

Body:
I am trying to return only the five largest places based on population in each state.  I am also trying to sort the result by state name, with places in each state listed in declining order of population.  What I have currently gives me only the first five places with states and not the five largest places for each state.

-- Groups places by state name.
group_by_state_name_populated_place_name =
    GROUP project_using_state_name
    BY (state::name, place::name);

-- Counts population for each place in every state.
count_population_for_each_place_in_every_state =
    FOREACH group_by_state_name_populated_place_name
    GENERATE group.state::name AS state_name,
             group.place::name AS name,
             COUNT(project_using_state_name.population) AS population;

-- Orders population in each group found above to enable the use of limit.
order_groups_of_states_and_population =
    ORDER count_population_for_each_place_in_every_state
    BY state_name ASC, population DESC, name ASC;

-- Limit the top 5 population for each state BUT currently returning just the first 5 tuples of the previous one and not 5 of each state.
limit_population =
    LIMIT order_groups_of_states_and_population 5;

Body:
Below code snippet may help

inp_data = load 'input_data.csv' using PigStorage(',') AS (state:chararray,place:chararray,population:long);

req_stats = FOREACH(GROUP inp_data BY state) {
    ordered = ORDER inp_data BY population DESC;
    required = LIMIT ordered 5;
    GENERATE FLATTEN(required);
};

req_stats_ordered = ORDER req_stats BY state, population DESC;

DUMP req_stats_ordered;


问:
unsigned char array from c++ in c#
I'm trying to call a C++ dll function in C#.
The function has a struct as a parameter and I have a problem with the variable aby_data[8]. I defined the unsigned char[] as a byte[], the program doesn't crash but I don't receive any data.

Struct C++

```<code>typedef struct st_canmsg
{
    long l_id;
    unsigned char by_len;
    unsigned char by_msg_lost;
    unsigned char by_extended;
    unsigned char by_remote;
    unsigned char aby_data[8];
    unsigned long ul_tstamp;
} CMSG;
</code>```

Conversion to C#

```<code>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CMSG
{
    public Int32 l_id;
    public byte by_len;
    public byte by_msg_lost;
    public byte by_extended;
    public byte by_remote;
    public byte aby_data[];
    public UInt32 ul_tstamp;
};

CMSG t_CANMsg[] = new CMSG[1];
t_CANMsg[0].aby_data = new byte[8];
t_CANMsg[0].aby_data[0] = 01;
t_CANMsg[0].aby_data[1] = 02;
t_CANMsg[0].aby_data[2] = 03;
t_CANMsg[0].aby_data[3] = 04;
t_CANMsg[0].aby_data[4] = 05;
t_CANMsg[0].aby_data[5] = 06;
t_CANMsg[0].aby_data[6] = 07;
t_CANMsg[0].aby_data[7] = 08;

l_retval = canSend(handle, out t_CANMsg[0], out len);
</code>```

答:
You're marshalling a fixed-length array, but you did not specify the size of your array in your struct definition.

Can you try to update your struct definition like this:

```<code>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CMSG
{
    public Int32 l_id;
    public byte by_len;
    public byte by_msg_lost;
    public byte by_extended;
    public byte by_remote;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
    public byte aby_data[];
    public UInt32 ul_tstamp;
};
</code>```

Alternatively, you can also try to explicitly define the bytes:

```<code>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CMSG
{
    public Int32 l_id;
    public byte by_len;
    public byte by_msg_lost;
    public byte by_extended;
    public byte by_remote;
    public byte aby_data_0;
    public byte aby_data_1;
    public byte aby_data_2;
    public byte aby_data_3;
    public byte aby_data_4;
    public byte aby_data_5;
    public byte aby_data_6;
    public byte aby_data_7;
    public UInt32 ul_tstamp;
};
</code>```

If you're still having issues, you also share the declaration of canSend?

Title: unsigned char array from c++ in c#

Body:
I'm trying to call a C++ dll function in C#.
The function has a struct as a parameter and I have a problem with the variable aby_data[8]. I defined the unsigned char[] as a byte[], the program doesn't crash but I don't receive any data.

Struct C++

typedef struct st_canmsg
{
    long l_id;
    unsigned char by_len;
    unsigned char by_msg_lost;
    unsigned char by_extended;
    unsigned char by_remote;
    unsigned char aby_data[8];
    unsigned long ul_tstamp;
} CMSG;

Conversion to C#

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CMSG
{
    public Int32 l_id;
    public byte by_len;
    public byte by_msg_lost;
    public byte by_extended;
    public byte by_remote;
    public byte aby_data[];
    public UInt32 ul_tstamp;
};

CMSG t_CANMsg[] = new CMSG[1];
t_CANMsg[0].aby_data = new byte[8];
t_CANMsg[0].aby_data[0] = 01;
t_CANMsg[0].aby_data[1] = 02;
t_CANMsg[0].aby_data[2] = 03;
t_CANMsg[0].aby_data[3] = 04;
t_CANMsg[0].aby_data[4] = 05;
t_CANMsg[0].aby_data[5] = 06;
t_CANMsg[0].aby_data[6] = 07;
t_CANMsg[0].aby_data[7] = 08;

l_retval = canSend(handle, out t_CANMsg[0], out len);

Body:
You're marshalling a fixed-length array, but you did not specify the size of your array in your struct definition.

Can you try to update your struct definition like this:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CMSG
{
    public Int32 l_id;
    public byte by_len;
    public byte by_msg_lost;
    public byte by_extended;
    public byte by_remote;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
    public byte aby_data[];
    public UInt32 ul_tstamp;
};

Alternatively, you can also try to explicitly define the bytes:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CMSG
{
    public Int32 l_id;
    public byte by_len;
    public byte by_msg_lost;
    public byte by_extended;
    public byte by_remote;
    public byte aby_data_0;
    public byte aby_data_1;
    public byte aby_data_2;
    public byte aby_data_3;
    public byte aby_data_4;
    public byte aby_data_5;
    public byte aby_data_6;
    public byte aby_data_7;
    public UInt32 ul_tstamp;
};

If you're still having issues, you also share the declaration of canSend?


问:
IE11 Angular 2 error "Expected identifier, string or number"
Well, I have created site using Angular 2. When I run "ng-serve" command and trying to test my site using "http://localhost:4200" in Google Chrome and IE11 it works perfectly, but, if I build project using "ng-build --prod", host it on IIS. Site still works on Chrome, but IE11 shows the following errors:

I googled it and found that it was maybe reserved words in my identifiers key:value pairs. So I added Apostrophes(') arround my keys.
For example I had the following object:

```<code>user:UserViewModel={
    Username:"",
    Age:0
};
and changed this to:
user:UserViewModel={
    'Username':"",
    'Age':0
};
</code>```

Also deleted last commas in key:value pairs and imported core.js in polyfills.ts

答:
I googled it and found that it was maybe reserved words in my identifiers key:value pairs.

No. These are not relevant to IE11.

Fix

You are most likely running raw .ts files. You should be hosting (in your script tags) the bundled / built .js files.

Body:
Well, I have created site using Angular 2. When I run "ng-serve" command and trying to test my site using "http://localhost:4200" in Google Chrome and IE11 it works perfectly, but, if I build project using "ng-build --prod", host it on IIS. Site still works on Chrome, but IE11 shows the following errors:

I googled it and found that it was maybe reserved words in my identifiers key:value pairs. So I added Apostrophes(') arround my keys.
For example I had the following object:

user:UserViewModel={
    Username:"",
    Age:0
};
and changed this to:
user:UserViewModel={
    'Username':"",
    'Age':0
};

Also deleted last commas in key:value pairs and imported core.js in polyfills.ts


问:
first occurrence of day of week in month
I want to configure a Event with a DateTime date.

I want to repeat the event every month in the same week and day of the week.

For examples, this event take place in April 2 2015, (thursday of the first week in April).

I want to repeat again every thursday on first week in every month.

How I can calculate the next date each time?

答:
I developed a little function that finds any nth day of a month. </p>

```<code>private static DateTime Next(int year, int month, DayOfWeek dayOfWeek, int occurrence)
        {
            return Enumerable.Range(1, 7).
                        Select(day => new DateTime(year, month, day)).
                        First(dateTime => (dateTime.DayOfWeek == dayOfWeek))
                        .AddDays(7 * (occurrence - 1));
        }
</code>```

Body:
I developed a little function that finds any nth day of a month.

private static DateTime Next(int year, int month, DayOfWeek dayOfWeek, int occurrence)
        {
            return Enumerable.Range(1, 7).
                        Select(day => new DateTime(year, month, day)).
                        First(dateTime => (dateTime.DayOfWeek == dayOfWeek))
                        .AddDays(7 * (occurrence - 1));
        }


问:
Javascript object members that are prototyped as arrays become shared by all class instances
Has anyone noticed this behavior before? This really threw me off... I would have expected prototyped arrays to be private to each class instance rather than shared between all class instances.

Can someone verify that this is the correct behavior and perhaps explain this behavior in more detail?

Notice the commented code and how it affects the behavior of the script.

```<code><html>
<head>

<script type="text/javascript">

function print_r( title, object ) {

    var output = '';
    for( var key in object ) {

        output += key + ": " + object[ key ] + "\n";

    }

    output = title + "\n\n" + output;

    alert( output );

}

function Sandwich() {

    // Uncomment this to fix the problem
    //this.ingredients = [];

}

Sandwich.prototype = {

    "ingredients" : [],
    "addIngredients" : function( ingArray ) {

        for( var key in ingArray ) {

            this.addIngredient( ingArray[ key ] );

        }

    },
    "addIngredient" : function( thing ) {

        this.ingredients.push( thing );

    }

}

var cheeseburger = new Sandwich();
cheeseburger.addIngredients( [ "burger", "cheese" ] );

var blt = new Sandwich();
blt.addIngredients( [ "bacon", "lettuce", "tomato" ] );

var spicy_chicken_sandwich = new Sandwich();
spicy_chicken_sandwich.addIngredients( [ "spicy chicken pattie", "lettuce", "tomato", "honey dijon mayo", "love" ] );

var onLoad = function() {

    print_r( "Cheeseburger contains:", cheeseburger.ingredients );

};

</script>

</head>
<body onload="onLoad();">
</body>
</html>
</code>```

Many thanks.

答: When you do var exp1 = new C(), JavaScript sets exp1.[[Prototype]] = C.prototype. When you then access properties of the instance, JavaScript first checks whether they exist on that object directly, and if not, it looks in [[Prototype]]. This means that all the stuff you define in prototype is effectively shared by all instances, and you can even later change parts of prototype and have the changes appear in all existing instances.

Body:
Has anyone noticed this behavior before? This really threw me off... I would have expected prototyped arrays to be private to each class instance rather than shared between all class instances.

Can someone verify that this is the correct behavior and perhaps explain this behavior in more detail?

Notice the commented code and how it affects the behavior of the script.

Many thanks.


答:
You are almost there... all you need to do is trigger your check_if_in_view function when all the html is ready - that just means passing in the function by name to your last document.ready call. Your snippet works with that one tweak.

For some general advice, I wouldn't try to "fake" a scroll event just to trigger other behaviours - it may get confusing with changes later on. What you really want is to run your custom function right after pageload, and jquery will let you do precisely that.

/*Interactivity to determine when an animated element in in view. In view elements trigger our animation*/
$(document).ready(function() {

  //window and animation items
  var animation_elements = $.find('.animation-element');
  var web_window = $(window);

  //check to see if any animation containers are currently in view
  function check_if_in_view() {
    //get current window information
    var window_height = web_window.height();
    var window_top_position = web_window.scrollTop();
    var window_bottom_position = (window_top_position + window_height);

    //iterate through elements to see if its in view
    $.each(animation_elements, function() {

      //get the elements information
      var element = $(this);
      var element_height = $(element).outerHeight();
      var element_top_position = $(element).offset().top;
      var element_bottom_position = (element_top_position + element_height);

      //check to see if this current container is visible (its viewable if it exists between the viewable space of the viewport)
      if ((element_bottom_position >= window_top_position) && (element_top_position <= window_bottom_position)) {
        element.addClass('in-view');
      } else {
        element.removeClass('in-view');
      }
    });

  }

  //on or scroll, detect elements in view
  $(window).on('scroll resize', function() {
    check_if_in_view()
  })
  //trigger our scroll event on initial load
  $(document).ready(check_if_in_view);

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  margin-left: auto;
  margin-right: auto;
  width: 80%;
}

.row {
  border-bottom: solid 1px transparent;
  margin-bottom: 2em;
}

.row>* {
  float: left;
}

.row:after,
.row:before {
  content: '';
  display: block;
  clear: both;
  height: 0;
}

.row.uniform>*> :first-child {
  margin-top: 0;
}

.row.uniform>*> :last-child {
  margin-bottom: 0;
}

.wrapper {
  padding: 1em 0em 4em;
}

.profiles {
  margin-bottom: 4em;
  padding-top: 4em;
  background-color: #fff;
  height: 200px;
}

.profile {
  width: 24%;
  height: 100px;
  margin-bottom: 2em;
  margin-right: 2px;
  text-align: center;
  background-color: #666;
  border: 1px solid #000;
  color: black;
}

.animation-element {
  opacity: 0;
  position: relative;
}

.animation-element.slide-left {
  opacity: 0;
  -moz-transition: all 500ms linear;
  -webkit-transition: all 500ms linear;
  -o-transition: all 500ms linear;
  transition: all 500ms linear;
  -moz-transform: translate3d(-150px, 0px, 0px);
  -webkit-transform: translate3d(-150px, 0px, 0px);
  -o-transform: translate(-150px, 0px);
  -ms-transform: translate(-150px, 0px);
  transform: translate3d(-150px, 0px, 0px);
}

.animation-element.slide-left.in-view {
  opacity: 1;
  -moz-transform: translate3d(0px, 0px, 0px);
  -webkit-transform: translate3d(0px, 0px, 0px);
  -o-transform: translate(0px, 0px);
  -ms-transform: translate(0px, 0px);
  transform: translate3d(0px, 0px, 0px);
}

/*animation element sliding right*/

.animation-element.slide-right {
  opacity: 0;
  -moz-transition: all 500ms linear;
  -webkit-transition: all 500ms linear;
  -o-transition: all 500ms linear;
  transition: all 500ms linear;
  -moz-transform: translate3d(150px, 0px, 0px);
  -webkit-transform: translate3d(150px, 0px, 0px);
  -o-transform: translate(150px, 0px);
  -ms-transform: translate(150px, 0px);
  transform: translate3d(150px, 0px, 0px);
}

.animation-element.slide-right.in-view {
  opacity: 1;
  -moz-transform: translate3d(0px, 0px, 0px);
  -webkit-transform: translate3d(0px, 0px, 0px);
  -o-transform: translate(0px, 0px);
  -ms-transform: translate(0px, 0px);
  transform: translate3d(0px, 0px, 0px);
}</code>```

```

Body:
You are almost there... all you need to do is trigger your check_if_in_view function when all the html is ready - that just means passing in the function by name to your last document.ready call. Your snippet works with that one tweak.

For some general advice, I wouldn't try to "fake" a scroll event just to trigger other behaviours - it may get confusing with changes later on. What you really want is to run your custom function right after pageload, and jquery will let you do precisely that.

/*Interactivity to determine when an animated element in in view. In view elements trigger our animation*/
$(document).ready(function() {

  //window and animation items
  var animation_elements = $.find('.animation-element');
  var web_window = $(window);

  //check to see if any animation containers are currently in view
  function check_if_in_view() {
    //get current window information
    var window_height = web_window.height();
    var window_top_position = web_window.scrollTop();
    var window_bottom_position = (window_top_position + window_height);

    //iterate through elements to see if its in view
    $.each(animation_elements, function() {

      //get the elements information
      var element = $(this);
      var element_height = $(element).outerHeight();
      var element_top_position = $(element).offset().top;
      var element_bottom_position = (element_top_position + element_height);

      //check to see if this current container is visible (its viewable if it exists between the viewable space of the viewport)
      if ((element_bottom_position >= window_top_position) && (element_top_position <= window_bottom_position)) {
        element.addClass('in-view');
      } else {
        element.removeClass('in-view');
      }
    });

  }

  //on or scroll, detect elements in view
  $(window).on('scroll resize', function() {
    check_if_in_view()
  })
  //trigger our scroll event on initial load
  $(document).ready(check_if_in_view);

});

.container {
  margin-left: auto;
  margin-right: auto;
  width: 80%;
}

.row {
  border-bottom: solid 1px transparent;
  margin-bottom: 2em;
}

.row>* {
  float: left;
}

.row:after,
.row:before {
  content: '';
  display: block;
  clear: both;
  height: 0;
}

.row.uniform>*> :first-child {
  margin-top: 0;
}

.row.uniform>*> :last-child {
  margin-bottom: 0;
}

.wrapper {
  padding: 1em 0em 4em;
}

.profiles {
  margin-bottom: 4em;
  padding-top: 4em;
  background-color: #fff;
  height: 200px;
}

.profile {
  width: 24%;
  height: 100px;
  margin-bottom: 2em;
  margin-right: 2px;
  text-align: center;
  background-color: #666;
  border: 1px solid #000;
  color: black;
}

.animation-element {
  opacity: 0;
  position: relative;
}

.animation-element.slide-left {
  opacity: 0;
  -moz-transition: all 500ms linear;
  -webkit-transition: all 500ms linear;
  -o-transition: all 500ms linear;
  transition: all 500ms linear;
  -moz-transform: translate3d(-150px, 0px, 0px);
  -webkit-transform: translate3d(-150px, 0px, 0px);
  -o-transform: translate(-150px, 0px);
  -ms-transform: translate(-150px, 0px);
  transform: translate3d(-150px, 0px, 0px);
}

.animation-element.slide-left.in-view {
  opacity: 1;
  -moz-transform: translate3d(0px, 0px, 0px);
  -webkit-transform: translate3d(0px, 0px, 0px);
  -o-transform: translate(0px, 0px);
  -ms-transform: translate(0px, 0px);
  transform: translate3d(0px, 0px, 0px);
}

/*animation element sliding right*/

.animation-element.slide-right {
  opacity: 0;
  -moz-transition: all 500ms linear;
  -webkit-transition: all 500ms linear;
  -o-transition: all 500ms linear;
  transition: all 500ms linear;
  -moz-transform: translate3d(150px, 0px, 0px);
  -webkit-transform: translate3d(150px, 0px, 0px);
  -o-transform: translate(150px, 0px);
  -ms-transform: translate(150px, 0px);
  transform: translate3d(150px, 0px, 0px);
}

.animation-element.slide-right.in-view {
  opacity: 1;
  -moz-transform: translate3d(0px, 0px, 0px);
  -webkit-transform: translate3d(0px, 0px, 0px);
  -o-transform: translate(0px, 0px);
  -ms-transform: translate(0px, 0px);
  transform: translate3d(0px, 0px, 0px);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="wrapper">
  <div class="container">
    <section class="profiles">
      <div class="row">
        <section class="profile animation-element slide-left">
        </section>
        <section class="profile animation-element slide-left">
        </section>
        <section class="profile animation-element slide-right">
        </section>
        <section class="profile animation-element slide-right">
        </section>
      </div>
    </section>
  </div>
</section>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>


问:
DocuSign API Metadata in envelope
Using the C# SDK for requesting signatures to remote recipients.  Was wondering if I could add metadata to the envelope itself, e.g. another id specific to our domain, that can be set once (initially) and be retrieved anytime regardless of document status.  I'm seeing the EnvelopeDocument.DocumentFields as a potential, but not sure if this is proper for what I'm doing.  Also seeing EnvelopeDefinition.CustomFields.*.  Tried to use TextCustomFields but I don't see this displayed on the document (when show=true), let alone if this is attached to the envelope throughout it's lifecycle.  Any help would be appreciated.  Thanks!</p>

答:
When you create a DocuSign Envelope, you can specify custom metadata either at the Document-level or at the Envelope-level (by using "custom fields").

Document-level custom fields get associated with a specific document within an Envelope.

Envelope-level custom fields get associated with the Envelope itself.

Metadata that's specified using custom fields (regardless of whether at the Document-level or Envelope-level) will not be visible to Envelope recipients, but can be subsequently retrieved via API at any time.

Based on the information you've provided, it sounds like you're most likely interested in Envelope custom fields. I don't have much experience using the DocuSign C# SDK, but here's the JSON portion of a Create Envelope request that specifies a single custom field at the Envelope-level:

```<code>{
    "emailSubject": "Please Print, Complete and Sign Document",
    "emailBlurb": "Please print and complete documents and sign on paper. ",
    "status": "sent",
    "compositeTemplates": [{
        "inlineTemplates": [{
            "sequence": "1",
            "customFields": {
                "textCustomFields": [{
                    "name": "MyOwnField",
                    "required": "true",
                    "show": "true",
                    "value": "MyValue"
                }]
            },
            "recipients": {
                "signers": [{
                    "requireSignOnPaper": "true",
                    "name": "John Doe",
                    "email": "jdoe@test.com",
                    "recipientId": "1",
                    "routingOrder": "1"
                }]
            }
        }],
        "document": {
            "documentId": "1",
            "name": "AccountApplication.pdf",
            "transformPdfFields": false
        }
    }]
}
</code>```

Based on this, if you're seeing EnvelopeDefinition.CustomFields.TextCustomFields in the C# SDK, I'd suspect that's what you'll use to create an Envelope Custom Field. As I mentioned earlier, recipients won't see the Envelope Custom Field value(s) in the DocuSign web UI, but you should be able to subsequently retrieve the Envelope Custom Field value(s) via API at any point in the Envelope lifecycle.

Update (C# code sample):

Based on a brief look at the C# SDK, here's a code sample that shows how to create two (text) custom fields on an Envelope:

```<code>// create a new envelope which we will use to send the signature request
EnvelopeDefinition envDef = new EnvelopeDefinition();

// create my first Envelope custom field
TextCustomField myFirstCustomField = new TextCustomField();
myFirstCustomField.Name = "field1";
myFirstCustomField.Value = "value1";

// create my second Envelope custom field
TextCustomField mySecondCustomField = new TextCustomField();
mySecondCustomField.Name = "field2";
mySecondCustomField.Value = "value2";

// add my custom fields to the envelope
envDef.CustomFields.TextCustomFields.Add(myFirstCustomField);
envDef.CustomFields.TextCustomFields.Add(mySecondCustomField);

...
</code>```

Title: DocuSign API Metadata in envelope

Body:
When you create a DocuSign Envelope, you can specify custom metadata either at the Document-level or at the Envelope-level (by using "custom fields").

Document-level custom fields get associated with a specific document within an Envelope.

Envelope-level custom fields get associated with the Envelope itself.

Metadata that's specified using custom fields (regardless of whether at the Document-level or Envelope-level) will not be visible to Envelope recipients, but can be subsequently retrieved via API at any time.

Based on the information you've provided, it sounds like you're most likely interested in Envelope custom fields. I don't have much experience using the DocuSign C# SDK, but here's the JSON portion of a Create Envelope request that specifies a single custom field at the Envelope-level:

{
    "emailSubject": "Please Print, Complete and Sign Document",
    "emailBlurb": "Please print and complete documents and sign on paper. ",
    "status": "sent",
    "compositeTemplates": [{
        "inlineTemplates": [{
            "sequence": "1",
            "customFields": {
                "textCustomFields": [{
                    "name": "MyOwnField",
                    "required": "true",
                    "show": "true",
                    "value": "MyValue"
                }]
            },
            "recipients": {
                "signers": [{
                    "requireSignOnPaper": "true",
                    "name": "John Doe",
                    "email": "jdoe@test.com",
                    "recipientId": "1",
                    "routingOrder": "1"
                }]
            }
        }],
        "document": {
            "documentId": "1",
            "name": "AccountApplication.pdf",
            "transformPdfFields": false
        }
    }]
}

Based on this, if you're seeing EnvelopeDefinition.CustomFields.TextCustomFields in the C# SDK, I'd suspect that's what you'll use to create an Envelope Custom Field. As I mentioned earlier, recipients won't see the Envelope Custom Field value(s) in the DocuSign web UI, but you should be able to subsequently retrieve the Envelope Custom Field value(s) via API at any point in the Envelope lifecycle.

Update (C# code sample):

Based on a brief look at the C# SDK, here's a code sample that shows how to create two (text) custom fields on an Envelope:

// create a new envelope which we will use to send the signature request
EnvelopeDefinition envDef = new EnvelopeDefinition();

// create my first Envelope custom field
TextCustomField myFirstCustomField = new TextCustomField();
myFirstCustomField.Name = "field1";
myFirstCustomField.Value = "value1";

// create my second Envelope custom field
TextCustomField mySecondCustomField = new TextCustomField();
mySecondCustomField.Name = "field2";
mySecondCustomField.Value = "value2";

// add my custom fields to the envelope
envDef.CustomFields.TextCustomFields.Add(myFirstCustomField);
envDef.CustomFields.TextCustomFields.Add(mySecondCustomField);

...


问:
How can I get scons to not fail-fast with multiple targets?
When scons is configured with multiple targets (e.g. build, static analysis, unit tests), if the static analysis fails then the unit tests don't run.

The builders run the relevant command using subprocess, then check the processes return code, and if non-zero, raises a BuildError exception.

How can I get scons to build every target and not fail-fast if one of the first targets fail?

答:
One way to do this from the command line is to use the --keep or -k flag:

```<code>scons -k
</code>```

SCons does not let you change this with the SetOption function.

Body:
One way to do this from the command line is to use the --keep or -k flag:

scons -k

SCons does not let you change this with the SetOption function.


答:
```<code>sorted = df.sort_values(['eventTime', 'Op.progress'])
</code>```

or if you want to modify the dataframe in place,

```<code>df.sort_values(['eventTime', 'Op.progress'], inplace = True)
</code>```

and if you want to do it backwards

```<code>sorted = df.sort_values(['eventTime', 'Op.progress'], ascending = False)
</code>```

Title: Ordering a Dataframe in Pandas

Body:
I would like to order the dataframe according to the Op.progressPercentage and averaging the eventTimes as in the following:

Input df:

uuid,eventTime,Op.progress,Op.progressPercentage, AnotherAttribute
C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:39,P,3.0,01:57:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:18,P,4.0,01:55:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:49,P,5.0,01:55:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:55,P,3.0,01:56:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:07,P,6.0,01:54:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:24,P,5.0,01:54:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:27,P,6.0,01:53:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:33:46,W,40.0,01:13:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:10,N,51.0,02:00:00

Output df:

uuid,eventTime,Op.progress,Op.progressPercentage, AnotherAttribute
C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:39,P,3.0,01:57:00
C0972765-8436-0000-0000-000000000000,avg(12:52:39,12:53:18),P,3.0,01:56:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:18,P,4.0,01:55:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:49,P,5.0,01:55:00
C0972765-8436-0000-0000-000000000000,avg(12:53:49,212:55:55),P,5.0,01:54:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:07,P,6.0,01:54:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:27,P,6.0,01:53:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:33:46,W,40.0,01:13:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:10,N,51.0,02:00:00

The Op.progressPercentage should be always monotonic crescent as well as eventTime.
Please, any help on this would be very appreciated.
Best Regards,
carlo

Body:
sorted = df.sort_values(['eventTime', 'Op.progress'])

or if you want to modify the dataframe in place,

df.sort_values(['eventTime', 'Op.progress'], inplace = True)

and if you want to do it backwards

sorted = df.sort_values(['eventTime', 'Op.progress'], ascending = False)


问:
How can I declare/ignore a missing JSX type?
I would like to use the SVG use element in a .tsx file:

```<code><mask id="mask1">
    <use ... />
</mask>
</code>```

I'm transpiling this to React calls directly. However, I keep receiving the following error:

Property 'use' does not exist on type 'JSX.IntrinsicElements'.

I believe this element is missing from the standard lib definitions. How can I declare this type for the TypeScript compiler to see, similar to how I can declare a class or variable? The usual declare var and declare class statements have no effect.

If that's not possible, how can I make the TypeScript compiler ignore this error?

答:
use and other SVG elements have been added to TS's JSX definitions at the time of this writing, so the accepted answer's workaround is no longer necessary--but for anyone brought here because they need to get a custom element (web component, different UI framework, etc) working in a TSX file, follow these steps:

Create a .d.ts file. I like to put mine in the same folder as tsconfig.json

Add your definitions to this file, like:

declare module JSX {
  interface IntrinsicElements {
    'some-custom-element': any;
  }
}

The .d.ts file is automatically found by TS and then it stops complaining. I had to restart my TS server for it to pick up the changes.

ContentLicense: CC BY-SA 4.0

Body:
I would like to use the SVG use element in a .tsx file:

<mask id="mask1">
    <use ... />
</mask>

I'm transpiling this to React calls directly. However, I keep receiving the following error:

Property 'use' does not exist on type 'JSX.IntrinsicElements'.

I believe this element is missing from the standard lib definitions. How can I declare this type for the TypeScript compiler to see, similar to how I can declare a class or variable? The usual declare var and declare class statements have no effect.

If that's not possible, how can I make the TypeScript compiler ignore this error?


问:
Conda update: installation progress (version 4.3)
Doing a conda update --all for a Python Anaconda environment, the list of downloads is tracked one-by-one, but as soon as the installation starts, there is no visible progress anymore.

As the installation is taking quite some time - is there any option to show the installation progress?

I am using conda --version: 4.3.30.

答:
According to the CHANGELOG over in the GitHub repository (https://github.com/conda/conda/blob/master/CHANGELOG.md), they had to accept some regressions on progress bar behavior that have been fixed in the (currently unreleased) conda 4.4.0.

various UI improvements: To push through some of the big leaps with transactions in conda 4.3, we accepted some regressions on progress bars and other user interface features. All of those indicators of progress, and more, have been brought back and further improved.


问:
react native how to get return from a promise
my problem is i want to get a json from this function but all i get is a only a promise and why i choose this way because in app that i'm working on it works dynamicly but the only place that i see i can put this promise is render()

this is my code :

```<code>var userInfo = (async()=>{
    var value = await AsyncStorage.getItem("@user_info");
    value = JSON.parse(value);
    return value ;
  })();
</code>```

and this is my result :

```<code>Promise {
 "_40": 0,
 "_55": null,
 "_65": 0,
 "_72": null,
}
</code>```

but what i want to get is a json what sould i have to do ?

答:
You should return value.json() . Try this

```<code>var userInfo = (async()=>{
    var value = await AsyncStorage.getItem("@user_info");
    return value.json() ;
  })();
</code>```

In addition, AsyncStorage.getItem is an asynchronous function, you will need to wrap that in try and catch in case if any error happened during the process

Note: If you use an await inside a function that is not explicitly declared with async, you'll end up with an Unexpected token syntax error.

```<code>async userInfo(){
    try{
        var value = await AsyncStorage.getItem("@user_info");
        return value.json() ;
    }
    catch(e){
        console.log('caught error', e);
        // Handle exceptions
    }
}
</code>```

Body:
my problem is i want to get a json from this function but all i get is a only a promise and why i choose this way because in app that i'm working on it works dynamicly but the only place that i see i can put this promise is render()

this is my code :

var userInfo = (async()=>{
    var value = await AsyncStorage.getItem("@user_info");
    value = JSON.parse(value);
    return value ;
  })();

and this is my result :

Promise {
 "_40": 0,
 "_55": null,
 "_65": 0,
 "_72": null,
}

but what i want to get is a json what sould i have to do ?

Body:
You should return value.json() . Try this

var userInfo = (async()=>{
    var value = await AsyncStorage.getItem("@user_info");
    return value.json() ;
  })();

In addition, AsyncStorage.getItem is an asynchronous function, you will need to wrap that in try and catch in case if any error happened during the process

Note: If you use an await inside a function that is not explicitly declared with async, you'll end up with an Unexpected token syntax error.

async userInfo(){
    try{
        var value = await AsyncStorage.getItem("@user_info");
        return value.json() ;
    }
    catch(e){
        console.log('caught error', e);
        // Handle exceptions
    }
}


问:
Baffling Sudden Error on loading data table
I'm using VB.net and WPF 4, as well as an SQL database.

I have been using this EXACT code successfully for several days now, with absolutely no problems whatsoever. However, now, suddenly, it is throwing the weirdest exception...

```<code>Public Class ROSTER
   Dim table_adapter As New AGENT_ROSTERTableAdapters.AGENTROSTERTableAdapter
   Dim roster_table As New AGENT_ROSTER.AGENT_ROSTERDataTable
...
</code>```

I have not deleted anything relating to this, and I can still do things similar to this, but I cannot, for the life of me, figure out why I am getting the following error:

XamlParseException occured
  'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '4' and line position '106'.

On detail, every field contains the following:

{Cannot evaluate expression because we are stopped in a place where garbage collection is impossible, possibly because the code of the current method may be optimized.}

Why is this doing this, and what can I do to fix it??

答: A XamlParseException is thrown whenever any exception is encountered while parsing XAML.  The message tells you that TypeConverterMarkupExtension is what threw the exception, so you need to take a look at the places in your XAML where you're using type converters.  Looking at the stack trace in the inner exception will help you there.

Body:
I'm using VB.net and WPF 4, as well as an SQL database.

I have been using this EXACT code successfully for several days now, with absolutely no problems whatsoever. However, now, suddenly, it is throwing the weirdest exception...

Public Class ROSTER
   Dim table_adapter As New AGENT_ROSTERTableAdapters.AGENTROSTERTableAdapter
   Dim roster_table As New AGENT_ROSTER.AGENT_ROSTERDataTable
...

I have not deleted anything relating to this, and I can still do things similar to this, but I cannot, for the life of me, figure out why I am getting the following error:

XamlParseException occured
  'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '4' and line position '106'.

On detail, every field contains the following:

{Cannot evaluate expression because we are stopped in a place where garbage collection is impossible, possibly because the code of the current method may be optimized.}

Why is this doing this, and what can I do to fix it??


问:
MiUi widget programming issues workaround?
I'm programming apps and widgets. Recently I was reported that widget programmed by me stopped worked after a minute or so. All of those issues had one similar thing: MiUi. One device was Redmi, another one was Huawei, but both had MiUi. I was looking all my code around and failed to reproduce error(widget not replying at all on button click etc). But after I noticed, that all those issues occured on MiUi only, I found this video: https://www.youtube.com/watch?v=F1QBqmgf7bg .

As I don't own any of deviced having MiUi myself, I wanted to ask, if any of developers have any known workaround on widget coding level? Is it possible to request that some weird permission from app itself or some manifest tune-ups?

Any help would be very much appriciated

答:
I had no Xioami phone reports yet. But Redmi and Huawei seem to have something similar that kills widget.

I am looking for more complex solution for those.

Redmi has also MiUi thing and Huawei some Emui thing that also kills widget


问:
Stop a countdown timer with user input
I want to know how I can create a countdown that can be stopped when the user inputs something such as writing a specific sentence.

In my case I want to do something like a 'Simon says' game. Simon says 'UP' and so you have to type in UP within a time limit of two seconds. If you type anything that is not 'UP' the countdown stops and it prints out that you fail whilst if you do type 'UP' it breaks the countdown and says you win. You are also notified that you fail when the countdown reaches zero and you haven't typed anything.

Here's what I've written so far:

```<code>#include <iostream>
   #include <string>
   #include <cmath>
   #include<windows.h>
   using namespace std;

int main() {
    string answer;
    int success = 0;
    int counter = 0;

    cout << "Simon says: UP" << endl;

    for (int i = 2; i > 0; i--) {

        cin >> answer;
        if (answer == "UP") {

            cout << "You win" << endl;
            break;

        }
        else {

            cout << "You lose" << endl;

        }

     }

    return 0;

}
</code>```

答:
Without going into multithreading, you could try _kbhit(), the non-blocking way of reading user input in combination with _getch(), both are in conio.h

```<code>#include <iostream>
#include <string>
#include <chrono>
#include <conio.h>

int main()
{

    int timeout = 2; //2 seconds

    std::string answer, say = "UP";

    std::cout << "Simon says: " << say << std::endl;
    std::cout << "You say: ";

    // get start time point
    std::chrono::system_clock::time_point start = std::chrono::system_clock::now();
    do
    {
        if (_kbhit()) // check user input
        {
            char hit = _getch(); // read user input
            std::cout << hit; // show what was entered

            if (hit == 13)
                break; // user hit enter, so end it

            answer += hit; // add char to user answer
        }
    }
    while (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - start).count() < timeout);

    // check if provided answer matches

    if (answer == say)
        std::cout << "\nYou win!" << std::endl;
    else
        std::cout << "\nYou lose!" << std::endl;

    return 0;
}
</code>```

Title: Stop a countdown timer with user input

Body:
I want to know how I can create a countdown that can be stopped when the user inputs something such as writing a specific sentence.

In my case I want to do something like a 'Simon says' game. Simon says 'UP' and so you have to type in UP within a time limit of two seconds. If you type anything that is not 'UP' the countdown stops and it prints out that you fail whilst if you do type 'UP' it breaks the countdown and says you win. You are also notified that you fail when the countdown reaches zero and you haven't typed anything.

Here's what I've written so far:

#include <iostream>
   #include <string>
   #include <cmath>
   #include<windows.h>
   using namespace std;

int main() {
    string answer;
    int success = 0;
    int counter = 0;

    cout << "Simon says: UP" << endl;

    for (int i = 2; i > 0; i--) {

        cin >> answer;
        if (answer == "UP") {

            cout << "You win" << endl;
            break;

        }
        else {

            cout << "You lose" << endl;

        }

     }

    return 0;

}

Body:
Without going into multithreading, you could try _kbhit(), the non-blocking way of reading user input in combination with _getch(), both are in conio.h

#include <iostream>
#include <string>
#include <chrono>
#include <conio.h>

int main()
{

    int timeout = 2; //2 seconds

    std::string answer, say = "UP";

    std::cout << "Simon says: " << say << std::endl;
    std::cout << "You say: ";

    // get start time point
    std::chrono::system_clock::time_point start = std::chrono::system_clock::now();
    do
    {
        if (_kbhit()) // check user input
        {
            char hit = _getch(); // read user input
            std::cout << hit; // show what was entered

            if (hit == 13)
                break; // user hit enter, so end it

            answer += hit; // add char to user answer
        }
    }
    while (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - start).count() < timeout);

    // check if provided answer matches

    if (answer == say)
        std::cout << "\nYou win!" << std::endl;
    else
        std::cout << "\nYou lose!" << std::endl;

    return 0;
}


问:
join multiple times in SQL
These are the 2 tables.
Tech_data:

```<code>Id Tech Agent1_id Agent2_ID
1  JAVA   1           2
2  SQL    3           4
</code>```

Agent_table

```<code>Id Name
1  Mike
2  John
3  Jim
4  Baron
</code>```

I need to write a query to bring the below output

```<code>TECH_ID   Tech  Agent1_Name Agent2_Name
1         Java    Mike       John
2         SQL     Jim        Baron
</code>```

I wrote LEFT OUTER JOIN ON tech_id=agent1_id, but i do not know how to join 2 ids in ON condition.

答:
To prevent having to do multiple joins to the same table, you can unpivot, join and then pivot (then if you had 50 ID columns you would still only need to perform one join):

SQL Fiddle

Oracle 11g R2 Schema Setup:

```<code>CREATE TABLE Tech_data (Id, Tech, Agent1_id, Agent2_ID ) AS
SELECT 1,  'JAVA', 1, 2 FROM DUAL UNION ALL
SELECT 2,  'SQL',  3, 4 FROM DUAL;

CREATE TABLE Agent_table ( Id, Name ) AS
SELECT 1,  'Mike' FROM DUAL UNION ALL
SELECT 2,  'John' FROM DUAL UNION ALL
SELECT 3,  'Jim' FROM DUAL UNION ALL
SELECT 4,  'Baron' FROM DUAL;
</code>```

Query 1:

```<code>SELECT *
FROM   (
  SELECT t.id,
         t.tech,
         t.num,
         a.name
  FROM   (
      SELECT *
      FROM   tech_data
      UNPIVOT ( Agent_ID FOR num IN ( Agent1_id AS 1, Agent2_id AS 2 ) )
    ) t
    INNER JOIN Agent_table a
    ON ( t.agent_id = a.id )
)
PIVOT ( MAX( name ) FOR num IN ( 1 AS Agent1_Name, 2 AS Agent2_Name ) )
</code>```

Results:

```<code>| ID | TECH | AGENT1_NAME | AGENT2_NAME |
|----|------|-------------|-------------|
|  1 | JAVA |        Mike |        John |
|  2 |  SQL |         Jim |       Baron |
</code>```

Title: join multiple times in SQL

Body:
These are the 2 tables.
Tech_data:

Id Tech Agent1_id Agent2_ID
1  JAVA   1           2
2  SQL    3           4

Agent_table

Id Name
1  Mike
2  John
3  Jim
4  Baron

I need to write a query to bring the below output

TECH_ID   Tech  Agent1_Name Agent2_Name
1         Java    Mike       John
2         SQL     Jim        Baron

I wrote LEFT OUTER JOIN ON tech_id=agent1_id, but i do not know how to join 2 ids in ON condition.

Body:
To prevent having to do multiple joins to the same table, you can unpivot, join and then pivot (then if you had 50 ID columns you would still only need to perform one join):

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE Tech_data (Id, Tech, Agent1_id, Agent2_ID ) AS
SELECT 1,  'JAVA', 1, 2 FROM DUAL UNION ALL
SELECT 2,  'SQL',  3, 4 FROM DUAL;

CREATE TABLE Agent_table ( Id, Name ) AS
SELECT 1,  'Mike' FROM DUAL UNION ALL
SELECT 2,  'John' FROM DUAL UNION ALL
SELECT 3,  'Jim' FROM DUAL UNION ALL
SELECT 4,  'Baron' FROM DUAL;

Query 1:

SELECT *
FROM   (
  SELECT t.id,
         t.tech,
         t.num,
         a.name
  FROM   (
      SELECT *
      FROM   tech_data
      UNPIVOT ( Agent_ID FOR num IN ( Agent1_id AS 1, Agent2_id AS 2 ) )
    ) t
    INNER JOIN Agent_table a
    ON ( t.agent_id = a.id )
)
PIVOT ( MAX( name ) FOR num IN ( 1 AS Agent1_Name, 2 AS Agent2_Name ) )

Results:

| ID | TECH | AGENT1_NAME | AGENT2_NAME |
|----|------|-------------|-------------|
|  1 | JAVA |        Mike |        John |
|  2 |  SQL |         Jim |       Baron |


问:
EF CTP5 error: Invalid object name
I followed the example on scottgu's  blog about EF code first CTP5 but I get the error that

System.Data.SqlClient.SqlException:
  Invalid object name 'dbo.Products'.

this is the code I got.

```<code><add name="CTP5Context"
     connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|EFCTP5.mdf;User Instance=true"
     providerName="System.Data.SqlClient" />

public class CTP5Context : DbContext
{
    public DbSet<Product> Products { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string ProductName { get; set; }
    public int Amount { get; set; }
}

var context = new CTP5Context();
        var products = context.Products;

        return View(products);
</code>```

im kinda clueless here I done the same as the blogpost, its not my first time with EF (But CTP5 tho), I'm I overlooking something?

答: The exception looks like it's coming from the database.  Are you sure your table name is 'Products' or is it 'Product' (singular instead of plural?)</p>

Title: EF CTP5 error: Invalid object name

Body:
I followed the example on scottgu's  blog about EF code first CTP5 but I get the error that

System.Data.SqlClient.SqlException:
  Invalid object name 'dbo.Products'.

this is the code I got.

<add name="CTP5Context"
     connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|EFCTP5.mdf;User Instance=true"
     providerName="System.Data.SqlClient" />

public class CTP5Context : DbContext
{
    public DbSet<Product> Products { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string ProductName { get; set; }
    public int Amount { get; set; }
}

var context = new CTP5Context();
        var products = context.Products;

        return View(products);

im kinda clueless here I done the same as the blogpost, its not my first time with EF (But CTP5 tho), I'm I overlooking something?


问:
Error 'Packet for query is too large' when I tried to make a query on my website
Again I need your help.
I'm trying to put my java web site online.

What I use :

MySQL server : command line mysql -V, result : mysql  Ver 15.1 Distrib 10.1.23-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2

Cayenne

Debian server

Java (Vaadin)

Packet for query is too large (4739923 > 1048576). You can change this
  value on the server by setting the max_allowed_packet' variable.

What I tried :

1. Like the error said, I tried to change the value on the server by doing :

Log on my server

Connect to MySQL with : mysql -u root

Enter : SET GLOBAL max_allowed_packet=1073741824;

then, restart the server with : /etc/init.d/mysql restart

But I still have the error.

2. I took a look to : How to change max_allowed_packet size

But, When I did the nano /etc/mysql/my.cnf, the file looks like (I don't have any [mysql]) :

```<code>Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Fri Nov 10 23:57:02 2017 from 82.236.220.195
root@XXXX:~# nano /etc/mysql/my.cnf
  GNU nano 2.7.4               File: /etc/mysql/my.cnf                Modified

# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.

#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]
# The MariaDB configuration file
#
# The MariaDB/MySQL tools read configuration files in the following order:
# 1. "/etc/mysql/mariadb.cnf" (this file) to set global defaults,
# 2. "/etc/mysql/conf.d/*.cnf" to set global options.
# 3. "/etc/mysql/mariadb.conf.d/*.cnf" to set MariaDB-only options.
# 4. "~/.my.cnf" to set user-specific options.
#
# If the same option is defined multiple times, the last one will apply.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.

#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]

# Import all .cnf files from configuration directory
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mariadb.conf.d/
</code>```

In mysql, the folders/files in the 'mysql' folder is :

Any hint will be very appreciate!
Thanks

EDIT: In /etc/mysql/mariadb.conf.d/50-server.cnf, I changed :

max_allowed_packet = 1073741824

max_connections = 100000

and I added : net_buffer_length   = 1048576

For info :
In my workbench, I can see the server variables :

EDIT2 : Now, when I select the variable in command line on the server, I have :

```<code>MariaDB [(none)]> SELECT @@global.max_allowed_packet;
+-----------------------------+
| @@global.max_allowed_packet |
+-----------------------------+
|                  1073741824 |
+-----------------------------+
1 row in set (0.00 sec)
</code>```

SOLUTION Because the error was not explicit.

Thanks to com.mysql.jdbc.PacketTooBigException

My cayenne configuration was :

```<code><url value="jdbc:mysql://IPADDRESS:22/DBBASENAME" />
<login userName="ServerUserName" password="ServerPassword" />
</code>```

But it should be :

```<code><url value="jdbc:mysql://IPADDRESS/DBBASENAME" />
<login userName="MYSQLUserName" password="MYSQLPassword" />
</code>```

答:
Change it in my.cnf, then restart mysqld.

Better yet, put it in a file under /etc/mysql/mariadb.conf.d/, and specify the section:

```<code>[mysqld]
max_allowed_packet = 1073741824
</code>```

What you did (SET) went away when you restarted.  Even so, it only applied to connections that logged in after doing the SET.

Body:
Again I need your help.
I'm trying to put my java web site online.

What I use :

MySQL server : command line mysql -V, result : mysql  Ver 15.1 Distrib 10.1.23-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2

Cayenne

Debian server

Java (Vaadin)

Packet for query is too large (4739923 > 1048576). You can change this
  value on the server by setting the max_allowed_packet' variable.

What I tried :

1. Like the error said, I tried to change the value on the server by doing :

Log on my server

Connect to MySQL with : mysql -u root

Enter : SET GLOBAL max_allowed_packet=1073741824;

then, restart the server with : /etc/init.d/mysql restart

But I still have the error.

2. I took a look to : How to change max_allowed_packet size

But, When I did the nano /etc/mysql/my.cnf, the file looks like (I don't have any [mysql]) :

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Fri Nov 10 23:57:02 2017 from 82.236.220.195
root@XXXX:~# nano /etc/mysql/my.cnf
  GNU nano 2.7.4               File: /etc/mysql/my.cnf                Modified

# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.

#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]
# The MariaDB configuration file
#
# The MariaDB/MySQL tools read configuration files in the following order:
# 1. "/etc/mysql/mariadb.cnf" (this file) to set global defaults,
# 2. "/etc/mysql/conf.d/*.cnf" to set global options.
# 3. "/etc/mysql/mariadb.conf.d/*.cnf" to set MariaDB-only options.
# 4. "~/.my.cnf" to set user-specific options.
#
# If the same option is defined multiple times, the last one will apply.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.

#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]

# Import all .cnf files from configuration directory
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mariadb.conf.d/

In mysql, the folders/files in the 'mysql' folder is :

Any hint will be very appreciate!
Thanks

EDIT: In /etc/mysql/mariadb.conf.d/50-server.cnf, I changed :

max_allowed_packet = 1073741824

max_connections = 100000

and I added : net_buffer_length   = 1048576

For info :
In my workbench, I can see the server variables :

EDIT2 : Now, when I select the variable in command line on the server, I have :

MariaDB [(none)]> SELECT @@global.max_allowed_packet;
+-----------------------------+
| @@global.max_allowed_packet |
+-----------------------------+
|                  1073741824 |
+-----------------------------+
1 row in set (0.00 sec)

SOLUTION Because the error was not explicit.

Thanks to com.mysql.jdbc.PacketTooBigException

My cayenne configuration was :

<url value="jdbc:mysql://IPADDRESS:22/DBBASENAME" />
<login userName="ServerUserName" password="ServerPassword" />

But it should be :

<url value="jdbc:mysql://IPADDRESS/DBBASENAME" />
<login userName="MYSQLUserName" password="MYSQLPassword" />

Body:
Change it in my.cnf, then restart mysqld.

Better yet, put it in a file under /etc/mysql/mariadb.conf.d/, and specify the section:

[mysqld]
max_allowed_packet = 1073741824

What you did (SET) went away when you restarted.  Even so, it only applied to connections that logged in after doing the SET.


问:
From my admin section, I cannot add new plugin and new theme (wordpress
In wordpress,  From my admin section I dont have the add new plugin button, add new theme button and some plugin cannot be use ...  Any ideal why?

Screenshot:
https://snag.gy/j1Dwxr.jpg

Your help will be appreciated .. I cannot find a fix for this..
Thanks in advance !

答:
1.) Make sure you account is an administrator account

2.) Check with your hosting provider to see if they allow you to install plugins and themes, they may disable your ability to update/install plugins and themes via your wp-config.php

```<code>define( 'DISALLOW_FILE_MODS', true );
</code>```

https://codex.wordpress.org/Editing_wp-config.php

Body:
1.) Make sure you account is an administrator account

2.) Check with your hosting provider to see if they allow you to install plugins and themes, they may disable your ability to update/install plugins and themes via your wp-config.php

define( 'DISALLOW_FILE_MODS', true );

https://codex.wordpress.org/Editing_wp-config.php


问:
C# - SQlite + Entity - Show items on a ListView
Using Visual Studio 2015 and learning ORM with SQlite + Entity (WPF application)

My database with fields: ID and ShipType

I can populate a listView with the ShypType field:

```<code>    private void button_Click(object sender, RoutedEventArgs e)
    {
        List<string> shipList = new List<string>();
        using (var db = new ImperialFleetDBEntities())
        {
            shipList = (from g in db.ShipsType select g.ShipType).ToList();
            db.Dispose();
        }

        listView.Items.Clear();
        foreach (string str in shipList)
        {
            listView.Items.Add(str);
        }

    }
</code>```

But I can't figure how to also diplay the ID field (g.ID on this example)

In this link C# ListView Display the solution is using ListViewSubItems

But If I type listView. I don't have any SubItems option

The solution is 5 years old, maybe that's de problem??

答:
The simplest way would probably be:

```<code>private void button_Click(object sender, RoutedEventArgs e)
{
    using (var db = new ImperialFleetDBEntities())
    {
        listView.Items.Clear();
        foreach(var item in (from g in db.ShipsType select new { ID = g.ID, ShipType = g.ShipType }))
        {
            listView.Items.Add(item)
        }
    }
}
</code>```

This should populate your listView in correct way and make sure these new objects won't be tracked by EF.

If you'd like, you could create full class, like ViewModel for listView containing fields you need and then select to them like:

```<code>foreach(var item in (from g in db.ShipsType select new NewShipType { ID = g.ID, ShipType = g.ShipType }))
{
    listView.Items.Add(item)
}
</code>```

or using constructor (if you make one).

With seprate ViewModel you can of course use in-between list object and clear and add them to listView.Items, which is impossible with anonymous object.

By the way, you don't have, and maybe you shouldn't write db.Dispose() inside using clause, as using is exactly meant to make sure the object inside is disposed - you cannot use using on object that is not implementing IDisposable interface.

Body:
Using Visual Studio 2015 and learning ORM with SQlite + Entity (WPF application)

My database with fields: ID and ShipType

I can populate a listView with the ShypType field:

    private void button_Click(object sender, RoutedEventArgs e)
    {
        List<string> shipList = new List<string>();
        using (var db = new ImperialFleetDBEntities())
        {
            shipList = (from g in db.ShipsType select g.ShipType).ToList();
            db.Dispose();
        }

        listView.Items.Clear();
        foreach (string str in shipList)
        {
            listView.Items.Add(str);
        }

    }

But I can't figure how to also diplay the ID field (g.ID on this example)

In this link C# ListView Display the solution is using ListViewSubItems

But If I type listView. I don't have any SubItems option

The solution is 5 years old, maybe that's de problem??

Body:
The simplest way would probably be:

private void button_Click(object sender, RoutedEventArgs e)
{
    using (var db = new ImperialFleetDBEntities())
    {
        listView.Items.Clear();
        foreach(var item in (from g in db.ShipsType select new { ID = g.ID, ShipType = g.ShipType }))
        {
            listView.Items.Add(item)
        }
    }
}

This should populate your listView in correct way and make sure these new objects won't be tracked by EF.

If you'd like, you could create full class, like ViewModel for listView containing fields you need and then select to them like:

foreach(var item in (from g in db.ShipsType select new NewShipType { ID = g.ID, ShipType = g.ShipType }))
{
    listView.Items.Add(item)
}

or using constructor (if you make one).

With seprate ViewModel you can of course use in-between list object and clear and add them to listView.Items, which is impossible with anonymous object.

By the way, you don't have, and maybe you shouldn't write db.Dispose() inside using clause, as using is exactly meant to make sure the object inside is disposed - you cannot use using on object that is not implementing IDisposable interface.


问:
Is this a bug in Method#to_proc? (Ruby 1.8.7)
Given the following method that takes one argument:

```<code>def foo(arg); p arg; end
</code>```

I can call it with an empty array:

```<code>foo([])
# prints []
</code>```

I can also save it as a Method object and call that with an empty array, with the same result:

```<code>method(:foo).call([])
# prints []
</code>```

However, if I convert the Method object to a Proc and call that with an empty array, I get an ArgumentError:

```<code>method(:foo).to_proc.call([])
# ArgumentError: wrong number of arguments (0 for 1)
#   from (irb):4:in `foo'
#   from (irb):4:in `to_proc'
#   from (irb):10:in `call'
</code>```

I expected it to behave the same as the previous two cases.  Instead, it seems to be behaving as if I'd written foo(*[]).  However, if I call it with a non-empty array, it does behave the way I expected:

```<code>method(:foo).to_proc.call([1])
# prints [1]
</code>```

So it destructures the argument, but only if the argument happens to be an empty array.  And only if I call Method#to_proc.

Is there a gap in my understanding of how Method or Proc work, or is this a bug?

I'm running Ruby 1.8.7-p299.  I observe the same behaviour in 1.8.6-p399 and 1.8.7-head.  However, I don't see it in 1.9.1-p378: there all three forms print [] when called with an empty array.

答:
This is almost certainly a bug,

I suspect the reason this is happening is that Method#call has arity -1 (Expecting a C array of arguments), and Proc#call has arity -2 (Expecting a Ruby Array of arguments).

There's a further helpful comment in eval.c above the definition of Proc#call that may shed further light on the issue:

/* CHECKME: are the argument checking semantics correct? */

Maybe we should change that to a FIXME :p

Body:
Given the following method that takes one argument:

def foo(arg); p arg; end

I can call it with an empty array:

foo([])
# prints []

I can also save it as a Method object and call that with an empty array, with the same result:

method(:foo).call([])
# prints []

However, if I convert the Method object to a Proc and call that with an empty array, I get an ArgumentError:

method(:foo).to_proc.call([])
# ArgumentError: wrong number of arguments (0 for 1)
#   from (irb):4:in `foo'
#   from (irb):4:in `to_proc'
#   from (irb):10:in `call'

I expected it to behave the same as the previous two cases.  Instead, it seems to be behaving as if I'd written foo(*[]).  However, if I call it with a non-empty array, it does behave the way I expected:

method(:foo).to_proc.call([1])
# prints [1]

So it destructures the argument, but only if the argument happens to be an empty array.  And only if I call Method#to_proc.

Is there a gap in my understanding of how Method or Proc work, or is this a bug?

I'm running Ruby 1.8.7-p299.  I observe the same behaviour in 1.8.6-p399 and 1.8.7-head.  However, I don't see it in 1.9.1-p378: there all three forms print [] when called with an empty array.


问:
Why use an exception instead of if...else
For example, in the case of "The array index out of bound" exception, why don't we check the array length in advance:

```<code> if(array.length < countNum)
 {
 //logic
 }
 else
 {
 //replace using exception
}
</code>```

My question is, why choose to use an exception? and when to use an exception, instead of if-else

Thanks.

答:
Using exceptions is universal method to notify other part of code that something wrong happened in a loosely coupled way. Let imagine that if you would like to handle some exceptional condition by using if.. and else.. you need to insert into different part of your code some arbitrary variables and other assertions which probably would easily led to have spaghetti code soon after.

Let next imagine that you are using any external library/package and it's author decided to put in his/her code other arbitrary way to handle wrong states - it would force you to adjust to its way of dealing with it - for example you would need to check if particular methods returns true or false or some other provided variables has proper values. Using exceptions makes handling errors much more easy - you just assume that if something goes wrong - the other code will throw exception, so you just wrap the code in try block.

Body:
For example, in the case of "The array index out of bound" exception, why don't we check the array length in advance:

 if(array.length < countNum)
 {
 //logic
 }
 else
 {
 //replace using exception
}

My question is, why choose to use an exception? and when to use an exception, instead of if-else

Thanks.


问:
Bootstrap responsive image fit to parent height, stretching full width
I have a row with a certain height (e.g. 600px) and would like fit an img (size 1920x1080) into this row, stretching responsively 100% to the row width but not exceeding the height.

In other words, only 600px of the height of the image should be shown (the rest can be cut off, hidden, etc.), and it should remain responsive to the row width. To illustrate, only the part within the red borders should show:

The problem I am having is that "img-fluid" always fits the image to the smaller height of the container, and thus shrinking the width to keep the aspect ratio. Without img-fluid, or adding a fixed height to the image, the aspect ratio gets lost and the image is "squeezed" into the row-container. My code:

.img-400 {
  height: 400px !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"  integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

<div class="container">
  <div class="row img-400">
    <div class="col-12">
      <img src="https://image.ibb.co/iG8OSb/dogs.jpg" class="img-fluid" />
    </div>
  </div>
</div></code>```

Note I tried this one: Constraining image height with bootstrap responsive image? but didn't work, it keeps scaling the img out of the container.

答:
Hi try this one,

```<code>.img-400 img{ width: 100% ; }
</code>```

Hope this helps :)

Body:
I have a row with a certain height (e.g. 600px) and would like fit an img (size 1920x1080) into this row, stretching responsively 100% to the row width but not exceeding the height.

In other words, only 600px of the height of the image should be shown (the rest can be cut off, hidden, etc.), and it should remain responsive to the row width. To illustrate, only the part within the red borders should show:

The problem I am having is that "img-fluid" always fits the image to the smaller height of the container, and thus shrinking the width to keep the aspect ratio. Without img-fluid, or adding a fixed height to the image, the aspect ratio gets lost and the image is "squeezed" into the row-container. My code:

.img-400 {
  height: 400px !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"  integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

Note I tried this one: Constraining image height with bootstrap responsive image? but didn't work, it keeps scaling the img out of the container.

Body:
Hi try this one,

.img-400 img{ width: 100% ; }

Hope this helps :)


问:
Why MySQL return column name with quotes?
i have this:

```<code>...
SELECT
    `id`,
    `name`,
    `user_id`,
    `xml_tables`
...
</code>```

and when making the query, I recive this:

```<code>+- ----+------+---------+------------+
| `id` | name | user_id | xml_tables |
+------+------+---------+------------+
|    1 | name |       1 |        xml |
+------+------+---------+------------+
</code>```

with the name of the ID column with quotes.

答:
These are not the quotes you are looking for.

Those are single quotes they look like this:

```<code>'HELLO'
</code>```

Those are backticks or:

```<code>`HELLO`
</code>```

MySQL uses backticks as delimiters around columns names. They are not part of the name just here for display.

This helps when you use a reserved word such as GROUP as a columns name.
This will fail:

```<code> SELECT Group
 FROM   UserGroup
</code>```

This will run

```<code>SELECT `Group`
FROM   UserGroup
</code>```

If you ran a create statement like the following you might have included the backticks as part of the name:

```<code>CREATE TABLE `log`
(
    ```log_id``` BIGINT(20) NOT NULL AUTO_INCREMENT,
    `log_text` LONGTEXT NULL,

    PRIMARY KEY (```log_id```)

)
</code>```

Body:
i have this:

...
SELECT
    `id`,
    `name`,
    `user_id`,
    `xml_tables`
...

and when making the query, I recive this:

+- ----+------+---------+------------+
| `id` | name | user_id | xml_tables |
+------+------+---------+------------+
|    1 | name |       1 |        xml |
+------+------+---------+------------+

with the name of the ID column with quotes.

Body:
These are not the quotes you are looking for.

Those are single quotes they look like this:

'HELLO'

Those are backticks or:

`HELLO`

MySQL uses backticks as delimiters around columns names. They are not part of the name just here for display.

This helps when you use a reserved word such as GROUP as a columns name.
This will fail:

 SELECT Group
 FROM   UserGroup

This will run

SELECT `Group`
FROM   UserGroup

If you ran a create statement like the following you might have included the backticks as part of the name:

CREATE TABLE `log`
(
    ```log_id``` BIGINT(20) NOT NULL AUTO_INCREMENT,
    `log_text` LONGTEXT NULL,

    PRIMARY KEY (```log_id```)

)