问:
loop through columns and generate rows for each record R
When I used to program in SAS, it was easy to loop across variables and generate rows after applying some sort of logic. I would like to do this in R. To illustrate, consider the following scenario.

```<code>Input
+----+----------------+-------------------+-------------+
| ID |      lvl1      |        lvl2       |     lvl3    |
+----+----------------+-------------------+-------------+
|  1 |  United States |  Ohio             |  Cincinnati |
|  2 |  Ohio          |  Cincinnati       |             |
|  3 |  Canada        |  British Columbia |  Vancouver  |
+----+----------------+-------------------+-------------+
</code>```

Let array _lvl contain lvl1, lvl2, and lvl3 and loop from i = 1 to 3 (the upper bound).

Loop 1: _lvl(1) Check whether lvl1 is null and output if not, supplying null values for the other values.

Loop 2: _lvl(2) Check whether lvl1 is null or lvl2 is null and output if not, supplying null for lvl3.

Loop 3: _lvl(3) Check whether lvl1 is null, lvl2 is null, or lvl3 is null and output if not.

This should produce the following for ID = 2.

```<code>Output
+----+-------+-------------+-------+
| ID |  lvl1 |     lvl2    |  lvl3 |
+----+-------+-------------+-------+
|  2 |  Ohio |             |       |
|  2 |  Ohio |  Cincinnati |       |
+----+-------+-------------+-------+
</code>```

Thank you in advance.

答:
Here's one attempt using some indexing to blank out values where appropriate:

```<code>newdat <- dat[rep(1:nrow(dat),each=3),]
newdat[-1][upper.tri(dat[-1])[rep(1:nrow(dat),3),]] <- ""
unique(newdat)

#    ID          lvl1             lvl2       lvl3
#1    1 United States
#1.1  1 United States             Ohio
#1.2  1 United States             Ohio Cincinnati
#2    2          Ohio
#2.1  2          Ohio       Cincinnati
#3    3        Canada
#3.1  3        Canada British Columbia
#3.2  3        Canada British Columbia  Vancouver
</code>```

This works because the created matrix is an indicator of which parts to delete of newdat:

```<code>upper.tri(dat[-1])[rep(1:nrow(dat),3),]
#       [,1]  [,2]  [,3]
# [1,] FALSE  TRUE  TRUE
# [2,] FALSE FALSE  TRUE
# [3,] FALSE FALSE FALSE
# [4,] FALSE  TRUE  TRUE
# [5,] FALSE FALSE  TRUE
# [6,] FALSE FALSE FALSE
# [7,] FALSE  TRUE  TRUE
# [8,] FALSE FALSE  TRUE
# [9,] FALSE FALSE FALSE
</code>```

Where dat was:

```<code>dat <- read.csv(text="ID,lvl1,lvl2,lvl3
1,United States,Ohio,Cincinnati
2,Ohio,Cincinnati,
3,Canada,British Columbia,Vancouver", stringsAsFactors=FALSE)
</code>```

Body:
When I used to program in SAS, it was easy to loop across variables and generate rows after applying some sort of logic. I would like to do this in R. To illustrate, consider the following scenario.

Input
+----+----------------+-------------------+-------------+
| ID |      lvl1      |        lvl2       |     lvl3    |
+----+----------------+-------------------+-------------+
|  1 |  United States |  Ohio             |  Cincinnati |
|  2 |  Ohio          |  Cincinnati       |             |
|  3 |  Canada        |  British Columbia |  Vancouver  |
+----+----------------+-------------------+-------------+

Let array _lvl contain lvl1, lvl2, and lvl3 and loop from i = 1 to 3 (the upper bound).

Loop 1: _lvl(1) Check whether lvl1 is null and output if not, supplying null values for the other values.

Loop 2: _lvl(2) Check whether lvl1 is null or lvl2 is null and output if not, supplying null for lvl3.

Loop 3: _lvl(3) Check whether lvl1 is null, lvl2 is null, or lvl3 is null and output if not.

This should produce the following for ID = 2.

Output
+----+-------+-------------+-------+
| ID |  lvl1 |     lvl2    |  lvl3 |
+----+-------+-------------+-------+
|  2 |  Ohio |             |       |
|  2 |  Ohio |  Cincinnati |       |
+----+-------+-------------+-------+

Thank you in advance.

Body:
Here's one attempt using some indexing to blank out values where appropriate:

newdat <- dat[rep(1:nrow(dat),each=3),]
newdat[-1][upper.tri(dat[-1])[rep(1:nrow(dat),3),]] <- ""
unique(newdat)

#    ID          lvl1             lvl2       lvl3
#1    1 United States
#1.1  1 United States             Ohio
#1.2  1 United States             Ohio Cincinnati
#2    2          Ohio
#2.1  2          Ohio       Cincinnati
#3    3        Canada
#3.1  3        Canada British Columbia
#3.2  3        Canada British Columbia  Vancouver

This works because the created matrix is an indicator of which parts to delete of newdat:

upper.tri(dat[-1])[rep(1:nrow(dat),3),]
#       [,1]  [,2]  [,3]
# [1,] FALSE  TRUE  TRUE
# [2,] FALSE FALSE  TRUE
# [3,] FALSE FALSE FALSE
# [4,] FALSE  TRUE  TRUE
# [5,] FALSE FALSE  TRUE
# [6,] FALSE FALSE FALSE
# [7,] FALSE  TRUE  TRUE
# [8,] FALSE FALSE  TRUE
# [9,] FALSE FALSE FALSE

Where dat was:

