问:
MethodReturnObject: Antipattern? How to refactor it?
In a project that I joined recently we have a class that looks like this:

```<code>class MethodReturn {
  public int    status    = C_OK
  public string message   = ""
  public string str_value = ""
  public int    int_value = 0
  public double dbl_value = 0
  // and some more

  // also some methods that set/get these values
}
</code>```

This class is used almost everywhere as a return type. So method signatures look like this:

```<code>public MethodReturn doSomething( int input, int output )
</code>```

And the calling code looks like this:

```<code>returnObj = doSomething( input, output )
if( returnObj.status != C_OK ) return returnObj

returnObj2 = doSomethingElse( input2, output2)
if( returnObj2.status != C_OK ) return returnObj2
</code>```

The MethodReturn object is claimed to be "genius", but to me it looks like an antipattern, since it hides the actual functionality of the code and adds a lot of overhead to the code, that could be handled much better by Exceptions.
Also I consider the manipulation of an Argument as a side effect that SHOULD be avoided.

Unfortunately those MethodReturn objects are given to the GUI to display the result of an operation or show a message when an error occurs.

So, is there an actual name for this "pattern"? Is it just a code smell that you could live with, as long as you stay consistent with it? Or should I try to refactor that object out of the project to avoid heavy problems in the future? Which specific problems could be named that relate to this pattern?

PS: The code above pseudo code, we actually code in VB.NET.

答:
First of all I should say that this question is largely opinion based and you should not expect to get a definitive answer. Having said that, here is my opinion.

Error codes vs Exceptions

Neither error-code-based nor exception-based approach is perfect. And this is the reason why even today some high-level languages still don't have exceptions (see Go for a fresh example). Personally I tend to agree with Raymond Chen's article "Cleaner, more elegant, and harder to recognize" that if proper error handling of all errors is of utmost importance, it is easier to write correct error-code handling than correct exception-based code. There is also an article with similar argument by ZeroMQ author "Why should I have written ZeroMQ in C, not C++ (part I)". AFAIU the main point of both articles is that when you use error-codes-based approach, usually it is easier to see when a piece of code doesn't handle errors properly because of better locality of error-handling code. With exceptions you often can't see if some method call can raise an exception but it is not handled (without analyzing the code of the whole call hierarchy). Actually this is why "checked exceptions" were added to Java but it achieved only a limited success because of various design limitations.

However error-codes are not free and one side of the price you pay is that you typically should write more code. In many business applications 100% correct error handling is not that important and it is often much easier to get "good enough" code using exceptions. This is why many business applications are written using exception-based languages and frameworks.

Generally to me this is similar to garbage collector vs manual memory management decision. In some contexts you really should use error codes or manual memory management but for the most of the use cases exceptions and GC are good enough.

Particular code

Even though I consider Error codes vs Exceptions to be an open question and a design decision that should be made basing on particular project context and goals, I really don't like the code you've shown in your question. The thing that I really don't like is that there is single MethodReturn that contains all possible return types. This is a bad thing because it hides from the developer the real method return type.

If I wanted to use error-codes in .Net, my first idea would be to use "out parameters" in a way similar to what standard Double.TryParse do. Obviosuly you can use some more complicated return type than just plain Boolean to return more details about error (such as error code + message). Again this approach has some pro and cons. The biggest con to me is that VB.NET unlike C# doesn't explicitly support out (only ByRef which is two-sided) so it also might confuse developer about what's really going on.

My second approach would be to use generic wrapper class similar to the one you've shown to encapsulate all error-related things but not the return value. Something like this (I'll use C# as I'm much more familiar with it):

class MethodReturn<TValue> {
  private readonly int    _status;
  private readonly string _errorMessage;
  private readonly TValue _successValue;

  private MethodReturn(int status, string errorMessage, TValue successValue) {
        _status = status;
        _errorMessage = errorMessage;
        _successValue = successValue;
  }

  public static MethodReturn<TValue> Success(TValue successValue)  {
      return new MethodReturn(C_OK, null, successValue);
  }

  public static MethodReturn<TValue> Failure(int status, string errorMessage)  {
      return new MethodReturn(status, errorMessage, default(TValue));
  }

  public int Status { get { return _status; } }
  public string ErrorMessage { get { return _errorMessage; } }
  public int SuccessValue { get { return _successValue; } }

  public bool IsSuccess {
      get {
          return _status == C_OK;
      }
  }
}
```

If I wanted to be more pedantic, I might also raise an exception if SuccessValue is accessed when IsSuccess is false and if ErrorMessage is accessed when IsSuccess is true but this might also become a source of a lot of false positives.

And if you want to go functional, you may notice that this class is actually almost a Monad similar to Scala Try which is a special case of Either monad defined in Scala and Haskell or similar Result from Chessie F# library. So you can extend this class with map and flatMap and use them to do some monad composition but I suspect that in VB.NET syntax that would look ugly.

It might make sense to switch from simpler Try to more generic Either if you have only a few different contexts with distinct error codes lists that you want to encode in the type system and thus make error handling code safer (see this F#/Result article for an example).

Body:
In a project that I joined recently we have a class that looks like this:

class MethodReturn {
  public int    status    = C_OK
  public string message   = ""
  public string str_value = ""
  public int    int_value = 0
  public double dbl_value = 0
  // and some more

  // also some methods that set/get these values
}

This class is used almost everywhere as a return type. So method signatures look like this:

public MethodReturn doSomething( int input, int output )

And the calling code looks like this:

returnObj = doSomething( input, output )
if( returnObj.status != C_OK ) return returnObj

returnObj2 = doSomethingElse( input2, output2)
if( returnObj2.status != C_OK ) return returnObj2

The MethodReturn object is claimed to be "genius", but to me it looks like an antipattern, since it hides the actual functionality of the code and adds a lot of overhead to the code, that could be handled much better by Exceptions.
Also I consider the manipulation of an Argument as a side effect that SHOULD be avoided.

Unfortunately those MethodReturn objects are given to the GUI to display the result of an operation or show a message when an error occurs.

So, is there an actual name for this "pattern"? Is it just a code smell that you could live with, as long as you stay consistent with it? Or should I try to refactor that object out of the project to avoid heavy problems in the future? Which specific problems could be named that relate to this pattern?

PS: The code above pseudo code, we actually code in VB.NET.

Body:
First of all I should say that this question is largely opinion based and you should not expect to get a definitive answer. Having said that, here is my opinion.

Error codes vs Exceptions

Neither error-code-based nor exception-based approach is perfect. And this is the reason why even today some high-level languages still don't have exceptions (see Go for a fresh example). Personally I tend to agree with Raymond Chen's article "Cleaner, more elegant, and harder to recognize" that if proper error handling of all errors is of utmost importance, it is easier to write correct error-code handling than correct exception-based code. There is also an article with similar argument by ZeroMQ author "Why should I have written ZeroMQ in C, not C++ (part I)". AFAIU the main point of both articles is that when you use error-codes-based approach, usually it is easier to see when a piece of code doesn't handle errors properly because of better locality of error-handling code. With exceptions you often can't see if some method call can raise an exception but it is not handled (without analyzing the code of the whole call hierarchy). Actually this is why "checked exceptions" were added to Java but it achieved only a limited success because of various design limitations.

However error-codes are not free and one side of the price you pay is that you typically should write more code. In many business applications 100% correct error handling is not that important and it is often much easier to get "good enough" code using exceptions. This is why many business applications are written using exception-based languages and frameworks.

Generally to me this is similar to garbage collector vs manual memory management decision. In some contexts you really should use error codes or manual memory management but for the most of the use cases exceptions and GC are good enough.

Particular code

Even though I consider Error codes vs Exceptions to be an open question and a design decision that should be made basing on particular project context and goals, I really don't like the code you've shown in your question. The thing that I really don't like is that there is single MethodReturn that contains all possible return types. This is a bad thing because it hides from the developer the real method return type.

If I wanted to use error-codes in .Net, my first idea would be to use "out parameters" in a way similar to what standard Double.TryParse do. Obviosuly you can use some more complicated return type than just plain Boolean to return more details about error (such as error code + message). Again this approach has some pro and cons. The biggest con to me is that VB.NET unlike C# doesn't explicitly support out (only ByRef which is two-sided) so it also might confuse developer about what's really going on.

My second approach would be to use generic wrapper class similar to the one you've shown to encapsulate all error-related things but not the return value. Something like this (I'll use C# as I'm much more familiar with it):

class MethodReturn<TValue> {
  private readonly int    _status;
  private readonly string _errorMessage;
  private readonly TValue _successValue;

  private MethodReturn(int status, string errorMessage, TValue successValue) {
        _status = status;
        _errorMessage = errorMessage;
        _successValue = successValue;
  }

  public static MethodReturn<TValue> Success(TValue successValue)  {
      return new MethodReturn(C_OK, null, successValue);
  }

  public static MethodReturn<TValue> Failure(int status, string errorMessage)  {
      return new MethodReturn(status, errorMessage, default(TValue));
  }

  public int Status { get { return _status; } }
  public string ErrorMessage { get { return _errorMessage; } }
  public int SuccessValue { get { return _successValue; } }

  public bool IsSuccess {
      get {
          return _status == C_OK;
      }
  }
}

If I wanted to be more pedantic, I might also raise an exception if SuccessValue is accessed when IsSuccess is false and if ErrorMessage is accessed when IsSuccess is true but this might also become a source of a lot of false positives.

And if you want to go functional, you may notice that this class is actually almost a Monad similar to Scala Try which is a special case of Either monad defined in Scala and Haskell or similar Result from Chessie F# library. So you can extend this class with map and flatMap and use them to do some monad composition but I suspect that in VB.NET syntax that would look ugly.

It might make sense to switch from simpler Try to more generic Either if you have only a few different contexts with distinct error codes lists that you want to encode in the type system and thus make error handling code safer (see this F#/Result article for an example).


来源: stackexchange

问:
clean up the header of csv files with awk
I have a bunch of csv files that look like this:

```<code>Time,Channel A
(s),(V)

