multiple if's for calculated field in tableau - if-statement

please pardon the absolutely newbie question but i'm very new to tableau.
what I'd like to do is create a message based on which filter flags are active. so, in psuedo code, i'd do something like this:
message = ''
if filter1 == 1:
message += 'filter 1 is active'
if filter2 == 1:
message += ' filter 2 is active'
return message
problem is, I'm not even sure how to do multiple if statements - i keep getting a syntax error. Any help will be greatly appreciated.

Here is an example of how I accomplished something similar:
IF [ZAVUFA1_FED_COLL_CHOICE_1] = 'xxxxx' THEN 1
ELSEIF [ZAVUFA1_FED_COLL_CHOICE_2] = 'xxxxx' THEN 2
ELSEIF [ZAVUFA1_FED_COLL_CHOICE_3] = 'xxxxx' THEN 3
ELSEIF [ZAVUFA1_FED_COLL_CHOICE_4] = 'xxxxx' THEN 4
ELSEIF [ZAVUFA1_FED_COLL_CHOICE_5] = 'xxxxxx' THEN 5
ELSEIF [ZAVUFA1_FED_COLL_CHOICE_6] = 'xxxxx' THEN 6
ELSEIF [ZAVUFA1_FED_COLL_CHOICE_7] = 'xxxxxx' THEN 7
ELSEIF [ZAVUFA1_FED_COLL_CHOICE_8] = 'xxxxxx' THEN 8
ELSEIF [ZAVUFA1_FED_COLL_CHOICE_9] = 'xxxxx' THEN 9
ELSEIF [ZAVUFA1_FED_COLL_CHOICE_10] = 'xxxxxx' THEN 10
ELSEIF ISNULL([ZAVUFA1_FED_COLL_CHOICE_1]) THEN 99
END
As much as I love stackoverflow, Tableau also has a great user forum on their site.

You would create a calculated field called message with this code:
IF filter1 = 1 THEN 'filter 1 is active' END
+ IF filter2 = 1 THEN ' filter 2 is active' END

what I ended up doing is creating a calculated field for each if statement. I then created yet another calculated field that concatenates all of the output from each of the first set of calculated fields I created. Seems like a bit of a hack so If anyone knows of a more elegant way of doing this (making a calculated field of a series of calulated fields seems awfully kludgy) I'd be glad to pass on the points for answering.

Related

Text.StartsWith but with a number field?