dat <- read.csv(text="ID,lvl1,lvl2,lvl3
1,United States,Ohio,Cincinnati
2,Ohio,Cincinnati,
3,Canada,British Columbia,Vancouver", stringsAsFactors=FALSE)


来源: stackexchange

问:
Another why won't my jquery ajax work in ie question
Just want to make sure my test code below is proper. I've been reading and it seems html syntax errors renders the jquery ajax unusable in ie?

There are a bunch of includes where this code resides, so is it possible there is something wrong in one of those files, having nothing to do with my ajax code?

```<code>$("#checkEmail").blur(function(){
  $.ajax({
    type: "POST",
    url: "adamcheck.php",
    data: "checkit=" + $("#checkEmail").val(),
    success: function(output){
      $("#userCheck").html(output);
    }
  });
});
</code>```

adamcheck.php

```<code><script type="text/javascript">
$(document).ready(function() {
   alert("FGHFGHGFH");
});
</script>
<?php
if(isset($_POST['checkit'])){
  $email= $_POST['checkit'];
  echo "<p>$email</p>";
}
?>
</code>```

答:
The only possible way in such a situation (where you have doubts on many things) is to debug step by step, entity by entity. First clear your doubt on the AJAX post. Take only this code and the necessary minimum HTML and php code, put them in a separate setup (separate from your project). There is no shortcut to this.

If this works, then move on to the bunch of includes. There

By the way, your AJAX post code looks syntactically correct and it is a very basic and simple.

ContentLicense: CC BY-SA 2.5

Body:
Just want to make sure my test code below is proper. I've been reading and it seems html syntax errors renders the jquery ajax unusable in ie?

There are a bunch of includes where this code resides, so is it possible there is something wrong in one of those files, having nothing to do with my ajax code?

$("#checkEmail").blur(function(){
  $.ajax({
    type: "POST",
    url: "adamcheck.php",
    data: "checkit=" + $("#checkEmail").val(),
    success: function(output){
      $("#userCheck").html(output);
    }
  });
});

adamcheck.php

<?php
if(isset($_POST['checkit'])){
  $email= $_POST['checkit'];
  echo "
$email
";
}
?>


问:
No option to set a static homepage in WordPress
I've just installed the newest WordPress (4.7.3). There is no option to set a static homepage, as shown below.

It should look like,

How do I set a set a static homepage in WordPress?

答:
First thing first, Please check switching another theme and also disable the plugins.

The cause might be wordpress installation is probably corrupt

You may want to check this & this

ContentLicense: CC BY-SA 3.0


问:
stateless ejb in WAR > package to EAR > local ejb call
I have an ear which contains 2 war files and each war contains stateless ejb and jersey rest classes. The interfaces locate in commons.jar file. The EAR structure looks like this:

```<code>EAR
 -- /lib/commons.jar

 -- rest-1.war
      -- stateless-ejb-1.java
      -- jersey-rest-1.java

 -- rest-2.war
      -- stateless-ejb-2.java
      -- jersey-rest-2.java
</code>```

I am trying to use stateless-ejb-1 from stateless-ejb-2 with @Inject annotation but I get a CDI deployment failure:WELD-001408: Unsatisfied dependencies error during deployment time. When I use @EJB in stateless-ejb-2 then the ear is deployed but I get a remote lookup error while calling jersey-rest-2.

This are my method call chains:

jersey-rest-1 > stateless-ejb-1: works fine

jersey-rest-2 > stateless-ejb-2 > stateless-ejb-1: I get an ejb-1 lookup error

I do not want to use remote ejb call because everything is packaged in the same ear (I would like to use @Inject instead of @EJB) but it does not work.

I guess that if I pack stateless-ejb-1.java to a jar and put it under EJB/lib than it will work. But I do not want to create a new module in my project just to pack this one file to separated jar file.
What is the solution?

答:
You need to move stateless-ejb-1 into an ejb-jar module in the EAR.

Classes in different WAR files are never visible to each other, even when built into an EAR file.

Body:
I have an ear which contains 2 war files and each war contains stateless ejb and jersey rest classes. The interfaces locate in commons.jar file. The EAR structure looks like this:

EAR
 -- /lib/commons.jar

 -- rest-1.war
      -- stateless-ejb-1.java
      -- jersey-rest-1.java

 -- rest-2.war
      -- stateless-ejb-2.java
      -- jersey-rest-2.java

I am trying to use stateless-ejb-1 from stateless-ejb-2 with @Inject annotation but I get a CDI deployment failure:WELD-001408: Unsatisfied dependencies error during deployment time. When I use @EJB in stateless-ejb-2 then the ear is deployed but I get a remote lookup error while calling jersey-rest-2.

This are my method call chains:

jersey-rest-1 > stateless-ejb-1: works fine

jersey-rest-2 > stateless-ejb-2 > stateless-ejb-1: I get an ejb-1 lookup error

I do not want to use remote ejb call because everything is packaged in the same ear (I would like to use @Inject instead of @EJB) but it does not work.

I guess that if I pack stateless-ejb-1.java to a jar and put it under EJB/lib than it will work. But I do not want to create a new module in my project just to pack this one file to separated jar file.
What is the solution?


问:
Func vs. Action vs. Predicate
With real examples and their use, can someone please help me understand:

When do we need a Func<T, ..> delegate?

When do we need an Action<T> delegate?

When do we need a Predicate<T> delegate?

答:
Func - When you want a delegate for a function that may or may not take parameters and returns a value. The most common example would be Select from LINQ:

```<code>var result = someCollection.Select( x => new { x.Name, x.Address });
</code>```

Action - When you want a delegate for a function that may or may not take parameters and does not return a value. I use these often for anonymous event handlers:

```<code>button1.Click += (sender, e) => { /* Do Some Work */ }
</code>```

Predicate -  When you want a specialized version of a Func that evaluates a value against a set of criteria and returns a boolean result (true for a match, false otherwise). Again, these are used in LINQ quite frequently for things like Where:

```<code>var filteredResults =
    someCollection.Where(x => x.someCriteriaHolder == someCriteria);
</code>```

I just double checked and it turns out that LINQ doesn't use Predicates. Not sure why they made that decision...but theoretically it is still a situation where a Predicate would fit.

ContentLicense: CC BY-SA 4.0

Title: Func vs. Action vs. Predicate

Body:
Func - When you want a delegate for a function that may or may not take parameters and returns a value. The most common example would be Select from LINQ:

var result = someCollection.Select( x => new { x.Name, x.Address });

Action - When you want a delegate for a function that may or may not take parameters and does not return a value. I use these often for anonymous event handlers:

button1.Click += (sender, e) => { /* Do Some Work */ }

Predicate -  When you want a specialized version of a Func that evaluates a value against a set of criteria and returns a boolean result (true for a match, false otherwise). Again, these are used in LINQ quite frequently for things like Where:

var filteredResults =
    someCollection.Where(x => x.someCriteriaHolder == someCriteria);

I just double checked and it turns out that LINQ doesn't use Predicates. Not sure why they made that decision...but theoretically it is still a situation where a Predicate would fit.


问:
How to determine whether an array is contained in another array
The question is, given [1,2,3,4,5] and [2,4,5], to determine whether (every element in) the second array is contained in the first one. The answer is true.

What's the most succinct and efficient way to do better than:

```<code>arr2.reject { |e| arr1.include?(e) } .empty?
</code>```

答:
As mentioned by @Ryan you can use sets. In which case Set#subset? is available to you which is pretty readable (note the two different ways of defining a set from an array):

```<code>require 'set'

s1 = Set.new([1, 2, 3])
s2 = [1, 2].to_set
s3 = [1, 3].to_set
s4 = [1, 4].to_set

s1.subset? s1 #=> true
s2.subset? s1 #=> true
s3.subset? s1 #=> true
s4.subset? s1 #=> false
</code>```

Also consider using Set#proper_subset if required.

```<code>s1.proper_subset? s1 #=> false
s2.proper_subset? s1 #=> true
</code>```

NB A set contains no duplicate elements e.g. Set.new([1,2,3,3]) #=> #<Set: {1, 2, 3}>

Body:
The question is, given [1,2,3,4,5] and [2,4,5], to determine whether (every element in) the second array is contained in the first one. The answer is true.

What's the most succinct and efficient way to do better than:

arr2.reject { |e| arr1.include?(e) } .empty?

Body:
As mentioned by @Ryan you can use sets. In which case Set#subset? is available to you which is pretty readable (note the two different ways of defining a set from an array):

require 'set'

s1 = Set.new([1, 2, 3])
s2 = [1, 2].to_set
s3 = [1, 3].to_set
s4 = [1, 4].to_set

s1.subset? s1 #=> true
s2.subset? s1 #=> true
s3.subset? s1 #=> true
s4.subset? s1 #=> false

Also consider using Set#proper_subset if required.

s1.proper_subset? s1 #=> false
s2.proper_subset? s1 #=> true

NB A set contains no duplicate elements e.g. Set.new([1,2,3,3]) #=> #<Set: {1, 2, 3}>


问:
Reverse the order of pairs
I am trying to write a function in Racket that will reverse the order of pairs.  For example, given the list '(1 2) the function should produce '(2 1).  Here is my code so far:

```<code>(define (reverse aList)
    (cons (second aList)
        (first aList))
</code>```

This is not producing the correct answer, however.  When I test with '(a b) it returns '(b . a) instead of '(b a).  How do I get rid of the period between the b and a?

答:
You should have:

```<code>(define (reverse-pair lst)
  (cons (second lst) (cons (first lst) empty)))
</code>```

As stated in Racket's docs:

The cons function actually accepts any two values, not just a list for the second argument. When the second argument is not empty and not itself produced by cons, the result prints in a special way. The two values joined with cons are printed between parentheses, but with a dot (i.e., a period surrounded by whitespace) in between.

So,

```<code>> (cons 1 2)
'(1 . 2)
> (cons 1 (cons 2 empty))     ; equivalent to (list 1 2)
'(1 2)
</code>```

Title: Reverse the order of pairs

Body:
I am trying to write a function in Racket that will reverse the order of pairs.  For example, given the list '(1 2) the function should produce '(2 1).  Here is my code so far:

(define (reverse aList)
    (cons (second aList)
        (first aList))

This is not producing the correct answer, however.  When I test with '(a b) it returns '(b . a) instead of '(b a).  How do I get rid of the period between the b and a?

Body:
You should have:

(define (reverse-pair lst)
  (cons (second lst) (cons (first lst) empty)))

As stated in Racket's docs:

The cons function actually accepts any two values, not just a list for the second argument. When the second argument is not empty and not itself produced by cons, the result prints in a special way. The two values joined with cons are printed between parentheses, but with a dot (i.e., a period surrounded by whitespace) in between.

So,

> (cons 1 2)
'(1 . 2)
> (cons 1 (cons 2 empty))     ; equivalent to (list 1 2)
'(1 2)


问:
Accees Hue error - 1045
I'm trying to connect the HUE and show this error:

Somenone help me please!

答:
```<code>Access denied for user 'hue'@'localhost'
</code>```

It means your database (= MySQL) doesn't permit hue user to login from localhost.
Please follow the procedure; Using an External Database for Hue Using the Command Line

Especially,

```<code>mysql> create database hue;
Query OK, 1 row affected (0.01 sec)
mysql> grant all on hue.* to 'hue'@'localhost' identified by '<secretpassword>';
Query OK, 0 rows affected (0.00 sec)
</code>```

Title: Accees Hue error - 1045

Body:
Access denied for user 'hue'@'localhost'

It means your database (= MySQL) doesn't permit hue user to login from localhost.
Please follow the procedure; Using an External Database for Hue Using the Command Line

Especially,

mysql> create database hue;
Query OK, 1 row affected (0.01 sec)
mysql> grant all on hue.* to 'hue'@'localhost' identified by '<secretpassword>';
Query OK, 0 rows affected (0.00 sec)


问:
Is there a way to trivially sum identical indices of a 2D-list into a 1D-list?
Say I have a list of lists

```<code>[[1, 2, 3], [4, 5, 6]]
</code>```

And I want to transform this such that the individual indices are summed and I get:

```<code>[5, 7, 9]
</code>```

Is there an easy combination of list comprehensions, zip(), sum() and so on for me to get this result without writing a clutter of for loops and accumulators?

答:
You can use numpy, convert your list into an array and sum over 0 axis as follows:

```<code>import numpy as np
list_of_lists = [[1, 2, 3], [4, 5, 6]]
arr = np.array(list_of_lists)
result = np.sum(arr, axis=0)
print(result)
</code>```

Although this would only work if all your lists within the list have the same length.

You can later convert the result into a list (if you need to) using:

```<code>result.tolist()
</code>```

Body:
Say I have a list of lists

[[1, 2, 3], [4, 5, 6]]

And I want to transform this such that the individual indices are summed and I get:

[5, 7, 9]

Is there an easy combination of list comprehensions, zip(), sum() and so on for me to get this result without writing a clutter of for loops and accumulators?

Body:
You can use numpy, convert your list into an array and sum over 0 axis as follows:

import numpy as np
list_of_lists = [[1, 2, 3], [4, 5, 6]]
arr = np.array(list_of_lists)
result = np.sum(arr, axis=0)
print(result)

Although this would only work if all your lists within the list have the same length.

You can later convert the result into a list (if you need to) using:

result.tolist()


问:
How to include an input to v-for in scoped slot?
I just learnt about slot today on Vue official tutorial. As I read through, I came across this example on scoped slot: https://v2.vuejs.org/v2/guide/components.html#Scoped-Slots.

I experimented a little by adding an input field to each item.

Parent:

```<code><my-list :items="items">
    <template slot="item" scope="props">
        <li class="my-fancy-item">{{ props.text }}</li>
    </template>
</my-list>
</code>```

Child template:

```<code>  <ul>
     <slot name="item" v-for="item in items" :text="item.text">
     </slot>
     <div> // this will appear at the end of list
         <input v-model = "message">
     </div>
     <p>{{message}}</p>
  </ul>
</code>```

My first attempt was to move the input to the parent scope and called a child function by passing into it the index and input value using props to modify the original array. It worked as intended.

Another attempt is to do binding on parent scope but it won't work because parent scope can't see child property: https://v2.vuejs.org/v2/guide/components.html#Compilation-Scope

What is the best way to insert this input so that it will appear in every item and still be able to bind input to child property?

答:
Base on our discussion, I think essentially what you want is this. Because you want the message to be independently editable, it needs to be part of the item. If you make message part of my-list, then all the messages will be the same. After that, all you need to do is pass the item to the scoped template.

```<code>Vue.component("my-list",{
  props:["items"],
  template: "#my-list-template",
})

new Vue({
  el:"#app",
  data:{
    items:[
      {text: "item 1", message: "message 1"},
      {text: "item 2", message: "message 2"},
      {text: "item 3", message: "message 3"}
    ]
  }
})
</code>```

And the templates:

```<code><div id="app">
  {{items}}
  <my-list :items="items">
      <template slot="item" scope="props">
        <li class="my-fancy-item">{{ props.item.text }}</li>
        <div>
             <input v-model="props.item.message">
         </div>
         <p>{{props.item.message}}</p>
      </template>
  </my-list>

</div>

<template id="my-list-template">
  <ul>
     <slot name="item"
           v-for="item in items"
           :item="item">
    </slot>
  </ul>
</template>
</code>```

Here is the working example.

Body:
I just learnt about slot today on Vue official tutorial. As I read through, I came across this example on scoped slot: https://v2.vuejs.org/v2/guide/components.html#Scoped-Slots.

I experimented a little by adding an input field to each item.

Parent:

<my-list :items="items">
    <template slot="item" scope="props">

{{ props.text }}

    </template>
</my-list>

Child template:

     <slot name="item" v-for="item in items" :text="item.text">
     </slot>

 // this will appear at the end of list
         <input v-model = "message">

{{message}}

My first attempt was to move the input to the parent scope and called a child function by passing into it the index and input value using props to modify the original array. It worked as intended.

Another attempt is to do binding on parent scope but it won't work because parent scope can't see child property: https://v2.vuejs.org/v2/guide/components.html#Compilation-Scope

What is the best way to insert this input so that it will appear in every item and still be able to bind input to child property?

Body:
Base on our discussion, I think essentially what you want is this. Because you want the message to be independently editable, it needs to be part of the item. If you make message part of my-list, then all the messages will be the same. After that, all you need to do is pass the item to the scoped template.

Vue.component("my-list",{
  props:["items"],
  template: "#my-list-template",
})

new Vue({
  el:"#app",
  data:{
    items:[
      {text: "item 1", message: "message 1"},
      {text: "item 2", message: "message 2"},
      {text: "item 3", message: "message 3"}
    ]
  }
})

And the templates:

<div id="app">
  {{items}}
  <my-list :items="items">
      <template slot="item" scope="props">
        <li class="my-fancy-item">{{ props.item.text }}</li>
        <div>
             <input v-model="props.item.message">
         </div>
         <p>{{props.item.message}}</p>
      </template>
  </my-list>

</div>

<template id="my-list-template">
  <ul>
     <slot name="item"
           v-for="item in items"
           :item="item">
    </slot>
  </ul>
</template>

Here is the working example.


问:
Calculating and Applying normals to a triangle mesh
I have a triangle mesh and I'm trying to calculate the normals so I can apply them when drawing the mesh. I'm using immediate mode (will probably change to vertex arrays when I get time to understand how they work) and drawing the mesh with GL_TRIANGLE_STRIP.

I am having trouble calculating the vertex normals. More precisely deciding which neighbouring vertices to use in the calculations and then deciding when to set those normals. Consider this:

```<code> 1_2
 |/|    Supposedly a square where the numbers represent the vertex number in a
 3 4    triangle strip.
</code>```

I know you have to compute the cross product of 2 vectors belonging to a plane in order to get the plane normal. So in that example the top triangle's normal could be calculated by doing (2-1)x(3-1), and the second one by doing (2-4)x(3-4). How do you then apply the normals when drawing the triangle strip in immediate mode?

What I was doing was setting the first normal when vtx 1 is set, the second when vtx 4 is set, the third when vtx 5 is set, etc. This however gives issues as you obviously end up by having different normals for each of the vertices of a triangle (when they should all be the same). For instance, triangle |2,3,4| would only have vertex 4 with the correct normal (since for vertices 2 and 3 the normal would be the one of the first triangle).

So how should it be done? Is there a way, or do I need to change to GL_TRIANGLES? (I don't want to stop using immediate mode for now as I don't have time).

答:
If I'm correct you're still only computing a normal per triangle? This is correct, but after that you should computed what the normal is per vertex. This is simply the normalized sum of all triangle normals that the specific vertex is attached to.
Once completed you can proceed with your immediate mode drawing, specifying a normal per vertex.</p>

Body:
I have a triangle mesh and I'm trying to calculate the normals so I can apply them when drawing the mesh. I'm using immediate mode (will probably change to vertex arrays when I get time to understand how they work) and drawing the mesh with GL_TRIANGLE_STRIP.

I am having trouble calculating the vertex normals. More precisely deciding which neighbouring vertices to use in the calculations and then deciding when to set those normals. Consider this:

 1_2
 |/|    Supposedly a square where the numbers represent the vertex number in a
 3 4    triangle strip.

I know you have to compute the cross product of 2 vectors belonging to a plane in order to get the plane normal. So in that example the top triangle's normal could be calculated by doing (2-1)x(3-1), and the second one by doing (2-4)x(3-4). How do you then apply the normals when drawing the triangle strip in immediate mode?

What I was doing was setting the first normal when vtx 1 is set, the second when vtx 4 is set, the third when vtx 5 is set, etc. This however gives issues as you obviously end up by having different normals for each of the vertices of a triangle (when they should all be the same). For instance, triangle |2,3,4| would only have vertex 4 with the correct normal (since for vertices 2 and 3 the normal would be the one of the first triangle).

So how should it be done? Is there a way, or do I need to change to GL_TRIANGLES? (I don't want to stop using immediate mode for now as I don't have time).


问:
simple recursive merge sort Stack java.lang.StackOverflowError
I have a simple recursive merge sort, I am just try to sort an array list of Integers that implement Comparable. I don't under stand why I am getting an error, when it runs it prints out the ArrayList of random Integers that I created and then it prints

no error yet

no error yet

Exception in thread "main" java.lang.StackOverflowError

and then it repeats

at MergeTemplate.rMerge(MergeTemplate.java:38)

a bunch of times until it finally says

Process complete

```<code>import java.util.*;
public class MergeTemplate{
private ArrayList <Comparable> temp1=new <Comparable> ArrayList();
int num;
Random ar=new Random();
public MergeTemplate(){
    num=25;
}
  public MergeTemplate(int n){
    num=n;
  }
      public ArrayList <Comparable> fillArray(){
          ArrayList <Comparable> ar1=new <Comparable> ArrayList();
          for(int i=0;i<num; i++)
              ar1.add(ar.nextInt(11));
          screenOutput(ar1);
      return ar1;
      }
      public void screenOutput(){
          for(Comparable x: temp1)
              System.out.print(x+ " ");
          System.out.println();
      }
      public void screenOutput(ArrayList <Comparable> temp){
          for(Comparable x: temp)
              System.out.print(x+ " ");
          System.out.println();
      }
      public void rMerge(ArrayList <Comparable> rList){
          rMerge(rList, 0, rList.size()-1);
      }

      public void rMerge(ArrayList <Comparable> rList, int first, int last){
          if (first-last==0){
              System.out.println("no error yet");
          }
          else{
              rMerge(rList, first, last/2);
              rMerge(rList, last/2 + 1, last);
              merge(rList, first, last);
          }
      }
      public void merge(ArrayList <Comparable> a, int first, int last){
          Comparable placeHolder;
          if(a.get(first).compareTo(a.get(last))>1){
              placeHolder=a.get(first);
              a.set(first, a.get(last));
              a.set(last, placeHolder);
          }
      }
}

public class Tester {
    public static void main(String[] args) {
    MergeTemplate one=new MergeTemplate(8);
    one.rMerge(one.fillArray());
    }
}
</code>```

答: Your merge method has an error, it doesn't iterate over the all list to verify the order result.

Body:
I have a simple recursive merge sort, I am just try to sort an array list of Integers that implement Comparable. I don't under stand why I am getting an error, when it runs it prints out the ArrayList of random Integers that I created and then it prints

no error yet

no error yet

Exception in thread "main" java.lang.StackOverflowError

and then it repeats

at MergeTemplate.rMerge(MergeTemplate.java:38)

a bunch of times until it finally says

Process complete

import java.util.*;
public class MergeTemplate{
private ArrayList <Comparable> temp1=new <Comparable> ArrayList();
int num;
Random ar=new Random();
public MergeTemplate(){
    num=25;
}
  public MergeTemplate(int n){
    num=n;
  }
      public ArrayList <Comparable> fillArray(){
          ArrayList <Comparable> ar1=new <Comparable> ArrayList();
          for(int i=0;i<num; i++)
              ar1.add(ar.nextInt(11));
          screenOutput(ar1);
      return ar1;
      }
      public void screenOutput(){
          for(Comparable x: temp1)
              System.out.print(x+ " ");
          System.out.println();
      }
      public void screenOutput(ArrayList <Comparable> temp){
          for(Comparable x: temp)
              System.out.print(x+ " ");
          System.out.println();
      }
      public void rMerge(ArrayList <Comparable> rList){
          rMerge(rList, 0, rList.size()-1);
      }

      public void rMerge(ArrayList <Comparable> rList, int first, int last){
          if (first-last==0){
              System.out.println("no error yet");
          }
          else{
              rMerge(rList, first, last/2);
              rMerge(rList, last/2 + 1, last);
              merge(rList, first, last);
          }
      }
      public void merge(ArrayList <Comparable> a, int first, int last){
          Comparable placeHolder;
          if(a.get(first).compareTo(a.get(last))>1){
              placeHolder=a.get(first);
              a.set(first, a.get(last));
              a.set(last, placeHolder);
          }
      }
}

public class Tester {
    public static void main(String[] args) {
    MergeTemplate one=new MergeTemplate(8);
    one.rMerge(one.fillArray());
    }
}


问:
Suppress Specific Doxygen Warnings
It seems others have asked this question before. Just wanted to check and see if an answer had been found.

I have several occurrences of the following situation: as I am documenting various functions, sometimes I run into the situation where I wish to document some function parameters but not others.  For example,

```<code>/**
 * This is the brief description for the function.
 * And here is the detailed description.
 * @param foo This parameter is not self-explanatory and needs a blurb
 */
void some_function(void *foo, int self_explanatory) {
    // function does stuff
}
</code>```

Adding the self_explanatory parameter to the Doxygen documentation just adds clutter, so I'd rather leave it out. However, Doxygen warns that the parameter is undocumented. I'm using Eclox, and it's annoying to have a bunch of warnings highlighted that I don't care about.

Right now, my doxyfile has the following options set:

```<code>EXTRACT_ALL          = YES
WARNINGS             = YES
WARN_IF_UNDOCUMENTED = NO
WARN_IF_DOC_ERROR    = YES
WARN_NO_PARAM_DOC    = NO
</code>```

The warnings are still generated.

One option is to add @cond and @endcond surrounding the offending code, but then none of the documentation is generated for my function(s). I want the documentation, just not the warnings.

What I'm looking for is something like...

```<code>/** @nowarn
 * This is the brief description for the function.
 * And here is the detailed description.
 * @param foo This parameter is not self-explanatory and needs a blurb
 * @endnowarn
 */
void some_function(void *foo, int self_explanatory) {
    // function does stuff
}
</code>```

... so that warnings are not generated in the enclosed code block.

Other SO questions I've found:

Suppressing Doxygen warnings

Suppress doxygen warning for undocumented member function, but leave synopsis in place

Is it possible to choose which Doxygen warning to show?

答:
Just document the self_explanatory parameter, or keep in mind that warnings are just that: warnings. All Doxygen is telling you is that there is something you might have overlooked.

You can take the warning or just ignore it. If you really want to suppress that warning, you might want to look in the first thread you linked. Specifically, https://stackoverflow.com/a/25137529/3121160.

Title: Suppress Specific Doxygen Warnings

Body:
It seems others have asked this question before. Just wanted to check and see if an answer had been found.

I have several occurrences of the following situation: as I am documenting various functions, sometimes I run into the situation where I wish to document some function parameters but not others.  For example,

/**
 * This is the brief description for the function.
 * And here is the detailed description.
 * @param foo This parameter is not self-explanatory and needs a blurb
 */
void some_function(void *foo, int self_explanatory) {
    // function does stuff
}

Adding the self_explanatory parameter to the Doxygen documentation just adds clutter, so I'd rather leave it out. However, Doxygen warns that the parameter is undocumented. I'm using Eclox, and it's annoying to have a bunch of warnings highlighted that I don't care about.

Right now, my doxyfile has the following options set:

EXTRACT_ALL          = YES
WARNINGS             = YES
WARN_IF_UNDOCUMENTED = NO
WARN_IF_DOC_ERROR    = YES
WARN_NO_PARAM_DOC    = NO

The warnings are still generated.

One option is to add @cond and @endcond surrounding the offending code, but then none of the documentation is generated for my function(s). I want the documentation, just not the warnings.

What I'm looking for is something like...

/** @nowarn
 * This is the brief description for the function.
 * And here is the detailed description.
 * @param foo This parameter is not self-explanatory and needs a blurb
 * @endnowarn
 */
void some_function(void *foo, int self_explanatory) {
    // function does stuff
}

... so that warnings are not generated in the enclosed code block.

Other SO questions I've found:

Suppressing Doxygen warnings

Suppress doxygen warning for undocumented member function, but leave synopsis in place

Is it possible to choose which Doxygen warning to show?


答:
For other circumstances in which you want the number string to be consistent, I made a function.

Someone may find this useful:

```<code>idnamer<-function(x,y){#Alphabetical designation and number of integers required
    id<-c(1:y)
    for (i in 1:length(id)){
         if(nchar(id[i])<2){
            id[i]<-paste("0",id[i],sep="")
         }
    }
    id<-paste(x,id,sep="")
    return(id)
}
idnamer("EF",28)
</code>```

Sorry about the formatting.

Title: How to add leading zeros?

Body:
I have a set of data which looks something like this:

anim <- c(25499,25500,25501,25502,25503,25504)
sex  <- c(1,2,2,1,2,1)
wt   <- c(0.8,1.2,1.0,2.0,1.8,1.4)
data <- data.frame(anim,sex,wt)

data
   anim sex  wt anim2
1 25499   1 0.8     2
2 25500   2 1.2     2
3 25501   2 1.0     2
4 25502   1 2.0     2
5 25503   2 1.8     2
6 25504   1 1.4     2

I would like a zero to be added before each animal id:

data
   anim sex  wt anim2
1 025499   1 0.8     2
2 025500   2 1.2     2
3 025501   2 1.0     2
4 025502   1 2.0     2
5 025503   2 1.8     2
6 025504   1 1.4     2

And for interest sake, what if I need to add two or three zeros before the animal id's?

Body:
For other circumstances in which you want the number string to be consistent, I made a function.

Someone may find this useful:

idnamer<-function(x,y){#Alphabetical designation and number of integers required
    id<-c(1:y)
    for (i in 1:length(id)){
         if(nchar(id[i])<2){
            id[i]<-paste("0",id[i],sep="")
         }
    }
    id<-paste(x,id,sep="")
    return(id)
}
idnamer("EF",28)

Sorry about the formatting.


问:
Using chart.js version 1.0.2 and 2.0 together
I created a full webpage report with many charts using chart.js version 1.0.2.

Only in a later stage I discovered multiple functionalities missing from version 1.0.2 but available on version 2.0 dev. I tried to use both in my page but just importing the chart.js 2.0 file () made most of my charts to not work anymore.
Is there a way I can locally import chart.js 2.0 just for one place on my page? Is there a smart way to move from chart.js version 1.0.2 to 2.0 dev or to solve my problem is a different way?

答:
Because I cannot find Chart.noConflict() in the Version 2, so I use the below solution to solve it. It is just a reference for you, and you can choose which is the default selection by yourself.

Set Version1 as the default version

```<code><script type="text/javascript" src="/v1/Chart.js-master/Chart.js"></script>
<script>
window.ChartV1 = Chart;
</script>
<script type="text/javascript" src="/v2/Chart.js-master/Chart.js"></script>
<script>
window.ChartV2 = Chart;
window.Chart = window.ChartV1;
</script>
</code>```

Set Version2 as the default version

```<code><script type="text/javascript" src="/v1/Chart.js-master/Chart.js"></script>
<script>
window.ChartV1 = Chart;
</script>
<script type="text/javascript" src="/v2/Chart.js-master/Chart.js"></script>
<script>
window.ChartV2 = Chart;
window.Chart = window.ChartV2;
</script>
</code>```

Body:
Because I cannot find Chart.noConflict() in the Version 2, so I use the below solution to solve it. It is just a reference for you, and you can choose which is the default selection by yourself.

Set Version1 as the default version

<script type="text/javascript" src="/v1/Chart.js-master/Chart.js"></script>
<script>
window.ChartV1 = Chart;
</script>
<script type="text/javascript" src="/v2/Chart.js-master/Chart.js"></script>
<script>
window.ChartV2 = Chart;
window.Chart = window.ChartV1;
</script>

Set Version2 as the default version

<script type="text/javascript" src="/v1/Chart.js-master/Chart.js"></script>
<script>
window.ChartV1 = Chart;
</script>
<script type="text/javascript" src="/v2/Chart.js-master/Chart.js"></script>
<script>
window.ChartV2 = Chart;
window.Chart = window.ChartV2;
</script>


问:
I'm having trouble opening a port into Azure VM
I have a simple Azure Windows Server VM set up and I have a NodeJS app running in it. Within the VM (using Windows RDP), I can access the app in a browser at http://localhost:4200. However, I can't manage to open port 4200 so that I can access it from the outside using my VM's IP.

I've tried the obvious, as outlined here: https://learn.microsoft.com/en-us/azure/virtual-machines/windows/nsg-quickstart-portal

The crazy thing is that I also have another app, running as a Windows service on port 8080, and that one works. I have a rule for each, and I can't see what I'm doing differently:

I also completely disabled the Windows Firewall within the VM, and it still doesn't work. Can't get through at all.

答:
According to your description, it seems that your app is only listening on 127.0.0.1. Please check as the following ways.

1.Check the port listening.

```<code>netstat -ant|findstr 4200
</code>```

Please ensure your service is listening on 0.0.0.0 not 127.0.0.1. If you service is listening on 127.0.0.0, please modify it. You could refer to this answer.

2.Please ensure your VM is listening on tcp  not tcp6.

Body:
According to your description, it seems that your app is only listening on 127.0.0.1. Please check as the following ways.

1.Check the port listening.

netstat -ant|findstr 4200

Please ensure your service is listening on 0.0.0.0 not 127.0.0.1. If you service is listening on 127.0.0.0, please modify it. You could refer to this answer.

2.Please ensure your VM is listening on tcp  not tcp6.


问:
angular2 how to iterate array of objects
I want to iterate an array of objects but I received the following error:

```<code>inline template:25:9 caused by: Cannot read property 'length' of null
</code>```

The followings are parts of my code:

```<code>// Definition of the array
public columnsConfig: Array<ColumnConfig>;
</code>```

where ColumnConfig is a class of all the instances included in the array.

```<code>// Constructor of the component
this.columnsConfig = new Array<ColumnConfig>();

// Function that builds the array to iterate
for(var columnName in _headers) {
  let config = new ColumnConfig(columnName, _headers[columnName]);`
   this.columnsConfig.push(config);`
}
</code>```

Template:

What am I missing here?

答: I found the problem: it was related to a default value of a string variable defined in the object that composes the array. So, I changed the default variable to an empty string ('') and it worked.</p>

Body:
I want to iterate an array of objects but I received the following error:

inline template:25:9 caused by: Cannot read property 'length' of null

The followings are parts of my code:

// Definition of the array
public columnsConfig: Array<ColumnConfig>;

where ColumnConfig is a class of all the instances included in the array.

// Constructor of the component
this.columnsConfig = new Array<ColumnConfig>();

// Function that builds the array to iterate
for(var columnName in _headers) {
  let config = new ColumnConfig(columnName, _headers[columnName]);`
   this.columnsConfig.push(config);`
}

Template:

What am I missing here?


问:
R: stratify by 2 factor variables in ggplot
```<code>library(ggplot2)
iris$Sepal.Length2 <- ifelse(iris$Sepal.Length < 5, 1, 0)
iris$Sepal.Width2 <- ifelse(iris$Sepal.Width < 3, 1, 0)

SmallLength <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Length2 == 1],
                         status = "Small Length")
LargeLength <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Length2 == 0],
                         status = "Large Length")
SmallWidth <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Width2 == 1],
                         status = "Small Width")
LargeWidth <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Width2 == 0],
                         status = "Large Width")

Length <- rbind(SmallLength, LargeLength)
Width <- rbind(SmallWidth, LargeWidth)
ggplot(Length, aes(Petal.Length, fill = status)) + geom_density(alpha = 0.2) + labs(x = "Petal Length")
</code>```

I have a continuous variable, Petal.Length, and I would like to stratify it by Sepal.Length, and Sepal.Width, both of which I have coded as binary variables. In the above plot, I stratified Petal.Length by Sepal.Length only. How can I further stratify it by Sepal.Width? The resulting plot should perhaps have 4 colors I think...1 for Petal.Length that have small length and small width, 1 for small length and large width, 1 for large length and small width, and 1 for large length and large width.

答:
There's no need to create separate dataframes for this, you can achieve everything you need using the full iris dataset:

```<code>iris$length_binary <- ifelse(iris$Sepal.Length < 5, "Small", "Large")
iris$width_binary <- ifelse(iris$Sepal.Width < 3, "Small", "Large")
iris$length_width = interaction(iris$length_binary, iris$width_binary, sep=", ")

ggplot(iris, aes(Petal.Length, fill = length_width)) +
    geom_density(alpha = 0.2) +
    labs(x = "Petal Length",
         fill = "Length, Width")
</code>```

Result:

Body:
library(ggplot2)
iris$Sepal.Length2 <- ifelse(iris$Sepal.Length < 5, 1, 0)
iris$Sepal.Width2 <- ifelse(iris$Sepal.Width < 3, 1, 0)

SmallLength <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Length2 == 1],
                         status = "Small Length")
