问:
Initializing React number input control with blank value?
I'd like my controlled input to initialize with no value in the box.
The input is a number, so I don't pass in an empty ''.
Using defaultProps, I initialize the input with a null.

When typing into the input the console reports this message:

<MyInput> is changing an uncontrolled input of type number to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa).

To prevent this normally I initialize with an empty string to prevent this "switching" from happening. But with a number (I don't want to show a 0, I want nothing to show) I am not sure how to do it.

```<code>static defaultProps = {
    estimatedHours: null,
    estimatedMinutes: null,
  }
</code>```

defalut values ^^

```<code><input
   type="number"
   onChange={(e) => this.handleChange('Hours', e.target.value)}
   onKeyDown={this.handleKeyDown}
   onPaste={this.handlePaste}
   value={estimatedHours}
   placeholder={hoursText}
   className="slds-input th-trailmix-textbox th-time-component__input"
/>
</code>```

答:
Uncontrolled inputs are simply inputs where you aren't tying value to JavaScript. So if you are rendering:

```<code><input value={any} />
</code>```

That is a controlled input.

If you want to render an uncontrolled input with an empty value you could simply write

```<code><input type="number" /> or <input type="number" placeholder="" />
or <input type="number" placeholder="please enter a number..." />
</code>```

Next, if you want to pull the value use a ref.

```<code>state = {
  query: ''
}

handleSubmit = (e) => {
  e.preventDefault()
  this.setState({ query: this.search.value })
}

render() {
  return (
    <form>
      <input
        type="number"
        ref={input => this.search = input}
        placeholder=""
      />
      <button type="submit" onClick={this.handleSubmit}>Submit</button>
    </form>
  )
}
</code>```

Additionally, you can still perform logic on the return value if you need to. ie:

```<code>handleSubmit = (e) => {
  e.preventDefault()
  this.setState({ query: this.search.value.toExponential(2) })
   // square whatever the user inputs and store in this.state.query
}
</code>```

Body:
I'd like my controlled input to initialize with no value in the box.
The input is a number, so I don't pass in an empty ''.
Using defaultProps, I initialize the input with a null.

When typing into the input the console reports this message:

<MyInput> is changing an uncontrolled input of type number to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa).

To prevent this normally I initialize with an empty string to prevent this "switching" from happening. But with a number (I don't want to show a 0, I want nothing to show) I am not sure how to do it.

static defaultProps = {
    estimatedHours: null,
    estimatedMinutes: null,
  }

defalut values ^^

<input
   type="number"
   onChange={(e) => this.handleChange('Hours', e.target.value)}
   onKeyDown={this.handleKeyDown}
   onPaste={this.handlePaste}
   value={estimatedHours}
   placeholder={hoursText}
   className="slds-input th-trailmix-textbox th-time-component__input"
/>

Body:
Uncontrolled inputs are simply inputs where you aren't tying value to JavaScript. So if you are rendering:

<input value={any} />

That is a controlled input.

If you want to render an uncontrolled input with an empty value you could simply write

<input type="number" /> or <input type="number" placeholder="" />
or <input type="number" placeholder="please enter a number..." />

Next, if you want to pull the value use a ref.

state = {
  query: ''
}

handleSubmit = (e) => {
  e.preventDefault()
  this.setState({ query: this.search.value })
}

render() {
  return (
    <form>
      <input
        type="number"
        ref={input => this.search = input}
        placeholder=""
      />
      <button type="submit" onClick={this.handleSubmit}>Submit</button>
    </form>
  )
}

Additionally, you can still perform logic on the return value if you need to. ie:

handleSubmit = (e) => {
  e.preventDefault()
  this.setState({ query: this.search.value.toExponential(2) })
   // square whatever the user inputs and store in this.state.query
}


来源: stackexchange

问:
Can't Read Updated ASP.NET Textbox on Submit
I have an ASP.NET webform that populates textboxes from a database. The user then changes values in the forms (i.e. password) and pressed the submit button to update his account information. The problem here is that when data is changed in the textboxes, the method below doesn't read the changed values but only sees the original values. I'm not sure why Textbox_field.Text wouldn't retrieve the current values of the control.

What am I doing wrong here? I've tried using IsPostback but didn't have any success with it.

Thanks.

```<code>protected void Button_Save_Click (object sender, EventArgs e)
{
        using (SqlConnection conn = new SqlConnection (_connectionString))
        {
            conn.Open ();

            string firstName = TextBox_FirstName.Text;
            string lastName = TextBox_LastName.Text;
            string email = TextBox_Email.Text;
            string login = TextBox_Username.Text;
            string password = TextBox_Password.Text;
            int userID = Convert.ToInt32 (Session ["UserID"]);

            string sql = "update Auth_Users"
                       + $"    set FirstName='{firstName}', LastName='{lastName}', Email='{email}', Login='{login}', Password='{password}'"
                       + $" where ID={userID}";

            using (SqlCommand command = new SqlCommand (sql, conn))
            {
                 command.ExecuteNonQuery ();
            }

            conn.Close ();
      }
}
</code>```

答:
```<code>string sql = "update Auth_Users set FirstName=@FirstNAme, LastName=@LastName"
                       + " where ID=@UserId";

using (SqlCommand command = new SqlCommand (sql, conn))
            {
                 command.parameters.AddWithValue("@FirstName", FirstName)
                 command.parameters.AddWithValue("@LastName", LastName)
                 command.parameters.AddWithValue("@UserId", userID)
                 command.ExecuteNonQuery ();
            }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an ASP.NET webform that populates textboxes from a database. The user then changes values in the forms (i.e. password) and pressed the submit button to update his account information. The problem here is that when data is changed in the textboxes, the method below doesn't read the changed values but only sees the original values. I'm not sure why Textbox_field.Text wouldn't retrieve the current values of the control.

What am I doing wrong here? I've tried using IsPostback but didn't have any success with it.

Thanks.

protected void Button_Save_Click (object sender, EventArgs e)
{
        using (SqlConnection conn = new SqlConnection (_connectionString))
        {
            conn.Open ();

            string firstName = TextBox_FirstName.Text;
            string lastName = TextBox_LastName.Text;
            string email = TextBox_Email.Text;
            string login = TextBox_Username.Text;
            string password = TextBox_Password.Text;
            int userID = Convert.ToInt32 (Session ["UserID"]);

            string sql = "update Auth_Users"
                       + $"    set FirstName='{firstName}', LastName='{lastName}', Email='{email}', Login='{login}', Password='{password}'"
                       + $" where ID={userID}";

            using (SqlCommand command = new SqlCommand (sql, conn))
            {
                 command.ExecuteNonQuery ();
            }

            conn.Close ();
      }
}


问:
Linker yells that my function from other file is not defined
I have a function int get_token(); defined in file scanner.c and I have a declaration of it in header file scanner.h. Now I included this header file in another header called precedence.h and at last I included precedence.h in precedence.c file where I want to call my function get_token();.

When I call this function, calling make throws following error:

```<code>gcc precedence.c t_stack.c -o expr
/tmp/ccNgwuFu.o: In function `main':
precedence.c:(.text+0x730): undefined reference to `get_token'
collect2: error: ld returned 1 exit status
Makefile:8: recipe for target 'expr' failed
make: *** [expr] Error 1
</code>```

and this is my Makefile

```<code>CC=gcc
CFILES=precedence.c t_stack.c
HFILES=precedence.h t_stack.h token.h error.h

all: expr

expr: $(CFILES) $(HFILES)
    $(CC) $(CFILES) -o $@
</code>```

I have tried including scanner.h along with precedence.h, also changing Makefile.

I'm just little experienced with C programming.

答:
The linker fails to address function get_token because it seems to be defined in a file scanner.c, which is not passed to the compiler. Your include files probably just declare this function (i.e. provide a function prototype without body/implementation).

You'd probably write:

```<code>gcc precedence.c t_stack.c scanner.c -o expr
</code>```

Body:
I have a function int get_token(); defined in file scanner.c and I have a declaration of it in header file scanner.h. Now I included this header file in another header called precedence.h and at last I included precedence.h in precedence.c file where I want to call my function get_token();.

When I call this function, calling make throws following error:

gcc precedence.c t_stack.c -o expr
/tmp/ccNgwuFu.o: In function `main':
precedence.c:(.text+0x730): undefined reference to `get_token'
collect2: error: ld returned 1 exit status
Makefile:8: recipe for target 'expr' failed
make: *** [expr] Error 1

and this is my Makefile

CC=gcc
CFILES=precedence.c t_stack.c
HFILES=precedence.h t_stack.h token.h error.h

all: expr

expr: $(CFILES) $(HFILES)
    $(CC) $(CFILES) -o $@

I have tried including scanner.h along with precedence.h, also changing Makefile.

I'm just little experienced with C programming.

Body:
The linker fails to address function get_token because it seems to be defined in a file scanner.c, which is not passed to the compiler. Your include files probably just declare this function (i.e. provide a function prototype without body/implementation).

You'd probably write:

gcc precedence.c t_stack.c scanner.c -o expr


问:
how to customize an element-wise function on tensor in tensorflow?
Say, I have a tensor, it might contain positive and negative values:

```<code>[ 1, -1, 2, -2 ]
</code>```

Now, I want to apply log(x) for positive values, and a constant -10 for negative values:

```<code>[ log(1), -10, log(2), -10 ]
</code>```

In another word, I want to have a function like numpy.vectorize. Is this possible in tensorflow?

One possible way is to use a non-learnable variable, but I don't know if it can properly do back propagation.

答:
tf.map_fn() enables you to map an arbitrary TensorFlow subcomputation across the elements of a vector (or the slices of a higher-dimensional tensor). For example:

```<code>a = tf.constant([1.0, -1.0, 2.0, -2.0])

def f(elem):
  return tf.where(elem > 0, tf.log(elem), -10.0)

  # Alternatively, if the computation is more expensive than `tf.log()`, use
  # `tf.cond()` to ensure that only one branch is executed:
  # return tf.where(elem > 0, lambda: tf.log(elem), lambda: -10.0)

result = tf.map_fn(f, a)
</code>```

Body:
Say, I have a tensor, it might contain positive and negative values:

[ 1, -1, 2, -2 ]

Now, I want to apply log(x) for positive values, and a constant -10 for negative values:

[ log(1), -10, log(2), -10 ]

In another word, I want to have a function like numpy.vectorize. Is this possible in tensorflow?

One possible way is to use a non-learnable variable, but I don't know if it can properly do back propagation.

Body:
tf.map_fn() enables you to map an arbitrary TensorFlow subcomputation across the elements of a vector (or the slices of a higher-dimensional tensor). For example:

a = tf.constant([1.0, -1.0, 2.0, -2.0])

def f(elem):
  return tf.where(elem > 0, tf.log(elem), -10.0)

  # Alternatively, if the computation is more expensive than `tf.log()`, use
  # `tf.cond()` to ensure that only one branch is executed:
  # return tf.where(elem > 0, lambda: tf.log(elem), lambda: -10.0)

result = tf.map_fn(f, a)


问:
toString(): for debugging or for humans?
```<code>class Address
{
  private enum Component
  {
    NUMBER,
    STREET,
    STATE,
    COUNTRY
  }

  private Map<Component, String> componentToValue = ...;
}
</code>```

I'd like my class to contain two methods:

One to indicate the value of each address component (so I can debug if anything goes wrong).

One to return the address in a form expected by humans: "1600 Amphitheatre Parkway Mountain View, CA 94043".

What is the best-practice for Object.toString()? Is it primary meant for #1 or #2? Is there a best-practice for the naming of these methods?

答:
ToString should generally only be used for debug information.  Keep in mind that you're overriding a method on Object; is it conceptually accurate to have a method call on an Object reference return a human readable address?  In some cases, depending on the project, this may actually make sense, but it sounds a bit odd to me.  I would implement a new method.

Another thing to note is that most modern IDEs use the ToString method to print debug information about objects when inspecting them.

ContentLicense: CC BY-SA 2.5

Body:
class Address
{
  private enum Component
  {
    NUMBER,
    STREET,
    STATE,
    COUNTRY
  }

  private Map<Component, String> componentToValue = ...;
}

I'd like my class to contain two methods:

One to indicate the value of each address component (so I can debug if anything goes wrong).

One to return the address in a form expected by humans: "1600 Amphitheatre Parkway Mountain View, CA 94043".

What is the best-practice for Object.toString()? Is it primary meant for #1 or #2? Is there a best-practice for the naming of these methods?


问:
Python convert image array(20,20) to array(400)
Using Python 2.7 and Numpy.

I have a B/W image stored in array(20,20) and I would like to convert it to an array(400). How can this be done in Python if I have many images, that is array(x,20,20)?

Thanks a lot!

EDIT: Thanks a lot. I got the problem wrong at the beginning, thus I was not able to figure out this simple piece of code.

答:
You can use np.ravel to get a 1D view of the array if possible; otherwise a copy is returned.  See the linked documentation for the definition of 'if possible'.

```<code>a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.ravel())
# [1 2 3 4 5 6]
</code>```

Body:
You can use np.ravel to get a 1D view of the array if possible; otherwise a copy is returned.  See the linked documentation for the definition of 'if possible'.

a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.ravel())
# [1 2 3 4 5 6]


问:
Why Log4j2 is taking an extra of 11 Milli seconds to write into the file?
I am new to Log4j2. I have written a simple program that actually logs data into RollingRandomAccessFile using log4j2. Below is the program:

```<code>public class Log4j2Example {

/**
 * @param args the command line arguments
 */
public static Logger mlogger = null;

public static void main(String[] args) throws InterruptedException {

    mlogger = LogManager.getLogger("Messages-log");
    int i = 0;
    while (true) {
        String str = "Hello" + i;
        System.out.println(str);
        mlogger.info(str);
        i++;
        Thread.sleep(20);
    }
}
}
</code>```

My log4j2.xml file

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
  <Appenders>
     <RollingRandomAccessFile name="Messages-log" fileName="Log4J/Messages-${date:yyyy-MM-dd}.log"
               immediateflush="true" filePattern="Log4J/Messages-%d{MM-dd-yyyy-HH}-%i.log.gz">
      <PatternLayout>
        <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %p %m%n</Pattern>
      </PatternLayout>
      <Policies>
        <TimeBasedTriggeringPolicy />
        <SizeBasedTriggeringPolicy size="500 MB"/>
      </Policies>
      <DefaultRolloverStrategy max="50"/>
    </RollingRandomAccessFile>
  </Appenders>
  <Loggers>
    <Logger name="Messages-log" level="info" additivity="false">
        <appender-ref ref="Messages-log" level="info"/>
      </Logger>
    <root level="info">
        <appender-ref ref="Messages-log"/>
    </root>
</Loggers>
</Configuration>
</code>```