0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560
</code>```

And I want to transform it to:

```<code>Time (s),Channel A (V)
0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560
</code>```

The units are not necessarily identical across files (i.e. there might be (ms),(µV) etc.)

I got as far as removing the blank line (which is always line no. 3) with awk 'FNR!=3' but cutting the 2nd row arguments and pasting them behind the first row fields is beyond my capacity ;(

Please help me out!
Motivation: there are lots of these files. Doing it by hand is not feasible…

EDIT:
First of all: thanks for helping me out. As there seems to be the same issue with 2 of your answers, there might be a problem in my file potentially? I suspect the empty line to somehow cause trouble?

the shell-script gives me the error 'xpected empty line, read '

the perl-script and the awk-script give me a faulty first line:

```<code> (V) (s),Channel A
0.00000000,0.58058560
</code>```

If it helps, I uploaded a sample infile.

ContentLicense: CC BY-SA 3.0

Body:
I have a bunch of csv files that look like this:

Time,Channel A
(s),(V)

0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560

And I want to transform it to:

Time (s),Channel A (V)
0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560

The units are not necessarily identical across files (i.e. there might be (ms),(µV) etc.)

I got as far as removing the blank line (which is always line no. 3) with awk 'FNR!=3' but cutting the 2nd row arguments and pasting them behind the first row fields is beyond my capacity ;(

Please help me out!
Motivation: there are lots of these files. Doing it by hand is not feasible…

EDIT:
First of all: thanks for helping me out. As there seems to be the same issue with 2 of your answers, there might be a problem in my file potentially? I suspect the empty line to somehow cause trouble?

the shell-script gives me the error 'xpected empty line, read '

the perl-script and the awk-script give me a faulty first line:

 (V) (s),Channel A
0.00000000,0.58058560

If it helps, I uploaded a sample infile.

Body:
You can do:

awk 'BEGIN{
           FS=OFS=","
           }
     FNR==1{
           for(i=1;i<=NF;i++) l1[i]=$i
           }
     FNR==2{
           for (i=1;i<=NF;i++) l2[i]=$i
           }
     FNR==3{
           s=""
           for (i=1;i in l1 || i in l2; i++)
               s=s ? s OFS l1[i] " " l2[i] : s l1[i] " " l2[i]
           print s
           }
     FNR<=3{ next }
     1' file

Prints:

Time (s),Channel A (V)
0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560


问:
Where does finite-state machine code belong in µC?
I asked this question on EE forum. You guys on StackOverflow know more about coding than we do on EE so maybe you can give more detail information about this :)

When I learned about micrcontrollers, teachers taught me to always end the code with  while(1); with no code inside that loop.

This was to be sure that the software get "stuck" to keep interruption working. When I asked them if it was possible to put some code in this infinite loop, they told me it was a bad idea. Knowing that, I now try my best to keep this loop empty.

I now need to implement a finite state machine in a microcontroller. At first view, it seems that that code belong in this loop. That makes coding easier.

Is that a good idea? What are the pros and cons?

This is what I plan to do :

```<code>void main(void)
{
    // init phase

 while(1)
 {
    switch(current_State)
    {
    case 1:
        if(...)
        {
            current_State = 2;
        }
        else(...)
        {
            current_State = 3;
        }
        else
            current_State = 4;
        break;

    case 2:
        if(...)
        {
            current_State = 3;
        }
        else(...)
        {
            current_State = 1;
        }
        else
            current_State = 5;
        break;
   }
}
</code>```

Instead of:

```<code> void main(void)
    {
        // init phase

     while(1);
    }
</code>```

And manage the FSM with interrupt

答:
It belongs in one thread that executes it in response to input messages from a producer-consumer queue.  All the interrupts etc. fire input to the queue and the thread processes them through its FSM serially.

It's the only way I've found to avoid undebuggable messes whilst retaining the low latencty and efficient CPU use of interrupt-driven I/O.

'while(1);' UGH!

Body:
I asked this question on EE forum. You guys on StackOverflow know more about coding than we do on EE so maybe you can give more detail information about this :)

When I learned about micrcontrollers, teachers taught me to always end the code with  while(1); with no code inside that loop.

This was to be sure that the software get "stuck" to keep interruption working. When I asked them if it was possible to put some code in this infinite loop, they told me it was a bad idea. Knowing that, I now try my best to keep this loop empty.

I now need to implement a finite state machine in a microcontroller. At first view, it seems that that code belong in this loop. That makes coding easier.

Is that a good idea? What are the pros and cons?

This is what I plan to do :

void main(void)
{
    // init phase

 while(1)
 {
    switch(current_State)
    {
    case 1:
        if(...)
        {
            current_State = 2;
        }
        else(...)
        {
            current_State = 3;
        }
        else
            current_State = 4;
        break;

    case 2:
        if(...)
        {
            current_State = 3;
        }
        else(...)
        {
            current_State = 1;
        }
        else
            current_State = 5;
        break;
   }
}

Instead of:

 void main(void)
    {
        // init phase

     while(1);
    }

And manage the FSM with interrupt


问:
Visual Studio Code Now Horizontally splits the window
I have been using Microsoft Visual Studio Code to write my Python code for awhile and have generally been pleased with it.  But sometimes it does 'strange' things.  Like now,  I tried to open the current window in split mode.  It did, but instead of splitting it vertically as it always does, it did so horizontally.  Any idea on how to open it split vertically as before?

I am using the most current version of the VSCode and have the VIM plugin installed which works great.

答:
Apologies for hasty posting.  Upon doing more google search, I came across the following post in StackOverflow:
how to toogle horizontal or vertical split

This answers my question fully.  You may delete this or mark it as duplicate.


问:
Creating lists of variable length from one list
I want to create a number of lists from a single list.  The lists will either have 1 value or 3 based on if there is data from a user.  However, since the data is attached to a specific user, the order must be maintained.

For example:

```<code>data = ['no data', 'choice 1', 'choice 4', 'choice 2', 'no data', 'choice 1', ...etc]
</code>```

I want the output to be:

```<code>list1 = ['no data']
list2 = ['choice 1', 'choice4', 'choice 2']
list3 = ['no data']
list4 = ['choice 1'...]
</code>```

How would I achieve this?

答:
Unfortunately, itertools.groupby won't work if you need to chunk runs of non-'no-data' into groups of 3, or as singltons for each individual 'no-data'. So, here's a something else thrown together:

```<code>In [40]: def group_lists(data):
    ...:     final = []
    ...:     contains_data = False
    ...:     temp = []
    ...:     for sub in data:
    ...:         if sub == 'no data':
    ...:             if contains_data:
    ...:                 final.append(temp)
    ...:                 temp = []
    ...:                 final.append([sub])
    ...:                 contains_data = False
    ...:             else:
    ...:                 final.append([sub])
    ...:         else:
    ...:             contains_data = True
    ...:             if len(temp) < 3:
    ...:                 temp.append(sub)
    ...:             else:
    ...:                 final.append(temp)
    ...:                 temp = []
    ...:                 contains_data = False
    ...:     return final
    ...:

In [41]: data = ['choice 1', 'choice 2', 'choice 1', 'choice 1', 'choice 4', 'choice 1', 'no data']

In [42]: group_lists(data)
Out[42]: [['choice 1', 'choice 2', 'choice 1'], ['choice 4', 'choice 1'], ['no data']]

In [43]: data2 = ['choice 1', 'choice 2', 'choice 1', 'choice 1', 'choice 4', 'choice 1', 'choice1', 'no data']

In [44]: group_lists(data2)
Out[44]:
[['choice 1', 'choice 2', 'choice 1'],
 ['choice 4', 'choice 1', 'choice1'],
 ['no data']]
</code>```

Original Answer

Use itertools.groupby:

```<code>In [15]: data = ['no data', 'choice 1', 'choice 4', 'choice 2', 'no data', 'choice 1']
    ...:

In [16]: import itertools

In [17]: grouped = [list(g) for _, g in itertools.groupby(data, lambda s: s == 'no data')]

In [18]: grouped[0]
Out[18]: ['no data']

In [19]: grouped[1]
Out[19]: ['choice 1', 'choice 4', 'choice 2']

In [20]: grouped[2]
Out[20]: ['no data']

In [21]: grouped[3]
Out[21]: ['choice 1']
</code>```

Unpacking that rather unwieldy one-liner:

```<code>In [26]: lists = []
    ...: for _, g in itertools.groupby(data, lambda s: s == 'no data'):
    ...:     lists.append(list(g))
    ...:

In [27]: lists[0]
Out[27]: ['no data']

In [28]: lists[1]
Out[28]: ['choice 1', 'choice 4', 'choice 2']

In [29]: lists[2]
Out[29]: ['no data']

In [30]: lists[3]
Out[30]: ['choice 1']
</code>```

So, the result is a lists of lists:

```<code>In [32]: lists
Out[32]: [['no data'], ['choice 1', 'choice 4', 'choice 2'], ['no data'], ['choice 1']]
</code>```

Body:
I want to create a number of lists from a single list.  The lists will either have 1 value or 3 based on if there is data from a user.  However, since the data is attached to a specific user, the order must be maintained.

For example:

data = ['no data', 'choice 1', 'choice 4', 'choice 2', 'no data', 'choice 1', ...etc]

I want the output to be:

list1 = ['no data']
list2 = ['choice 1', 'choice4', 'choice 2']
list3 = ['no data']
list4 = ['choice 1'...]

How would I achieve this?

Body:
Unfortunately, itertools.groupby won't work if you need to chunk runs of non-'no-data' into groups of 3, or as singltons for each individual 'no-data'. So, here's a something else thrown together:

In [40]: def group_lists(data):
    ...:     final = []
    ...:     contains_data = False
    ...:     temp = []
    ...:     for sub in data:
    ...:         if sub == 'no data':
    ...:             if contains_data:
    ...:                 final.append(temp)
    ...:                 temp = []
    ...:                 final.append([sub])
    ...:                 contains_data = False
    ...:             else:
    ...:                 final.append([sub])
    ...:         else:
    ...:             contains_data = True
    ...:             if len(temp) < 3:
    ...:                 temp.append(sub)
    ...:             else:
    ...:                 final.append(temp)
    ...:                 temp = []
    ...:                 contains_data = False
    ...:     return final
    ...:

In [41]: data = ['choice 1', 'choice 2', 'choice 1', 'choice 1', 'choice 4', 'choice 1', 'no data']

In [42]: group_lists(data)
Out[42]: [['choice 1', 'choice 2', 'choice 1'], ['choice 4', 'choice 1'], ['no data']]

In [43]: data2 = ['choice 1', 'choice 2', 'choice 1', 'choice 1', 'choice 4', 'choice 1', 'choice1', 'no data']

In [44]: group_lists(data2)
Out[44]:
[['choice 1', 'choice 2', 'choice 1'],
 ['choice 4', 'choice 1', 'choice1'],
 ['no data']]

Original Answer

Use itertools.groupby:

In [15]: data = ['no data', 'choice 1', 'choice 4', 'choice 2', 'no data', 'choice 1']
    ...:

In [16]: import itertools

In [17]: grouped = [list(g) for _, g in itertools.groupby(data, lambda s: s == 'no data')]

In [18]: grouped[0]
Out[18]: ['no data']

In [19]: grouped[1]
Out[19]: ['choice 1', 'choice 4', 'choice 2']

In [20]: grouped[2]
Out[20]: ['no data']

In [21]: grouped[3]
Out[21]: ['choice 1']

Unpacking that rather unwieldy one-liner:

In [26]: lists = []
    ...: for _, g in itertools.groupby(data, lambda s: s == 'no data'):
    ...:     lists.append(list(g))
    ...:

In [27]: lists[0]
Out[27]: ['no data']

In [28]: lists[1]
Out[28]: ['choice 1', 'choice 4', 'choice 2']

In [29]: lists[2]
Out[29]: ['no data']

In [30]: lists[3]
Out[30]: ['choice 1']

So, the result is a lists of lists:

In [32]: lists
Out[32]: [['no data'], ['choice 1', 'choice 4', 'choice 2'], ['no data'], ['choice 1']]


问:
asp.net MVC - Is there a way to set a TimeSpan's max range in it's editor in a view?
I want to set a max TimeSpan range so that only 8AM - 8PM can be selected.

I'm using razor, so my html looks like this:

```<code>@Html.EditorFor(model => model.BookingEndTime, new { htmlAttributes = new { @class = "form-control" } })
</code>```

Which renders as

Is it possible to just set the Html.EditorFor so that it can only go up to 8 instead of 12? Otherwise, will I have to use the [Range] data annotation?

答:
Set the input type and ranges in the html attributes

```<code>type="time" min="08:00:00" max="20:00:00"
</code>```

Do note that not all browsers respect these attributes.

Reference: https://www.w3.org/wiki/HTML/Elements/input/time

For Razor

```<code>@Html.EditorFor(model => model.BookingEndTime, new { htmlAttributes = new { @class = "form-control", type = "time", min = "08:00:00", max = "20:00:00"} })
</code>```

Body:
I want to set a max TimeSpan range so that only 8AM - 8PM can be selected.

I'm using razor, so my html looks like this:

@Html.EditorFor(model => model.BookingEndTime, new { htmlAttributes = new { @class = "form-control" } })

Which renders as

Is it possible to just set the Html.EditorFor so that it can only go up to 8 instead of 12? Otherwise, will I have to use the [Range] data annotation?

Body:
Set the input type and ranges in the html attributes

type="time" min="08:00:00" max="20:00:00"

Do note that not all browsers respect these attributes.

Reference: https://www.w3.org/wiki/HTML/Elements/input/time

For Razor

@Html.EditorFor(model => model.BookingEndTime, new { htmlAttributes = new { @class = "form-control", type = "time", min = "08:00:00", max = "20:00:00"} })


问:
Jest error: Test suite failed to run, how to solve?
I am testing Jest for reactjs and particularly the snapshottesting. This is my test:

```<code>import React, { Component } from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import Hello from 'hello';

test('if am then return goodmorning', () => {

    const wrapper = shallow(
        <Hello timeofday="am">
            <strong>Hello World!</strong>
        </Hello>
    );

    expect(toJson(wrapper)).toMatchSnapshot();

});
</code>```

The component I am testing:

```<code>import React from 'react';

export default class Hello extends React.Component {

    constructor(props) {
        super();
        this.props = props;
        //todo remove
        console.log('testing props', props);
    }

    render() {
        let greet ;

        if (this.props) {
            greet= this.props.timeofday ==='am' ? 'morning' : 'evening'
        }
        return <h1>Good {greet}</h1>
    }
}
</code>```

When I run jest from the commandline I get this error:

```<code>    jest

 FAIL  app/components/hello.test.js
  ● Test suite failed to run

    Cannot find module 'hello' from 'hello.test.js'

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
      at Object.<anonymous> (app/components/hello.test.js:4:14)

Test Suites: 1 failed, 1 total
</code>```

Why can I not run the jest? what is the issue here?

答:
In your test file,

```<code>import Hello from 'hello';
</code>```

should be changed to

```<code>import Hello from './hello';
</code>```

or you can setup the path in webpack config file.

Body:
I am testing Jest for reactjs and particularly the snapshottesting. This is my test:

import React, { Component } from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import Hello from 'hello';

test('if am then return goodmorning', () => {

    const wrapper = shallow(
        <Hello timeofday="am">
            Hello World!
        </Hello>
    );

    expect(toJson(wrapper)).toMatchSnapshot();

});

The component I am testing:

import React from 'react';

export default class Hello extends React.Component {

    constructor(props) {
        super();
        this.props = props;
        //todo remove
        console.log('testing props', props);
    }

    render() {
        let greet ;

        if (this.props) {
            greet= this.props.timeofday ==='am' ? 'morning' : 'evening'
        }
        return
Good {greet}

    }
}

When I run jest from the commandline I get this error:

    jest

 FAIL  app/components/hello.test.js
  ● Test suite failed to run

    Cannot find module 'hello' from 'hello.test.js'

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
      at Object.<anonymous> (app/components/hello.test.js:4:14)

Test Suites: 1 failed, 1 total

Why can I not run the jest? what is the issue here?

Body:
In your test file,

import Hello from 'hello';

should be changed to

import Hello from './hello';

or you can setup the path in webpack config file.


Title: clean up the header of csv files with awk

Body:
You could use perl instead

perl -lpe 'if($.==1){$x=<>;($T,$C)=$x=~/(\([^\)]\))/g;s/[^,]+\K,.*/ $T$& $C/;<>}' file

Time (s),Channel A (V)
0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560

If you have CRLF file, which it looks like you do.

perl -lpe 'chop;if($.==1){$x=<>;($T,$C)=$x=~/(\([^\)]\))/g;s/[^,]+\K,.*/ $T$& $C/;<>}' file


问:
How to Authenticate a Django user from another application
I want to redirect a user from my Django application to another web application. Only permitted users can be allowed access to visit the other web application, this permission is set in the Django User model. I want that other web application to verify whether the visited user has permission by querying the Django application using API endpoint.

But the other web application no longer has the request.user parameter or other way to authenticate the user based on Django User model (don't wan't him to login again). Is there any way like setting a cross-domain session cookie or something, i can achieve it?

答:
I did that recently.

You don't even need the second app to retrieve the users, you can create those users on the fly!

On the first app, have them click a url that will do a very special GET request to the other app.

The GET request will encode a few variables with hmac.  Name, emails, or any other values you need using a particular SECRET_KEY that both server will share.

In the second app, you can decode that request with the same SECRET_KEY and log in your user.

See : https://docs.python.org/3/library/hmac.html


问:
Cast string data type to Int in SQL QUery for MS Access
I am trying to write a query in access that will pull results that are
in the database in a text
Acually,I have RECEIPTNO Column whose datatype is TEXT in Table Membership, & I want to pull all the results from RECEIPTNO column where RECEIPTNO is BETWEEN 1 AND 10

And I tried Below Code.

```<code>SELECT Cint(RECEIPTNO) FROM MEMBERSHIP where Cint(RECEIPTNO) BETWEEN 1 AND 10
</code>```

Result is: Overflow ,
Any Idea?

答:
This gives you what you want. ss

```<code>SELECT RECEIPTNO FROM MEMBERSHIP
WHERE Val(RECEIPTNO & "") BETWEEN 1 AND 10
</code>```

Others using Val(RECEIPTNO) will only TRY to work somehow half-heartedly where it does beacuse the system doesn not recognise the RECEIPTNO as text and so, it is funny to it to see you passing a number instead of a string. However, to convince the system that the format is actually a number, concatenate it with an empty string which I have done.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to write a query in access that will pull results that are
in the database in a text
Acually,I have RECEIPTNO Column whose datatype is TEXT in Table Membership, & I want to pull all the results from RECEIPTNO column where RECEIPTNO is BETWEEN 1 AND 10

And I tried Below Code.

SELECT Cint(RECEIPTNO) FROM MEMBERSHIP where Cint(RECEIPTNO) BETWEEN 1 AND 10

Result is: Overflow ,
Any Idea?

Body:
This gives you what you want. ss

SELECT RECEIPTNO FROM MEMBERSHIP
WHERE Val(RECEIPTNO & "") BETWEEN 1 AND 10

Others using Val(RECEIPTNO) will only TRY to work somehow half-heartedly where it does beacuse the system doesn not recognise the RECEIPTNO as text and so, it is funny to it to see you passing a number instead of a string. However, to convince the system that the format is actually a number, concatenate it with an empty string which I have done.


问:
Displaying Console Ouput in Browser while the Perl Script is still running
Here's very simple program that I am testing on

```<code>#!/usr/bin/perl

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "Script Testing Done\n";
</code>```

Now PHP should output the script output (which is going to console) every maybe 10 seconds or 5 seconds or whenever the php sees the output on the console.

I have hundreds of perl scripts and I cannot go and change those script and direct the output to a file where php/ajax can get the content and output to the browser.

Thanks

答:
Um, back in the old days I'd use CGI with non-parsed headers (NPH... google it) and $|=1 "when you want your pipes to be piping hot".

You're going to have to do something similar with the PHP side.

Body:
Here's very simple program that I am testing on

#!/usr/bin/perl

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "Script Testing Done\n";

Now PHP should output the script output (which is going to console) every maybe 10 seconds or 5 seconds or whenever the php sees the output on the console.

I have hundreds of perl scripts and I cannot go and change those script and direct the output to a file where php/ajax can get the content and output to the browser.

Thanks


问:
Eigen, function of RowXpr
I am using Eigen, and am currently trying to write a function to operate on rows of a matrix. I've followed the guidelines in the docs but nothing I try compiles (with either clang or g++); I'm at my wits end. How should one actually write functions which will take a RowXpr?

For reference, here is what I have tried so far:

```<code>#include <iostream>
#include <Eigen/Core>

using namespace std;
using namespace Eigen;

constexpr Eigen::StorageOptions Order = ColMajor;

using vect_t = Matrix<double, 1, 3, Order>;
using matr_t = Matrix<double, Dynamic, 3, Order>;

#define FUNC 3

#if FUNC == 1

vect_t func(const vect_t& f)
{
    return f;
}

#elif FUNC == 2

vect_t func(const Ref<vect_t>& f)
{
    return f;
}

#elif FUNC == 3

template<class D> vect_t func(const MatrixBase<D>& f)
{
    return f;
}

#endif

int main()
{
    matr_t M = matr_t::Random(5,3);
    cout << M << endl;
    cout << func( M.row(2) ) << endl;

    return 0;
}
</code>```

Thanks!

Edit:

With clang (version 3.8.0-2ubuntu4) the error I get is as below. The error is comparable with g++.

```<code>dan@dan-laptop:~/workspace/scratch$ clang++ eigen_func_test.cpp -I /home/dan/Downloads/eigen_3.3.3/ --std=c++11 && ./a.out
In file included from eigen_func_test.cpp:2:
In file included from /home/dan/Downloads/eigen_3.3.3/Eigen/Core:436:
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/PlainObjectBase.h:899:7: error: static_assert failed
      "INVALID_MATRIX_TEMPLATE_PARAMETERS"
  ...EIGEN_STATIC_ASSERT((EIGEN_IMPLIES(MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1, (Options&RowMajor)==RowMajor)
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/util/StaticAssert.h:32:40: note: expanded from macro
      'EIGEN_STATIC_ASSERT'
    #define EIGEN_STATIC_ASSERT(X,MSG) static_assert(X,#MSG);
                                       ^             ~
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/PlainObjectBase.h:535:7: note: in instantiation of member function
      'Eigen::PlainObjectBase<Eigen::Matrix<double, 1, 3, 0, 1, 3> >::_check_template_params' requested here
      _check_template_params();
      ^
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/Matrix.h:379:9: note: in instantiation of function template
      specialization 'Eigen::PlainObjectBase<Eigen::Matrix<double, 1, 3, 0, 1, 3>
      >::PlainObjectBase<Eigen::Block<Eigen::Matrix<double, -1, 3, 0, -1, 3>, 1, 3, false> >' requested here
      : Base(other.derived())
        ^
eigen_func_test.cpp:32:9: note: in instantiation of function template specialization 'Eigen::Matrix<double, 1, 3, 0,
      1, 3>::Matrix<Eigen::Block<Eigen::Matrix<double, -1, 3, 0, -1, 3>, 1, 3, false> >' requested here
        return f;
               ^
eigen_func_test.cpp:41:10: note: in instantiation of function template specialization
      'func<Eigen::Block<Eigen::Matrix<double, -1, 3, 0, -1, 3>, 1, 3, false> >' requested here
        cout << func( M.row(2) ) << endl;
                ^
1 error generated.
</code>```

答:
Not exactly sure what is causing your compiler error directly but from what you have shown in your source code as well as your compiler errors. This is the part of the compiler error message that I'm basing this off of.

```<code>/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/PlainObjectBase.h:899:7: error: static_assert failed
  "INVALID_MATRIX_TEMPLATE_PARAMETERS"
</code>```

So when looking at the source code you are trying to use the #define func3

that you have declared as such:

```<code>template<class D> vect_t func(const MatrixBase<D>& f) {
    return f;
}
</code>```

with the using directives that you have declared as:

```<code>constexpr Eigen::StorageOptions Order = ColMajor;

using vect_t = Matrix<double, 1, 3, Order>;
using matr_t = Matrix<double, Dynamic, 3, Order>;
</code>```

So let's expand this to the full form to see what the compiler is trying to parse or deduce as your parameters and return type.

```<code>template<class D>
Matrix<double, 1, 3, constexpr Eigen::StorageOptions Order = ColMajor>
func( const MatrixBase<D>& f ) {
    return f;
}
</code>```

Then in your main you use this with:

```<code>int main() {
    // matr_t M = matr_t::Random(5,3);
    Matrix<double, Dynamic, 3, constexpr Eigen::StorageOptions Order = ColMajor> M
      = Matrix<double, Dynamic, 3, constexpr Eigen::StorageOptions Order = ColMajor>::Random(5, 3);

    // Then you call your function passing it this:
    std::cout << func( M.row(2) ) << std::endl;

    return 0;
}
</code>```

func() is returning Matrix<double, 1, 3, Order>;
and it takes const MatrixBase<D>&
however it appears you are passing it: M.row(2)
that is constructed from: Matrix<double, Dynamic, 3, constexpr Eigen::StorageOptions Order = ColMajor>::Random(5, 3)

In the function itself you are returning f which happens to be
the function's const ref of MatrixBase<D> parameter yet the declaration is expecting to return a Matrix<double, 1, 3, Order>

So I think the compiler is having a hard time trying to convert a
Matrix<double, Dynamic, 3, Order> to a Matrix<double, 1, 3, Order>

Maybe this will help you to understand the compiler error a little better; as you can see when you look at the rest of the compilation error message you can tell that this is evident when it is trying to do the specializations of this template.

Title: Eigen, function of RowXpr

Body:
I am using Eigen, and am currently trying to write a function to operate on rows of a matrix. I've followed the guidelines in the docs but nothing I try compiles (with either clang or g++); I'm at my wits end. How should one actually write functions which will take a RowXpr?

For reference, here is what I have tried so far:

#include <iostream>
#include <Eigen/Core>

using namespace std;
using namespace Eigen;

constexpr Eigen::StorageOptions Order = ColMajor;

using vect_t = Matrix<double, 1, 3, Order>;
using matr_t = Matrix<double, Dynamic, 3, Order>;

#define FUNC 3

#if FUNC == 1

vect_t func(const vect_t& f)
{
    return f;
}

#elif FUNC == 2

vect_t func(const Ref<vect_t>& f)
{
    return f;
}

#elif FUNC == 3

template<class D> vect_t func(const MatrixBase<D>& f)
{
    return f;
}

#endif

int main()
{
    matr_t M = matr_t::Random(5,3);
    cout << M << endl;
    cout << func( M.row(2) ) << endl;

    return 0;
}

Thanks!

Edit:

With clang (version 3.8.0-2ubuntu4) the error I get is as below. The error is comparable with g++.

dan@dan-laptop:~/workspace/scratch$ clang++ eigen_func_test.cpp -I /home/dan/Downloads/eigen_3.3.3/ --std=c++11 && ./a.out
In file included from eigen_func_test.cpp:2:
In file included from /home/dan/Downloads/eigen_3.3.3/Eigen/Core:436:
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/PlainObjectBase.h:899:7: error: static_assert failed
      "INVALID_MATRIX_TEMPLATE_PARAMETERS"
  ...EIGEN_STATIC_ASSERT((EIGEN_IMPLIES(MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1, (Options&RowMajor)==RowMajor)
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/util/StaticAssert.h:32:40: note: expanded from macro
      'EIGEN_STATIC_ASSERT'
    #define EIGEN_STATIC_ASSERT(X,MSG) static_assert(X,#MSG);
                                       ^             ~
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/PlainObjectBase.h:535:7: note: in instantiation of member function
      'Eigen::PlainObjectBase<Eigen::Matrix<double, 1, 3, 0, 1, 3> >::_check_template_params' requested here
      _check_template_params();
      ^
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/Matrix.h:379:9: note: in instantiation of function template
      specialization 'Eigen::PlainObjectBase<Eigen::Matrix<double, 1, 3, 0, 1, 3>
      >::PlainObjectBase<Eigen::Block<Eigen::Matrix<double, -1, 3, 0, -1, 3>, 1, 3, false> >' requested here
      : Base(other.derived())
        ^
eigen_func_test.cpp:32:9: note: in instantiation of function template specialization 'Eigen::Matrix<double, 1, 3, 0,
      1, 3>::Matrix<Eigen::Block<Eigen::Matrix<double, -1, 3, 0, -1, 3>, 1, 3, false> >' requested here
        return f;
               ^
eigen_func_test.cpp:41:10: note: in instantiation of function template specialization
      'func<Eigen::Block<Eigen::Matrix<double, -1, 3, 0, -1, 3>, 1, 3, false> >' requested here
        cout << func( M.row(2) ) << endl;
                ^
1 error generated.

Body:
Not exactly sure what is causing your compiler error directly but from what you have shown in your source code as well as your compiler errors. This is the part of the compiler error message that I'm basing this off of.

/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/PlainObjectBase.h:899:7: error: static_assert failed
  "INVALID_MATRIX_TEMPLATE_PARAMETERS"

So when looking at the source code you are trying to use the #define func3

that you have declared as such:

template<class D> vect_t func(const MatrixBase<D>& f) {
    return f;
}

with the using directives that you have declared as:

constexpr Eigen::StorageOptions Order = ColMajor;

using vect_t = Matrix<double, 1, 3, Order>;
using matr_t = Matrix<double, Dynamic, 3, Order>;

So let's expand this to the full form to see what the compiler is trying to parse or deduce as your parameters and return type.

template<class D>
Matrix<double, 1, 3, constexpr Eigen::StorageOptions Order = ColMajor>
func( const MatrixBase<D>& f ) {
    return f;
}

Then in your main you use this with:

int main() {
    // matr_t M = matr_t::Random(5,3);
    Matrix<double, Dynamic, 3, constexpr Eigen::StorageOptions Order = ColMajor> M
      = Matrix<double, Dynamic, 3, constexpr Eigen::StorageOptions Order = ColMajor>::Random(5, 3);

    // Then you call your function passing it this:
    std::cout << func( M.row(2) ) << std::endl;

    return 0;
}

func() is returning Matrix<double, 1, 3, Order>;
and it takes const MatrixBase<D>&
however it appears you are passing it: M.row(2)
that is constructed from: Matrix<double, Dynamic, 3, constexpr Eigen::StorageOptions Order = ColMajor>::Random(5, 3)

In the function itself you are returning f which happens to be
the function's const ref of MatrixBase<D> parameter yet the declaration is expecting to return a Matrix<double, 1, 3, Order>

So I think the compiler is having a hard time trying to convert a
Matrix<double, Dynamic, 3, Order> to a Matrix<double, 1, 3, Order>

Maybe this will help you to understand the compiler error a little better; as you can see when you look at the rest of the compilation error message you can tell that this is evident when it is trying to do the specializations of this template.


问:
Calculate linear commission - Looking for a formula
Using R, Is there a formula that can help me calculate a sales commission based on this condition. For eg:

If the growth (in %) is between 5% and 7% then the salesman will receive a commission which will be linear from 10% to 12.5%

The variables:

```<code>TargetAmt<-100
Earned<-105.6
PctGrowth<-((Earned-TargetAmt)/TargetAmt)*100
PctGrowth
</code>```

5.6

Therefore, I now need to calculate his commission, which will be linear from 10% to 12.5%.

I can do this manually by calculating  slope of the line. However, how can I do this in R?

答:
1) lm For a growth of 5.6% the commission is 10.6%

```<code>growth <- c(5, 7)
commission <- c(10, 12.5)

fit <- lm(commission ~ growth)
predict(fit, list(growth = 5.6))
##     1
## 10.75
</code>```

1a) Alternately, we can get the formula from the linear regression and then just apply it ourself.  In this case the slope is 1.25 and the intercept is 3.75:

```<code>> fit
Call:
lm(formula = commission ~ growth)

Coefficients:
(Intercept)       growth
       3.75         1.25
</code>```

so the commision is the 1.25 times the growth as a percentage plus 3.75 percentage points, i.e. 1.25 * 5.6 + 3.75 = 10.75 .

2) approx Another way is to use approx like this:

```<code>approx(growth, commission, xout = 5.6)$y
## [1] 10.75
</code>```

Body:
Using R, Is there a formula that can help me calculate a sales commission based on this condition. For eg:

If the growth (in %) is between 5% and 7% then the salesman will receive a commission which will be linear from 10% to 12.5%

The variables:

TargetAmt<-100
Earned<-105.6
PctGrowth<-((Earned-TargetAmt)/TargetAmt)*100
PctGrowth

5.6

Therefore, I now need to calculate his commission, which will be linear from 10% to 12.5%.

I can do this manually by calculating  slope of the line. However, how can I do this in R?

Body:
1) lm For a growth of 5.6% the commission is 10.6%

growth <- c(5, 7)
commission <- c(10, 12.5)

fit <- lm(commission ~ growth)
predict(fit, list(growth = 5.6))
##     1
## 10.75

1a) Alternately, we can get the formula from the linear regression and then just apply it ourself.  In this case the slope is 1.25 and the intercept is 3.75:

> fit
Call:
lm(formula = commission ~ growth)

Coefficients:
(Intercept)       growth
       3.75         1.25

so the commision is the 1.25 times the growth as a percentage plus 3.75 percentage points, i.e. 1.25 * 5.6 + 3.75 = 10.75 .

2) approx Another way is to use approx like this:

approx(growth, commission, xout = 5.6)$y
## [1] 10.75


问:
Generate random binaries with avg hamming distance of 50%?
I want to generate binaries, where the average hamming distance between the items is around 50%.
The second condition is that the distance should not fall below ~40% or go above ~60%.
Another complication is that the items are not generated in sequence, but once in a while and I don't want to loop over all of the items to check and regenerate, because it will become a slow process after a while.

Is there a mechanism or algorithm to achieve this ?

Currently I use the following code :

```<code>def rand(size):
    op = np.random.uniform()
    return np.random.choice([0,1], size=size, p=[op, 1-op] )
</code>```

but it breaks even when I generate 10 items f.e. (hamming dist) :

```<code>[ [   0 2510 8209 4305 3896 1619 7231 6356 8103 3265]
  [2510    0 8131 4347 3940 1697 7219 6334 8037 3305]
  [8209 8131    0 5858 6449 9312 2100 3317 1030 7196]
  [4305 4347 5858    0 4661 4088 5598 5311 5764 4590]
  [3896 3940 6449 4661    0 3485 6093 5650 6385 4251]
  [1619 1697 9312 4088 3485    0 8034 6739 9152 2716]
  [7231 7219 2100 5598 6093 8034    0 3831 2238 6510]
  [6356 6334 3317 5311 5650 6739 3831    0 3405 5933]
  [8103 8037 1030 5764 6385 9152 2238 3405    0 7112]
  [3265 3305 7196 4590 4251 2716 6510 5933 7112    0]]
</code>```

min: 1030
  Avg distance : 0.470624%

btw. binaries are  10 000 bits.

答:
So far the following solution seems to behave as to my expectation.

```<code>def rand(size):
    return [np.random.randint(0,2) for _ in xrange(size)]
</code>```

will update when I do more extensive tests, if it is ok.

Body:
I want to generate binaries, where the average hamming distance between the items is around 50%.
The second condition is that the distance should not fall below ~40% or go above ~60%.
Another complication is that the items are not generated in sequence, but once in a while and I don't want to loop over all of the items to check and regenerate, because it will become a slow process after a while.

Is there a mechanism or algorithm to achieve this ?

Currently I use the following code :

def rand(size):
    op = np.random.uniform()
    return np.random.choice([0,1], size=size, p=[op, 1-op] )

but it breaks even when I generate 10 items f.e. (hamming dist) :

[ [   0 2510 8209 4305 3896 1619 7231 6356 8103 3265]
  [2510    0 8131 4347 3940 1697 7219 6334 8037 3305]
  [8209 8131    0 5858 6449 9312 2100 3317 1030 7196]
  [4305 4347 5858    0 4661 4088 5598 5311 5764 4590]
  [3896 3940 6449 4661    0 3485 6093 5650 6385 4251]
  [1619 1697 9312 4088 3485    0 8034 6739 9152 2716]
  [7231 7219 2100 5598 6093 8034    0 3831 2238 6510]
  [6356 6334 3317 5311 5650 6739 3831    0 3405 5933]
  [8103 8037 1030 5764 6385 9152 2238 3405    0 7112]
  [3265 3305 7196 4590 4251 2716 6510 5933 7112    0]]

min: 1030
  Avg distance : 0.470624%

btw. binaries are  10 000 bits.

Body:
So far the following solution seems to behave as to my expectation.

def rand(size):
    return [np.random.randint(0,2) for _ in xrange(size)]

will update when I do more extensive tests, if it is ok.


问:
Bootstrap Mobile versions have space on the right side, container is also not proper size. have overflow-x:hidden.. Any ideas on how to fix it?
Bootstrap Mobile versions have space on the right side, container is also not proper size. have overflow-x:hidden..

I also double checked the container and rows to make sure the containers divs are all closed and there are no nested containers, or containers inside of rows.

You can view a sample here: http://holbrookautoparts.com/mock/index.html

答:
Change your .signupform css at line number 980 as follows:

```<code>@media (max-width: 414px){
  .signupform {
    top: 100px;
    left: 43px;
    width: auto;
    right: 43px;
  }
}
</code>```

Body:
Change your .signupform css at line number 980 as follows:

@media (max-width: 414px){
  .signupform {
    top: 100px;
    left: 43px;
    width: auto;
    right: 43px;
  }
}


问:
How to get header and nav menu on same line
I am trying to get the header of my site and the navigation on the same line.  I want the header to be aligned left and the navigation to be centered.  My code doesn't seem to be working, so I was wondering if anyone has any solutions?  Thanks in advance.

an example of what I am trying to have it look like...

my header.php

<!DOCTYPE html>
<html <?php language_attributes(); ?>>

<meta charset="<?php bloginfo('charset'); ?>">
<meta name="viewport" content="width=device-width">
<title><?php bloginfo('name'); ?></title>
<?php wp_head(); ?>

<body <?php body_class(); ?>>

"><?php bloginfo('name'); ?>

<?php bloginfo('description'); ?>

        <?php
          wp_nav_menu(array(
            'menu' => 'Primary Menu Links',
            'container_id' => 'cssmenu',
            'walker' => new CSS_Menu_Walker()
          ));
        ?>

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

<p>my css</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>.site-header h1 {
margin: 0;
    font-family: 'futura_tbold';
    font-size: 24px;
    text-align: left;
    text-transform: uppercase;
    letter-spacing: 6px;
    padding-top: 20px;
    position: fixed;
    z-index: 10000;
}
/* Drop Down Menu */
#cssmenu,
#cssmenu ul,
#cssmenu li,
#cssmenu a {
}

#cssmenu {
height: 37px;
text-align: center;
margin-bottom:50px;
width: 0 auto;
    margin-right:38px;
}
#cssmenu,
#cssmenu > ul > li > ul > li a:hover
}
#cssmenu > ul {
}
#cssmenu > ul > li {
list-style: inside none;

position: relative;
display: inline-block;
}
#cssmenu > ul > li > a {

display: block;
position: relative;
padding: 12px 20px;
text-align: center;
text-decoration: none;
font-size: 13px;
font-family: 'textaw00-heavyregular', 'AvenirNextLTW01', 'Helvetica Neue', 'Helvetica', 'Arial', 'sans-serif';
color: #2f3847;
    text-transform:uppercase;
    letter-spacing: 1px;
    font-weight:normal;
    -webkit-font-smoothing: antialiased;
}
#cssmenu > ul > li > a:hover {
color:#8F1E3E;
}
#cssmenu > ul > li:first-child > a {
}
#cssmenu > ul > li > a:after {
content: '';
position: absolute;
}
#cssmenu ul li.has-sub:hover > a:after {
  position: absolute;
  top: 28px;
  left: 11px;
  display: inline-block;
  border-right: 7px solid transparent;
  border-bottom: 7px solid #3d0d1d;
  border-left: 7px solid transparent;
  border-bottom-color: rgba(61, 13, 29, 1);
  content: '';
width: 0;
height: 0;
border-style: solid;
border-width: 0 10px 10px 10px;
border-color: transparent transparent #3d0d1d transparent;
}
#cssmenu > ul > li.has-sub > a:before {
}
#cssmenu > ul > li.has-sub:hover > a:before {

}
#cssmenu ul li.has-sub:hover > a {
}
#cssmenu ul li.has-sub:hover > ul,
#cssmenu ul li.has-sub:hover > div {
display: block;
}
#cssmenu ul li.has-sub > a:hover {
color: #8F1E3E;
}
#cssmenu ul li > ul,
#cssmenu ul li > div {
display: none;
width: auto;
position: absolute;
top: 38px;
padding: 10px 0;
background: #490f20;
border-radius: 0px 0px 0px 0px;
z-index: 999;
}
#cssmenu ul li > ul {
width: 200px;
}
#cssmenu ul li > ul li {
display: block;
list-style: inside none;
padding: 0;
margin: 0;
position: relative;
}
#cssmenu ul li > ul li a {
outline: none;
display: block;
position: relative;
margin: 0;
padding: 8px 20px;
color: #ffffff;
text-decoration: none;
text-align: left;
    font-size: 13px;
font-family: 'textaw00-heavyregular', 'AvenirNextLTW01', 'Helvetica Neue', 'Helvetica', 'Arial', 'sans-serif';
    text-transform:uppercase;
    letter-spacing: 1px;
    font-weight:normal;
    -webkit-font-smoothing: antialiased;
    line-height:25px;
}
#cssmenu ul ul a:hover {
color: #ffffff;
    background-color:#8F1E3E;
}
#cssmenu > ul > li.has-sub > a:hover:before {
border-top: 5px solid #ffffff;
}</code>```

答:
Here you go buddy hope this helps

Jsfiddle

```<code><div class="navigation">
  <div class="container">
    <div class="logo">
      <!-- <img src="#" alt=""> -->
      <span>LOGO</span>
    </div>
    <nav>
      <ul>
        <li>Page 1</li>
        <li>Page 2</li>
        <li>Page 3</li>
        <li>Page 4</li>
      </ul>
    </nav>
  </div>
</div>

.navigation {
  float: left;
  width: 100%;
  padding: 10px 0;
  border-bottom: 2px solid black;
}

.container {
  max-width: 90%;
  margin: 0 auto;
  position: relative;
}

.logo {
  position: absolute;
  top: 0;
  left: 0;
}

nav ul {
  margin: 0 auto;
  text-align: center;
}

nav ul li {
  display: inline-block;
}
</code>```

Body:
I am trying to get the header of my site and the navigation on the same line.  I want the header to be aligned left and the navigation to be centered.  My code doesn't seem to be working, so I was wondering if anyone has any solutions?  Thanks in advance.

an example of what I am trying to have it look like...

my header.php

<!DOCTYPE html>
<html <?php language_attributes(); ?>>

<meta charset="<?php bloginfo('charset'); ?>">
<meta name="viewport" content="width=device-width">
<title><?php bloginfo('name'); ?></title>
<?php wp_head(); ?>

<body <?php body_class(); ?>>

<a href="<?php echo home_url(); ?>"><?php bloginfo('name'); ?>

<?php bloginfo('description'); ?>

        <?php
          wp_nav_menu(array(
            'menu' => 'Primary Menu Links',
            'container_id' => 'cssmenu',
            'walker' => new CSS_Menu_Walker()
          ));
        ?>

my css

.site-header h1 {
margin: 0;
    font-family: 'futura_tbold';
    font-size: 24px;
    text-align: left;
    text-transform: uppercase;
    letter-spacing: 6px;
    padding-top: 20px;
    position: fixed;
    z-index: 10000;
}
/* Drop Down Menu */
#cssmenu,
#cssmenu ul,
#cssmenu li,
#cssmenu a {
}

#cssmenu {
height: 37px;
text-align: center;
margin-bottom:50px;
width: 0 auto;
    margin-right:38px;
}
#cssmenu,
#cssmenu > ul > li > ul > li a:hover
}
#cssmenu > ul {
}
#cssmenu > ul > li {
list-style: inside none;