LargeLength <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Length2 == 0],
                         status = "Large Length")
SmallWidth <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Width2 == 1],
                         status = "Small Width")
LargeWidth <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Width2 == 0],
                         status = "Large Width")

Length <- rbind(SmallLength, LargeLength)
Width <- rbind(SmallWidth, LargeWidth)
ggplot(Length, aes(Petal.Length, fill = status)) + geom_density(alpha = 0.2) + labs(x = "Petal Length")

I have a continuous variable, Petal.Length, and I would like to stratify it by Sepal.Length, and Sepal.Width, both of which I have coded as binary variables. In the above plot, I stratified Petal.Length by Sepal.Length only. How can I further stratify it by Sepal.Width? The resulting plot should perhaps have 4 colors I think...1 for Petal.Length that have small length and small width, 1 for small length and large width, 1 for large length and small width, and 1 for large length and large width.

Body:
There's no need to create separate dataframes for this, you can achieve everything you need using the full iris dataset:

iris$length_binary <- ifelse(iris$Sepal.Length < 5, "Small", "Large")
iris$width_binary <- ifelse(iris$Sepal.Width < 3, "Small", "Large")
iris$length_width = interaction(iris$length_binary, iris$width_binary, sep=", ")

ggplot(iris, aes(Petal.Length, fill = length_width)) +
    geom_density(alpha = 0.2) +
    labs(x = "Petal Length",
         fill = "Length, Width")