I am writing a simple statement into the log file sleeping for 20 milli-seconds for every record. Now the time stamp in the file should be for example:
If the first statement is logged at 17:20:32:354 then the next statement should be logged at 17:20:32:374 but it is logging at 17:20:32:384. An extra of 11 milli-seconds constantly is added for every record. Below is my log file output

```<code>2017-12-04 17:40:42.205 INFO Hello11
2017-12-04 17:40:42.236 INFO Hello12
2017-12-04 17:40:42.268 INFO Hello13
2017-12-04 17:40:42.299 INFO Hello14
2017-12-04 17:40:42.330 INFO Hello15
2017-12-04 17:40:42.361 INFO Hello16
2017-12-04 17:40:42.393 INFO Hello17
2017-12-04 17:40:42.424 INFO Hello18
</code>```

You can see that first statement is logged at .205 milli second and the second statement is logged at .236 milli second. Infact I am sleeping the thread for 20 milliseconds so the correct timestamp should be .226 milli second. What am I doing wrong here? I need the exact time stamp to be written as it is very important in production. I have also tried this with log4j 1 but the same result. I have synchronized my System time with Internet time also. And one thing I found it worked perfectly with 5 and 15 milli-seconds of sleep but from 20 milli seconds this is causing a big issue.

答:
I don’t think that this is caused by logging. You can verify this by changing your test code to the below (to exclude the logging) and see if you are getting similar results:

```<code>   public static void main(String[] args) throws InterruptedException {
       SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS");
       int i = 0;
       while (true) {
           System.out.println(format.format(new Date()) + " Hello " + i);
           i++;
           Thread.sleep(20);
       }
   }
</code>```

As Ralph pointed out in Log4j2-2141, it is likely that you are running into the granularity of the Windows scheduler. See WinAPI Sleep() function call sleeps for longer than expected and https://forum.sysinternals.com/bug-in-waitable-timers_topic16229.html.

Body:
I am new to Log4j2. I have written a simple program that actually logs data into RollingRandomAccessFile using log4j2. Below is the program:

public class Log4j2Example {

/**
 * @param args the command line arguments
 */
public static Logger mlogger = null;

public static void main(String[] args) throws InterruptedException {

    mlogger = LogManager.getLogger("Messages-log");
    int i = 0;
    while (true) {
        String str = "Hello" + i;
        System.out.println(str);
        mlogger.info(str);
        i++;
        Thread.sleep(20);
    }
}
}

My log4j2.xml file

    <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
  <Appenders>
     <RollingRandomAccessFile name="Messages-log" fileName="Log4J/Messages-${date:yyyy-MM-dd}.log"
               immediateflush="true" filePattern="Log4J/Messages-%d{MM-dd-yyyy-HH}-%i.log.gz">
      <PatternLayout>
        <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %p %m%n</Pattern>
      </PatternLayout>
      <Policies>
        <TimeBasedTriggeringPolicy />
        <SizeBasedTriggeringPolicy size="500 MB"/>
      </Policies>
      <DefaultRolloverStrategy max="50"/>
    </RollingRandomAccessFile>
  </Appenders>
  <Loggers>
    <Logger name="Messages-log" level="info" additivity="false">
        <appender-ref ref="Messages-log" level="info"/>
      </Logger>
    <root level="info">
        <appender-ref ref="Messages-log"/>
    </root>
</Loggers>
</Configuration>

I am writing a simple statement into the log file sleeping for 20 milli-seconds for every record. Now the time stamp in the file should be for example:
If the first statement is logged at 17:20:32:354 then the next statement should be logged at 17:20:32:374 but it is logging at 17:20:32:384. An extra of 11 milli-seconds constantly is added for every record. Below is my log file output

2017-12-04 17:40:42.205 INFO Hello11
2017-12-04 17:40:42.236 INFO Hello12
2017-12-04 17:40:42.268 INFO Hello13
2017-12-04 17:40:42.299 INFO Hello14
2017-12-04 17:40:42.330 INFO Hello15
2017-12-04 17:40:42.361 INFO Hello16
2017-12-04 17:40:42.393 INFO Hello17
2017-12-04 17:40:42.424 INFO Hello18

You can see that first statement is logged at .205 milli second and the second statement is logged at .236 milli second. Infact I am sleeping the thread for 20 milliseconds so the correct timestamp should be .226 milli second. What am I doing wrong here? I need the exact time stamp to be written as it is very important in production. I have also tried this with log4j 1 but the same result. I have synchronized my System time with Internet time also. And one thing I found it worked perfectly with 5 and 15 milli-seconds of sleep but from 20 milli seconds this is causing a big issue.

Body:
I don’t think that this is caused by logging. You can verify this by changing your test code to the below (to exclude the logging) and see if you are getting similar results:

   public static void main(String[] args) throws InterruptedException {
       SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS");
       int i = 0;
       while (true) {
           System.out.println(format.format(new Date()) + " Hello " + i);
           i++;
           Thread.sleep(20);
       }
   }

As Ralph pointed out in Log4j2-2141, it is likely that you are running into the granularity of the Windows scheduler. See WinAPI Sleep() function call sleeps for longer than expected and https://forum.sysinternals.com/bug-in-waitable-timers_topic16229.html.


问:
VSTS build agent failed to clean up folder
If anyone get this error "Unable to run "git clean -fdx" and "git reset --hard HEAD" successfully, delete source folder instead."</p>

答:
Go to your build machine.

Go to the build folder and trace what application is blocking the build folder.

Kill the application.
This occurred when you create a build and then cancel immediately.


问:
How to null N indices following a number in pandas?
I have a Series containing values and NaN's like so:

```<code>0    NaN
1    1.0
2    NaN
3    2.0
4    3.0
5    NaN
6    NaN
7    4.0
8    5.0
9    NaN
dtype: float64
</code>```

And say for example I'd like to null out the next four indices after each initial value, like so:

```<code>0    NaN
1    1.0
2    NaN
3    NaN
4    NaN
5    NaN
6    NaN
7    4.0
8    NaN
9    NaN
dtype: float64
</code>```

