No output for map function in playground - swift

I have these very simple lines of code:
var friends = ["Mike", "Marika", "Andreas", "Peter", "Sabine"]
friends.map{
println("Hallo \($0)!")
}
This works fine in a program but I get no output in a playground.
It only tells me the count of the elements and how many times to function needs to run. But it does not write the strings.
Is it me or is this a bug in Xcode?

It's not a bug in Xcode. While your map code will print to the standard out (hit cmd-opt-enter to reveal the output in the assistant editor on the right), stylistically you should avoid using map for this. You would be better off with a for...in loop:
for friend in friends {
println("Hallo \(friend)")
}
If you quick-look the results this time, you'll see a more helpful result:
(note, I've switched the quick look to the list view, which shows every result, rather than just the last one)
Why is this working differently? It's because map isn't really for running arbitrary code against your array. It's more specifically for transforming (i.e. mapping) your array into another array. So suppose instead of printing a list of friends, you wanted a list of greetings, you could do this:
let greetings = friends.map { friend in
"Hallo \(friend)"
}
greetings will now be set to a new array of 5 strings, one for each name, of the form "Hallo <name>". map is taking a closure that takes a string, and maps it to a new string.
So what is happening when you write friends.map { println("...") } is that map is calling the closure, and getting the result of the expression in the closure, and populating a new array with it. Since println returns Void, the result of that expression each time is Void. And it is that Void that Xcode is displaying (as "(0 elements)" which is how the UI displays Void).
Instead, with the for-loop, Xcode knows that a stand-alone println who's value isn't being used should be interpreted not as a result, but as what got output to the standard out, so that's what it does.

Related

Gatling: Access variables from saved "findAll" list in foreach loop

I'm new to Gatling and Scala, and I had a hopefully quick and basic question about how to access the elements that are saved as from a findAll in the previous request.
The regex in the below code matches multiple button values. I eventually want to find the "max" button value (by something I'll come up with later), and based on that use that button in subsequent requests. However, I'm unable to actually access the values in button_list. In the terminal when I try to print the values, the values don't get substituted and literally print like this for each button:
Button ${count}: ${button}
Button ${count}: ${button}
Here's the snippet producing this:
...
.exec(http("click_ok")
.post("www.foo.com")
.headers(headers_0)
.formParam("_flowExecutionKey", "${flow_execution_key}")
.formParam("_eventId_submit", "${_eventId_submit}")
.check(regex("""foo(.*?)bar""").findAll.saveAs("button_list"))).exitHereIfFailed
.pause(1)
.foreach("${button_list}", "button", "count") {
exec(session => {
println("Button ${count}: ${button}")
session})
}
...
When I see the session print out in the logs, I can see that the buttons have matched and the session contains a list like the following, so I know there are successful matches:
button_list -> List(c11/98/280, c11/98/390)
Anyone have an example or know what I'm doing wrong?
Thanks!
As explained in the official documentation, Gatling Expression Language is not something that magically works anywhere. It only works when passing such String to a Gatling DSL method, not in your own code. You must use the Gatling Session API.

Function runs twice in console (python3, eclipse)

Hi! Could you please explain why the function runs twice in console?
def changeList(myList1):
myList2 = myList1.append(4)
print(myList2)
return
myList1 = [1,2,3]
changeList(myList1)
print (myList1)
The result in console:
None
[1, 2, 3, 4]
Does it mean function runs twice as "None" appears in the console?
tl;dr - the function is only running once -- there are two print statements producing output
The function is not running twice: indeed, it is only being run once. The output in the console is instead coming from the two calls to print() contained within your program: one inside the function changeList() and one outside the function (print(myList1)).
None is being printed to the console because the return statement within the function changeList() isn't returning anything - there is no value to return:
If an expression list is present, it is evaluated, else None is
substituted.
[Taken from the Python 3.6 Documentation]
Seeing as how the return statement isn't doing anything, you can safely remove it - the function will still end anyway.
Hope that helps you out!
The function is running only once. You are appending one item to list and tried to store in other list by just assigning list with one more item appending which returns None and assigns to myList2. So, the code is wrong because append() function return's None.
I think you wan't to do like this so, here is the correct code:
comment if is it solved your problem or not.
def changeList(myList1):
myList2=[]
myList2.extend(myList1)
myList2.append(4)
print(myList2)
return
myList1 = [1,2,3]
changeList(myList1)
print (myList1)
Because in the function definition of changeList, there is a print statement, and then another print statement after calling changeList. The function is only running once actually, but you simply have two separate print statements.

pytest function without return value

I'm trying to do a pytest on a function without return value, but obviously value is None in pytets. I was wondering if there is a solution for that?
here is function which I'm trying to test:
def print_top_movies_url():
for item in movie_link[:100]:
print item.contents[1]
The best thing to do would be to separate getting the top movies and printing them.
For example, you could have a top_movie_urls which looks like this:
def top_movie_urls():
urls = []
for item in movie_link[:100]:
urls.append(item.contents[1])
return urls
(or make it a generator function)
That's easy to test, and wherever you call it, you can now just do something like print('\n'.join(top_movie_urls())).
If you really want to test the output instead, you can use pytest's output capturing to access the output of the tested function and check that.

Play/Scala Template Block Statement HTML Output Syntax with Local Variable

Ok, I've been stuggling with this one for a while, and have spent a lot of time trying different things to do something that I have done very easily using PHP.
I am trying to iterate over a list while keeping track of a variable locally, while spitting out HTML attempting to populate a table.
Attempt #1:
#{
var curDate : Date = null
for(ind <- indicators){
if(curDate == null || !curDate.equals(ind.getFirstFound())){
curDate = ind.getFirstFound()
<tr><th colspan='5' class='day'>#(ind.getFirstFound())</th></tr>
<tr><th>Document ID</th><th>Value</th><th>Owner</th><th>Document Title / Comment</th></tr>
}
}
}
I attempt too user a scala block statement to allow me to keep curDate as a variable within the created scope. This block correctly maintains curDate state, but does not allow me to output anything to the DOM. I did not actually expect this to compile, due to my unescaped, randomly thrown in HTML, but it does. this loop simply places nothing on the DOM, although the decision structure is correctly executed on the server.
I tried escaping using #Html('...'), but that produced compile errors.
Attempt #2:
A lot of google searches led me to the "for comprehension":
#for(ind <- indicators; curDate = ind.getFirstFound()){
#if(curDate == null || !curDate.equals(ind.getFirstFound())){
#(curDate = ind.getFirstFound())
}
<tr><th colspan='5' class='day'>#(ind.getFirstFound())</th></tr>
<tr><th>Document ID</th><th>Value</th><th>Owner</th><th>Document Title / Comment</th></tr>
}
Without the if statement in this block, this is the closest I got to doing what I actually wanted, but apparently I am not allowed to reassign a non-reference type, which is why I was hoping attempt #1's reference declaration of curDate : Date = null would work. This attempt gets me the HTML on the page (again, if i remove the nested if statement) but doesn't get me the
My question is, how do i implement this intention? I am very painfully aware of my lack of Scala knowledge, which is being exacerbated by Play templating syntax. I am not sure what to do.
Thanks in advance!
Play's template language is very geared towards functional programming. It might be possible to achieve what you want to achieve using mutable state, but you'll probably be best going with the flow, and using a functional solution.
If you want to maintain state between iterations of a loop in functional programming, that can be done by doing a fold - you start with some state, and on each iteration, you get the previous state and the next element, and you then return the new state based on those two things.
So, looking at your first solution, it looks like what you're trying to do is only print an element out if it's date is different from the previous one, is that correct? Another way of putting this is you want to filter out all the elements that have a date that's the same date as the previous one. Expressing that in terms of a fold, we're going to fold the elements into a sequence (our initial state), and if the last element of the folded sequence has a different date to the current one, we add it, otherwise we ignore it.
Our fold looks like this:
indicators.foldLeft(Vector.empty[Indicator]) { (collected, next) =>
if (collected.lastOption.forall(_.getFirstFound != next.getFirstFound)) {
collected :+ next
} else {
collected
}
}
Just to explain the above, we're folding into a Vector because Vector has constant time append and last, List has n time. The forall will return true if there is no last element in collected, otherwise if there is, it will return true if the passed in lambda evaluates to true. And in Scala, == invokes .equals (after doing a null check), so you don't need to use .equals in Scala.
So, putting this in a template:
#for(ind <- indicators.foldLeft(Vector.empty[Indicator]) { (collected, next) =>
if (collected.lastOption.forall(_.getFirstFound != next.getFirstFound)) {
collected :+ next
} else {
collected
}
}){
...
}

What is [ ] in google chrome developer console?

While testing code in the google chrome developer console, i get
[]
and sometimes i get "".
The later shows up,when i think there not such strings available with the current selector combinations.But i still couldn't figure out the meaning of the former [] square brakets.
Please help.
With the information that you've given, all we can do is make assumptions. However, when you're logging things to the console, [] is an empty array, whereas "" is an empty string.
[] are returned whenever you jquery returns empty object. i.e. you selector expression cant locate what you are trying to search.
whereas "" is just simple string
i looked into your given site..
when i tried :
$('.four columns alpha') i get object[] (which means there jquery is returning empty object)
but when you write correct expression like :
$('.four.columns') you will get array of Div's which can be used like object.
Hope i'm able to make you understand. if any doubts do write.
And $('.four columns alpha') this is not the right way to select div's with more than one css class right way is to do something like below:
$('.four.columns.alpha')