Rxjava - How to get the current and the previous item? - kotlin

How do to use operators so that i always get the previous and the current value? If possible i want to avoid creating state outside the pipe.
- time ->
1 2 3 4
| | | |
Operations
| | |
(1,2) (2,3) (3,4)
Note that every value besides the first and the last one have to appear twice, so a simple buffer won't do.
I thought about combining skip with merge and buffer but merge does not seem to guarantee ordering.
val s = PublishSubject.create<Int>()
s.mergeWith(s.skip(1)).buffer(2).subscribe{i -> print(i)}
s.onNext(1)
s.onNext(2)
s.onNext(3)
s.onNext(4)
output:
[1, 2][2, 3][3, 4]
val o = Observable.just(1,2,3,4)
o.mergeWith(o.skip(1)).buffer(2).subscribe{i -> print(i)}
output:
[1, 2][3, 4][2, 3][4]
(the sole 4 is fine, and expected)

Looks like you still can use buffer:
Observable.just(1, 2, 3, 4)
.buffer(2, 1)
.subscribe { println(it) }
// prints
// [1, 2]
// [2, 3]
// [3, 4]
// [4]

Related

How to modify each element of a block by "foreach" in red/rebol

I want to modify each element of a block by foreach. I tried like this but failed:
>> a: [3 4 5 6]
== [3 4 5 6]
>> foreach i a [i + 1]
== 7
>> a
== [3 4 5 6] ;; block a is not changed. What I want is [4 5 6 7]
Is there a better way to achieve it?
Changes that you made to values do not persist in a block itself. This ties back to your question about call-by-value parameter passing in Rebol and Red: you modify a copy on the stack (passed down to + along with 1), not the actual value slot that sits inside block a.
To achieve what you want, you need to increment integers in-place, without pushing them on the stack. One way to do so is by using forall.
>> block: [1 2 3]
== [1 2 3]
>> also block forall block [block/1: block/1 + 1]
== [2 3 4]
What forall does is setting a word to a series and then incrementally bumping its index:
>> forall block [probe block]
[1 2 3]
[2 3]
[3]
Since it doesn't extract the actual values, you can access them using path notation, and then modify them in place. block/1 always pick the first value on each iteration.
As usual, no reply with your foreach.
a: [2 3 4 5]
b: copy []
foreach i a [append b i + 1]
and if you wish you can set a to b now
a: b
The problem with doing this in one step is that you do not have an index you can use here (despite the suggestive letter i, but that is representing the content of each item inside the block).
So now you can choose your favourite solution.
>> help forall
USAGE:
FORALL 'word body
DESCRIPTION:
Evaluates body for all values in a series.
FORALL is a native! value.
ARGUMENTS:
'word [word!] "Word referring to series to iterate over."
body [block!]
use forall
> a: [3 4 5 6]
== [3 4 5 6]
>> forall a [a/1: a/1 + 1]
== 7
>> probe a
[4 5 6 7]
== [4 5 6 7]

Most elegant way to extract block by skipping every 2 element

Let's say I have
block: [a 1 b 2 c 3]
I want
[1 2 3]
Something like this is clunky and it doesn't work because I use word type (I'd like to have it word with word not string):
block: [a 1 b 2 c 3]
block2: []
counter: -1
foreach 'element block [
counter: negate counter
if counter append block2 element
]
The EXTRACT function should fit the bill here:
>> extract/index [a 1 b 2 c 3] 2 2
== [1 2 3]
It's fairly versatile for this type of thing.
>> help extract
USAGE:
EXTRACT series width
DESCRIPTION:
Extracts a value from a series at regular intervals.
EXTRACT is a function! value.
ARGUMENTS:
series [series!]
width [integer!] "Size of each entry (the skip)".
REFINEMENTS:
/index => Extract from an offset position.
pos [integer!] "The position".
/into => Provide an output series instead of creating a new one.
output [series!] "Output series".

