Ruby on Rails: Retrieve css element and check value - css

I think this is a pretty straight forward question so I'll get to it:
subject.rb
def current_step
#current_step || steps.first
end
def steps
if #title = 'Baseline'
%w[sfmfa phq whoqol_bref positive_negative mses_self pam spsir change_questionnaire prosthesis cognitive comorbidity pain mspss audit ]
elsif #title = 'Treatment Completion'
%w[smfa phq whoqol_bref positive_negative pam spsir ssscq prosthesis pain complications mspss audit ptcs accessing_resources satisfaction ]
else
redirect_to #subjects_path
flash[:notice] = "Did not find title"
end
end
I'm trying to check the value of the Title element on my tc.html.erb webpage (this should return 'Treatment Completion'). At the moment the check isn't working, and I end up with the steps defined under 'Baseline' every time.
I have steps for a paginated form, and it all works for the Baseline page, so now I'm trying to pass a different set of elements as the steps definition for a different page.
I think I'm using the wrong accessor (#title). This ruby I'm using to provide the Title is:
<% provide(:title, 'Baseline') %>
Any input would be appreciated.

Well there are a couple of things that are wrong. The first thing is that you're trying to use redirect_to in a model. This should be used in a controller. Second, #subjects_path is not an instance variable, it's a url helper, so that should not have an # sign before it. Third, you're assigning, not comparing the if statement (using = and not ==).
So, to answer the original question, you could fix your original problem by:
def steps
if #title == 'Baseline'
%w[sfmfa phq whoqol_bref positive_negative mses_self pam spsir change_questionnaire prosthesis cognitive comorbidity pain mspss audit]
elsif #title == 'Treatment Completion'
%w[smfa phq whoqol_bref positive_negative pam spsir ssscq prosthesis pain complications mspss audit ptcs accessing_resources satisfaction]
else
redirect_to #subjects_path
flash[:notice] = "Did not find title"
end
end
Note that that only fixes the third error.

Related

Program recurs in different line than supposed to

I have some rules called sessions that have a Title(String) and Topics (a list of String). I'm creating a query where I input some keywords and find which session has a best match. Each keyword can have a weight (keyword is followed by -2 for example if weight of keyword is 2, if weight is 1 there is nothing next to the keyword).
My problem is in the recursion. For inputs without weights everything is ok but with weights the program recurs differently.
session('Rules; Semantic Technology; and Cross-Industry Standards',
['XBRL - Extensible Business Reporting Language',
'MISMO - Mortgage Industry Standards Maintenance Org',
'FIXatdl - FIX Algorithmic Trading Definition Language',
'FpML - Financial products Markup Language',
'HL7 - Health Level 7',
'Acord - Association for Cooperative Operations Research and Development (Insurance Industry)',
'Rules for Governance; Risk; and Compliance (GRC); eg; rules for internal audit; SOX compliance; enterprise risk management (ERM); operational risk; etc',
'Rules and Corporate Actions']).
session('Rule Transformation and Extraction',
['Transformation and extraction with rule standards; such as SBVR; RIF and OCL',
'Extraction of rules from code',
'Transformation and extraction in the context of frameworks such as KDM (Knowledge Discovery meta-model)',
'Extraction of rules from natural language',
'Transformation or rules from one dialect into another']).
accessList([H|T], H, T).
is_empty_string(String) :-
String == ''.
not_empty_string(String) :-
String \== ''.
get_weight_of_token(MyToken, WeightOfToken) :-
split_string(MyToken,"-","",TempList), % tokenize MyToken into a list ( [string_of_token, weight_of_token] )
accessList(TempList,_,TempWeight), %
accessList(TempWeight,TempWeight2,_), % accessing the tail of the list (weight_of_token)
number_string(WeightOfToken,TempWeight2) % convert string to number
;
WeightOfToken is 1.
find_relevance([], SessionTitle, SessionTopics).
find_relevance([H | T], SessionTitle, SessionTopics) :-
get_weight_of_token(H, WeightOfToken),
format('Token = ~w with weight = ~d ~n', [H,WeightOfToken]),
format('Title = ~w~nTopics = ~w ~n', [SessionTitle,SessionTopics]),
find_relevance(T, SessionTitle, SessionTopics).
query(ListOfKeywords) :-
is_empty_string(ListOfKeywords), write('List of keywords is empty!')
;
not_empty_string(ListOfKeywords),
split_string(ListOfKeywords," ","",KeywordsTokens), %tokenize string with space as separator
session(Title,Topics), find_relevance(KeywordsTokens, Title, Topics), fail.
With an input without weights like 'firword secword', this is the result:
https://imgur.com/a/Q2fU2IM
As you can see the program recurs fine and calls find_revelance for the next session.
With an input with weights like 'firword-2 secword', this is the result:
https://imgur.com/xKFpFvh
As you can see the program doesn't recur to (9) for the next session but recurs to (10) for some reason.. and specifically to the part after ;..
Why is this happening? Thanks in advance.
*I changed the titles and topics to something smaller so the images can be more clear