position: relative;
display: inline-block;
}
#cssmenu > ul > li > a {

display: block;
position: relative;
padding: 12px 20px;
text-align: center;
text-decoration: none;
font-size: 13px;
font-family: 'textaw00-heavyregular', 'AvenirNextLTW01', 'Helvetica Neue', 'Helvetica', 'Arial', 'sans-serif';
color: #2f3847;
    text-transform:uppercase;
    letter-spacing: 1px;
    font-weight:normal;
    -webkit-font-smoothing: antialiased;
}
#cssmenu > ul > li > a:hover {
color:#8F1E3E;
}
#cssmenu > ul > li:first-child > a {
}
#cssmenu > ul > li > a:after {
content: '';
position: absolute;
}
#cssmenu ul li.has-sub:hover > a:after {
  position: absolute;
  top: 28px;
  left: 11px;
  display: inline-block;
  border-right: 7px solid transparent;
  border-bottom: 7px solid #3d0d1d;
  border-left: 7px solid transparent;
  border-bottom-color: rgba(61, 13, 29, 1);
  content: '';
width: 0;
height: 0;
border-style: solid;
border-width: 0 10px 10px 10px;
border-color: transparent transparent #3d0d1d transparent;
}
#cssmenu > ul > li.has-sub > a:before {
}
#cssmenu > ul > li.has-sub:hover > a:before {

}
#cssmenu ul li.has-sub:hover > a {
}
#cssmenu ul li.has-sub:hover > ul,
#cssmenu ul li.has-sub:hover > div {
display: block;
}
#cssmenu ul li.has-sub > a:hover {
color: #8F1E3E;
}
#cssmenu ul li > ul,
#cssmenu ul li > div {
display: none;
width: auto;
position: absolute;
top: 38px;
padding: 10px 0;
background: #490f20;
border-radius: 0px 0px 0px 0px;
z-index: 999;
}
#cssmenu ul li > ul {
width: 200px;
}
#cssmenu ul li > ul li {
display: block;
list-style: inside none;
padding: 0;
margin: 0;
position: relative;
}
#cssmenu ul li > ul li a {
outline: none;
display: block;
position: relative;
margin: 0;
padding: 8px 20px;
color: #ffffff;
text-decoration: none;
text-align: left;
    font-size: 13px;