What's the preferred way to implement Data Driven Testing using Elixir/ExUnit?

I'd like to reuse the same code of a test case for several handcrafted combinations of input data and expected outcomes, but without copypasting the code for each set. Frameworks in other languages support it in different ways, for example in Groovy/Spock:
def "maximum of two numbers"(int a, int b, int c) {
expect:
Math.max(a, b) == c
where:
a | b | c
1 | 3 | 3
7 | 4 | 4
0 | 0 | 0
}
What's the preferred way to do this in ExUnit?
Maybe ExUnit is not the best framework to this?
I guess you could do something very simple like:
test "Math.max/2" do
data = [
{1, 3, 3},
{7, 4, 4},
]
for {a, b, c} <- data do
assert Math.max(b, c) == a
end
end
Pattern matching allows you to be pretty explicit when doing these thing in my opinion. And you can keep the simplicity of just variables and assertions, all inside ExUnit.
You can also wrap test definitions with an enumerable. Dave Thomas's Blog provides an extended example.
data = [
{1, 3, 3},
{7, 4, 4},
]
for {a,b,c} <- data do
#a a
#b b
#c c
test "func "<>#a<>", "<>#b<>" equals"<>#c do
assert fun(#a,#b) == #c
end
end
For a relatively simple test like this, I'm not sure this approach is any better, but for more complex tests this can provide better reporting and you can dynamically create tests at test time by using a function as in
the blog entry.

Understanding PsychoPy's data logging

I have a test PsychoPy Builder script that I am using to investigate some counter-intuitive behaviour. The structure is four routines:
"Init", not in a loop, the following code in "Begin Experiment":
x = 0
y = 0
z = 0
foo = [0, 0, 0]
"One", in a loop, the following code in "End Routine":
x = x + 1
foo[0] = foo[0] + 1
thisExp.addData("x", x)
thisExp.addData("y", y)
thisExp.addData("z", z)
thisExp.addData("foo", foo)
"Two", in a loop, the following code in "End Routine":
y = y + 2
foo[1] = foo[1] + 2
thisExp.addData("x", x)
thisExp.addData("y", y)
thisExp.addData("z", z)
thisExp.addData("fooY", foo[1])
thisExp.addData("foo", foo)
"Three", in a loop, the following code in "End Routine":
z = z + 3
foo[2] = foo[2] + 3
thisExp.addData("x", x)
thisExp.addData("y", y)
thisExp.addData("z", z)
thisExp.addData("foo", foo)
There is no other code, no other components. The routines "One", "Two", and "Three" form a loop in that order executed five times. The relevant columns of the CSV output file are as follows:
trials.thisRepN trials.thisTrialN trials.thisN trials.thisIndex x y z foo fooY
0 0 0 0 1 2 3 [5, 10, 15] 2
1 0 1 0 2 4 6 [5, 10, 15] 4
2 0 2 0 3 6 9 [5, 10, 15] 6
3 0 3 0 4 8 12 [5, 10, 15] 8
4 0 4 0 5 10 15 [5, 10, 15] 10
Is this the expected output? If so, why? Note that the individual variables, x, y, and z, are displaying updated values each time through the loop (at the end of the loop), while the list foo shows only the final value after the loop iterates all five times, but it shows this in every line. But calling out individual elements of the list displays as individual variables do.
What is the logic and rationale behind this?
Is there a way to make the list output perform as the others do?
Is there a way to force the output to capture/display any of these variables as they are when the addData() is invoked rather than waiting until the end of the loop?
I think I know what is going wrong here. It's probably because python assigns by reference rather than copy. This is explained in detail elsewhere but briefly,
original = [1, 2]
new = original # new is simply a reference to original! It is not a copy.
new[0] = 'Oops' # original is now ['Oops', 2] as is new (which is just a reference or pointer
In your case, the TrialHandler receives the reference, which simply points to the "foo" variable which is updated throughout the experiment. Since the log is only saved in the end of the experiment, all the rows in "foo" now points to the "foo variable" which now holds the value [5, 10, 15].
This assignment-by-reference can be extremely beautiful and handy, but sometimes cause headache like in your example. It applies to all python mutables: lists, dicts, functions, and classes. But not for immutables, like numbers, tuples and strings! That's why your script works for digits but not for the list.
There are different solutions. The simplest is probably to replace the addData calls with thisExp.addData("foo", tuple(foo)) which converts the mutable list to an immutable tuple. One can also do thisExp.addData("foo", [x for x in foo]). A more all-round solution for all kinds of objects is to run import copy in the beginning of the experiment and then add data like thisExp.addData("foo", copy.copy(foo)) in the other codeblocks (if you have a complicated object, use copy.deepcopy instead).

How to format two separate lists in columns, rather than rows in Mathematica?

This seems like it should be a piece of cake, but I haven't found the answer in Mathematica's documentation. Say I have two separate lists, for example x={1,2,3,4,5} and y={1,4,9,16,25}. I want to format these lists as a table with each list as a column, like this:
x y
1 1
2 4
3 9
4 16
5 25
But if I do TableForm[x,y], I get only the first column, like this:
1
2
3
4
5
If I do Grid[{x,y}], I get a table, but formatted as rows instead of columns, like this:
1 2 3 4 5
1 4 9 16 25
Now, if I have my values as {x,y} pairs, rather than separate lists, then I can get almost what I want,like so:
Input: Table[{n,n^2},{n,1,5}]//TableForm
Output:
1 1
2 4
3 9
4 16
5 25
I say almost, because I'd like to have the variable names at the top of each column, and I'd like the columns justified so that the ones digits are always placed vertically in the "ones place", the tens digits in the "tens place", etc.
So, back to my question: If I have two separate lists of the same length, how can I format them as a table of columns? I checked the MMA documentation for Grid and TableForm, but I couldn't find a way to do it. Did I miss something? If there's no direct way to do it, is there a way to transform two separate lists into pairs of values that could then be formatted in columns using TableForm?
Thanks for any suggestions you might have.
Personally I prefer Grid to TableForm. Maybe something like this?
Some preliminaries:
x = {1, 2, 3, 4, 5};
y = {1, 4, 9, 16, 25};
grid = Transpose#{x, y};
headings = {{Item["x", Frame -> {True, True}],
Item["y", Frame -> {True, False}]}};
The following code,
Grid[Join[headings, grid], Alignment -> Right, Dividers -> All,
Spacings -> {3, 1}, FrameStyle -> Orange]
gives this as output, for example:
Often in Mathematica, you use Transpose to switch the role of row and column.
In[6]:= x = {1,2,3,4,5}; y = {1,4,9,16,25};
In[7]:= {x,y} // Transpose // TableForm
Out[7]//TableForm= 1 1
2 4
3 9
4 16
5 25
Instead of using Transpose you can use the option TableDirection:
x={1,2,3,4,5};y={1,4,9,16,25};
TableForm[{x,y},TableDirections->Row,TableHeadings->{{"x","y"}}]
Grid[Transpose[{x, y}], Alignment -> Right]
I would use:
x = {1, 2, 3, 4, 5};
y = {1, 4, 9, 16, 25};
TableForm[{{x, y}}, TableAlignments -> Right]
Here are some more convoluted examples, demonstrating the way TableForm works. It does get complicated, and I usually have to experiment a bit to get what I want.
a = {1, 2, 3};
b = {4, 5, 6};
{a, b} // TableForm
{{a}, {b}} // TableForm
{{{a}}, {{b}}} // TableForm
{{{a}, {b}}} // TableForm
{{List /# a, List /# b}} // TableForm
{{a}, b} // TableForm
{{{a}, b}} // TableForm
{{{a}}, {b}} // TableForm
{{{{a}}, {b}}} // TableForm