How to make this function where I can give it an argument or not

So I made this very small function. it is a bonehead easy function but frankly borderline my capabilities.. Im learning. The function works as expected, but I would like to go further. I would like to make it so I can either give it an argument (a username) and just get the information for that single user, or default to reporting all users. is this possible w/o starting over from what I have so far?
I have just poked around and seen some examples but nothing that I can fit into my script. that I can understand at least.
import boto3
iam = boto3.client('iam')
def user_group():
for myusers in iam.list_users()['Users']:
Group = iam.list_groups_for_user(UserName=myusers['UserName'])
print("User: " + myusers['UserName'])
for groupName in Group['Groups']:
print("Group: " + groupName['GroupName'])
print("----------------------------")
user_group()
I would like to have the ability to run this script in two fashions.
1) add an argument(s) of 'username' so I can get the response for a particular user
2) default to getting response for all users if no argument is given.
This can be done by using an argument with a default value:
def user_group(user = None):
if user is None:
print("No user")
else:
print(user)
user_group()
user_group('some user')
prints
No user
some user
In your case you may want to write
def user_group(user = None):
users_to_list = iam.list_users()['Users'] if user is None else [user]
for myusers in user_to_list:
...

Rails conditional CSS in view helper

I have a simple rails app and I'm trying to write a view helper that does the following.
Compares two values. If the current_month amount is greater than the forecast amount then make the text green. If the current_month amount is less than the forecast amount then make the text red.
I wrote out this simple helper to append text to the output of the the rails method, but I'm unsure of how to inject CSS/styling into this.
def target_hit(forecast, current)
(if current.amount > forecast.amount
number_to_currency(current.amount.to_s) + " Yay"
elsif current.amount < forecast.amount
number_to_currency(current.amount.to_s) + " No dice"
end).html_safe
end
I'm pretty proficient on the backend but when it comes to front-end stuff I'm stumbling a lot. Any help would be greatly appreciated.
example view code
<p class='total'>Current: <%= target_hit(#forecast, #current) %></p>
The rails helper content_tag http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag, is useful and means you don't have to use html_safe. I try to move all the logic from the views to helpers to make the view easy to read e.g.
def target_hit(current_amt, forecast_amt)
content_tag(:p, "#{number_to_currency(current_amt.to_s)} target_content(current_amt, forecast_amt)", class: "total #{target_class(current_amt, forecast_amt)}")
end
def target_content(current_amt, forecast_amt)
forecast_reached?(current_amt, forecast_amt) ? "Yay" : "No dice"
end
def target_class(current_amt, forecast_amt)
forecast_reached?(current_amt, forecast_amt) ? "green" : "red"
end
def forecast_reached?(current_amt, forecast_amt)
current_amt >= forecast_amt
end
in the view, you just call the helper method
<%= target_hit(#current.amount, #forecast.amount) %>

How can I find the duration of a song when given its ID using XQuery?

First off, yes this is homework - please suggest where I am going wrong,but please do not do my homework for me.
I am learning XQuery, and one of my tasks is to take a list of song ID's for a performance and determine the total duration of the performance. Given the snippits below, can anyone point me to where I can determine how to cross reference the songID from the performance to the duration of the song?
I've listed my attempts at the end of the question.
my current XQuery code looks like:
let $songIDs := doc("C:/Users/rob/Downloads/A4_FLOWR.xml")
//SongSet/Song
for $performance in doc("C:/Users/rob/Downloads/A4_FLOWR.xml")
//ContestantSet/Contestant/Performance
return if($performance/SongRef[. =$songIDs/#SongID])
then <performanceDuration>{
data($performance/SongRef)
}</performanceDuration>
else ()
Which outputs:
<performanceDuration>S005 S003 S004</performanceDuration>
<performanceDuration>S001 S007 S002</performanceDuration>
<performanceDuration>S008 S009 S006</performanceDuration>
<performanceDuration>S002 S004 S007</performanceDuration>
Each S00x is the ID of a song, which us found in the referenced xml document (partial document):
<SongSet>
<Song SongID="S001">
<Title>Bah Bah Black Sheep</Title>
<Composer>Mother Goose</Composer>
<Duration>2.99</Duration>
</Song>
<Song SongID="S005">
<Title>Thank You Baby</Title>
<Composer>Shania Twain</Composer>
<Duration>3.02</Duration>
</Song>
</SongSet>
The performance section looks like:
<Contestant Name="Fletcher Gee" Hometown="Toronto">
<Repertoire>
<SongRef>S001</SongRef>
<SongRef>S002</SongRef>
<SongRef>S007</SongRef>
<SongRef>S010</SongRef>
</Repertoire>
<Performance>
<SongRef>S001</SongRef>
<SongRef>S007</SongRef>
<SongRef>S002</SongRef>
</Performance>
</Contestant>
My Attempts
I thought I would use nested loops, but that fails:
let $songs := doc("C:/Users/rob/Downloads/A4_FLOWR.xml")
//SongSet/Song
for $performance in doc("C:/Users/rob/Downloads/A4_FLOWR.xml")
//ContestantSet/Contestant/Performance
return if($performance/SongRef[. =$songs/#SongID])
for $song in $songIDs
(: gives an error in BaseX about incomplete if :)
then <performanceDuration>{
data($performance/SongRef)
}</performanceDuration>
else ()
--Edit--
I've fixed the inner loop, however I am getting all the songs durations, not just the ones that match id's. I have a feeling that this is due to variable scope, but I'm not sure:
let $songs := doc("C:/Users/rob/Downloads/A4_FLOWR.xml")//SongSet/Song
for $performance in doc("C:/Users/rob/Downloads/A4_FLOWR.xml")//ContestantSet/Contestant/Performance
return if($performance/SongRef[. =$songs/#SongID])
then <performanceDuration>{
for $song in $songs
return if($performance/SongRef[. =$songs/#SongID])
then
sum($song/Duration)
else ()
}</performanceDuration>
else ()
}
Output:
<performanceDuration>2.99 1.15 3.15 2.2 3.02 2.25 3.45 1.29 2.33 3.1</performanceDuration>
Your immediate problem is syntactic: you've inserted your inner loop between the condition and the keyword 'then' in a conditional. Fix that first:
return if ($performance/SongRef = $songs/#SongID) then
<performanceDuration>{
(: put your inner loop HERE :)
}</performanceDuration>
else ()
Now think yourself into the situation of the query evaluator inside the performanceDuration element. You have the variable $performance, you can find all the song references using $performance/SongRef, and for each song reference in the performance element, you can find the corresponding song element by matching the SongRef value with $songs/#SongID.
My next step at this point would be to ask myself:
For a given song reference, how do I find the song element for that song, and then the duration for that song?
Is there a way to get the sum of some set of durations? Is there, for example, a sum() function? (I'm pretty sure there is, but at this point I always pull up the Functions and Operators spec and look it up to be sure of the signature.)
What type does the duration info have? I'd expect it to be minutes and seconds, and I'd be worrying about duration arithmetic, but your sample makes it look like decimals, which will be easy.

How can I model a scalable set of definition/term pairs?

Right now my flashcard game is using a prepvocab() method where I
define the terms and translations for a week's worth of terms as a dictionary
add a description of that week's terms
lump them into a list of dictionaries, where a user selects their "weeks" to study
Every time I add a new week's worth of terms and translations, I'm stuck adding another element to the list of available dictionaries. I can definitely see this as not being a Good Thing.
class Vocab(object):
def __init__(self):
vocab = {}
self.new_vocab = vocab
self.prepvocab()
def prepvocab(self):
week01 = {"term":"translation"} #and many more...
week01d = "Simple Latvian words"
week02 = {"term":"translation"}
week02d = "Simple Latvian colors"
week03 = {"I need to add this":"to self.selvocab below"}
week03d = "Body parts"
self.selvocab = [week01, week02] #, week03, weekn]
self.descs = [week01d, week02d] #, week03, weekn]
Vocab.selvocab(self)
def selvocab(self):
"""I like this because as long as I maintain self.selvocab,
the for loop cycles through the options just fine"""
for x in range(self.selvocab):
YN = input("Would you like to add week " \
+ repr(x + 1) + " vocab? (y or n) \n" \
"Description: " + self.descs[x] + " ").lower()
if YN in "yes":
self.new_vocab.update(self.selvocab[x])
self.makevocab()
I can definitely see that this is going to be a pain with 20+ yes no questions. I'm reading up on curses at the moment, and was thinking of printing all the descriptions at once, and letting the user pick all that they'd like to study for the round.
How do I keep this part of my code better maintained? Anybody got a radical overhaul that isn't so....procedural?
You should store your term:translation pairs and descriptions in a text file in some manner. Your program should then parse the text file and discover all available lessons. This will allow you to extend the set of lessons available without having to edit any code.
As for your selection of lessons, write a print_lesson_choices function that displays the available lessons and descriptions to the user, and then ask for their input in selecting them. Instead of asking a question of them for every lesson, why not make your prompt something like:
self.selected_weeks = []
def selvocab(self):
self.print_lesson_choices()
selection = input("Select a lesson number or leave blank if done selecting: ")
if selection == "": #Done selecting
self.makevocab()
elif selection in self.available_lessons:
if selection not in self.selected_weeks:
self.selected_weeks.append(selection)
print "Added lesson %s"%selection
self.selvocab() #Display the list of options so the user can select again
else:
print "Bad selection, try again."
self.selvocab()
Pickling objects into a database means it'll take some effort to create an interface to modify the weekly lessons from the front end, but is well worth the time.

Resources