Result:


问:
python saving xlsx as csv date saves as date time
I need to read an xlsx, format the date from dd-mm-yy to yyyy-mm-dd and then save as csv for the inport to sqllite

I have everything working but when it saves as csv it converts the date to date time, e.g. 2016-11-29 becomes 2016-11-29 00:00:00. How can I have the csv be formatted to only date?

```<code>import win32com.client
from win32com.client import constants

import openpyxl
import csv
import pandas as pd
import sqlite3

f = r"Services.xlsx"

exc = win32com.client.gencache.EnsureDispatch("Excel.Application")
exc.Visible = 0
exc.Workbooks.Open(Filename=f)
exc.Rows("1:1").Select()
exc.Selection.Delete(Shift=constants.xlUp)
exc.Range("K:M").Select()
exc.Selection.NumberFormat = "yyyy-mm-dd"

exc.ActiveWorkbook.Save()
exc.Quit()

data_xls = pd.read_excel('c:\Data\Programs\Cashflow\Database\Services.xlsx', 'Sheet', index_col=None)
data_xls.to_csv('c:\Data\Programs\Cashflow\Database\Services.csv', encoding='utf-8')
</code>```

答:
The answer from Sangbok Lee worked but I ran into issues with null entries for my date column. I was able to solve with the following try except</p>

```<code>try:
    data_xls["Final Report Date"] = data_xls["Final Report Date"].datetime.strptime(data_xls["Final Report Date"], '%d-%m-%Y')
except:
    pd.NaT
</code>```

Body:
I need to read an xlsx, format the date from dd-mm-yy to yyyy-mm-dd and then save as csv for the inport to sqllite

I have everything working but when it saves as csv it converts the date to date time, e.g. 2016-11-29 becomes 2016-11-29 00:00:00. How can I have the csv be formatted to only date?

import win32com.client
from win32com.client import constants

import openpyxl
import csv
import pandas as pd
import sqlite3