font-family: 'textaw00-heavyregular', 'AvenirNextLTW01', 'Helvetica Neue', 'Helvetica', 'Arial', 'sans-serif';
    text-transform:uppercase;
    letter-spacing: 1px;
    font-weight:normal;
    -webkit-font-smoothing: antialiased;
    line-height:25px;
}
#cssmenu ul ul a:hover {
color: #ffffff;
    background-color:#8F1E3E;
}
#cssmenu > ul > li.has-sub > a:hover:before {
border-top: 5px solid #ffffff;
}

Body:
Here you go buddy hope this helps

Jsfiddle

<div class="navigation">
  <div class="container">
    <div class="logo">
      <!-- <img src="#" alt=""> -->
      <span>LOGO</span>
    </div>
    <nav>
      <ul>
        <li>Page 1</li>
        <li>Page 2</li>
        <li>Page 3</li>
        <li>Page 4</li>
      </ul>
    </nav>
  </div>
</div>

.navigation {
  float: left;
  width: 100%;
  padding: 10px 0;
  border-bottom: 2px solid black;
}

.container {
  max-width: 90%;
  margin: 0 auto;
  position: relative;
}

.logo {
  position: absolute;
  top: 0;
  left: 0;
}

nav ul {
  margin: 0 auto;
  text-align: center;
}