(The four directly after the first 1.0 are null'd, as well as the last two directly after the next value, 4.0.)

答:
Approach #1

Here's a loopy way that iterates only through the list of non-null positions -

```<code>def nullnext(s, W):
    a = s.values
    idx = np.flatnonzero(s.notnull().values)+1
    last_idx = idx[0]
    a[last_idx:last_idx+W] = np.nan
    for i in idx[1:]:
        if i > last_idx + W:
            last_idx = i
            a[last_idx:last_idx+W] = np.nan
    return s
</code>```

Sample run -

```<code>In [336]: s
Out[336]:
0    1.0
1    NaN
2    2.0
3    3.0
4    NaN
5    NaN
6    4.0
7    5.0
8    NaN
Name: NaN, dtype: float64

In [337]: nullnext(s, W=4)
Out[337]:
0    1.0
1    NaN
2    NaN
3    NaN
4    NaN
5    NaN
6    4.0
7    NaN
8    NaN
Name: NaN, dtype: float64
</code>```

Approach #2

With few tweaks, we can port this onto numba for performance efficiency. The implementation involves using strides. The relevant codes would look something like this -

```<code>from numba import njit

# https://stackoverflow.com/a/40085052/ @Divakar
def strided_app(a, L, S ):  # Window len = L, Stride len/stepsize = S
    nrows = ((a.size-L)//S)+1
    n = a.strides[0]
    return np.lib.stride_tricks.as_strided(a, shape=(nrows,L), strides=(S*n,n))

@njit
def set_mask(mask, idx, W):
    last_idx = idx[0]
    mask[0] = True
    l = len(idx)
    for i in range(1,l):
        if idx[i] > last_idx + W:
            last_idx = idx[i]
            mask[i] = True
    return mask

def nullnext_numba(s, W):
    a = s.values
    idx = np.flatnonzero(s.notnull().values)+1

    mask = np.zeros(len(idx),dtype=bool)
    set_mask(mask, idx, W)

    a_ext = np.concatenate((a, np.full(W,np.nan)))
    strided_app(a_ext, W, 1)[idx[mask]] = np.nan
    return pd.Series(a_ext[:-W])
</code>```

Further improvement

We could optimize it further to improve memory efficiency by avoiding the concatenation and do all those edits in-situ with the input series and hence improve performance as well, like so -

```<code>def nullnext_numba_v2(s, W):
    a = s.values
    idx = np.flatnonzero(s.notnull().values)+1

    mask = np.zeros(len(idx),dtype=bool)
    set_mask(mask, idx, W)

    valid_idx = idx[mask]
    limit_mask = valid_idx < len(a) - W
    strided_app(a, W, 1)[valid_idx[limit_mask]] = np.nan

    leftover_idx = valid_idx[~limit_mask]
    if len(leftover_idx)>0:
        a[leftover_idx[0]:] = np.nan
    return s
</code>```

Body:
I have a Series containing values and NaN's like so:

0    NaN
1    1.0
2    NaN
3    2.0
4    3.0
5    NaN
6    NaN
7    4.0
8    5.0
9    NaN
dtype: float64

And say for example I'd like to null out the next four indices after each initial value, like so:

0    NaN
1    1.0
2    NaN
3    NaN
4    NaN
5    NaN
6    NaN
7    4.0
8    NaN
9    NaN
dtype: float64

(The four directly after the first 1.0 are null'd, as well as the last two directly after the next value, 4.0.)

Body:
Approach #1

Here's a loopy way that iterates only through the list of non-null positions -

def nullnext(s, W):
    a = s.values
    idx = np.flatnonzero(s.notnull().values)+1
    last_idx = idx[0]
    a[last_idx:last_idx+W] = np.nan
    for i in idx[1:]:
        if i > last_idx + W:
            last_idx = i
            a[last_idx:last_idx+W] = np.nan
    return s

Sample run -

In [336]: s
Out[336]:
0    1.0
1    NaN
2    2.0
3    3.0
4    NaN
5    NaN
6    4.0
7    5.0
8    NaN
Name: NaN, dtype: float64

In [337]: nullnext(s, W=4)
Out[337]:
0    1.0
1    NaN
2    NaN
3    NaN
4    NaN
5    NaN
6    4.0
7    NaN
8    NaN
Name: NaN, dtype: float64

Approach #2

With few tweaks, we can port this onto numba for performance efficiency. The implementation involves using strides. The relevant codes would look something like this -

from numba import njit

# https://stackoverflow.com/a/40085052/ @Divakar
def strided_app(a, L, S ):  # Window len = L, Stride len/stepsize = S
    nrows = ((a.size-L)//S)+1
    n = a.strides[0]
    return np.lib.stride_tricks.as_strided(a, shape=(nrows,L), strides=(S*n,n))

@njit
def set_mask(mask, idx, W):
    last_idx = idx[0]
    mask[0] = True
    l = len(idx)
    for i in range(1,l):
        if idx[i] > last_idx + W:
            last_idx = idx[i]
            mask[i] = True
    return mask

def nullnext_numba(s, W):
    a = s.values
    idx = np.flatnonzero(s.notnull().values)+1

    mask = np.zeros(len(idx),dtype=bool)
    set_mask(mask, idx, W)

    a_ext = np.concatenate((a, np.full(W,np.nan)))
    strided_app(a_ext, W, 1)[idx[mask]] = np.nan
    return pd.Series(a_ext[:-W])

Further improvement

We could optimize it further to improve memory efficiency by avoiding the concatenation and do all those edits in-situ with the input series and hence improve performance as well, like so -

def nullnext_numba_v2(s, W):
    a = s.values
    idx = np.flatnonzero(s.notnull().values)+1

    mask = np.zeros(len(idx),dtype=bool)
    set_mask(mask, idx, W)

    valid_idx = idx[mask]
    limit_mask = valid_idx < len(a) - W
    strided_app(a, W, 1)[valid_idx[limit_mask]] = np.nan

    leftover_idx = valid_idx[~limit_mask]
    if len(leftover_idx)>0:
        a[leftover_idx[0]:] = np.nan
    return s


问:
How do I add Jwt authentication from IdentityServer4 and Auth0 in an ASP.NET Core 2.0 web api?
We have need to utilize JWT tokens coming from IdentityServer4 typically, but also from Auth0 for more complex SSO scenarios to authorize access to an asp.net core 2.0 web api.

This code snippet from Startup.cs ConfigureServices tries to register Authentication handlers for both Auth0 and IdentityServer4 processing, but obviously fails with an InvalidOperationException: "Scheme already exists: Bearer"

```<code>        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.Audience = Configuration["Auth0:ApiIdentifier"];
            options.Authority = $"https://{Configuration["Auth0:Domain"]}/";
        })
        .AddIdentityServerAuthentication(options =>
        {
            options.Authority = "http://localhost:5000";
            options.RequireHttpsMetadata = false;
            options.ApiName = "api1";
        });
</code>```

How can this best be accomplished, I assume involving some type of separate handling based on the issuer in the token?

答:
It turns out that as Muqeet Khan hinted above, the schemes must be named differently, as shown below.

```<code>    services.AddAuthentication()
    .AddJwtBearer("Auth0", options =>
    {
        options.Audience = Configuration["Auth0:ApiIdentifier"];
        options.Authority = $"https://{Configuration["Auth0:Domain"]}/";
    })
    .AddIdentityServerAuthentication("IdSrv", options =>
    {
        options.Authority = "http://localhost:5000";
        options.RequireHttpsMetadata = false;
        options.ApiName = "api1";
    });
</code>```

However, the default [Authorize] attribute only calls the default AuthenticationScheme.  Rather than specifying both schemes for every Authorization, I registered them globally as so:

```<code>    services.AddMvcCore()
      .AddAuthorization()
      .AddJsonFormatters()
      .AddMvcOptions(options =>
      {
        var policy = new AuthorizationPolicyBuilder("IdSrv", "Auth0")
          .RequireAuthenticatedUser()
          .Build();
        options.Filters.Add(new AuthorizeFilter(policy));
      });
</code>```

Body:
We have need to utilize JWT tokens coming from IdentityServer4 typically, but also from Auth0 for more complex SSO scenarios to authorize access to an asp.net core 2.0 web api.

This code snippet from Startup.cs ConfigureServices tries to register Authentication handlers for both Auth0 and IdentityServer4 processing, but obviously fails with an InvalidOperationException: "Scheme already exists: Bearer"

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.Audience = Configuration["Auth0:ApiIdentifier"];
            options.Authority = $"https://{Configuration["Auth0:Domain"]}/";
        })
        .AddIdentityServerAuthentication(options =>
        {
            options.Authority = "http://localhost:5000";
            options.RequireHttpsMetadata = false;
            options.ApiName = "api1";
        });

How can this best be accomplished, I assume involving some type of separate handling based on the issuer in the token?

Body:
It turns out that as Muqeet Khan hinted above, the schemes must be named differently, as shown below.

    services.AddAuthentication()
    .AddJwtBearer("Auth0", options =>
    {
        options.Audience = Configuration["Auth0:ApiIdentifier"];
        options.Authority = $"https://{Configuration["Auth0:Domain"]}/";
    })
    .AddIdentityServerAuthentication("IdSrv", options =>
    {
        options.Authority = "http://localhost:5000";
        options.RequireHttpsMetadata = false;
        options.ApiName = "api1";
    });

However, the default [Authorize] attribute only calls the default AuthenticationScheme.  Rather than specifying both schemes for every Authorization, I registered them globally as so:

    services.AddMvcCore()
      .AddAuthorization()
      .AddJsonFormatters()
      .AddMvcOptions(options =>
      {
        var policy = new AuthorizationPolicyBuilder("IdSrv", "Auth0")
          .RequireAuthenticatedUser()
          .Build();
        options.Filters.Add(new AuthorizeFilter(policy));
      });


问:
Are unit-test names important?
If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names?

ie

```<code>[Test]
public void ShouldValidateUserNameIsLessThan100Characters() {}
</code>```

verse

```<code>[Test]
public void UserNameTestValidation1() {}
</code>```

答: Yes, they are.  I'd personally recommend looking at SSW's rules to better unit tests.  It contains some very helpful naming guidelines.</p>

OwnerDisplayName: Xian

Title: Are unit-test names important?

Body:
If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names?

ie

[Test]
public void ShouldValidateUserNameIsLessThan100Characters() {}

verse

[Test]
public void UserNameTestValidation1() {}

OwnerDisplayName: VanOrman


问:
Twilio CallResource not posting on busy signal
I dial a number using CallResource.Create and specify To, From, Url and MachineDetection=Enable.  I get an event post to the Url I specify most of the time however if the call result is 'busy' (according to the Twilio Console logs), I do not get a post. I need to react no matter the call result, there are other processes in play that are left hanging if I don't get some event notification.

How do I guarantee I get a response; human, machine, busy, fail, etc. no matter the result consistently?

Update: This also happens when the result of a call is 'fail'. We just had that happen. I need to know if a call is answering machine or human (that works) or if the call ends for any other reason like 'busy' or 'fail' or whatever else is out there. How is this supposed to be done if not via the URL call back parameter when making a call?

答:
Twilio developer evangelist here.

When a call receives a "busy" signal or fails, the URL in the url parameter won't be called.

However, you can get this information by setting up a StatusCallback URL. This URL is used to send call progress events over the life of a call, and by default it will send a callback at the end of a call regardless of its outcome. This will breakdown to "completed" (a successful call), "busy", "no-answer", "failed" and "canceled" (call canceled via the REST API while still ringing).

Let me know if this helps.


问:
Selenium WD | Trying to use an 'If' statement with logical 'or'
I have a step in my test that goes into several html pages and looks for an element on the screen. That element can have 2 different CSS class names while looking the same in the website (visually speaking) , I have to use an if statement with a logical 'or' to identify them

```<code>if (Status == driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-2")) || Status == driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-1")));
System.out.println("Stock is closed");)
</code>```

I expected that if one of the 2 elements would appear, the Eclipse would

recognize it. Well - The second element out of the 2 appeared - and for some reason I've got an exception error. The if statement gave attention only to the first condition in the if, and ignored the second.

org.openqa.selenium.NoSuchElementException: no such element:

locate element: {"method":"css
  selector","selector":".inlineblock.redClockBigIcon.middle.isOpenExchBig-2"}Unable to

How can I make the || to work in this 'if' statement?
Thanks

Screenshots of the elements

答:
In your above logic, you have Status which is an already existing WebElement that you're comparing against another Webelement that you're looking up. I don't think this is what your intention was so I'm going to make some assumptions in a solution.

First: Find all of the elements that might exist with your desired selector (Note I'm using findElements instead of findElement)

```<code>List<WebElement> clockIconThingies = driver.findElements(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-2, .inlineblock.redClockBigIcon.middle.isOpenExchBig-1"));
</code>```

Second: Check if that found anything

```<code>if(clockIconThingies.size() > 0)
{
    System.out.println("Stock is closed");
}
</code>```

Alternatively for your css selector, from the image it looks like you might not need to do an or at all and just look for the class redClockBigIcon like this:

```<code>List<WebElement> clockIconThingies = driver.findElements(By.cssSelector(".redClockBigIcon"));
</code>```

Body:
I have a step in my test that goes into several html pages and looks for an element on the screen. That element can have 2 different CSS class names while looking the same in the website (visually speaking) , I have to use an if statement with a logical 'or' to identify them

if (Status == driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-2")) || Status == driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-1")));
System.out.println("Stock is closed");)

I expected that if one of the 2 elements would appear, the Eclipse would

recognize it. Well - The second element out of the 2 appeared - and for some reason I've got an exception error. The if statement gave attention only to the first condition in the if, and ignored the second.

org.openqa.selenium.NoSuchElementException: no such element:

locate element: {"method":"css
  selector","selector":".inlineblock.redClockBigIcon.middle.isOpenExchBig-2"}Unable to

How can I make the || to work in this 'if' statement?
Thanks

Screenshots of the elements

Body:
In your above logic, you have Status which is an already existing WebElement that you're comparing against another Webelement that you're looking up. I don't think this is what your intention was so I'm going to make some assumptions in a solution.

First: Find all of the elements that might exist with your desired selector (Note I'm using findElements instead of findElement)

List<WebElement> clockIconThingies = driver.findElements(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-2, .inlineblock.redClockBigIcon.middle.isOpenExchBig-1"));

Second: Check if that found anything

if(clockIconThingies.size() > 0)
{
    System.out.println("Stock is closed");
}

Alternatively for your css selector, from the image it looks like you might not need to do an or at all and just look for the class redClockBigIcon like this:

List<WebElement> clockIconThingies = driver.findElements(By.cssSelector(".redClockBigIcon"));


问:
Vba Loop to Edit Excel files fails on Second Iteration
I am trying to build a routine that opens each excel file in a folder, searches ( using the Find command) for the string
 “# Issues”, selects the entire row where it finds the string, then delete that row and the next two additional rows. It runs successfully the first iteration, but fails the second time through the loop st the Find command.

I have struggled with this failure on second iteration several times with different code, making me think I am making some kind of mistake in defining my objects.

My code:

Function CleanFilesInAGivenFolder(strFolder As String, _
         strCellLoc As String, _
         strNewValue As String)

Dim strReportType As String
Dim myfile
Dim mypath
Dim strPathFileName As String

If Right(strFolder, 1) <> "\" Then
   strFolder = strFolder & "\"
End If
mypath = strFolder
ChDir (strFolder)

myfile = Dir(mypath)
ChDir (mypath)
myfile = Dir("")

Do While myfile <> ""

        'Format the excel report
            strPathFileName = mypath & myfile

            Dim appExcel As Excel.Application
            Dim wkb As Excel.Workbook
            Dim sht As Worksheet
            Dim rng As Range
            Dim FoundCell As Range

          'Define the file and location
            strPathFileName = mypath & myfile

           'define the excel session
            Set appExcel = New Excel.Application
            appExcel.Visible = True

           'Define the workbook
            Set wkb = appExcel.Workbooks.Open(strPathFileName)
                          'Make sheet 1 the active sheet
                          Set wkb = ActiveWorkbook
           Set sht = ActiveSheet

           'Find the row with "# Issues" in column A,
           'delete row this next 2 rows
           'Only works the first iteration of loop

    With sht
         Set FoundCell = Selection.Find(What:="# Issues", _
         After:=[a1],
         LookIn:=xlValues, _
         LookAt:=xlPart, _
         SearchOrder:=xlByRows, _
         SearchDirection:=xlNext, _
         MatchCase:=False, _
         SearchFormat:=False)
         ActiveCell.EntireRow.Select
     End With

If Not FoundCell Is Nothing Then
    Selection.Delete Shift:=xlUp
    Selection.Delete Shift:=xlUp
    Selection.Delete Shift:=xlUp
End If
          'Clear Objects
            appExcel.DisplayAlerts = False
            wkb.Save
            wkb.Close
            appExcel.DisplayAlerts = True
            Set rng = Nothing
            Set sht = Nothing
            Set wkb = Nothing
            appExcel.Quit
            Set appExcel = Nothing

     myfile = Dir()

Loop
End Function
```

答:
Keeping in mind some of the comments from above:</p>

```<code>Sub CleanFilesInAGivenFolder(strFolder As String)
    Dim FoundCell As Range
    Dim myFile As String
    Dim wkb As Workbook
    If Right(strFolder, 1) <> "\" Then
        strFolder = strFolder & "\"
    End If
    myFile = Dir(strFolder & "*.xlsx")
    Do While myFile <> ""
        Set wkb = Workbooks.Open(myFile)
        Do
            With Worksheets(1)
                Set FoundCell = .Cells.Find(What:="# Issues", _
                    After:=Range("A1"), _
                    LookIn:=xlFormulas, _
                    LookAt:=xlPart, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlNext, _
                    MatchCase:=False, _
                    SearchFormat:=False)
            End With
            If Not FoundCell Is Nothing Then
                FoundCell.EntireRow.Resize(3).Delete
            Else
                Exit Do
            End If
        Loop
        wkb.Save
        wkb.Close
        myFile = Dir()
    Loop
End Sub
</code>```

Body:
Keeping in mind some of the comments from above:

Sub CleanFilesInAGivenFolder(strFolder As String)
    Dim FoundCell As Range
    Dim myFile As String
    Dim wkb As Workbook
    If Right(strFolder, 1) <> "\" Then
        strFolder = strFolder & "\"
    End If
    myFile = Dir(strFolder & "*.xlsx")
    Do While myFile <> ""
        Set wkb = Workbooks.Open(myFile)
        Do
            With Worksheets(1)
                Set FoundCell = .Cells.Find(What:="# Issues", _
                    After:=Range("A1"), _
                    LookIn:=xlFormulas, _
                    LookAt:=xlPart, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlNext, _
                    MatchCase:=False, _
                    SearchFormat:=False)
            End With
            If Not FoundCell Is Nothing Then
                FoundCell.EntireRow.Resize(3).Delete
            Else
                Exit Do
            End If
        Loop
        wkb.Save
        wkb.Close
        myFile = Dir()
    Loop
End Sub


问:
Prometheus: cannot export metrics from connected Kubernetes cluster
The issue: I have a Prometheus outside of Kubernetes cluster. So, I want to export metrics from remote cluster.

I took the config sample from Prometheus Github repo and modified this a little bit. So, here is my jobs config.

```<code>  - job_name: 'kubernetes-apiservers'

    scheme: http

    kubernetes_sd_configs:
    - role: endpoints
      api_server: http://cluster-manager.dev.example.net:8080

    bearer_token_file: /opt/prometheus/prometheus/kube_tokens/dev
    tls_config:
      insecure_skip_verify: true

    relabel_configs:
    - source_labels: [__meta_kubernetes_namespace, __meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name]
      action: keep
      regex: default;kubernetes;http

  - job_name: 'kubernetes-nodes'

    scheme: http

    kubernetes_sd_configs:
    - role: node
      api_server: http://cluster-manager.dev.example.net:8080

    bearer_token_file: /opt/prometheus/prometheus/kube_tokens/dev
    tls_config:
      insecure_skip_verify: true

    relabel_configs:
    - action: labelmap
      regex: __meta_kubernetes_node_label_(.+)

  - job_name: 'kubernetes-service-endpoints'

    scheme: http

    kubernetes_sd_configs:
    - role: endpoints
      api_server: http://cluster-manager.dev.example.net:8080

    bearer_token_file: /opt/prometheus/prometheus/kube_tokens/dev
    tls_config:
      insecure_skip_verify: true

    relabel_configs:
    - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scrape]
      action: keep
      regex: true
    - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scheme]
      action: replace
      target_label: __scheme__
      regex: (http?)
    - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_path]
      action: replace
      target_label: __metrics_path__
      regex: (.+)
    - source_labels: [__address__, __meta_kubernetes_service_annotation_prometheus_io_port]
      action: replace
      target_label: __address__
      regex: (.+)(?::\d+);(\d+)
      replacement: $1:$2
    - action: labelmap
      regex: __meta_kubernetes_service_label_(.+)
    - source_labels: [__meta_kubernetes_namespace]
      action: replace
      target_label: kubernetes_namespace
    - source_labels: [__meta_kubernetes_service_name]
      action: replace
      target_label: kubernetes_name

  - job_name: 'kubernetes-services'

    scheme: http

    metrics_path: /probe
    params:
      module: [http_2xx]

    kubernetes_sd_configs:
    - role: service
      api_server: http://cluster-manager.dev.example.net:8080

    bearer_token_file: /opt/prometheus/prometheus/kube_tokens/dev
    tls_config:
      insecure_skip_verify: true

    relabel_configs:
    - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_probe]
      action: keep
      regex: true
    - source_labels: [__address__]
      target_label: __param_target
    - target_label: __address__
      replacement: blackbox
    - source_labels: [__param_target]
      target_label: instance
    - action: labelmap
      regex: __meta_kubernetes_service_label_(.+)
    - source_labels: [__meta_kubernetes_service_namespace]
      target_label: kubernetes_namespace
    - source_labels: [__meta_kubernetes_service_name]
      target_label: kubernetes_name

  - job_name: 'kubernetes-pods'

    scheme: http

    kubernetes_sd_configs:
    - role: pod
      api_server: http://cluster-manager.dev.example.net:8080

    bearer_token_file: /opt/prometheus/prometheus/kube_tokens/dev
    tls_config:
      insecure_skip_verify: true

    relabel_configs:
    - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
      action: keep
      regex: true
    - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
      action: replace
      target_label: __metrics_path__
      regex: (.+)
    - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
      action: replace
      regex: (.+):(?:\d+);(\d+)
      replacement: ${1}:${2}
      target_label: __address__
    - action: labelmap
      regex: __meta_kubernetes_pod_label_(.+)
    - source_labels: [__meta_kubernetes_namespace]
      action: replace
      target_label: kubernetes_namespace
    - source_labels: [__meta_kubernetes_pod_name]
      action: replace
      target_label: kubernetes_pod_name