f = r"Services.xlsx"

exc = win32com.client.gencache.EnsureDispatch("Excel.Application")
exc.Visible = 0
exc.Workbooks.Open(Filename=f)
exc.Rows("1:1").Select()
exc.Selection.Delete(Shift=constants.xlUp)
exc.Range("K:M").Select()
exc.Selection.NumberFormat = "yyyy-mm-dd"

exc.ActiveWorkbook.Save()
exc.Quit()

data_xls = pd.read_excel('c:\Data\Programs\Cashflow\Database\Services.xlsx', 'Sheet', index_col=None)
data_xls.to_csv('c:\Data\Programs\Cashflow\Database\Services.csv', encoding='utf-8')

Body:
The answer from Sangbok Lee worked but I ran into issues with null entries for my date column. I was able to solve with the following try except

try:
    data_xls["Final Report Date"] = data_xls["Final Report Date"].datetime.strptime(data_xls["Final Report Date"], '%d-%m-%Y')
except:
    pd.NaT


答:
I think you should add (last < first) to your condition to be:</p>

```<code>if (first-last==0 && last < first){
   System.out.println("no error yet");
}
</code>```

Title: simple recursive merge sort Stack java.lang.StackOverflowError

Body:
I think you should add (last < first) to your condition to be:

if (first-last==0 && last < first){
   System.out.println("no error yet");
}


答:
Here is an example using pipes - using your data as is you would need to rbind the length and weight data.frames.</p>

```<code>library(tidyverse)
iris %>%
   mutate(statusl = factor(ifelse(Sepal.Length<5,'Small length', 'Large length')),
          statusw = factor(ifelse(Sepal.Width<3,'Small width', 'Large width')))  %>%
   ggplot(aes(Petal.Length, fill=interaction(statusl, statusw))) +
         geom_density(alpha = 0.2) + xlab("Petal Length")
</code>```

Title: R: stratify by 2 factor variables in ggplot

Body:
Here is an example using pipes - using your data as is you would need to rbind the length and weight data.frames.

library(tidyverse)
iris %>%
   mutate(statusl = factor(ifelse(Sepal.Length<5,'Small length', 'Large length')),
          statusw = factor(ifelse(Sepal.Width<3,'Small width', 'Large width')))  %>%
   ggplot(aes(Petal.Length, fill=interaction(statusl, statusw))) +
         geom_density(alpha = 0.2) + xlab("Petal Length")


问:
How to use both binary and continuous features in the k-Nearest-Neighbor algorithm?
My feature vector has both continuous (or widely ranging) and binary components.  If I simply use Euclidean distance, the continuous components will have a much greater impact:

Representing symmetric vs. asymmetric as 0 and 1 and some less important ratio ranging from 0 to 100, changing from symmetric to asymmetric has a tiny distance impact compared to changing the ratio by 25.

I can add more weight to the symmetry (by making it 0 or 100 for example), but is there a better way to do this?

答:
If i correctly understand your question, normalizing (aka 'rescaling) each dimension or column in the data set is the conventional technique for dealing with over-weighting dimensions, e.g.,

```<code>ev_scaled = (ev_raw - ev_min) / (ev_max - ev_min)
</code>```

In R, for instance, you can write this function:

```<code>ev_scaled = function(x) {
    (x - min(x)) / (max(x) - min(x))
}
</code>```

which works like this:

```<code># generate some data:
# v1, v2 are two expectation variables in the same dataset
# but have very different 'scale':
> v1 = seq(100, 550, 50)
> v1
  [1] 100 150 200 250 300 350 400 450 500 550
> v2 = sort(sample(seq(.1, 20, .1), 10))
> v2
  [1]  0.2  3.5  5.1  5.6  8.0  8.3  9.9 11.3 15.5 19.4
> mean(v1)
  [1] 325
> mean(v2)
  [1] 8.68

# now normalize v1 & v2 using the function above:
> v1_scaled = ev_scaled(v1)
> v1_scaled
  [1] 0.000 0.111 0.222 0.333 0.444 0.556 0.667 0.778 0.889 1.000
> v2_scaled = ev_scaled(v2)
> v2_scaled
  [1] 0.000 0.172 0.255 0.281 0.406 0.422 0.505 0.578 0.797 1.000
> mean(v1_scaled)
  [1] 0.5
> mean(v2_scaled)
  [1] 0.442
> range(v1_scaled)
  [1] 0 1
> range(v2_scaled)
  [1] 0 1
</code>```

Body:
If i correctly understand your question, normalizing (aka 'rescaling) each dimension or column in the data set is the conventional technique for dealing with over-weighting dimensions, e.g.,

ev_scaled = (ev_raw - ev_min) / (ev_max - ev_min)

In R, for instance, you can write this function:

ev_scaled = function(x) {
    (x - min(x)) / (max(x) - min(x))
}

which works like this:

# generate some data:
# v1, v2 are two expectation variables in the same dataset
# but have very different 'scale':
> v1 = seq(100, 550, 50)
> v1
  [1] 100 150 200 250 300 350 400 450 500 550
> v2 = sort(sample(seq(.1, 20, .1), 10))
> v2
  [1]  0.2  3.5  5.1  5.6  8.0  8.3  9.9 11.3 15.5 19.4
> mean(v1)
  [1] 325
> mean(v2)
  [1] 8.68

# now normalize v1 & v2 using the function above:
> v1_scaled = ev_scaled(v1)
> v1_scaled
  [1] 0.000 0.111 0.222 0.333 0.444 0.556 0.667 0.778 0.889 1.000
> v2_scaled = ev_scaled(v2)
> v2_scaled
  [1] 0.000 0.172 0.255 0.281 0.406 0.422 0.505 0.578 0.797 1.000
> mean(v1_scaled)
  [1] 0.5
> mean(v2_scaled)
  [1] 0.442
> range(v1_scaled)
  [1] 0 1
> range(v2_scaled)
  [1] 0 1


问:
AlchemyData News History Longer than 60 days?
I'm using the AlchemyData News Demo, and in the demo I can choose dates between today and three months ago,

Do we have in the full version the ability to Search articles older than three months? If not, is there a way to load articles that I choose and use AlchemyData News ?

答:
AlchemyData News was deprecated in favor of the new Discovery service. With Discovery, you can use the news dataset as with AlchemyData News and you can also ingest your own documents.

If you want to learn more about the service, take a look at the API Reference. It describes the different endpoints and has some code snippets based on the Watson SDKs.

You can also play with the Discovery demo, it will give you information about a company based on the news dataset.

And finally, take a look at the migration guide if you want to transition from AlchemyData News to the Discovery service.


答:
zip will take a splatted list/tuple, so you can use a comprehension to get a sum of any size:

```<code>lol = [ [1,2,3],
        [4,5,6],
        [7,8,9],
        ]

s = [sum(a) for a in zip(*lol)]
print(s)
</code>```

prints:

```<code>[12, 15, 18]
</code>```

Title: Is there a way to trivially sum identical indices of a 2D-list into a 1D-list?

Body:
Say I have a list of lists

[[1, 2, 3], [4, 5, 6]]

And I want to transform this such that the individual indices are summed and I get:

[5, 7, 9]

Is there an easy combination of list comprehensions, zip(), sum() and so on for me to get this result without writing a clutter of for loops and accumulators?

Body:
zip will take a splatted list/tuple, so you can use a comprehension to get a sum of any size:

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

s = [sum(a) for a in zip(*lol)]
print(s)

prints:

[12, 15, 18]


问:
How to configure Azure load balancer NAT rules for multiple VMs?
Here is what I am trying to achieve:

I created two Linux VMs in same virtual network (same subnet)

These two VMs don't any public IP address. For security, I don't want to have any public IP associated with them.

However, I need ssh into those VMs. Since, they just have private IP and not public IP addresses, I am setting up a load balancer with public IP.

Now I am using inbound NAT rules to redirect SSH traffic to those VMs.

When I add first NAT rules, it gives me a choice to choose VM to where I want to redirect the traffic to. So all is good so far.

However, when I try to add one more NAT rule, portal UI doesn't provide me any option to choose other VM. It adds the rule against the same VM.

Is there anything am I missing? Is it supposed to work differently? I also tried add multiple virtual machines to backend pool. That also doesn't let me add more than one VM.

Should I put two VMs in VM Scaleset or Availability set?

答:
In Azure, we can use Load balancer with a single standalone VM, also we can use Load Balancer with multiple VMs in an availability set.

If you want to use Load Balancer NAT to multiple VMs, we should re-create VMs in same availability set.

In Azure Resource Module, we can delete VMs and keep the VHD, then use PowerShell to create VMs in the same availability set.  (Re-create)


问:
How to create popup windows in html
I want to know how the pop up windows integrated into websites are built. I am trying to create one for my websites but i don't really know it is created whether they are plugins or not. Any help as to how to go about it.
Below is an example of what i want to do.

答: You can use hotjar.com to put a feedback box in your page, there is a lot of services that provides this feature, but hotjar gets the job done

Title: How to create popup windows in html


问:
sql create random table function
So I am new to SQL and this is actually my very first project..
What I am trying to do is to create a fanction that returns a table with random numbers. I am using pgAdmin 4 IDE

This is the code:

```<code>CREATE OR REPLACE FUNCTION create_amka(n integer)
RETURNS TABLE(amka integer) AS
$$
BEGIN
 return query

  select cast(random()*100 as integer)
  ORDER BY random() LIMIT n;

END;
$$
LANGUAGE 'plpgsql' IMMUTABLE;
</code>```

So the fanction has an input (n integer) and is supposed to return a table with n random numbers. But it only returns 1 number. Is the "LIMIT n" the problem? Is there a better way to create such a fanction?
Thanks in advance

答:
If you want to return n numbers, you an use generate_series():

```<code>select cast(random()*100 as integer)
from generate_series(1, n);
</code>```

There is no need to order them.  They are already random.

Title: sql create random table function

Body:
So I am new to SQL and this is actually my very first project..
What I am trying to do is to create a fanction that returns a table with random numbers. I am using pgAdmin 4 IDE

This is the code:

CREATE OR REPLACE FUNCTION create_amka(n integer)
RETURNS TABLE(amka integer) AS
$$
BEGIN
 return query

  select cast(random()*100 as integer)
  ORDER BY random() LIMIT n;

END;
$$
LANGUAGE 'plpgsql' IMMUTABLE;

So the fanction has an input (n integer) and is supposed to return a table with n random numbers. But it only returns 1 number. Is the "LIMIT n" the problem? Is there a better way to create such a fanction?
Thanks in advance

Body:
If you want to return n numbers, you an use generate_series():

select cast(random()*100 as integer)
from generate_series(1, n);

There is no need to order them.  They are already random.


问:
Delete m2m through field from admin panel
I searched and could not find a way to do this. Here's my situation:

I have 3 classes:

Publication

Person

AuthorOrder

The last is a through class that allows me to specify the author order for a publication, as this does not normally seem possible to do.

Initially, I made Author a mandatory field (blank=False) for Publication and added a placeholder Person object to add Publications to that don't have a proper author. However, a better solution seems to be to just handle missing authors in Views appropriately. Now, I've changed the field to be optional, but I cannot seem to set the authors to empty via the admin panel. It gives me a "This field is required." error. My guess is that this is because the Person is required of the through class, but setting the Person to null/empty in the admin panel does not set the through object to null/empty.

I found a workaround. One can delete the placeholder Person object. This unsets the through class from the Publications without deleting them via cascade as they are no longer mandatory. However, this is not always a good workaround, so I hope there's a better method.

models.py

There is a lot of code, I reproduce only the minimal necessary:

```<code>#Publication
class Publication(models.Model):
    authors = models.ManyToManyField(Person, blank=True, related_name="author_of", through='AuthorOrder')

#Person
class Person(models.Model):
    # mandatory
    firstname = models.CharField(max_length=200)

# AuthorOrder
class AuthorOrder(models.Model):
    publication = models.ForeignKey(Publication)
    author = models.ForeignKey(Person)
</code>```

admin.py

```<code># AuthorInline
class AuthorInline(admin.StackedInline):
    model = AuthorOrder
    extra = 3

# Publication
class PublicationAdmin(admin.ModelAdmin):
    list_display = ("title", 'issue', "keywords")
    search_fields = ['title', "keywords"]
    list_filter = ['issue']

    # author list via Inline
    inlines = [AuthorInline]

admin.site.register(Publication, PublicationAdmin)
</code>```

答: It's simple. To the very right of the "Author order: AuthorOrder object" line, there is a small "Delete" box. Check it and save. It's small and somewhat oddly placed, so easily gets missed.</p>

Body:
I searched and could not find a way to do this. Here's my situation:

I have 3 classes:

Publication

Person

AuthorOrder

The last is a through class that allows me to specify the author order for a publication, as this does not normally seem possible to do.

Initially, I made Author a mandatory field (blank=False) for Publication and added a placeholder Person object to add Publications to that don't have a proper author. However, a better solution seems to be to just handle missing authors in Views appropriately. Now, I've changed the field to be optional, but I cannot seem to set the authors to empty via the admin panel. It gives me a "This field is required." error. My guess is that this is because the Person is required of the through class, but setting the Person to null/empty in the admin panel does not set the through object to null/empty.

I found a workaround. One can delete the placeholder Person object. This unsets the through class from the Publications without deleting them via cascade as they are no longer mandatory. However, this is not always a good workaround, so I hope there's a better method.

models.py

There is a lot of code, I reproduce only the minimal necessary:

#Publication
class Publication(models.Model):
    authors = models.ManyToManyField(Person, blank=True, related_name="author_of", through='AuthorOrder')

#Person
class Person(models.Model):
    # mandatory
    firstname = models.CharField(max_length=200)

# AuthorOrder
class AuthorOrder(models.Model):
    publication = models.ForeignKey(Publication)
    author = models.ForeignKey(Person)

admin.py

# AuthorInline
class AuthorInline(admin.StackedInline):
    model = AuthorOrder
    extra = 3

# Publication
class PublicationAdmin(admin.ModelAdmin):
    list_display = ("title", 'issue', "keywords")
    search_fields = ['title', "keywords"]
    list_filter = ['issue']

    # author list via Inline
    inlines = [AuthorInline]

admin.site.register(Publication, PublicationAdmin)


问:
Go Tour Exercise #7: Binary Trees equivalence
I am trying to solve equivalent binary trees exercise on go tour. Here is what I did;

```<code>package main

import "tour/tree"
import "fmt"

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    if t.Left != nil {
        Walk(t.Left, ch)
    }
    ch <- t.Value
    if t.Right != nil {
        Walk(t.Right, ch)
    }

}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
    ch1 := make(chan int)
    ch2 := make(chan int)
    go Walk(t1, ch1)
    go Walk(t2, ch2)
    for k := range ch1 {
        select {
        case g := <-ch2:
            if k != g {
                return false
            }
        default:
            break
        }
    }
    return true
}

func main() {
    fmt.Println(Same(tree.New(1), tree.New(1)))
    fmt.Println(Same(tree.New(1), tree.New(2)))
}
</code>```

However, I couldn't find out how to signal if any no more elements left in trees. I can't use close(ch) on Walk() because it makes the channel close before all values are sent (because of recursion.) Can anyone lend me a hand here?

答:
For whoever interested, if you wonder how to solve this without creating a separate recursive function, here is an answer using a stack:</p>

```<code>func Walk(t *tree.Tree, ch chan int) {
    defer close(ch)
    visitStack := []*tree.Tree{t}
    visited := make(map[*tree.Tree]bool, 1)
    for len(visitStack) > 0 {
        var n *tree.Tree
        n, visitStack = visitStack[len(visitStack)-1], visitStack[:len(visitStack)-1]
        if visited[n] {
            ch <- n.Value
            continue
        }
        if n.Right != nil {
            visitStack = append(visitStack, n.Right)
        }
        visitStack = append(visitStack, n)
        if n.Left != nil {
            visitStack = append(visitStack, n.Left)
        }
        visited[n] = true
    }
}
</code>```

Body:
I am trying to solve equivalent binary trees exercise on go tour. Here is what I did;

package main

import "tour/tree"
import "fmt"

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    if t.Left != nil {
        Walk(t.Left, ch)
    }
    ch <- t.Value
    if t.Right != nil {
        Walk(t.Right, ch)
    }

}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
    ch1 := make(chan int)
    ch2 := make(chan int)
    go Walk(t1, ch1)
    go Walk(t2, ch2)
    for k := range ch1 {
        select {
        case g := <-ch2:
            if k != g {
                return false
            }
        default:
            break
        }
    }
    return true
}