nav ul li {
  display: inline-block;
}


问:
Generating all variations of certain length out of string
I've seen few implementations of variations of string in C#, but none of them had any limitation on their length. Unfortunately, I cannot modify them to achieve my goal which is e.g.

for:

```<code>string = "ABCD" and variationLength = 2
</code>```

generate new strings:

```<code>AB, AC, AD, BA, BC, BD, CA, CB, CD, DA, DB, DC
</code>```

I'm looking for exactly this Python's itertools.permutations implementation but in C#. (https://docs.python.org/3/library/itertools.html#itertools.permutations)

Is there anything similar to its in C#? If not, then what is the easiest way to implement it?

Edit_2:
so far I came up with an idea to list all unique chars of given string and then get variations out of them

```<code>static void PrintAllKLengthPerm(string str, int k)
{
    int n = str.Length;
    PrintAllKLengthPermRec(str, "", n, k);
}

// The main recursive method to print all possible strings of length k
static void PrintAllKLengthPermRec(string str, String prefix, int n, int k)
{
    // Base case: k is 0, print prefix
    if (k == 0)
    {
        Console.WriteLine(prefix);
        return;
    }

    // One by one add all characters from str and recursively
    // call for k equals to k-1
    for (int i = 0; i < n; ++i)
    {
        // Next character of input added
        String newPrefix = prefix + str[i];

        // k is decreased, because we have added a new character
        PrintAllKLengthPermRec(str, newPrefix, n, k - 1);
    }
}

static void Main(string[] args)
{
    string str = "ABCD";
    int permLen = 2;

    //get all unique characters in string
    string uniqStr = new String(str.Distinct().ToArray());

    // Print all possible strings of length permLen out of uniqStr characters
    PrintAllKLengthPerm(uniqStr, permLen);
}
</code>```