</code>```

I don't use a TLS connection to API, so I want to disable it.

When I curl /metrics URL from Prometheus host - it prints them.

Finally I connected to the cluster, but...the jobs are not up and therefore Prometheus doesn't expose relabeled metrics.

What I see in Console.

Targets state:

Also I checked the Prometheus debug. It's thought the system gets any necessary information and requests are done successfully.

```<code>time="2017-01-25T06:58:04Z" level=debug msg="pod update" kubernetes_sd=pod source="pod.go:66" tg="&config.TargetGroup{Targets:[]model.LabelSet{model.LabelSet{\"__meta_kubernetes_pod_container_port_protocol\":\"UDP\", \"__address__\":\"10.32.0.2:10053\", \"__meta_kubernetes_pod_container_name\":\"kube-dns\", \"__meta_kubernetes_pod_container_port_number\":\"10053\", \"__meta_kubernetes_pod_container_port_name\":\"dns-local\"}, model.LabelSet{\"__address__\":\"10.32.0.2:10053\", \"__meta_kubernetes_pod_container_name\":\"kube-dns\", \"__meta_kubernetes_pod_container_port_number\":\"10053\", \"__meta_kubernetes_pod_container_port_name\":\"dns-tcp-local\", \"__meta_kubernetes_pod_container_port_protocol\":\"TCP\"}, model.LabelSet{\"__meta_kubernetes_pod_container_name\":\"kube-dns\", \"__meta_kubernetes_pod_container_port_number\":\"10055\", \"__meta_kubernetes_pod_container_port_name\":\"metrics\", \"__meta_kubernetes_pod_container_port_protocol\":\"TCP\", \"__address__\":\"10.32.0.2:10055\"}, model.LabelSet{\"__address__\":\"10.32.0.2:53\", \"__meta_kubernetes_pod_container_name\":\"dnsmasq\", \"__meta_kubernetes_pod_container_port_number\":\"53\", \"__meta_kubernetes_pod_container_port_name\":\"dns\", \"__meta_kubernetes_pod_container_port_protocol\":\"UDP\"}, model.LabelSet{\"__address__\":\"10.32.0.2:53\", \"__meta_kubernetes_pod_container_name\":\"dnsmasq\", \"__meta_kubernetes_pod_container_port_number\":\"53\", \"__meta_kubernetes_pod_container_port_name\":\"dns-tcp\", \"__meta_kubernetes_pod_container_port_protocol\":\"TCP\"}, model.LabelSet{\"__meta_kubernetes_pod_container_port_number\":\"10054\", \"__meta_kubernetes_pod_container_port_name\":\"metrics\", \"__meta_kubernetes_pod_container_port_protocol\":\"TCP\", \"__address__\":\"10.32.0.2:10054\", \"__meta_kubernetes_pod_container_name\":\"dnsmasq-metrics\"}, model.LabelSet{\"__meta_kubernetes_pod_container_port_protocol\":\"TCP\", \"__address__\":\"10.32.0.2:8080\", \"__meta_kubernetes_pod_container_name\":\"healthz\", \"__meta_kubernetes_pod_container_port_number\":\"8080\", \"__meta_kubernetes_pod_container_port_name\":\"\"}}, Labels:model.LabelSet{\"__meta_kubernetes_pod_ready\":\"true\", \"__meta_kubernetes_pod_annotation_kubernetes_io_created_by\":\"{\\\"kind\\\":\\\"SerializedReference\\\",\\\"apiVersion\\\":\\\"v1\\\",\\\"reference\\\":{\\\"kind\\\":\\\"ReplicaSet\\\",\\\"namespace\\\":\\\"kube-system\\\",\\\"name\\\":\\\"kube-dns-2924299975\\\",\\\"uid\\\":\\\"fa808d95-d7d9-11e6-9ac9-02dfdae1a1e9\\\",\\\"apiVersion\\\":\\\"extensions\\\",\\\"resourceVersion\\\":\\\"89\\\"}}\\n\", \"__meta_kubernetes_pod_annotation_scheduler_alpha_kubernetes_io_affinity\":\"{\\\"nodeAffinity\\\":{\\\"requiredDuringSchedulingIgnoredDuringExecution\\\":{\\\"nodeSelectorTerms\\\":[{\\\"matchExpressions\\\":[{\\\"key\\\":\\\"beta.kubernetes.io/arch\\\",\\\"operator\\\":\\\"In\\\",\\\"values\\\":[\\\"amd64\\\"]}]}]}}}\", \"__meta_kubernetes_pod_name\":\"kube-dns-2924299975-dksg5\", \"__meta_kubernetes_pod_ip\":\"10.32.0.2\", \"__meta_kubernetes_pod_label_k8s_app\":\"kube-dns\", \"__meta_kubernetes_pod_label_pod_template_hash\":\"2924299975\", \"__meta_kubernetes_pod_label_tier\":\"node\", \"__meta_kubernetes_pod_annotation_scheduler_alpha_kubernetes_io_tolerations\":\"[{\\\"key\\\":\\\"dedicated\\\",\\\"value\\\":\\\"master\\\",\\\"effect\\\":\\\"NoSchedule\\\"}]\", \"__meta_kubernetes_namespace\":\"kube-system\", \"__meta_kubernetes_pod_node_name\":\"cluster-manager.dev.example.net\", \"__meta_kubernetes_pod_label_component\":\"kube-dns\", \"__meta_kubernetes_pod_label_kubernetes_io_cluster_service\":\"true\", \"__meta_kubernetes_pod_host_ip\":\"54.194.166.39\", \"__meta_kubernetes_pod_label_name\":\"kube-dns\"}, Source:\"pod/kube-system/kube-dns-2924299975-dksg5\"}"
time="2017-01-25T06:58:04Z" level=debug msg="pod update" kubernetes_sd=pod source="pod.go:66" tg="&config.TargetGroup{Targets:[]model.LabelSet{model.LabelSet{\"__address__\":\"10.43.0.0\", \"__meta_kubernetes_pod_container_name\":\"bot\"}}, Labels:model.LabelSet{\"__meta_kubernetes_pod_host_ip\":\"172.17.101.25\", \"__meta_kubernetes_pod_label_app\":\"bot\", \"__meta_kubernetes_namespace\":\"default\", \"__meta_kubernetes_pod_name\":\"bot-272181271-pnzsz\", \"__meta_kubernetes_pod_ip\":\"10.43.0.0\", \"__meta_kubernetes_pod_node_name\":\"ip-172-17-101-25\", \"__meta_kubernetes_pod_annotation_kubernetes_io_created_by\":\"{\\\"kind\\\":\\\"SerializedReference\\\",\\\"apiVersion\\\":\\\"v1\\\",\\\"reference\\\":{\\\"kind\\\":\\\"ReplicaSet\\\",\\\"namespace\\\":\\\"default\\\",\\\"name\\\":\\\"bot-272181271\\\",\\\"uid\\\":\\\"c297b3c2-e15d-11e6-a28a-02dfdae1a1e9\\\",\\\"apiVersion\\\":\\\"extensions\\\",\\\"resourceVersion\\\":\\\"1465127\\\"}}\\n\", \"__meta_kubernetes_pod_ready\":\"true\", \"__meta_kubernetes_pod_label_pod_template_hash\":\"272181271\", \"__meta_kubernetes_pod_label_version\":\"v0.1\"}, Source:\"pod/default/bot-272181271-pnzsz\"}"
</code>```

Prometheus fetches updates, but...doesn't convert them to metrics.
So, I've broken my brain to figure out why is it going this way. So, please, help if you can figure out where might be mistake.

答:
If you want to monitor a Kubernetes cluster from an external Prometheus server, I would suggest to set up a Prometheus federation topology:

Inside the K8s, install node-exporter pods and a Prometheus instance with short-term storage.

Expose the Prometheus service out of the K8s cluster, either via an ingress-controller (LB), or a node port. You can protect this endpoint with HTTPS + basic authentication.

Configure the center Prometheus to scrape metrics from above endpoint with proper authentication and tags.

This is the scalable solution. You can add monitor as many K8s clusters you want, until it reaches the capacities of the center Prometheus. Then you can add another center Prometheus instance to monitor others.

Body:
The issue: I have a Prometheus outside of Kubernetes cluster. So, I want to export metrics from remote cluster.

I took the config sample from Prometheus Github repo and modified this a little bit. So, here is my jobs config.

  - job_name: 'kubernetes-apiservers'

    scheme: http

    kubernetes_sd_configs:
    - role: endpoints
      api_server: http://cluster-manager.dev.example.net:8080

    bearer_token_file: /opt/prometheus/prometheus/kube_tokens/dev
    tls_config:
      insecure_skip_verify: true

    relabel_configs:
    - source_labels: [__meta_kubernetes_namespace, __meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name]
      action: keep
      regex: default;kubernetes;http

  - job_name: 'kubernetes-nodes'

    scheme: http

    kubernetes_sd_configs:
    - role: node
      api_server: http://cluster-manager.dev.example.net:8080

    bearer_token_file: /opt/prometheus/prometheus/kube_tokens/dev
    tls_config:
      insecure_skip_verify: true

    relabel_configs:
    - action: labelmap
      regex: __meta_kubernetes_node_label_(.+)

  - job_name: 'kubernetes-service-endpoints'

    scheme: http

    kubernetes_sd_configs:
    - role: endpoints
      api_server: http://cluster-manager.dev.example.net:8080

    bearer_token_file: /opt/prometheus/prometheus/kube_tokens/dev
    tls_config:
      insecure_skip_verify: true

    relabel_configs:
    - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scrape]
      action: keep
      regex: true
    - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scheme]
      action: replace
      target_label: __scheme__
      regex: (http?)
    - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_path]
      action: replace
      target_label: __metrics_path__
      regex: (.+)
    - source_labels: [__address__, __meta_kubernetes_service_annotation_prometheus_io_port]
      action: replace
      target_label: __address__
      regex: (.+)(?::\d+);(\d+)
      replacement: $1:$2
    - action: labelmap
      regex: __meta_kubernetes_service_label_(.+)
    - source_labels: [__meta_kubernetes_namespace]
      action: replace
      target_label: kubernetes_namespace
    - source_labels: [__meta_kubernetes_service_name]
      action: replace
      target_label: kubernetes_name

  - job_name: 'kubernetes-services'

    scheme: http

    metrics_path: /probe
    params:
      module: [http_2xx]

    kubernetes_sd_configs:
    - role: service
      api_server: http://cluster-manager.dev.example.net:8080

    bearer_token_file: /opt/prometheus/prometheus/kube_tokens/dev
    tls_config:
      insecure_skip_verify: true

    relabel_configs:
    - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_probe]
      action: keep
      regex: true
    - source_labels: [__address__]
      target_label: __param_target
    - target_label: __address__
      replacement: blackbox
    - source_labels: [__param_target]
      target_label: instance
    - action: labelmap
      regex: __meta_kubernetes_service_label_(.+)
    - source_labels: [__meta_kubernetes_service_namespace]
      target_label: kubernetes_namespace
    - source_labels: [__meta_kubernetes_service_name]
      target_label: kubernetes_name

  - job_name: 'kubernetes-pods'

    scheme: http

    kubernetes_sd_configs:
    - role: pod
      api_server: http://cluster-manager.dev.example.net:8080

    bearer_token_file: /opt/prometheus/prometheus/kube_tokens/dev
    tls_config:
      insecure_skip_verify: true

    relabel_configs:
    - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
      action: keep
      regex: true
    - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
      action: replace
      target_label: __metrics_path__
      regex: (.+)
    - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
      action: replace
      regex: (.+):(?:\d+);(\d+)
      replacement: ${1}:${2}
      target_label: __address__
    - action: labelmap
      regex: __meta_kubernetes_pod_label_(.+)
    - source_labels: [__meta_kubernetes_namespace]
      action: replace
      target_label: kubernetes_namespace
    - source_labels: [__meta_kubernetes_pod_name]
      action: replace
      target_label: kubernetes_pod_name

I don't use a TLS connection to API, so I want to disable it.

When I curl /metrics URL from Prometheus host - it prints them.

Finally I connected to the cluster, but...the jobs are not up and therefore Prometheus doesn't expose relabeled metrics.

What I see in Console.

Targets state:

Also I checked the Prometheus debug. It's thought the system gets any necessary information and requests are done successfully.

time="2017-01-25T06:58:04Z" level=debug msg="pod update" kubernetes_sd=pod source="pod.go:66" tg="&config.TargetGroup{Targets:[]model.LabelSet{model.LabelSet{\"__meta_kubernetes_pod_container_port_protocol\":\"UDP\", \"__address__\":\"10.32.0.2:10053\", \"__meta_kubernetes_pod_container_name\":\"kube-dns\", \"__meta_kubernetes_pod_container_port_number\":\"10053\", \"__meta_kubernetes_pod_container_port_name\":\"dns-local\"}, model.LabelSet{\"__address__\":\"10.32.0.2:10053\", \"__meta_kubernetes_pod_container_name\":\"kube-dns\", \"__meta_kubernetes_pod_container_port_number\":\"10053\", \"__meta_kubernetes_pod_container_port_name\":\"dns-tcp-local\", \"__meta_kubernetes_pod_container_port_protocol\":\"TCP\"}, model.LabelSet{\"__meta_kubernetes_pod_container_name\":\"kube-dns\", \"__meta_kubernetes_pod_container_port_number\":\"10055\", \"__meta_kubernetes_pod_container_port_name\":\"metrics\", \"__meta_kubernetes_pod_container_port_protocol\":\"TCP\", \"__address__\":\"10.32.0.2:10055\"}, model.LabelSet{\"__address__\":\"10.32.0.2:53\", \"__meta_kubernetes_pod_container_name\":\"dnsmasq\", \"__meta_kubernetes_pod_container_port_number\":\"53\", \"__meta_kubernetes_pod_container_port_name\":\"dns\", \"__meta_kubernetes_pod_container_port_protocol\":\"UDP\"}, model.LabelSet{\"__address__\":\"10.32.0.2:53\", \"__meta_kubernetes_pod_container_name\":\"dnsmasq\", \"__meta_kubernetes_pod_container_port_number\":\"53\", \"__meta_kubernetes_pod_container_port_name\":\"dns-tcp\", \"__meta_kubernetes_pod_container_port_protocol\":\"TCP\"}, model.LabelSet{\"__meta_kubernetes_pod_container_port_number\":\"10054\", \"__meta_kubernetes_pod_container_port_name\":\"metrics\", \"__meta_kubernetes_pod_container_port_protocol\":\"TCP\", \"__address__\":\"10.32.0.2:10054\", \"__meta_kubernetes_pod_container_name\":\"dnsmasq-metrics\"}, model.LabelSet{\"__meta_kubernetes_pod_container_port_protocol\":\"TCP\", \"__address__\":\"10.32.0.2:8080\", \"__meta_kubernetes_pod_container_name\":\"healthz\", \"__meta_kubernetes_pod_container_port_number\":\"8080\", \"__meta_kubernetes_pod_container_port_name\":\"\"}}, Labels:model.LabelSet{\"__meta_kubernetes_pod_ready\":\"true\", \"__meta_kubernetes_pod_annotation_kubernetes_io_created_by\":\"{\\\"kind\\\":\\\"SerializedReference\\\",\\\"apiVersion\\\":\\\"v1\\\",\\\"reference\\\":{\\\"kind\\\":\\\"ReplicaSet\\\",\\\"namespace\\\":\\\"kube-system\\\",\\\"name\\\":\\\"kube-dns-2924299975\\\",\\\"uid\\\":\\\"fa808d95-d7d9-11e6-9ac9-02dfdae1a1e9\\\",\\\"apiVersion\\\":\\\"extensions\\\",\\\"resourceVersion\\\":\\\"89\\\"}}\\n\", \"__meta_kubernetes_pod_annotation_scheduler_alpha_kubernetes_io_affinity\":\"{\\\"nodeAffinity\\\":{\\\"requiredDuringSchedulingIgnoredDuringExecution\\\":{\\\"nodeSelectorTerms\\\":[{\\\"matchExpressions\\\":[{\\\"key\\\":\\\"beta.kubernetes.io/arch\\\",\\\"operator\\\":\\\"In\\\",\\\"values\\\":[\\\"amd64\\\"]}]}]}}}\", \"__meta_kubernetes_pod_name\":\"kube-dns-2924299975-dksg5\", \"__meta_kubernetes_pod_ip\":\"10.32.0.2\", \"__meta_kubernetes_pod_label_k8s_app\":\"kube-dns\", \"__meta_kubernetes_pod_label_pod_template_hash\":\"2924299975\", \"__meta_kubernetes_pod_label_tier\":\"node\", \"__meta_kubernetes_pod_annotation_scheduler_alpha_kubernetes_io_tolerations\":\"[{\\\"key\\\":\\\"dedicated\\\",\\\"value\\\":\\\"master\\\",\\\"effect\\\":\\\"NoSchedule\\\"}]\", \"__meta_kubernetes_namespace\":\"kube-system\", \"__meta_kubernetes_pod_node_name\":\"cluster-manager.dev.example.net\", \"__meta_kubernetes_pod_label_component\":\"kube-dns\", \"__meta_kubernetes_pod_label_kubernetes_io_cluster_service\":\"true\", \"__meta_kubernetes_pod_host_ip\":\"54.194.166.39\", \"__meta_kubernetes_pod_label_name\":\"kube-dns\"}, Source:\"pod/kube-system/kube-dns-2924299975-dksg5\"}"
time="2017-01-25T06:58:04Z" level=debug msg="pod update" kubernetes_sd=pod source="pod.go:66" tg="&config.TargetGroup{Targets:[]model.LabelSet{model.LabelSet{\"__address__\":\"10.43.0.0\", \"__meta_kubernetes_pod_container_name\":\"bot\"}}, Labels:model.LabelSet{\"__meta_kubernetes_pod_host_ip\":\"172.17.101.25\", \"__meta_kubernetes_pod_label_app\":\"bot\", \"__meta_kubernetes_namespace\":\"default\", \"__meta_kubernetes_pod_name\":\"bot-272181271-pnzsz\", \"__meta_kubernetes_pod_ip\":\"10.43.0.0\", \"__meta_kubernetes_pod_node_name\":\"ip-172-17-101-25\", \"__meta_kubernetes_pod_annotation_kubernetes_io_created_by\":\"{\\\"kind\\\":\\\"SerializedReference\\\",\\\"apiVersion\\\":\\\"v1\\\",\\\"reference\\\":{\\\"kind\\\":\\\"ReplicaSet\\\",\\\"namespace\\\":\\\"default\\\",\\\"name\\\":\\\"bot-272181271\\\",\\\"uid\\\":\\\"c297b3c2-e15d-11e6-a28a-02dfdae1a1e9\\\",\\\"apiVersion\\\":\\\"extensions\\\",\\\"resourceVersion\\\":\\\"1465127\\\"}}\\n\", \"__meta_kubernetes_pod_ready\":\"true\", \"__meta_kubernetes_pod_label_pod_template_hash\":\"272181271\", \"__meta_kubernetes_pod_label_version\":\"v0.1\"}, Source:\"pod/default/bot-272181271-pnzsz\"}"

Prometheus fetches updates, but...doesn't convert them to metrics.
So, I've broken my brain to figure out why is it going this way. So, please, help if you can figure out where might be mistake.


问:
Signed Addition overflow in VHDL
I tried to implement and addition of two signed numbers. The first one is 32 bit and the second one is also 32 bit, but correspond the addition of the earlier operation. The code VHLD is below :

```<code>Entity Sum_Position is
  port
  (
     Clk: in std_logic;
     Reset: in std_logic;
     Raz_position: in std_logic;
     Position_In: in std_logic_vector(31 downto 0);
     Position_Out: out std_logic_vector(31 downto 0)
  );