func main() {
    fmt.Println(Same(tree.New(1), tree.New(1)))
    fmt.Println(Same(tree.New(1), tree.New(2)))
}

However, I couldn't find out how to signal if any no more elements left in trees. I can't use close(ch) on Walk() because it makes the channel close before all values are sent (because of recursion.) Can anyone lend me a hand here?

Body:
For whoever interested, if you wonder how to solve this without creating a separate recursive function, here is an answer using a stack:

func Walk(t *tree.Tree, ch chan int) {
    defer close(ch)
    visitStack := []*tree.Tree{t}
    visited := make(map[*tree.Tree]bool, 1)
    for len(visitStack) > 0 {
        var n *tree.Tree
        n, visitStack = visitStack[len(visitStack)-1], visitStack[:len(visitStack)-1]
        if visited[n] {
            ch <- n.Value
            continue
        }
        if n.Right != nil {
            visitStack = append(visitStack, n.Right)
        }
        visitStack = append(visitStack, n)
        if n.Left != nil {
            visitStack = append(visitStack, n.Left)
        }
        visited[n] = true
    }
}


问:
Cannot Set Getters and Setters in Swift
I have created a custom class and I want to add associated getters and setters. I have read the official documentation from Apple and notice that when setting a getter and setter, you actually create a separate variable, which seems really confusing. For instance, in the documentation linked above, getters and setters are applied to a new variable called perimeter to obtain values from another variable called sidelength. Below is my code:

答:
Getters and setters like you are implementing them are only used for computed variables in Swift. A variable with a getter and setter doesn't actually store anything, but does something when assigned or used for its value with other variables. When appropriate to use, the usage would be more like this.

```<code>var _key: String?

var key: String? {
    get {
        return _key
    }
    set {
        _key = newValue
    }
}
</code>```

You would rarely if ever use this on an identical data type though. I use these for communication with CoreData often, and setting things like dates as a string or back to a date. Occasionally I might use it to handle the change in an optional to a non optional.

Getters and setters are not needed in order to use the variable in Swift though. If you are used to languages with them, I can understand the confusion here, but forget the correlation and start over with how you think about it. I am sure after a short amount of time, you will like the way Swift works with its datatypes!

Edit:

In order to do what you want, all you need is this:

```<code>class PollCell: UICollectionViewCell {
    var key: String?
}
</code>```

Now you can assign any value you want to cell.key and retrieve any value you want from cell.key.

Title: Cannot Set Getters and Setters in Swift

Body:
Getters and setters like you are implementing them are only used for computed variables in Swift. A variable with a getter and setter doesn't actually store anything, but does something when assigned or used for its value with other variables. When appropriate to use, the usage would be more like this.

var _key: String?

var key: String? {
    get {
        return _key
    }
    set {
        _key = newValue
    }
}

You would rarely if ever use this on an identical data type though. I use these for communication with CoreData often, and setting things like dates as a string or back to a date. Occasionally I might use it to handle the change in an optional to a non optional.

Getters and setters are not needed in order to use the variable in Swift though. If you are used to languages with them, I can understand the confusion here, but forget the correlation and start over with how you think about it. I am sure after a short amount of time, you will like the way Swift works with its datatypes!

Edit:

In order to do what you want, all you need is this:

class PollCell: UICollectionViewCell {
    var key: String?
}

Now you can assign any value you want to cell.key and retrieve any value you want from cell.key.