However I am looking for more optimal and effective solution

答:
```<code>List<string> newPermutations = new List<string>();
for(int a = 0; a!=inString.Count; a++)
    for((int b = 0; b!=inString.Count; b++)
        if(noRepetitions && a == b) continue;
        newPermutations.Add(""+inString[a] + inString[b]);
</code>```

I think that that should work; I am still trying to figure out a way to not only have 2 letters.

Edit: Edited it to work, the old one just didn't work... lol
Edit: Thanks to @Bloopy, they helped me spot some errors in my for loops

Body:
I've seen few implementations of variations of string in C#, but none of them had any limitation on their length. Unfortunately, I cannot modify them to achieve my goal which is e.g.

for:

string = "ABCD" and variationLength = 2

generate new strings:

AB, AC, AD, BA, BC, BD, CA, CB, CD, DA, DB, DC

I'm looking for exactly this Python's itertools.permutations implementation but in C#. (https://docs.python.org/3/library/itertools.html#itertools.permutations)

Is there anything similar to its in C#? If not, then what is the easiest way to implement it?

Edit_2:
so far I came up with an idea to list all unique chars of given string and then get variations out of them

static void PrintAllKLengthPerm(string str, int k)
{
    int n = str.Length;
    PrintAllKLengthPermRec(str, "", n, k);
}

// The main recursive method to print all possible strings of length k
static void PrintAllKLengthPermRec(string str, String prefix, int n, int k)
{
    // Base case: k is 0, print prefix
    if (k == 0)
    {
        Console.WriteLine(prefix);
        return;
    }

    // One by one add all characters from str and recursively
    // call for k equals to k-1
    for (int i = 0; i < n; ++i)
    {
        // Next character of input added
        String newPrefix = prefix + str[i];

        // k is decreased, because we have added a new character
        PrintAllKLengthPermRec(str, newPrefix, n, k - 1);
    }
}

static void Main(string[] args)
{
    string str = "ABCD";
    int permLen = 2;

    //get all unique characters in string
    string uniqStr = new String(str.Distinct().ToArray());

    // Print all possible strings of length permLen out of uniqStr characters
    PrintAllKLengthPerm(uniqStr, permLen);
}

However I am looking for more optimal and effective solution

Body:
List<string> newPermutations = new List<string>();
for(int a = 0; a!=inString.Count; a++)
    for((int b = 0; b!=inString.Count; b++)
        if(noRepetitions && a == b) continue;
        newPermutations.Add(""+inString[a] + inString[b]);

I think that that should work; I am still trying to figure out a way to not only have 2 letters.

Edit: Edited it to work, the old one just didn't work... lol
Edit: Thanks to @Bloopy, they helped me spot some errors in my for loops


问:
Scheduling a monthly event “Every Nth Weekday or Weekend Day” using RFC 5545 recurrence rule
I've found similar question name, but it is a little different.

Office365 UI interface can provide recurring rule where repeat: monthly On second weekday or repeat: monthly On third weekend day

How I could represent second weekday and third weekend day using RFC 5545?

答:
monthly on second weekday:

FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=2

This rule expands to every weekday of each month, but in the end selects only the 2nd day of the set.

See the expanded result: http://recurrence-expansion-service.appspot.com/reaas?dtstart=20170602T000000&rrule=FREQ%3DMONTHLY%3BBYDAY%3DMO%2CTU%2CWE%2CTH%2CFR%3BBYSETPOS%3D2&skip=&max_instances=100&expansion_window_end=21000101T000000&strict=1

monthly on third weekend day

FREQ=MONTHLY;BYDAY=SA,SU;BYSETPOS=3

This rule expands to every weekend day of each month, but in the end selects only the 3rd result of the set.

See the expanded result: http://recurrence-expansion-service.appspot.com/reaas?dtstart=20170610T000000&rrule=FREQ%3DMONTHLY%3BBYDAY%3DSA%2CSU%3BBYSETPOS%3D3&skip=&max_instances=100&expansion_window_end=21000101T000000&strict=1


问:
Unexpected behavior when printing out char array
i'm currently trying to debug my program over UART by printing the values of some variables at specific points. My issue is with printing two char arrays. The order in which i print them seems to have an effect on if it prints. The declarations of the arrays are in a struct in a header file as follows-

```<code>//header file
typedef struct
{
  char latitude[10];
  char longitude[11];
}NMEA_RMC_t;

NMEA_RMC_t rmc;
</code>```

The char arrays are manipulated in another function after parsing data from an input. They are not updated with an interrupt, although there are interrupts elsewhere in the program. In the main code if i print them as follows-

```<code>//main program loop
printf("lat: %s \t long: %s \n", rmc.latitude, rmc.longitude);
</code>```

the output to the terminal is this-

lat: +50.71735        long:

whereas if i print them in a different order like this-

```<code>printf("long: %s \t lat: %s \n", rmc.longitude, rmc.latitude);
</code>```

i get this output.

long: -001.39118         lat:

also if i split the printing up into two separate printf statements, only the first print statement correctly prints the char array. I haven't had to ask for help on here before but this has had me stuck for a good week now. Any help would be massively appreciated! cheers.

edit

The part of the program that writes into the array is this. its essentially the same for the latitude and longitude array.

```<code>/* now we are in first char of latitude */

/* copy latitude chars */
strlcpy ((char*)lat, (const char*)ptr_to_comma, 10 );/*copies most size-1, null terminated*/   //changed 11 to 10

/* default latitude presentation is ddmm.mmmmm
    we need to change it to dd.mmmmmmm
*/
unsigned char ind;
for (ind=0; ind<9; ind++)
{
    if (*ptr_to_comma == '.')
    {
        ptr_to_comma++;//step over '.'
    }
    if ( ind==2 )
    {
        lat[ind++]='.';
    }
    lat[ind] = *ptr_to_comma;
    ptr_to_comma++;
}
lat[10] = '\0'; //terminate
/* now lat == dd.mmmmmmm */

ptr_to_comma++; /*step over comma to the NS-indicator*/

/*catch NorthSouth-indicator and step*/
if ( *ptr_to_comma == 'N'){ /*if we are in the North*/
    sign = '+';
    rmc.ns_indicator = 'N';
} else if ( *ptr_to_comma == 'S'){ /*else we are in the South*/
    sign = '-';
    rmc.ns_indicator = 'S';
}
ptr_to_comma++;//step over NS-indicator
ptr_to_comma++;//step over comma to the longitude field

/* dd.mmmmmmm to dd.ddddddd */

_convert_minutes( (unsigned char*) lat+3 );

/* copy latitude with sign to the rmc-struct */
rmc.latitude[0] = sign;
strcpy ( (char*)rmc.latitude+1, (const char*)lat);
rmc.latitude[10]='\0';
</code>```

essentially it is parsing the information from a stream of data coming in.

答:
Your code for converting the strings and putting them in the struct is inadvertently placing a '\0' character at the beginning of rmc.longitude. The code then goes on the fill the rest of the array with the correct value, but the printf() function sees rmc.longitude as a zero-length string and ignores what follows.

It is an an off-by-one error. rmc.latitude[10]='\0'; places a 0 in the 11th position of the rmc.latitude array, but this array was declared to only have 10 positions. What is actually happening instead is rmc.longitude[0] is getting the '\0' character, as it is adjacent in memory.

Body:
i'm currently trying to debug my program over UART by printing the values of some variables at specific points. My issue is with printing two char arrays. The order in which i print them seems to have an effect on if it prints. The declarations of the arrays are in a struct in a header file as follows-

//header file
typedef struct
{
  char latitude[10];
  char longitude[11];
}NMEA_RMC_t;

NMEA_RMC_t rmc;

The char arrays are manipulated in another function after parsing data from an input. They are not updated with an interrupt, although there are interrupts elsewhere in the program. In the main code if i print them as follows-

//main program loop
printf("lat: %s \t long: %s \n", rmc.latitude, rmc.longitude);

the output to the terminal is this-

lat: +50.71735        long:

whereas if i print them in a different order like this-

printf("long: %s \t lat: %s \n", rmc.longitude, rmc.latitude);

i get this output.

long: -001.39118         lat:

also if i split the printing up into two separate printf statements, only the first print statement correctly prints the char array. I haven't had to ask for help on here before but this has had me stuck for a good week now. Any help would be massively appreciated! cheers.

edit

The part of the program that writes into the array is this. its essentially the same for the latitude and longitude array.

/* now we are in first char of latitude */

/* copy latitude chars */
strlcpy ((char*)lat, (const char*)ptr_to_comma, 10 );/*copies most size-1, null terminated*/   //changed 11 to 10

/* default latitude presentation is ddmm.mmmmm
    we need to change it to dd.mmmmmmm
*/
unsigned char ind;
for (ind=0; ind<9; ind++)
{
    if (*ptr_to_comma == '.')
    {
        ptr_to_comma++;//step over '.'
    }
    if ( ind==2 )
    {
        lat[ind++]='.';
    }
    lat[ind] = *ptr_to_comma;
    ptr_to_comma++;
}
lat[10] = '\0'; //terminate
/* now lat == dd.mmmmmmm */

ptr_to_comma++; /*step over comma to the NS-indicator*/

/*catch NorthSouth-indicator and step*/
if ( *ptr_to_comma == 'N'){ /*if we are in the North*/
    sign = '+';
    rmc.ns_indicator = 'N';
} else if ( *ptr_to_comma == 'S'){ /*else we are in the South*/
    sign = '-';
    rmc.ns_indicator = 'S';
}
ptr_to_comma++;//step over NS-indicator
ptr_to_comma++;//step over comma to the longitude field

/* dd.mmmmmmm to dd.ddddddd */

_convert_minutes( (unsigned char*) lat+3 );

/* copy latitude with sign to the rmc-struct */
rmc.latitude[0] = sign;
strcpy ( (char*)rmc.latitude+1, (const char*)lat);
rmc.latitude[10]='\0';

essentially it is parsing the information from a stream of data coming in.


问:
Zoom Image into a new Activity
I want to zoom an Image into a new Activity when I click on it.
To undestand what Im trying to achive I uploaded some pictures in a row.
If it is hard to understand it through a picture I could try to upload a video.
The only thing I found was this . But its only for a View. I want to start a complete new Activity or Dialog whatever.

Any suggestions how I could do it on the best way?

答:
API 14+

I believe this library does exactly what you want: https://github.com/albinmathew/PreLollipopTransition (yes, what you want is part of Android API, but only from Lollipop up - you probably want to support lower APIs too, and that is what this library is for).

EDIT: original https://github.com/takahirom/PreLollipopTransition seems to be more up-to-date, so you probably want to use this instead.

With it, you can basically do just this in one Activity:

```<code>findViewById(R.id.imageView).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        final Intent intent = new Intent(MainActivity.this, SubActivity.class);
        ActivityTransitionLauncher.with(MainActivity.this).from(v).launch(intent);
    }
});
</code>```

... and this in the second activity

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub);
        ActivityTransition.with(getIntent()).to(findViewById(R.id.sub_imageView)).start(savedInstanceState);
    }