end Sum_Position;

Architecture Arch_position of sum_Position is

    -- create locale signals
    signal position_before: signed (31 downto 0):= (OTHERS => '0');
    -- both signals have one more bit than the original
    signal Position_s   : SIGNED(Position_In'length downto 0):= (OTHERS => '0');
    signal Position_Before_s   : SIGNED(Position_In'length downto 0):= (OTHERS => '0');
    signal Sum_Pos_s : SIGNED(Position_In'length downto 0):= (OTHERS => '0');

    Begin  -- begin of architecture

     -- convert type and perform a sign-extension
    Position_s <=SIGNED(Position_In(31) & Position_In);
    Position_Before_s<=resize(signed(position_before), Position_Before_s'length);

    Sum_of_position: process(Clk, Reset)

    begin

       IF (Reset='0') THEN          -- when reset is selected
           -- initialize all values
          Sum_Pos_s<= (OTHERS => '0');
       ELSIF (Clk'event and Clk = '1') then
           -- addition of two 33 bit values
          Sum_Pos_s <= Position_s + Position_Before_s;

       END IF;

    end process Sum_of_position;

    -- resize to require size and type conversion
    position_before <= (OTHERS => '0') WHEN Raz_position='1' else
                        signed(resize(Sum_Pos_s, position_before'length));

    -- Resize and output the result
    Position_Out  <= (OTHERS => '0') WHEN Raz_position='1' else
                     std_logic_vector(resize(Sum_Pos_s, Position_Out'length));

    end Arch_position;
</code>```

But, i have overflow because the result is very strange. Can you please suggest me a solution?

Best regards;

答:
Most modern VHDL tools have Integer types (signed and unsigned).
These are usually 32 bits wide unless you use the Range modifier.

I suggest you consider using integers rather than std_logic_vector.

You can convert between types like casts in C.

This is my favourite diagram on casting/ converting VHDL types. I have printed it out and put it on my wall http://www.bitweenie.com/listings/vhdl-type-conversion

A page in integers in VHDL http://vhdl.renerta.com/mobile/source/vhd00039.htm

Title: Signed Addition overflow in VHDL

Body:
I tried to implement and addition of two signed numbers. The first one is 32 bit and the second one is also 32 bit, but correspond the addition of the earlier operation. The code VHLD is below :

Entity Sum_Position is
  port
  (
     Clk: in std_logic;
     Reset: in std_logic;
     Raz_position: in std_logic;
     Position_In: in std_logic_vector(31 downto 0);
     Position_Out: out std_logic_vector(31 downto 0)
  );
end Sum_Position;

Architecture Arch_position of sum_Position is

    -- create locale signals
    signal position_before: signed (31 downto 0):= (OTHERS => '0');
    -- both signals have one more bit than the original
    signal Position_s   : SIGNED(Position_In'length downto 0):= (OTHERS => '0');
    signal Position_Before_s   : SIGNED(Position_In'length downto 0):= (OTHERS => '0');
    signal Sum_Pos_s : SIGNED(Position_In'length downto 0):= (OTHERS => '0');

    Begin  -- begin of architecture

     -- convert type and perform a sign-extension
    Position_s <=SIGNED(Position_In(31) & Position_In);
    Position_Before_s<=resize(signed(position_before), Position_Before_s'length);

    Sum_of_position: process(Clk, Reset)

    begin

       IF (Reset='0') THEN          -- when reset is selected
           -- initialize all values
          Sum_Pos_s<= (OTHERS => '0');
       ELSIF (Clk'event and Clk = '1') then
           -- addition of two 33 bit values
          Sum_Pos_s <= Position_s + Position_Before_s;

       END IF;

    end process Sum_of_position;

    -- resize to require size and type conversion
    position_before <= (OTHERS => '0') WHEN Raz_position='1' else
                        signed(resize(Sum_Pos_s, position_before'length));

    -- Resize and output the result
    Position_Out  <= (OTHERS => '0') WHEN Raz_position='1' else
                     std_logic_vector(resize(Sum_Pos_s, Position_Out'length));

    end Arch_position;

But, i have overflow because the result is very strange. Can you please suggest me a solution?

Best regards;

ContentLicense: CC BY-SA 4.0


问:
Returning the same type As Supplied as an Argument - Java8 Generics
I'm supposed to write a generic method called getLowCost that takes two arguments : An array list arLst1 that is either type Battery, Single Use, or Rechargeable, and a double cost. I'm supposed to return an array list of all batteries in arLst1 that have a cost less than or equal to the cost supplied.

I thought I would begin like this,

```<code>public ArrayList<? extends Battery> getLowCost(ArrayList<? extends Battery> list, double val) {
    ArrayList<? extends Battery> list2 = new ArrayList<>();
    for (Battery obj: list) {
        if (obj.getLifeTimeCost() < val) {
            list2.add(obj);
        }
    }
}
</code>```

Unfortunately, I cannot add the object to my my list2. How can I guarantee that the return type has the same type as the first argument?

答:
Use a type variable:</p>

```<code>public <T extends Battery> ArrayList<T> getLowCost(ArrayList<T> list, double val) {
    ArrayList<T> list2 = new ArrayList<>();
    for (T obj: list) {
        if (obj.getLifeTimeCost() < val) {
            list2.add(obj);
        }
    }
    return list2;
}
</code>```

Body:
I'm supposed to write a generic method called getLowCost that takes two arguments : An array list arLst1 that is either type Battery, Single Use, or Rechargeable, and a double cost. I'm supposed to return an array list of all batteries in arLst1 that have a cost less than or equal to the cost supplied.

I thought I would begin like this,

public ArrayList<? extends Battery> getLowCost(ArrayList<? extends Battery> list, double val) {
    ArrayList<? extends Battery> list2 = new ArrayList<>();
    for (Battery obj: list) {
        if (obj.getLifeTimeCost() < val) {
            list2.add(obj);
        }
    }
}

Unfortunately, I cannot add the object to my my list2. How can I guarantee that the return type has the same type as the first argument?

Body:
Use a type variable:

public <T extends Battery> ArrayList<T> getLowCost(ArrayList<T> list, double val) {
    ArrayList<T> list2 = new ArrayList<>();
    for (T obj: list) {
        if (obj.getLifeTimeCost() < val) {
            list2.add(obj);
        }
    }
    return list2;
}


问:
Restore GtkWindow at location where it was hidden?
I am hiding a preference window with gtk_widget_hide, but when I unhide it using gtk_widget_show, it shows up at the location where it was created, i.e. on the center of the screen, instead of where I left it. Looks like I'm overlooking a triviality: any help is appreciated.</p>

答:
You probably need gtk_window_get_position before hiding.

And then gtk_window_move after showing.


问:
Google Sheets Script getLastRow() not returning all values

I have email addresses in first column. When I try to get the last row of this column, the function only returns the first two values. Here is a link to the sheet: https://docs.google.com/spreadsheets/d/1piGCiWMcUKUWagIJSZ_0SxxuNG3tcEcrx-fKnMDOIlQ/edit?usp=sharing

Here is the script function:

```<code>function myFunction() {
  var rangeLastRow = SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(2, 1).getLastRow();
  var emails = SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(2, 1,rangeLastRow).getValues();
  Logger.log(emails);
}
</code>```

Shouldn't it be returning all of the email addresses in the first column?

It is only returning the first two email addresses.

答:
How about this modification?

Modification points :

getRange(2, 1).getLastRow() means that it is to retrieve the last row for the range of "a2". So the result is 2.

In order to retrieve the last　row of the sheet, please use SpreadsheetApp.getActive().getSheetByName('Sheet1').getLastRow()

The 3rd parameter of getRange(row, column, numRows) is the numRows. When you want to retrieve data of "a2:a6", numRows is rangeLastRow - 1.

By above reason, getRange(2, 1, 2).getValues() retrieves only 2 cells.

SpreadsheetApp.getActive().getSheetByName('Sheet1') can be used by importing a variable.

The modified script which reflected above is as follows.

Modified script :

```<code>var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var rangeLastRow = sheet.getLastRow();
var emails = sheet.getRange(2, 1, rangeLastRow - 1).getValues();
Logger.log(emails);
</code>```

References :

getRange(row, column, numRows)

Body:
I have email addresses in first column. When I try to get the last row of this column, the function only returns the first two values. Here is a link to the sheet: https://docs.google.com/spreadsheets/d/1piGCiWMcUKUWagIJSZ_0SxxuNG3tcEcrx-fKnMDOIlQ/edit?usp=sharing

Here is the script function:

function myFunction() {
  var rangeLastRow = SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(2, 1).getLastRow();
  var emails = SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(2, 1,rangeLastRow).getValues();
  Logger.log(emails);
}

Shouldn't it be returning all of the email addresses in the first column?

It is only returning the first two email addresses.

Body:
How about this modification?

Modification points :

getRange(2, 1).getLastRow() means that it is to retrieve the last row for the range of "a2". So the result is 2.

In order to retrieve the last　row of the sheet, please use SpreadsheetApp.getActive().getSheetByName('Sheet1').getLastRow()

The 3rd parameter of getRange(row, column, numRows) is the numRows. When you want to retrieve data of "a2:a6", numRows is rangeLastRow - 1.

By above reason, getRange(2, 1, 2).getValues() retrieves only 2 cells.

SpreadsheetApp.getActive().getSheetByName('Sheet1') can be used by importing a variable.

The modified script which reflected above is as follows.

Modified script :

var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var rangeLastRow = sheet.getLastRow();
var emails = sheet.getRange(2, 1, rangeLastRow - 1).getValues();
Logger.log(emails);

References :

getRange(row, column, numRows)


问:
Is is possible to apply this data-frame transform?
Turn this data-frame :

```<code>  Name  │  car
  ──────┼────────
  John  │  Volvo
  John  │  Fiat
  Paul  │  Dacia
</code>```

Into this? :

```<code>  Name  │  car_1  │   car_2
  ──────┼─────────┼─────────
  John  │  Volvo  │   Fiat
  Paul  │  Dacia  │   NaN
</code>```

for an arbitrary number of duplicates (arbitrary number of cars a person ) IDs in the first table.

答:
```<code>In [190]: (df.assign(x=df.groupby('Name').cumcount()+1)
     ...:    .pivot(index='Name', columns='x', values='car')
     ...:    .add_prefix('car_')
     ...:    .reset_index()
     ...:    .rename_axis(None,1))
     ...:
Out[190]:
   Name  car_1 car_2
0  John  Volvo  Fiat
1  Paul  Dacia  None
</code>```

Body:
Turn this data-frame :

  Name  │  car
  ──────┼────────
  John  │  Volvo
  John  │  Fiat
  Paul  │  Dacia

Into this? :

  Name  │  car_1  │   car_2
  ──────┼─────────┼─────────
  John  │  Volvo  │   Fiat
  Paul  │  Dacia  │   NaN

for an arbitrary number of duplicates (arbitrary number of cars a person ) IDs in the first table.


问:
Adding error bars to line graph in R
I'm trying to add error bars to line graphs to the following script.

```<code>#####Plot FW roses####
ntreatments <- max(df$Treats)

#get the range for the x and y axis
x2range <- range(df$Days)
y2range <- range(df$FWs)

# set up plot
plot(x2range, y2range,
     type = "n",
     xlab= "Time (days)",
     ylab= "Fresh weight (g)")

colors <- c("blue", "red", "black", "darkgreen", "Purple")
linetype <- c(1:ntreatments)
plotchar <- seq(18, 18+ntreatments, 1)

# add lines
for(i in 1:ntreatments) {
  tr2 <- subset(df, Treats==i)
  lines(tr2$Days, tr2$FWs, type="b",
        lwd=1.5,
        lty=linetype[i],
        col=colors[i],
        pch=plotchar[i])
}

# add a title and subtitle
title("Fresh weight")

# add a legend
legend(x2range[1],
       y2range[2],
       ncol = 2,
       1:ntreatments,
       cex=0.8,
       col=colors,
       pch=plotchar,
       lty=linetype,
       title="Treatment")
</code>```

I have tried errbar(x2range, y2range, y2range+df$sd, y2range-df$sd)

But the result is that all errorbars gather at the beginning and the end of the graph and not on the corresponding y coordinates.

How can I solve this?

答:
Since you don't provide any sample data, here is a simple example using some simulated data.

```<code># Generate some sample data
set.seed(2017);
x <- seq(0, 1, length.out = 10);
y <- 1 + 4 * x + runif(10);
dy <- sqrt(y);
df <- data.frame(x = x, y = y, dy = dy);
</code>```

Plot in base R and add error bars using segments.

```<code># Plot in base R
plot(df$x, df$y, ylim = c(0, 8), type = "l");
segments(df$x, df$y - df$dy, df$x, df$y + df$dy);
</code>```

Or plot using ggplot2.

```<code># Plot in ggplot
ggplot(df, aes(x = x, y = y)) +
    geom_line() +
    geom_errorbar(aes(ymin = y - dy, ymax = y + dy));
</code>```

Title: Adding error bars to line graph in R

Body:
I'm trying to add error bars to line graphs to the following script.

#####Plot FW roses####
ntreatments <- max(df$Treats)

#get the range for the x and y axis
x2range <- range(df$Days)
y2range <- range(df$FWs)

# set up plot
plot(x2range, y2range,
     type = "n",
     xlab= "Time (days)",
     ylab= "Fresh weight (g)")

colors <- c("blue", "red", "black", "darkgreen", "Purple")
linetype <- c(1:ntreatments)
plotchar <- seq(18, 18+ntreatments, 1)

# add lines
for(i in 1:ntreatments) {
  tr2 <- subset(df, Treats==i)
  lines(tr2$Days, tr2$FWs, type="b",
        lwd=1.5,
        lty=linetype[i],
        col=colors[i],
        pch=plotchar[i])
}

# add a title and subtitle
title("Fresh weight")

# add a legend
legend(x2range[1],
       y2range[2],
       ncol = 2,
       1:ntreatments,
       cex=0.8,
       col=colors,
       pch=plotchar,
       lty=linetype,
       title="Treatment")

I have tried errbar(x2range, y2range, y2range+df$sd, y2range-df$sd)

But the result is that all errorbars gather at the beginning and the end of the graph and not on the corresponding y coordinates.

How can I solve this?

Body:
Since you don't provide any sample data, here is a simple example using some simulated data.

# Generate some sample data
set.seed(2017);
x <- seq(0, 1, length.out = 10);
y <- 1 + 4 * x + runif(10);
dy <- sqrt(y);
df <- data.frame(x = x, y = y, dy = dy);

Plot in base R and add error bars using segments.

# Plot in base R
plot(df$x, df$y, ylim = c(0, 8), type = "l");
segments(df$x, df$y - df$dy, df$x, df$y + df$dy);

Or plot using ggplot2.

# Plot in ggplot
ggplot(df, aes(x = x, y = y)) +
    geom_line() +
    geom_errorbar(aes(ymin = y - dy, ymax = y + dy));


问:
Add New View to Layout Upon Button Click in Android
I'm developing a Scorekeeping Application for the card game "Spades".

Upon a button click at the end of each hand, I would like to store some information about the hand into a TextView and display all of the hand histories in a ScrollView.

How can I modify an .XML layout or otherwise add a new TextView to a layout in code?

I have tried...

```<code>public static LinearLayout gamehistory;

gamehistory = (LinearLayout) findViewById(R.id.gamehistory);

public void setClickListener1(){

lockwagersButton.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

setContentView(R.layout.results_layout);

gameHistory.addView(new TextView(...));       //  I can't get this to work
            ...
</code>```

Thanks!
-K.H.

答:
```<code>public void setClickListeners()
{
    lockwagersButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
         // Do Stuff
        lockresultsButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                        calculateScores();
                        setContentView(R.layout.scoreboard_layout);
                        SettingsActivity.currentdealer.getNextDealer();
                        setSpinners1();
                        findDisplays();
                        setPlayerNamesScoreboard();
                        lockwagersButton = (Button) findViewById(R.id.lockwagers);
                        displayScores();
                        checkForWinner();
                        saveHandHistory();
                        setClickListeners(); // This is the recursion <------
                    }
                }
            });
        }
    });
}
</code>```

Based on what you gave me

```<code>public void saveHandHistory(){
    scrollview = (ScrollView) findViewById(R.id.ScrollView1);
    gamehistory = (LinearLayout) findViewById(R.id.gamehistory);
    layoutparams = new LinearLayout.LayoutParams (LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
    TextView handHistory = new TextView(ScoreboardActivity.this);
    handHistory.setText("Hand History Will Go Here");
    gamehistory.addView(handHistory, layoutparams);
}
</code>```

Body:
I'm developing a Scorekeeping Application for the card game "Spades".

Upon a button click at the end of each hand, I would like to store some information about the hand into a TextView and display all of the hand histories in a ScrollView.

How can I modify an .XML layout or otherwise add a new TextView to a layout in code?

I have tried...

public static LinearLayout gamehistory;

gamehistory = (LinearLayout) findViewById(R.id.gamehistory);

public void setClickListener1(){

lockwagersButton.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

setContentView(R.layout.results_layout);

gameHistory.addView(new TextView(...));       //  I can't get this to work
            ...

Thanks!
-K.H.

Body:
public void setClickListeners()
{
    lockwagersButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
         // Do Stuff
        lockresultsButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                        calculateScores();
                        setContentView(R.layout.scoreboard_layout);
                        SettingsActivity.currentdealer.getNextDealer();
                        setSpinners1();
                        findDisplays();
                        setPlayerNamesScoreboard();
                        lockwagersButton = (Button) findViewById(R.id.lockwagers);
                        displayScores();
                        checkForWinner();
                        saveHandHistory();
                        setClickListeners(); // This is the recursion <------
                    }
                }
            });
        }
    });
}

Based on what you gave me

public void saveHandHistory(){
    scrollview = (ScrollView) findViewById(R.id.ScrollView1);
    gamehistory = (LinearLayout) findViewById(R.id.gamehistory);
    layoutparams = new LinearLayout.LayoutParams (LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
    TextView handHistory = new TextView(ScoreboardActivity.this);
    handHistory.setText("Hand History Will Go Here");
    gamehistory.addView(handHistory, layoutparams);
}


问:
Cant load this JSON into my table
I 've got a simple thing:

There's a JSON with books objects,every book has a title,author and year.
I would like to choose one option from the list and display chosen property in a table.I've used an example from W3 but right now i'm stuck and nothing works as it should...

Link's here

```<code>function change_myselect(sel) {
    var obj, dbParam, xmlhttp, myObj, x, txt = "";
    obj = { "table":sel, "limit":20 };
    dbParam = JSON.stringify(obj);
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            myObj = JSON.parse(this.responseText);
            txt += "<table border='1'>"
            for (x in myObj) {
                txt += "<tr><td>" + myObj[x].name + "</td></tr>";
            }
            txt += "</table>"
            document.getElementById("demo").innerHTML = txt;
        }
    };
    xmlhttp.open("GET", "generated.json", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("x=" + dbParam);
}
</code>```

答:
You are iterating over a single property books in an object instead of iterating over the array that property contains.

Instead of this:

```<code>for (x in myObj) {
  txt += "<tr><td>" + myObj[x].name + "</td></tr>";
}
</code>```

try something like this:

```<code>myObj.books.forEach((book) => {
  txt += "<tr><td>" + book[sel.toLowerCase()] + "</td></tr>";
});
</code>```

Title: Cant load this JSON into my table

Body:
I 've got a simple thing:

There's a JSON with books objects,every book has a title,author and year.
I would like to choose one option from the list and display chosen property in a table.I've used an example from W3 but right now i'm stuck and nothing works as it should...

Link's here

function change_myselect(sel) {
    var obj, dbParam, xmlhttp, myObj, x, txt = "";
    obj = { "table":sel, "limit":20 };
    dbParam = JSON.stringify(obj);
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            myObj = JSON.parse(this.responseText);
            txt += "
"
            for (x in myObj) {
                txt += "
" + myObj[x].name + "
";
            }
            txt += "
"
            document.getElementById("demo").innerHTML = txt;
        }
    };
    xmlhttp.open("GET", "generated.json", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("x=" + dbParam);
}

Body:
You are iterating over a single property books in an object instead of iterating over the array that property contains.

Instead of this:

for (x in myObj) {
  txt += "<tr><td>" + myObj[x].name + "</td></tr>";
}

try something like this:

myObj.books.forEach((book) => {
  txt += "<tr><td>" + book[sel.toLowerCase()] + "</td></tr>";
});


问:
How do I specify a build entrypoint via command line?
I have a webpack config like this:

```<code>module.exports = [
    {
     name: 'build1',
     entry: './src/mebuild.ts'
     output: {
         filename: 'bundle.js'
     }
    },
    {
     name: 'build2',
     entry: './src/mebuild2.ts'
     output: {
         filename: 'bundle2.js'
     }
    }
]
</code>```

When I run webpack the project builds fine. However, it builds both entrypoints and copies both built bundle files to the output folder. Is there a way I can specify a specific one at build time? Something like this would be ideal:

```<code>webpack --name build1
</code>```

But the docs dont have any information on this. Any advice?

答:
It's possible for webpack.config.js to export a function that you can pass parameters into from the command line.

Passing parameters from the command line:

```<code>webpack --env.name=build1
</code>```

This will pass an object to webpack.config.js:

```<code>{ name: 'build1' }
</code>```

Then in webpack.config.js:

```<code>module.exports = env => {
  const { name } = env;

  return {
    // Rest of config utilizing name
  };
};
</code>```

This process was described by Sean Larkin in the Web Fundamentals course he created on https://webpack.academy. You need to create an account to view it, but it's all free.

Body:
I have a webpack config like this:

module.exports = [
    {
     name: 'build1',
     entry: './src/mebuild.ts'
     output: {
         filename: 'bundle.js'
     }
    },
    {
     name: 'build2',
     entry: './src/mebuild2.ts'
     output: {
         filename: 'bundle2.js'
     }
    }
]

When I run webpack the project builds fine. However, it builds both entrypoints and copies both built bundle files to the output folder. Is there a way I can specify a specific one at build time? Something like this would be ideal:

webpack --name build1

But the docs dont have any information on this. Any advice?

Body:
It's possible for webpack.config.js to export a function that you can pass parameters into from the command line.

Passing parameters from the command line:

webpack --env.name=build1

This will pass an object to webpack.config.js:

{ name: 'build1' }

Then in webpack.config.js:

module.exports = env => {
  const { name } = env;

  return {
    // Rest of config utilizing name
  };
};

This process was described by Sean Larkin in the Web Fundamentals course he created on https://webpack.academy. You need to create an account to view it, but it's all free.


问:
PHP PDO statement will NOT submit information to database
I have literally been working on this for hours. And I have absolutely 0 clue why it will not send my information to my database... I have used the same tactic before and it has worked brilliantly. Now it will not INSERT no matter what. Please help!

```<code>if ($validForm) {

    try {
        $stmt = $conn->prepare('INSERT INTO credentials (firstname, lastname, username, password) VALUES (:fname, :lname, :username, :password)');
        $stmt->bindValue(':fname',$firstname);
        $stmt->bindValue(':lname',$lastname);
        $stmt->bindValue(':username',$username);
        $stmt->bindValue(':password',$password);
        $passwordHash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
        $stmt->bindValue(':password',$passwordHash);
        $stmt->execute();
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
?>

<p class="success-message">Thank You. Your Form Has Been Submitted.</p>

<?php
}
</code>```

答:
What datatype, collation and length is your password column set to?

In your screenshot all the passwords are short text strings, but if I apply your hash code to the first password the result is:

$2y$12$S7tIbSxqNNhn/Z7AyA8ewuq09IE/psFyVL5udLUNgmP4Q7vTd/qFO

Is your table going to accept that?

Body:
I have literally been working on this for hours. And I have absolutely 0 clue why it will not send my information to my database... I have used the same tactic before and it has worked brilliantly. Now it will not INSERT no matter what. Please help!

if ($validForm) {

    try {
        $stmt = $conn->prepare('INSERT INTO credentials (firstname, lastname, username, password) VALUES (:fname, :lname, :username, :password)');
        $stmt->bindValue(':fname',$firstname);
        $stmt->bindValue(':lname',$lastname);
        $stmt->bindValue(':username',$username);
        $stmt->bindValue(':password',$password);
        $passwordHash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
        $stmt->bindValue(':password',$passwordHash);
        $stmt->execute();
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
?>

Thank You. Your Form Has Been Submitted.

<?php
}


问:
wordpress -override number of posts in loop
See: http://jasondaydesign.com/portfolio

Also, for this custom loop, how would I override the number of posts as set by WP Settings > Reading > show 10 posts.

thanks!

```<code><?php
/*
Template Name: Portfolio
*/
?>

<?php get_header(); ?>

<ul id="portfolio-filter">
  <li><a href="#all">All</a></li>
  <li><a href="#web-design">Web</a></li>
  <li><a href="#logo-and-branding-design">Logo</a></li>
  <li><a href="#print-and-graphic-design">Print</a></li>
  <li><a href="#sculpture">Sculpture </a></li>
  <li><a href="#for-sale">For Sale </a></li>
 </ul>

        <ul id="portfolio-list">
        <?php query_posts('cat=5&showposts='); ?>
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<!-- ** store the category slugs for each post in a variable $catSlug ** -->
  <li class="<?php foreach((get_the_category()) as $category ) { echo $category->category_nicename . ' '; } ?>all">

 <!-- ** This is my own plugin to get the thumbnail from the post - you may use some custom field you have to get the image. ** -->
                    <a href='<?php the_permalink() ?>' title='<?php the_title(); ?>'><img src='<?php woo_image('width='.$woo_options['woo_thumb_w'].'&height='.$woo_options['woo_thumb_h'].'&class=thumbnail '.$woo_options['woo_thumb_align']); ?>' alt='<?php the_title(); ?>' /></a>

                    <p><?php the_title(); ?></p>
     <p><?php the_excerpt(); ?></p>

                </li>
            <? endwhile; ?>
        <? endif; ?>
  <?php wp_reset_query(); ?>
        </ul>

<?php get_footer(); ?>
</code>```

答:
```<code><?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
</code>```

Becomes this:

```<code><?php $i = 0; ?>
<?php if ( have_posts() ) : while ( have_posts() && $i < 10 ) : the_post(); ?>
<?php $i++; ?>
</code>```

Replace the number 10 with whatever number, that being how many times the loop should run.

Body:
See: http://jasondaydesign.com/portfolio

Also, for this custom loop, how would I override the number of posts as set by WP Settings > Reading > show 10 posts.

thanks!

<?php
/*
Template Name: Portfolio
*/
?>

<?php get_header(); ?>

All

Web

Logo

Print

Sculpture

For Sale

        <?php query_posts('cat=5&showposts='); ?>
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

  <li class="<?php foreach((get_the_category()) as $category ) { echo $category->category_nicename . ' '; } ?>all">

                    <a href='<?php the_permalink() ?>' title='<?php the_title(); ?>'><img src='<?php woo_image('width='.$woo_options['woo_thumb_w'].'&height='.$woo_options['woo_thumb_h'].'&class=thumbnail '.$woo_options['woo_thumb_align']); ?>' alt='<?php the_title(); ?>' />

<?php the_title(); ?>

<?php the_excerpt(); ?>

            <? endwhile; ?>
        <? endif; ?>
  <?php wp_reset_query(); ?>

<?php get_footer(); ?>

Body:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

Becomes this:

<?php $i = 0; ?>
<?php if ( have_posts() ) : while ( have_posts() && $i < 10 ) : the_post(); ?>
<?php $i++; ?>

Replace the number 10 with whatever number, that being how many times the loop should run.


问:
Matrix multiplication - How to make a planet spin on it's own axis, and orbit it's parent?
I've got two planets, the sun and the earth. I want them to spin on their own axis, and orbit the planet at the same time.

I can get these two behaviors to work individually, but I'm stumped as to how to combine them.

```<code>void planet::render() {
    mat4 axisPos = mat4(1.0f);
    axialRotation = rotate(axisPos, axisRotationSpeedConstant, vec3(0.0f, 1.0f, 0.0f));

    if (hostPlanet != NULL) {
        mat4 hostTransformPosition = mat4(1.0f);
        hostTransformPosition[3] = hostPlanet->getTransform()[3];
        orbitalSpeed += orbitalSpeedConstant;

        orbitRotation = rotate(hostTransformPosition, orbitalSpeed, vec3(0.0f, 1.0f, 0.0f));
        orbitRotation = translate(orbitRotation, vec3(distanceFromParent, 0.0f, 0.0f));

        //rotTransform will make them spin on their axis, but not orbit their parent planet
        mat4 rotTransform = transform * axialRotation;

        //transform *= rotTransform;

        //orbitRotation will make the planet orbit, but it won't spin on it's own axis.
        transform = orbitRotation;
    }
    else {
        transform *= axialRotation;
    }

    glUniform4fv(gColLoc, 1, &color[0]);
    glUniformMatrix4fv(gModelToWorldTransformLoc, 1, GL_FALSE, &getTransform()[0][0]);
    glDrawArrays(GL_LINES, 0, NUMVERTS);
};
</code>```

答:
Woohoo! As usual, asking the question lead me to being able to answer it. After the last line, knowing that transform[0 to 2] represents the rotation in the 4x4 matrix (with transform[3] representing the position in 3D space), I thought to replace the rotation from the previous matrix calculation with the current one.
Badabing, I got my answer.

```<code>    transform = orbitRotation;
    transform[0] = rotTransform[0];
    transform[1] = rotTransform[1];
    transform[2] = rotTransform[2];
</code>```

Body:
I've got two planets, the sun and the earth. I want them to spin on their own axis, and orbit the planet at the same time.

I can get these two behaviors to work individually, but I'm stumped as to how to combine them.

void planet::render() {
    mat4 axisPos = mat4(1.0f);
    axialRotation = rotate(axisPos, axisRotationSpeedConstant, vec3(0.0f, 1.0f, 0.0f));

    if (hostPlanet != NULL) {
        mat4 hostTransformPosition = mat4(1.0f);
        hostTransformPosition[3] = hostPlanet->getTransform()[3];
        orbitalSpeed += orbitalSpeedConstant;

        orbitRotation = rotate(hostTransformPosition, orbitalSpeed, vec3(0.0f, 1.0f, 0.0f));
        orbitRotation = translate(orbitRotation, vec3(distanceFromParent, 0.0f, 0.0f));

        //rotTransform will make them spin on their axis, but not orbit their parent planet
        mat4 rotTransform = transform * axialRotation;

        //transform *= rotTransform;

        //orbitRotation will make the planet orbit, but it won't spin on it's own axis.
        transform = orbitRotation;
    }
    else {
        transform *= axialRotation;
    }

    glUniform4fv(gColLoc, 1, &color[0]);
    glUniformMatrix4fv(gModelToWorldTransformLoc, 1, GL_FALSE, &getTransform()[0][0]);
    glDrawArrays(GL_LINES, 0, NUMVERTS);
};

Body:
Woohoo! As usual, asking the question lead me to being able to answer it. After the last line, knowing that transform[0 to 2] represents the rotation in the 4x4 matrix (with transform[3] representing the position in 3D space), I thought to replace the rotation from the previous matrix calculation with the current one.
Badabing, I got my answer.

    transform = orbitRotation;
    transform[0] = rotTransform[0];
    transform[1] = rotTransform[1];
    transform[2] = rotTransform[2];