问:
float object over an image using CSS?
Is it possible to float an object over an image using css? I want to place a form over an image (that isn't a background). Float doesn't work, but is there some variable that does provide this function?

When you float an object it pushes the text to either side of the object. What I am looking for is something that will not do this, that will just float without regard to what is underneath it.

答:
Try z-index property</p>

```<code><html>
<head>
<style type="text/css">
img
{
position:absolute;
left:0px;
top:0px;
z-index:-1;
}
</style>
</head>

<body>
<h1>This is a heading</h1>
<img src="w3css.gif" width="100" height="140" />
<p>Because the image has a z-index of -1, it will be placed behind the text.</p>
</body>
</html>
</code>```

Title: float object over an image using CSS?

Body:
Try z-index property

<html>
<head>
<style type="text/css">
img
{
position:absolute;
left:0px;
top:0px;
z-index:-1;
}
</style>
</head>

<body>
<h1>This is a heading</h1>
<img src="w3css.gif" width="100" height="140" />
<p>Because the image has a z-index of -1, it will be placed behind the text.</p>
</body>
</html>


问:
Python Random Number File Writer
This is what I have so far. It worked until I added the functions. I need to have two functions in the code and I don't know how to make this work correctly and have tried several different ways. The code needs to write X amount of random numbers to a text file.</p>

```<code>import random

random_numbers = open('ran_numbers.txt', 'w')

def main():

    getRandom()
    writeFunction()

def getRandom():
    qty_numbers = int(input('How many random numbers should be written to the file? '))

    for count in range (qty_numbers):
        number = random.randint(1,500)

def writeFunction():
    random_numbers.write(str(number)+ '\n')
    random_numbers.close()
    print('Your list of random numbers have been written to the file named')
    print('ran_numbers.txt')

main()
</code>```

答:
Change this:

```<code>random_numbers = open('ran_numbers.txt', 'w')

def main():

    getRandom()
    writeFunction()

def getRandom():
    qty_numbers = int(input('How many random numbers should be written to the file? '))

    for count in range (qty_numbers):
        number = random.randint(1,500)
</code>```

To this:

```<code>random_numbers = open('ran_numbers.txt', 'w')

def main():

    getRandom()

def getRandom():
    qty_numbers = int(input('How many random numbers should be written to the file? '))

    for count in range (qty_numbers):
        number = random.randint(1,500)
        writeFunction(number)
</code>```

Because, numbers is a local variable for the getRandom() function, so either directly write to the file in that function itself or return the number in the main function and pass it to writeFunction()

```<code>def main():
    number= getRandom()
    writeFunction(number)
</code>```

What you do is your choice, but defining number in one block isn't going to work.

Title: Python Random Number File Writer

Body:
This is what I have so far. It worked until I added the functions. I need to have two functions in the code and I don't know how to make this work correctly and have tried several different ways. The code needs to write X amount of random numbers to a text file.

import random

random_numbers = open('ran_numbers.txt', 'w')

def main():

    getRandom()
    writeFunction()

def getRandom():
    qty_numbers = int(input('How many random numbers should be written to the file? '))

    for count in range (qty_numbers):
        number = random.randint(1,500)

def writeFunction():
    random_numbers.write(str(number)+ '\n')
    random_numbers.close()
    print('Your list of random numbers have been written to the file named')
    print('ran_numbers.txt')

main()

Body:
Change this:

random_numbers = open('ran_numbers.txt', 'w')

def main():

    getRandom()
    writeFunction()

def getRandom():
    qty_numbers = int(input('How many random numbers should be written to the file? '))

    for count in range (qty_numbers):
        number = random.randint(1,500)

To this:

random_numbers = open('ran_numbers.txt', 'w')

def main():

    getRandom()

def getRandom():
    qty_numbers = int(input('How many random numbers should be written to the file? '))

    for count in range (qty_numbers):
        number = random.randint(1,500)
        writeFunction(number)

Because, numbers is a local variable for the getRandom() function, so either directly write to the file in that function itself or return the number in the main function and pass it to writeFunction()

def main():
    number= getRandom()
    writeFunction(number)

What you do is your choice, but defining number in one block isn't going to work.


问:
No Operator error code
I am completing a hotel reservation form using C++ language. I keep getting no operator error for fin !=0. How can I address this error? Here is the actual coding...</p>

```<code>void Hotel::show_room_record()
{
    cout << "R.Num" << setw(10) << "R.Stat" << setw(10) << "Category" << setw(10) << "Rent\n";
    ifstream fin("room.dat", ios::in);
    for (int p = 0; fin != 0; p = p + 15)
    {
        fin.seekg(p);
        fin >> room_no;
        fin >> room_status;
        fin >> category;
        fin >> rent;
        cout << room_no << setw(10) << room_status << setw(10) << category << setw(10) << rent << "\n";
    }
    fin.close();
}
</code>```

答:
You cannot test fin != 0. fin isn't a number, to testing for equality with 0 makes about as much sense as testing what kind of orange an apple is. You can test that fin is still readable though with a simple fin by taking advantage of operator bool, but that's tricky because the test for is readable will be made before reading. You can't test for failure before you have a chance to fail and that leaves open the possibility that the last reads failed and were not checked for validity.

Instead of trying to fix this, I'm going to go all X-Y on you here and suggest something completely different.

Define a structure

```<code>struct room
{
    int room_no;
    string room_status;
    string category;
    int rent; // could be a float. Don't care much for this example
              // that said, watch out for rounding errors when dealing with floats
};
</code>```

Create a function that makes it really easy to read into this structure

```<code>std::istream & operator>>(std::istream & in,
                          room & inroom)
{
    in >> inroom.room_no >> inroom.room_status >> inroom.category >> inroom.rent;
    return in;
}
</code>```

Create a function that makes it really easy to write this structure

```<code>std::ostream & operator<<(std::ostream & out,
                          const room & outroom)
{
    out << outroom.room_no << setw(10) << outroom.room_status <<
           setw(10) << outroom.category << setw(10) << outroom.rent;
    return out;
}
</code>```

Make a std::vector of the above structure a member of the Hotel class

```<code>std::vector<room> rooms;
</code>```

Read the file into it

```<code>room temp;
while (in >> temp)
{
    rooms.push_back(temp);
}
</code>```

Now the hotel knows the status of all the rooms without having to keep looking at the file. This makes printing easy.

```<code>for(room & r: rooms)
{
    cout << r << '\n';
}
</code>```

It makes finding any room a simple traversal of rooms

```<code>for(room & r: rooms)
{
    if (r.whatever == desiredwhatever)
    {
        return r;
    }
}
</code>```

and every now and then you rewrite the file if a room was changed.

```<code>std::ostream outfile("path to file goes here");
for(room & r: rooms)
{
    if (!(outfile << r << '\n'))
    {
        //handle error
    }
}
</code>```

All of these things you probably have to do anyway. The only downside is if you are not allowed to use std::vector. In that case you either write a simple vector substitute or use an array and pray it never overflows.

Title: No Operator error code

Body:
I am completing a hotel reservation form using C++ language. I keep getting no operator error for fin !=0. How can I address this error? Here is the actual coding...

void Hotel::show_room_record()
{
    cout << "R.Num" << setw(10) << "R.Stat" << setw(10) << "Category" << setw(10) << "Rent\n";
    ifstream fin("room.dat", ios::in);
    for (int p = 0; fin != 0; p = p + 15)
    {
        fin.seekg(p);
        fin >> room_no;
        fin >> room_status;
        fin >> category;
        fin >> rent;
        cout << room_no << setw(10) << room_status << setw(10) << category << setw(10) << rent << "\n";
    }
    fin.close();
}

Body:
You cannot test fin != 0. fin isn't a number, to testing for equality with 0 makes about as much sense as testing what kind of orange an apple is. You can test that fin is still readable though with a simple fin by taking advantage of operator bool, but that's tricky because the test for is readable will be made before reading. You can't test for failure before you have a chance to fail and that leaves open the possibility that the last reads failed and were not checked for validity.

Instead of trying to fix this, I'm going to go all X-Y on you here and suggest something completely different.

Define a structure

struct room
{
    int room_no;
    string room_status;
    string category;
    int rent; // could be a float. Don't care much for this example
              // that said, watch out for rounding errors when dealing with floats
};

Create a function that makes it really easy to read into this structure

std::istream & operator>>(std::istream & in,
                          room & inroom)
{
    in >> inroom.room_no >> inroom.room_status >> inroom.category >> inroom.rent;
    return in;
}

Create a function that makes it really easy to write this structure

std::ostream & operator<<(std::ostream & out,
                          const room & outroom)
{
    out << outroom.room_no << setw(10) << outroom.room_status <<
           setw(10) << outroom.category << setw(10) << outroom.rent;
    return out;
}

Make a std::vector of the above structure a member of the Hotel class

std::vector<room> rooms;

Read the file into it

room temp;
while (in >> temp)
{
    rooms.push_back(temp);
}

Now the hotel knows the status of all the rooms without having to keep looking at the file. This makes printing easy.

for(room & r: rooms)
{
    cout << r << '\n';
}

It makes finding any room a simple traversal of rooms

for(room & r: rooms)
{
    if (r.whatever == desiredwhatever)
    {
        return r;
    }
}

and every now and then you rewrite the file if a room was changed.

std::ostream outfile("path to file goes here");
for(room & r: rooms)
{
    if (!(outfile << r << '\n'))
    {
        //handle error
    }
}

All of these things you probably have to do anyway. The only downside is if you are not allowed to use std::vector. In that case you either write a simple vector substitute or use an array and pray it never overflows.


问:
How to dynamicaly resize a button on stage in as2.0
I have a button on stage in a movie, the button ("clicker") is empty apart from the "hit" frame. The stage and button are 300x300 and i'm using swfobject to display the flash movie at 400x600 pixels. I have the following actionscript...

Stage.showMenu = false;
Stage.scaleMode = "noScale";
Stage.align = "TL";

clicker._x = 0;
clicker._y = 0;

clicker.onRelease = function() {
 trace("onMouseDown called");
 getURL(link_url, "_blank");
};

I want teh button to expand to fill the available stage space (which is 400x600 in this example) so i use the following...

clicker._width = Stage.width;
clicker._height = Stage.height;

however this causes the button to disapear from the stage, possibly down to 0x0 in size, as opposed to filling the available stage space. It's been a while since i worked with actionscript so it's probably something obvious, however i can't seem to spot what the problem is. Any suggestions would be greatly appreciated?

答:
You need to add an event listener to the Stage:

var stageListener:Object = new Object();

stageListener.onResize = function() {
  clicker._width = Stage.width;
  clicker._height = Stage.height;
};

Stage.addListener(stageListener);


问:
How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'
I'm using Bootstrap V4 and the following error is logged in the console;

Error: Bootstrap tooltips require Tether
  (http://github.hubspot.com/tether/)

I have tried to remove the error by installing Tether but it hasn't worked. I have 'installed' Tether by including the following lines of code;

```<code><link rel="stylesheet" href="http://www.atlasestateagents.co.uk/css/tether.min.css">
<script src="http://www.atlasestateagents.co.uk/javascript/tether.min.js"></script>
</code>```

Have I 'installed' tether correctly?

Can anyone help me remove this error?

If you wish to view the error on my site, please click here and load your console.

答:
I had the same problem and this is how I solved it.
I'm on rails 5.1.0rc1

Make sure to add require jquery and tether inside your application.js file they must be at the very top like this

```<code>//= require jquery
//= require tether
</code>```

Just make sure to have tether installed

Body:
I'm using Bootstrap V4 and the following error is logged in the console;

Error: Bootstrap tooltips require Tether
  (http://github.hubspot.com/tether/)

I have tried to remove the error by installing Tether but it hasn't worked. I have 'installed' Tether by including the following lines of code;

<link rel="stylesheet" href="http://www.atlasestateagents.co.uk/css/tether.min.css">

Have I 'installed' tether correctly?

Can anyone help me remove this error?

If you wish to view the error on my site, please click here and load your console.

Body:
I had the same problem and this is how I solved it.
I'm on rails 5.1.0rc1

Make sure to add require jquery and tether inside your application.js file they must be at the very top like this

//= require jquery
//= require tether

Just make sure to have tether installed


问:
Is it possible to use CONCAT_WS add separator only if value not empty
Let say I have this table

```<code>id  a       b
1   data    1234
2   data
</code>```

I want to concat with separator (but) if no data, don't add the separator.

If I do

```<code>UPDATE `table` SET `b` = CONCAT_WS(',',`b`,'newData') WHERE `id` = '1'
</code>```

I get the expected 1234,newData in b

but I I do

```<code>UPDATE `table` SET `b` = CONCAT_WS(',',`b`,'newData') WHERE `id` = '2'
</code>```

I get ,newData in b (( but I want only newData without the separator )).

IS there a way to do this ?

答:
You can try this one Mate:

```<code># [A] sample result set for checking
SELECT
    `a`, `b`,
    IF(
        (`a` IS NOT NULL AND `a` != '')
        AND (`b` IS NOT NULL AND `b` != ''),
        CONCAT_WS(',', `a`, `b`),
        REPLACE(CONCAT_WS(',', `a`, `b`), ',', '')
    ) `result`
FROM `table`
WHERE `id` IN (1, 2);
</code>```

If the result set in [A] satisfied what you need, you can proceed with the script using [B]

The Update query:

```<code># [B] process query for the new values
UPDATE `table`
SET `b` = IF(
    (`a` IS NOT NULL AND `a` != '')
    AND (`b` IS NOT NULL AND `b` != ''),
    CONCAT_WS(',', `a`, `b`),
    REPLACE(CONCAT_WS(',', `a`, `b`), ',', '')
)
WHERE `id` IN (1, 2);
</code>```

Hope I can help, cheers!

Body:
Let say I have this table

id  a       b
1   data    1234
2   data

I want to concat with separator (but) if no data, don't add the separator.

If I do

UPDATE `table` SET `b` = CONCAT_WS(',',`b`,'newData') WHERE `id` = '1'

I get the expected 1234,newData in b

but I I do

UPDATE `table` SET `b` = CONCAT_WS(',',`b`,'newData') WHERE `id` = '2'

I get ,newData in b (( but I want only newData without the separator )).

IS there a way to do this ?

Body:
You can try this one Mate:

# [A] sample result set for checking
SELECT
    `a`, `b`,
    IF(
        (`a` IS NOT NULL AND `a` != '')
        AND (`b` IS NOT NULL AND `b` != ''),
        CONCAT_WS(',', `a`, `b`),
        REPLACE(CONCAT_WS(',', `a`, `b`), ',', '')
    ) `result`
FROM `table`
WHERE `id` IN (1, 2);

If the result set in [A] satisfied what you need, you can proceed with the script using [B]

The Update query:

# [B] process query for the new values
UPDATE `table`
SET `b` = IF(
    (`a` IS NOT NULL AND `a` != '')
    AND (`b` IS NOT NULL AND `b` != ''),
    CONCAT_WS(',', `a`, `b`),
    REPLACE(CONCAT_WS(',', `a`, `b`), ',', '')
)
WHERE `id` IN (1, 2);

Hope I can help, cheers!


答:
You never call the writeFunction() after creating the random number

Just change:

```<code>for count in range (qty_numbers):
    number = random.randint(1,500)
</code>```

to this:

```<code>for count in range (qty_numbers):
    number = random.randint(1,500)
    writeFunction(number)
</code>```

and change the line:

```<code>def writeFunction():
</code>```

to:

```<code>def writeFunction(number):
</code>```

and finally change your main() to:

```<code>def main():

    getRandom()
    random_numbers.close()
</code>```

and remove

```<code>random_numbers.close()
</code>```

from the writeFunction()

I hope this helps you.

Title: Python Random Number File Writer

Body:
You never call the writeFunction() after creating the random number

Just change:

for count in range (qty_numbers):
    number = random.randint(1,500)

to this:

for count in range (qty_numbers):
    number = random.randint(1,500)
    writeFunction(number)

and change the line:

def writeFunction():

to:

def writeFunction(number):

and finally change your main() to:

def main():

    getRandom()
    random_numbers.close()

and remove

random_numbers.close()

from the writeFunction()

I hope this helps you.


问:
When/Where to call self.update_from_feed_continuously?
Just a quick question. After watching RailsCasts ep #168 and coming across the following code:

```<code>class FeedEntry < ActiveRecord::Base
  def self.update_from_feed(feed_url)
    feed = Feedzirra::Feed.fetch_and_parse(feed_url)
    add_entries(feed.entries)
  end

  def self.update_from_feed_continuously(feed_url, delay_interval = 15.minutes)
    feed = Feedzirra::Feed.fetch_and_parse(feed_url)
    add_entries(feed.entries)
    loop do
      sleep delay_interval
      feed = Feedzirra::Feed.update(feed)
      add_entries(feed.new_entries) if feed.updated?
    end
  end

  private

  def self.add_entries(entries)
    entries.each do |entry|
      unless exists? :guid => entry.id
        create!(
          :name         => entry.title,
          :summary      => entry.summary,
          :url          => entry.url,
          :published_at => entry.published,
          :guid         => entry.id
        )
      end
    end
  end
end
</code>```

I'm asking myself where/when should I call the method self.update_from_feed_continuously(blah, blah)? Is it going to be in my Feed Controller, or a View (ie Index, show, etc..)

Any help is much appreciated. This question has been bugging me for a while...

答:
It is just a method to fetch feeds from the input url continuously.

It can be called at anywhere, it depended on the situation.

When you submit the feed url through controller, then call the method in controller.

When you decide that the feed task should be run regularly, then it can be called by a rake task through whenever, https://github.com/javan/whenever

Body:
Just a quick question. After watching RailsCasts ep #168 and coming across the following code:

class FeedEntry < ActiveRecord::Base
  def self.update_from_feed(feed_url)
    feed = Feedzirra::Feed.fetch_and_parse(feed_url)
    add_entries(feed.entries)
  end

  def self.update_from_feed_continuously(feed_url, delay_interval = 15.minutes)
    feed = Feedzirra::Feed.fetch_and_parse(feed_url)
    add_entries(feed.entries)
    loop do
      sleep delay_interval
      feed = Feedzirra::Feed.update(feed)
      add_entries(feed.new_entries) if feed.updated?
    end
  end

  private

  def self.add_entries(entries)
    entries.each do |entry|
      unless exists? :guid => entry.id
        create!(
          :name         => entry.title,
          :summary      => entry.summary,
          :url          => entry.url,
          :published_at => entry.published,
          :guid         => entry.id
        )
      end
    end
  end
end

I'm asking myself where/when should I call the method self.update_from_feed_continuously(blah, blah)? Is it going to be in my Feed Controller, or a View (ie Index, show, etc..)

Any help is much appreciated. This question has been bugging me for a while...


问:
How to reformat axis labels?
I've begun learning D3, and many tutorials are written for v3. I read through a lot of v4's documentation, but I can't wrap my mind around how to format my axis labels. Right now I have a visualization that looks like this:

The months overlapping is not ideal. I know I can use d3's timeFormat and use "%b" to use an abbreviated month. But I'm not sure how syntactically it fits in. My code for the bottom axis is:

```<code>svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x)
    .ticks(d3.timeMonth.every(4)));
</code>```

I would've expected it to be something like

```<code>format = d3.time.format("%b")
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x)
    .ticks(format(d3.timeMonth.every(4))));
</code>```

But that doesn't work. I know this is probably very simple, but I'm not getting it.

答:
You should use tickFormat instead of ticks:

```<code>.tickFormat(d3.timeFormat("%b"))
</code>```

Here is a demo:

var svg = d3.select("svg")
var scale = d3.scaleTime()
  .range([20, 480])
  .domain([new Date(), new Date().setYear(new Date().getFullYear() + 1)]);

var axis = d3.axisBottom(scale)
  .tickFormat(d3.timeFormat("%b"))
  .ticks(d3.timeMonth);

svg.append("g")
  .attr("transform", "translate(0,50)")
  .call(axis)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="500"></svg></code>```

EDIT: For showing the year instead of January:

var svg = d3.select("svg")
var scale = d3.scaleTime()
  .range([20, 480])
  .domain([new Date(), new Date().setYear(new Date().getFullYear() + 1)]);

var axis = d3.axisBottom(scale)
  .tickFormat(function(d) {
    return d3.timeFormat("%b")(d) === "Jan" ?
      d3.timeFormat("%Y")(d) : d3.timeFormat("%b")(d);
  })
  .ticks(d3.timeMonth);

svg.append("g")
  .attr("transform", "translate(0,50)")
  .call(axis)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="500"></svg></code>```

Title: How to reformat axis labels?

Body:
I've begun learning D3, and many tutorials are written for v3. I read through a lot of v4's documentation, but I can't wrap my mind around how to format my axis labels. Right now I have a visualization that looks like this:

The months overlapping is not ideal. I know I can use d3's timeFormat and use "%b" to use an abbreviated month. But I'm not sure how syntactically it fits in. My code for the bottom axis is:

svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x)
    .ticks(d3.timeMonth.every(4)));

I would've expected it to be something like

format = d3.time.format("%b")
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x)
    .ticks(format(d3.timeMonth.every(4))));