</code>```

API 21+

According to http://guides.codepath.com/android/shared-element-activity-transition, you can simply add <item name="android:windowContentTransitions">true</item> to your Activity style and, define elements with android:transitionName="<some name>" in both Activities (transitionName must be the same in both of them), then start Activity like this:

```<code>Intent intent = new Intent(this, DetailsActivity.class);
// Pass data object in the bundle and populate details activity.
intent.putExtra(DetailsActivity.EXTRA_CONTACT, contact);
ActivityOptionsCompat options = ActivityOptionsCompat.
    makeSceneTransitionAnimation(this, (View)ivProfile, "<transition name>");
startActivity(intent, options.toBundle());
</code>```

(taken directly from the link). But note that this will work only on L+ devices, while the solution above will run on anything with API 14+. I personally think there's no point in using native API if a good wrapper providing backward compatibility is available, but you asked for it, so here it is.

Hope this helps you, comment if you have any questions

Title: Zoom Image into a new Activity

Body:
API 14+

I believe this library does exactly what you want: https://github.com/albinmathew/PreLollipopTransition (yes, what you want is part of Android API, but only from Lollipop up - you probably want to support lower APIs too, and that is what this library is for).

EDIT: original https://github.com/takahirom/PreLollipopTransition seems to be more up-to-date, so you probably want to use this instead.

With it, you can basically do just this in one Activity:

findViewById(R.id.imageView).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        final Intent intent = new Intent(MainActivity.this, SubActivity.class);
        ActivityTransitionLauncher.with(MainActivity.this).from(v).launch(intent);
    }
});

... and this in the second activity

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub);
        ActivityTransition.with(getIntent()).to(findViewById(R.id.sub_imageView)).start(savedInstanceState);
    }

API 21+

According to http://guides.codepath.com/android/shared-element-activity-transition, you can simply add <item name="android:windowContentTransitions">true</item> to your Activity style and, define elements with android:transitionName="<some name>" in both Activities (transitionName must be the same in both of them), then start Activity like this:

Intent intent = new Intent(this, DetailsActivity.class);
// Pass data object in the bundle and populate details activity.
intent.putExtra(DetailsActivity.EXTRA_CONTACT, contact);
ActivityOptionsCompat options = ActivityOptionsCompat.
    makeSceneTransitionAnimation(this, (View)ivProfile, "<transition name>");
startActivity(intent, options.toBundle());

(taken directly from the link). But note that this will work only on L+ devices, while the solution above will run on anything with API 14+. I personally think there's no point in using native API if a good wrapper providing backward compatibility is available, but you asked for it, so here it is.

Hope this helps you, comment if you have any questions


问:
Nullpointer exception when using setLocation of an object of type Point2D.double
This is my first time using points and I seem to run into an issue when initially setting the location of a Point2D object. Here is my code snippet:

```<code>public class Circle {
 private Ellipse2D circle;
 private int radius,speed=4,direction;
 private Color color;
 private Point2D.Double loc=null;
 private final int MAXSIZE = 15;

public Circle() {
 int tempRadius,x,y;
 //setting default color
 ...

 //initializing radius
 ...

 //initializing location
 x=temp.nextInt(1024); y=temp.nextInt(1024);
 loc.setLocation((double)x, (double)y);
</code>```

I get the nullpointer exception when trying to do loc.setLocation(). I've been messing around trying to figure out if I'm initializing the point2s incorrectly and if so how. Could someone help me?

答:
Oh wait it's kinda obvious.
You need to make a new Point2D.Double before setting it's location.</p>

Body:
This is my first time using points and I seem to run into an issue when initially setting the location of a Point2D object. Here is my code snippet:

public class Circle {
 private Ellipse2D circle;
 private int radius,speed=4,direction;
 private Color color;
 private Point2D.Double loc=null;
 private final int MAXSIZE = 15;

public Circle() {
 int tempRadius,x,y;
 //setting default color
 ...

 //initializing radius
 ...

 //initializing location
 x=temp.nextInt(1024); y=temp.nextInt(1024);
 loc.setLocation((double)x, (double)y);

I get the nullpointer exception when trying to do loc.setLocation(). I've been messing around trying to figure out if I'm initializing the point2s incorrectly and if so how. Could someone help me?


问:
Calling converted string from UIDataPicker date
Now I am learning Swift and making a typical ToDo app.
I found a function to convert date data from UIDatePicker to String, here is my ViewController chunk of code:

```<code>@IBAction func dateToString(sender: UIDatePicker) {
            var dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
            var strDate = dateFormatter.stringFromDate(myDatePicker.date)
            return ()
        }
</code>```

But the problem is that I can not access the string results from this function, in my app
i have 2 labels in every tableViewCell, one simple label text data, and another is date data from date picker (also should be a string):

```<code>@IBOutlet weak var saveButton: UIBarButtonItem!

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if saveButton === sender {
        let name = nameTextField.text ?? ""
        let date =
        item = Item (name: name, date: date)
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    if let item = item {
        nameTextField.text = item.name
                           = item.date

}
</code>```

}

please help, what should I write in

```<code>let date =
</code>```

and

```<code>= item.date
</code>```

to define a date?
I've tried to call a function let date = dateToString; but it doesn't work for me.
Greatly appreciate any help here!

答:
First, your dateToString function shouldn't be an IBAction. Those are used for methods called directly by interface items and hooked up in Interface Builder. What you want here is a regular function that takes a date and returns a formatted string, like this:

```<code>func dateToString(date: NSDate) -> String {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
    return dateFormatter.string(from: date)
}
</code>```

Now when you want a formatted date string, you call it and pass it the Date you want it to format. It looks like you're using a UIDatePicker to specify the date, so you need to set up an @IBOutlet in your view controller (if you haven't already done so) to give you access to that object. To do that, control-drag from the date picker to your view controller source, then name the outlet. It will generate code in your source like:

```<code>@IBOutlet weak var myDatePicker: UIDatePicker!
</code>```

Now you can refer to the datePicker elsewhere in your class. So you can get the date as a formatted string like this:

```<code>let dateString = dateToString(date: myDatePicker.date)
</code>```

You can then pass this string to an Item, or set it as the text of a field or label.

Body:
Now I am learning Swift and making a typical ToDo app.
I found a function to convert date data from UIDatePicker to String, here is my ViewController chunk of code:

@IBAction func dateToString(sender: UIDatePicker) {
            var dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
            var strDate = dateFormatter.stringFromDate(myDatePicker.date)
            return ()
        }

But the problem is that I can not access the string results from this function, in my app
i have 2 labels in every tableViewCell, one simple label text data, and another is date data from date picker (also should be a string):

@IBOutlet weak var saveButton: UIBarButtonItem!

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if saveButton === sender {
        let name = nameTextField.text ?? ""
        let date =
        item = Item (name: name, date: date)
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    if let item = item {
        nameTextField.text = item.name
                           = item.date

}

}

please help, what should I write in

let date =

and

= item.date

to define a date?
I've tried to call a function let date = dateToString; but it doesn't work for me.
Greatly appreciate any help here!

Body:
First, your dateToString function shouldn't be an IBAction. Those are used for methods called directly by interface items and hooked up in Interface Builder. What you want here is a regular function that takes a date and returns a formatted string, like this:

func dateToString(date: NSDate) -> String {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
    return dateFormatter.string(from: date)
}

Now when you want a formatted date string, you call it and pass it the Date you want it to format. It looks like you're using a UIDatePicker to specify the date, so you need to set up an @IBOutlet in your view controller (if you haven't already done so) to give you access to that object. To do that, control-drag from the date picker to your view controller source, then name the outlet. It will generate code in your source like:

@IBOutlet weak var myDatePicker: UIDatePicker!

Now you can refer to the datePicker elsewhere in your class. So you can get the date as a formatted string like this:

let dateString = dateToString(date: myDatePicker.date)

You can then pass this string to an Item, or set it as the text of a field or label.


问:
Trying to create two different account types in rails
I am trying to build a simple donation app in rails. In this application, patrons would give amounts of money to clients. Both the patron and the client share large amounts of the same functionality. They are both linked to a user and have a username. However, the client is also supposed to have a content_type and a content_list property. At first glance, my guess is that I want to have both my patron and client inherit from the account class. However, the client has additional functionality, which seems to preclude any STI-based implementation (though I will be the first to admit that my understanding of STI is shaky at best). As it stands, it seems to simply make more sense to write out two separate resources, but I would like to keep my code as DRY as humanly possible. Is there a simple way for me to create the behaviors I want through inheritance, or should I simply go with overlapping resources?

答:
Here's an idea, as both of your user-types share the same basic functionalities.

As you said, make one make one unified User or Account model. Include the database fields customer (as boolean) and patron (also as boolean).

In the signup process, the user can then select if they're a patron or customer, as they would regardless.

Then inside your view, you can then call, if you use Devise for instance (which I personally think is great)

```<code><% if current_user.patron == true %>
<!-- all relevant UI functionality for patrons -->
<% end %>
</code>```

or if the User is a customer

```<code><% if current_user.customer == true %>
<!-- all relevant UI functionality for customers -->
<% end %>
</code>```

Or if you want to loop through a list of patrons or customers:

```<code><% @user.where(:customer == true).each do |users| %>
   <% @user.first_name %> <% @user.last_name %>
<% end %>
</code>```

These are just basic examples, but it would do just fine for what you're trying to achieve.

P.S You could also create one migration called "account_type" as a
  string and then with the help of radio_buttons in the signup process
  store the account_type as a string value.

```<code><%= f.radio_button :account_type, "customer" %>
<%= f.radio_button :account_type, "patron" %>
</code>```

I actually think that would be better. Then you would split the views up
  like this:

```<code><% if current_user.account_type => "customer" %>
Show the list that only customer should have or see.
<% end %>

   <% if current_user.account_type => "patron" %>
   Show the list that only patron should have or see.
   <% end %>

<% @user.where(:account_type => "customer").each do |users| %>
  <% @user.first_name %> <% @user.last_name %>
<% end %>
</code>```

Body:
Here's an idea, as both of your user-types share the same basic functionalities.

As you said, make one make one unified User or Account model. Include the database fields customer (as boolean) and patron (also as boolean).

In the signup process, the user can then select if they're a patron or customer, as they would regardless.

Then inside your view, you can then call, if you use Devise for instance (which I personally think is great)

<% if current_user.patron == true %>
<!-- all relevant UI functionality for patrons -->
<% end %>

or if the User is a customer

<% if current_user.customer == true %>
<!-- all relevant UI functionality for customers -->
<% end %>

Or if you want to loop through a list of patrons or customers:

<% @user.where(:customer == true).each do |users| %>
   <% @user.first_name %> <% @user.last_name %>
<% end %>

These are just basic examples, but it would do just fine for what you're trying to achieve.

P.S You could also create one migration called "account_type" as a
  string and then with the help of radio_buttons in the signup process
  store the account_type as a string value.

<%= f.radio_button :account_type, "customer" %>
<%= f.radio_button :account_type, "patron" %>

I actually think that would be better. Then you would split the views up
  like this:

<% if current_user.account_type => "customer" %>
Show the list that only customer should have or see.
<% end %>

   <% if current_user.account_type => "patron" %>
   Show the list that only patron should have or see.
   <% end %>

<% @user.where(:account_type => "customer").each do |users| %>
  <% @user.first_name %> <% @user.last_name %>
<% end %>


问:
How to pass rest of props to react component while also having required props defined in an interface
So is this the same issue, or am I just missing something?

```<code>import * as React from 'react';

interface Props {
    value: string;
}

const MyComponent = (props: Props) => {
    const { value, ...rest } = props;

    return (
        <input {...rest} type="text" value={value} />
    );
}

interface ParentState {
    searchText: string;
}

class ParentComponent extends React.Component<{}, ParentState> {
    state: ParentState = {
        searchText: ''
    };

    onSearchTextChanged = (e: React.FormEvent<HTMLInputElement>) => {
        this.setState({
            searchText: e.currentTarget.value
        });
    }

    render() {
        const { searchText } = this.state;

        return (
            <div>
                <h2>Some Text</h2>
                <MyComponent value={searchText} onChange={this.onSearchTextChanged} className="search-input" placeholder="Enter text"/>
// Errors here
            </div>
        )
    }
}

export default ParentComponent
</code>```

When I have my props for MyComponent defined in an interface, I get the following error:

error TS2339: Property 'onChange' does not exist on type 'IntrinsicAttributes & Props'.

However if I change the props type to any, it compiles just fine.

```<code>const MyComponent = (props: any) => {
</code>```

Is it possible to define the props in an interface so that there are specific props that are required, but also allow additional props to be passed in so I don't have to explicitly add them into the interface?

I'm using TypeScript 2.3.4 and React 15.5.4.

答:
You can avoid excess property/attribute checks by adding a string index signature to your interface:

```<code>interface Props {
    value: string;

    // This is a string index signature.
    // This means that all properties in 'Props' are assignable to
    // the empty object type ({})
    [propName: string]: {};
}
</code>```

You could also write [propName: string]: any but that generally makes it less safe to use in MyComponent itself.

Body:
So is this the same issue, or am I just missing something?

import * as React from 'react';

interface Props {
    value: string;
}

const MyComponent = (props: Props) => {
    const { value, ...rest } = props;

    return (
        <input {...rest} type="text" value={value} />
    );
}

interface ParentState {
    searchText: string;
}

class ParentComponent extends React.Component<{}, ParentState> {
    state: ParentState = {
        searchText: ''
    };

    onSearchTextChanged = (e: React.FormEvent<HTMLInputElement>) => {
        this.setState({
            searchText: e.currentTarget.value
        });
    }

    render() {
        const { searchText } = this.state;

        return (

Some Text

                <MyComponent value={searchText} onChange={this.onSearchTextChanged} className="search-input" placeholder="Enter text"/>
// Errors here

        )
    }
}

export default ParentComponent

When I have my props for MyComponent defined in an interface, I get the following error:

error TS2339: Property 'onChange' does not exist on type 'IntrinsicAttributes & Props'.

However if I change the props type to any, it compiles just fine.

const MyComponent = (props: any) => {

Is it possible to define the props in an interface so that there are specific props that are required, but also allow additional props to be passed in so I don't have to explicitly add them into the interface?

I'm using TypeScript 2.3.4 and React 15.5.4.

Body:
You can avoid excess property/attribute checks by adding a string index signature to your interface:

interface Props {
    value: string;

    // This is a string index signature.
    // This means that all properties in 'Props' are assignable to
    // the empty object type ({})
    [propName: string]: {};
}

You could also write [propName: string]: any but that generally makes it less safe to use in MyComponent itself.


问:
how to monitor db audio loudness with ios?
I want to write a simple app to monitor audio loudness (in db offcourse) through iphone microphone. My question is: which framework do I need to implement that functionality?</p>

答: I would try AVAudioRecorder, specifically the section Using Audio Level Metering.


问:
Dropped table became permanently deleted
I'm new to this Oracle Database. Today  I ran DROP TABLE table1; and tried to FLASHBACK it. But the Script Output returned this :

FLASHBACK TABLE TABLE1 TO BEFORE DROP

  Error report -

  ORA-38305: object not in RECYCLE BIN

  38305. 00000 -  "object not in RECYCLE BIN"

  *Cause:    Trying to Flashback Drop an object which is not in RecycleBin.

  *Action:   Only the objects in RecycleBin can be Flashback Dropped.

I thought that the recyclebin was somehow disabled. So I opened another connection and input this command :

```<code>ALTER SESSION SET recyclebin = ON;
</code>```

and repeated the process again, the result was still the same. There was nothing in the recyclebin when I  ran SELECT * FROM RECYCLEBIN;

Did I unintentionally mess up anything ?

答: you didn't mess up anything with the command ALTER SESSION SET recyclebin = ON; but it's late to invoke that command. I think your problem is due your default tablespace to be SYSTEM for tables.

Body:
I'm new to this Oracle Database. Today  I ran DROP TABLE table1; and tried to FLASHBACK it. But the Script Output returned this :

FLASHBACK TABLE TABLE1 TO BEFORE DROP

  Error report -

  ORA-38305: object not in RECYCLE BIN

  38305. 00000 -  "object not in RECYCLE BIN"

  *Cause:    Trying to Flashback Drop an object which is not in RecycleBin.

  *Action:   Only the objects in RecycleBin can be Flashback Dropped.

I thought that the recyclebin was somehow disabled. So I opened another connection and input this command :

ALTER SESSION SET recyclebin = ON;

and repeated the process again, the result was still the same. There was nothing in the recyclebin when I  ran SELECT * FROM RECYCLEBIN;

Did I unintentionally mess up anything ?


问:
Measure performance of a Web Server
Which tools can be used to measure performance of a webserver?</p>

答:
It always depends on the setup.

Depending on the application there can be different bottlenecks.

Sometimes its the CPU, sometimtes the database connections, sometimes the sockets, sometimes the hard disc etc...

Most common practice is to use siege (simple command line tool) and increase the concurrent connections and see how many transactions per second go through.

It will increase per connection until an optimum is reached, then it will slowly decrase.

You can produce a set of urls that are randomly accessed, maby biased and/or send random data, request random ids etc to simulate more "real" clients.

Completely depends on your application whether this is relevant.

Title: Measure performance of a Web Server


答:
Oracle Flashback Drop reverses the effects of a DROP TABLE operation. It can be used to recover after the accidental drop of a table. Flashback Drop is substantially faster than other recovery mechanisms that can be used in this situation, such as point-in-time recovery, and does not lead to any loss of recent transactions or downtime.

The table and its dependent objects will remain in the recycle bin until they are purged from the recycle bin. You can explicitly purge a table or other object from the recycle bin with the command:

```<code>DROP TABLE some_table PURGE;
</code>```

Dropped objects are kept in the recycle bin until such time as no new extents can be allocated in the tablespace to which the objects belong without growing the tablespace. This condition is referred to as space pressure. Space pressure can also arise due to user quotas defined for a particular tablespace. A tablespace may have free space, but the user may have exhausted his or her quota on it.

When space pressure arises, the database selects objects for automatic purging from the recycle bin. Objects are selected for purging on a first-in, first-out basis, that is, the first objects dropped are the first selected for purging.

There is no fixed amount of space preallocated for the recycle bin. Therefore, there is no guaranteed minimum amount of time during which a dropped object will remain in the recycle bin.

To view only objects in the recycle bin, use the USER_RECYCLEBIN and DBA_RECYCLEBIN views.

Title: Dropped table became permanently deleted

Body:
Oracle Flashback Drop reverses the effects of a DROP TABLE operation. It can be used to recover after the accidental drop of a table. Flashback Drop is substantially faster than other recovery mechanisms that can be used in this situation, such as point-in-time recovery, and does not lead to any loss of recent transactions or downtime.

The table and its dependent objects will remain in the recycle bin until they are purged from the recycle bin. You can explicitly purge a table or other object from the recycle bin with the command:

DROP TABLE some_table PURGE;

Dropped objects are kept in the recycle bin until such time as no new extents can be allocated in the tablespace to which the objects belong without growing the tablespace. This condition is referred to as space pressure. Space pressure can also arise due to user quotas defined for a particular tablespace. A tablespace may have free space, but the user may have exhausted his or her quota on it.

When space pressure arises, the database selects objects for automatic purging from the recycle bin. Objects are selected for purging on a first-in, first-out basis, that is, the first objects dropped are the first selected for purging.

There is no fixed amount of space preallocated for the recycle bin. Therefore, there is no guaranteed minimum amount of time during which a dropped object will remain in the recycle bin.

To view only objects in the recycle bin, use the USER_RECYCLEBIN and DBA_RECYCLEBIN views.