I've got the below as a transformation step against a table, but it isn't working. I think it's due to the fact that it's not a text field, but a number field.
= Table.ReplaceValue(
#"Custom1",
each [Sign],
each if Text.StartsWith([Account No], "4") then -1 else [Sign] ,
Replacer.ReplaceText,{"Sign"}
)
If I create a Step with the following, I get correct results for those [Account No] valuese that start with a 4.
= Table.AddColumn(#"Replaced Value2", "AccountNoStartsWithFour", each Text.StartsWith([Account No], "4"))
Does anyone know what I need to do to get this working?
There are values such as:
4001
4201
1240
3556
I have a sample file here: https://easyupload.io/7v68iw
Is this what you require?
= Table.ReplaceValue(AccountNoStartsWithFour, each [Sign] ,each if Text.StartsWith([Account No], "4") then -1 else [Sign],Replacer.ReplaceValue,{"Sign"})

Calculate the difference between 2 rows in PowerBI using DAX

I'm trying to complete something which should be quite simple but for the life of me, I can't work it out.
I'm trying to calculate the difference between 2 rows that share the same 'Scan type'.
I have attached a photo showing sample data from production. We run a scan and depending on the results of the scan, it's assigned a color.
I want to find the difference in Scan IDs between each Red scan.
Using the attached Photo of Sample data, I would expect a difference of 0 for id 3. A difference of 1 for id 4 and a difference of 10 for id 14.
I have (poorly) written something that works based on the maximum value from the scan id.
I have also tried following a few posts to see if I can get it to work..
var _curid= MAX(table1[scanid])
var _curclueid = MAX(table1[scanid])
var _calc =CALCULATE(SUM(TABLE1[scanid],FILTER(ALLSELECTED(table1[scanid]),table1[scanid]))
return if(_curid-_calc=curid,0,_curid-_calc)
Edit;
Forgot to mention I have checked threads;
57699052
61464745
56703516
57710425
Try the following DAX and if it helps then accept it as the answer.
Create a calculated column that returns the ID where the colour is Red as follows:
Column = IF('Table'[Colour] = "Red", 'Table'[ID])
Create another column as following:
Column 2 =
VAR Colr = 'Table'[Colour]
VAR SCAN = 'Table'[Scan ID]
VAR Prev_ID =
CALCULATE(MAX('Table'[Column 2]),
FILTER('Table', 'Table'[Colour] = Colr && 'Table'[Scan ID] < SCAN))
RETURN
'Table'[Column] - Prev_ID
Output:
EDIT:-
If you want your first value(ID3) to be 0 then relace the RETURN line with the following line:
IF(ISBLANK(Prev_ID) && 'Table'[Colour] = "Red", 0, 'Table'[Column] - Prev_ID )
This will give you the following result:

Python 2.7 - use waitKeys to capture user input (string) of a specified length

Please note I am a novice trying to learn
I've searched for ages, but haven't found an answer to my problem.
Basically, I'm displaying a number of alphabetical characters on a screen. The number of character increases in increments (5, 7, 9).
What I need is to have the loop pause and wait for the user to input the characters they've just seen, but so far, the code I have only seems to allow the user to input ONE character (or keypress), and I can't figure out how to make it keep waiting until a specified number of characters has been entered by the user. My code is below:
letter5.draw()
win.flip()
respClock.reset()
core.wait(info['letterTime'])
win.flip()
#wait for response
respList = waitKeys(maxWait = float('inf'), keyList = letters)
keys = respList [0]
I think a while loop may work here, but I've not managed to come up with a piece of code that works properly.
Thanks for any help!
Figured it out on my own and thought I'd share:
resp = ''
done = False
while len(resp) < 4:
respList = waitKeys(maxWait = float('inf'), keyList = alpha)
key = respList[0]
if len(key) == 1:
resp += key
elif key == 'space':
resp += ''
elif key == 'backspace' and len(resp) > 0:
resp = resp[0:-1]
if key == 'return':
done = True

Pandas: Iterate on a column one row at a time to automate a google search?

I am trying to automate 100 google searches (one per individual String in a row and return urls per each query) on a specific column in a csv (via python 2.7); however, I am unable to get Pandas to read the row contents to the Google Search automater.
*GoogleSearch source = https://breakingcode.wordpress.com/2010/06/29/google-search-python/
Overall, I can print Urls successfully for a query when I utilize the following code:
from google import search
query = "apples"
for url in search(query, stop=5, pause=2.0):
print(url)
However, when I add Pandas ( to read each "query") the rows are not read -> queried as intended. I.E. "data.irow(n)" is being queired instead of the row contents, one at a time.
from google import search
import pandas as pd
from pandas import DataFrame
query_performed = 0
querying = True
query = 'data.irow(n)'
#read the excel file at column 2 (i.e. "Fruit")
df = pd.read_csv('C:\Users\Desktop\query_results.csv', header=0, sep=',', index_col= 'Fruit')
# need to specify "Column2" and one "data.irow(n)" queried at a time
while querying:
if query_performed <= 100:
print("query")
query_performed +=1
else:
querying = False
print("Asked all 100 query's")
#prints initial urls for each "query" in a google search
for url in search(query, stop=5, pause=2.0):
print(url)
Incorrect output I receive at the command line:
query
Asked all 100 query's
query
Asked all 100 query's
Asked all 100 query's
http://www.irondata.com/
http://www.irondata.com/careers
http://transportation.irondata.com/
http://www.irondata.com/about
http://www.irondata.com/public-sector/regulatory/products/versa
http://www.irondata.com/contact-us
http://www.irondata.com/public-sector/regulatory/products/cavu
https://www.linkedin.com/company/iron-data-solutions
http://www.glassdoor.com/Reviews/Iron-Data-Reviews-E332311.htm
https://www.facebook.com/IronData
http://www.bloomberg.com/research/stocks/private/snapshot.asp?privcapId=35267805
http://www.indeed.com/cmp/Iron-Data
http://www.ironmountain.com/Services/Data-Centers.aspx
FYI: My Excel .CSV format is the following:
B
1 **Fruit**
2 apples
2 oranges
4 mangos
5 mangos
6 mangos
...
101 mangos
Any advice on next steps is greatly appreciated! Thanks in advance!
Here's what I got. Like I mentioned in my comment, I couldn't get the stop parameter to work like i thought it should. Maybe i'm misunderstanding how its used. I'm assuming you only want the first 5 urls per search.
a sample df
d = {"B" : ["mangos", "oranges", "apples"]}
df = pd.DataFrame(d)
Then
stop = 5
urlcols = ["C","D","E","F","G"]
# Here i'm using an apply() to call the google search for each 'row'
# and a list is built for the urls return by search()
df[urlcols] = df["B"].apply(lambda fruit : pd.Series([url for url in
search(fruit, stop=stop, pause=2.0)][:stop])) #get 5 by slicing
which gives you. Formatting is a bit rough on this
B C D E F G
0 mangos http://en.wikipedia.org/wiki/Mango http://en.wikipedia.org/wiki/Mango_(disambigua... http://en.wikipedia.org/wiki/Mangifera http://en.wikipedia.org/wiki/Mangifera_indica http://en.wikipedia.org/wiki/Purple_mangosteen
1 oranges http://en.wikipedia.org/wiki/Orange_(fruit) http://en.wikipedia.org/wiki/Bitter_orange http://en.wikipedia.org/wiki/Valencia_orange http://en.wikipedia.org/wiki/Rutaceae http://en.wikipedia.org/wiki/Cherry_Orange
2 apples https://www.apple.com/ http://desmoines.citysearch.com/review/692986920 http://local.yahoo.com/info-28919583-apple-sto... http://www.judysbook.com/Apple-Store-BtoB~Cell... https://tr.foursquare.com/v/apple-store/4b466b...
if you'd rather not specify the columns (i.e. ["C",D"..]) you could do the following.
df.join(df["B"].apply(lambda fruit : pd.Series([url for url in
search(fruit, stop=stop, pause=2.0)][:stop])))

Doctrine2 How to compare two result sets

I have two entities: Category and Icon they have a many to many relationship so i end up with three tables: category icon and icon_category
My goal is to find Icons that are in multiple categories.
For example I have the following
categories: a b c and icons 1 2 3
Here are the categories for the icons:
1 - a b
2 - a
3 - c
I would like to search for an icon that is in category a and b and get 1 as the result.
My first approach was to load in each category (a and b) into separate results and then compare using array_intersect():
$cats = array();
foreach($terms as $term){
$cat = $em->getRepository('SixStringPearBundle:Category')->findOneBy(array("name" => $term));
if($cat){
$cats[$term] = $cat->getIcons();
}
}
This returned $cats[a] = array(icon(1), icon(2) and $cats[b] = array(icon(1))
I then tried the following:
$res = array_shift($cats);
foreach($cats as $cat){
$res = array_intersect($res, $cat);
}
but got the following error: Argument #1 is not an array
I checked the type of $cat[a] and $cat[b] and they are a Doctrine Persistence Collection
I also tried calling $res = $res->toArray() and $cat = $cat->toArray() before calling array_intersect This resolved the error but did not return the expected results: Icon(1)
Does anyone have any thoughts or maybe even a better approach to all of this?
I ended up using the doctrine query builder. It was agonizing but I finally figure it out. Here is the end result:
$qb->select('i')
->from('SixStringPearBundle:Icon', 'i')
->leftJoin('i.categories', 'c')
->where('c.name IN (?1)')
->groupBy('i.id')
->having('count(i.id) = ?2')
->setParameters(array(1 => $terms, 2 => count($terms)));