But that doesn't work. I know this is probably very simple, but I'm not getting it.

Body:
You should use tickFormat instead of ticks:

.tickFormat(d3.timeFormat("%b"))

Here is a demo:

var svg = d3.select("svg")
var scale = d3.scaleTime()
  .range([20, 480])
  .domain([new Date(), new Date().setYear(new Date().getFullYear() + 1)]);

var axis = d3.axisBottom(scale)
  .tickFormat(d3.timeFormat("%b"))
  .ticks(d3.timeMonth);

svg.append("g")
  .attr("transform", "translate(0,50)")
  .call(axis)

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="500"></svg>

EDIT: For showing the year instead of January:

var svg = d3.select("svg")
var scale = d3.scaleTime()
  .range([20, 480])
  .domain([new Date(), new Date().setYear(new Date().getFullYear() + 1)]);

var axis = d3.axisBottom(scale)
  .tickFormat(function(d) {
    return d3.timeFormat("%b")(d) === "Jan" ?
      d3.timeFormat("%Y")(d) : d3.timeFormat("%b")(d);
  })
  .ticks(d3.timeMonth);

svg.append("g")
  .attr("transform", "translate(0,50)")
  .call(axis)

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="500"></svg>


问:
Drupal: rogrammatically change file system path
Is there a way to change the files directory path, using a function from the drupal api?

Thanks in advance,

—Albe

答:
EDIT: Failed initial reading comprehension. Answer:

```<code>variable_set('file_directory_path', 'path/to/files');
</code>```

Drupal uses conf_path() . '/files' as the default fallback value.

Answers to Related Questions

To change the location of the files directory itself, check out the File System configuration page at admin/settings/file-system. You can change the path of the files directory to any Drupal-writable path on your server.

If you mean, how do you change the path to which files are saved within the files directory, that depends on what you are using to do file uploads.

Upload module: The Uploadpath module mentioned by @vilepickle looks good.

Filefield module: It already allows the path to be configured by global and user tokens in a similar way to uploadpath, and configurable by the node information where you upload the file by Filefield Paths.

If you are using IMCE or one of the assortment of graphical file managing modules, this is answered on a per module basis.

Body:
EDIT: Failed initial reading comprehension. Answer:

variable_set('file_directory_path', 'path/to/files');

Drupal uses conf_path() . '/files' as the default fallback value.

Answers to Related Questions

To change the location of the files directory itself, check out the File System configuration page at admin/settings/file-system. You can change the path of the files directory to any Drupal-writable path on your server.

If you mean, how do you change the path to which files are saved within the files directory, that depends on what you are using to do file uploads.

Upload module: The Uploadpath module mentioned by @vilepickle looks good.

Filefield module: It already allows the path to be configured by global and user tokens in a similar way to uploadpath, and configurable by the node information where you upload the file by Filefield Paths.

If you are using IMCE or one of the assortment of graphical file managing modules, this is answered on a per module basis.


问:
Convert key value pairs with duplicate keys into a Counter
I've got this in Python 2.7

```<code>l = [('a', 1), ('a', 2), ('b', 3), ('b', 4)]
</code>```

How do I get a Counter c where:

```<code>c = Counter({'a': 3, 'b': 7 }]
</code>```

I would prefer to use comprehension if possible or the fastest possible way to do this.

答:
Just iterate and add, Counter takes care of this automatically!

```<code>In [5]: l = [('a', 1), ('a', 2), ('b', 3), ('b', 4)]
    ...:

In [6]: c = Counter()

In [7]: for k, v in l:
    ...:     c[k] += v
    ...:

In [8]: c
Out[8]: Counter({'a': 3, 'b': 7})
</code>```

This is how Counter is designed to be used.

Body:
I've got this in Python 2.7

l = [('a', 1), ('a', 2), ('b', 3), ('b', 4)]

How do I get a Counter c where:

c = Counter({'a': 3, 'b': 7 }]

I would prefer to use comprehension if possible or the fastest possible way to do this.

Body:
Just iterate and add, Counter takes care of this automatically!

In [5]: l = [('a', 1), ('a', 2), ('b', 3), ('b', 4)]
    ...:

In [6]: c = Counter()

In [7]: for k, v in l:
    ...:     c[k] += v
    ...:

In [8]: c
Out[8]: Counter({'a': 3, 'b': 7})

This is how Counter is designed to be used.