Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm working on a project that selects one or more words contains entered(user) keywords.That's why I'm using a set. But the set is turkish dictionary. That is to say, it contains 68k words(most-used). How can I use datas from a text file to avoid overload?
It isn't very clear what you are asking.
If you want to load words from a text file you should look at using NSString's string parsing methods. The NSString method componentsSeparatedByString: will break a large string up into an array of pieces using the specified string as a delimiter. (You can use "\n" to separate words that are on separate lines, or " " to separate your words by spaces.)
If you want a set it's easy to load a set with the items in an array.
However I would recommend using an array and arc4random_uniform to select one of the items randomly.
Something like this
var working_array: = [String]()
let path = "your_path"
let textFile = NSString(
contentsOfFile: path,
encoding: NSUTF8StringEncoding,
error: nil)
let full_array = textFile.componentsSeparatedByString("\n")
Loading array of random words
if working_array isEmpty
{
working_array += full_array
}
fetching an element:
let random_index = arc4random_uniform(working_array.count)
a_word = working_array.removeAtIndex(random_index)
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to extract the data in my sheet from this huge paragraph. The data behind and after the highlighted data that I need to extract is fixed all the way with no change at all. I guess it can be a guideline.
I tried using Regextract but for some reason it's showing some extra data with the data that I need and I can't seem to use trim to cut it :(
Could you try this implementation I just tested? It should work alright for your purpose.
import re
text = ' 2021-06-09 00:58:49 48s Redz#gmail.com selectedPoliyCode: a8b8a620poliList: {"code":"a8b8a620","isPolicyList":true,"poliyChecked":[{"label":["Audio"],"version":"8","results":[{"results":{"action_audio":"violation"},"area_code":"ALL"}],"description":"Bullying statements in","level":"L1","pt":"ccde764f","categories":["Harassment and bullying"],"poliy":"Bullying statements in","language":"en","isRecommend":false,"checked":true,"pseudo":"","tags":["audio"],"code":"a8b8a620","keywords":["audio"],"content":"<span style=\"background: #ffff00;\">Bull</span>ying statements in NPGA","id":"ccde764f_a8b8a620_en"}]} selectedTitle: Bullying statements;pipeline_infos: {"review_target":"mt_music_report_queue","config_key":"mt_music_report","create_task_logid":"","use_hawk2_config":1,"object_id":"6943268167347227394","env":"prod","object_type":"music_report","create_time":1623166571,"fr_idc":"alisg","mos_extra_data":{}}action: Delete '
pattern_mail = r'(?:\d+s)(.*)(?:selectedPoliyCode)'
pattern_title = r'(?:selectedTitle:)(.*)?;'
pattern_object_id = r'(?:"object_id":")(.*?)(?:")'
mail = re.findall(pattern_mail, text)[0].strip()
title = re.findall(pattern_title, text)[0].strip()
object_id = re.findall(pattern_object_id, text)[0].strip()
Note that the text is the one you posted in the spreadsheet. Also, the pattern for mail might be "selectedPolicyCode".
The three variables should contain the desired values.
My solution is in python, but the regex should work the same. Let me know if it works.
mail: (?:\d+s)(.)(?:selectedPoliyCode)
title: (?:selectedTitle:)(.)?;
id: (?:"object_id":")(.*?)(?:")
Here you can find them used in the black row of words (formula is there):
https://docs.google.com/spreadsheets/d/1m7Z9R1KKwcvGN0K_2TwOO19KsehfDWIcxoL9potYG7M/edit?usp=sharing
mail: =REGEXEXTRACT(B5, "(?:\d+s)(.*)(?:selectedPoliyCode)")
title: =REGEXEXTRACT(B5, "(?:selectedTitle:)(.*)?;")
id: =REGEXEXTRACT(B5, "(?:""object_id"":"")(.*?)(?:"")")
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have an array of objects in which I need to check if it meets a specific criteria.
What I've done is looped through the array and then matched it with the ruby include? object. Problem is I've noticed that there are instances where this causes some codes to return true, when they really should be returning false.
group.plan_codes.each do |code|
normalized_plan_code = code.upcase.gsub(" ", "").gsub("+", "")
normalized_plan_code.include? coverage['plan_description'].upcase.gsub(" ", "").gsub("+", "")
end
I'm basically taking these group.plan_codes and matching them with the coverage['plan_description']. Problem I found was that if the code was something like group plan submitting a code like not group plan would still return true because the group plan is included in the plan description
Would anyone know a better way about doing this? I was thinking it could stop looking after the first element is completed, but am a little caught up on the ruby detect
Use a Regex or a straight equality test (==). For sake of clarity, let's assume (that I'm understanding your question correctly and) that you have an array such as:
plans = [ 'not group plan', 'group plan' ]
and you are trying to find the second element:
including = 'group plan'
plans.detect { |plan| plan.include?(including) }
this returns "not group plan", the first element, because it also includes the string 'group plan'. To remedy that, using regex you could use something like:
plans.detect { |plan| plan.match?(/\A#{Regexp.escape(including)}\z/) }
Now, this returns the second element, because you're looking for an exact match. Since it is an exact match, though, you could also use something simpler:
plans.detect { |plan| plan == including }
What the regex gives you is if each plan can include multiple items:
plans = ['plan a,not group plan,plan b', 'plan a,group plan,plan b']
Which is a comma separated list of plan codes and you're looking for any plan that includes 'group plan', now you can use the regex:
plans.detect { |plan| plan.match?(/,#{Regexp.escape(including)},/) }
and have the second element returned. You'll need to work the regex into a format that works for how you are saving the plan codes (in this example, I chose comma separated list, you might have tabs or semicolons or whatever else. If you have just a white space separated list of codes that can contain whitespace, you need to do more work and reject any items that include any codes that are longer and include the code you're looking for.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Trying to add the contents of an array together.
["75.00", "50.00", "25.00"] the way I'm getting that info is with
c = Credit.last
c.payments.map(&:payment_amount).to_a
I'm trying to add up all the values together in the array.
The other posters are correct in that your question doesn't conform to the how to ask guidelines. The responses are not intended to put you down but rather to maintain the quality of content for stack overflow. That said this should get you where you need to go. IN the future please read the guidelines and submit accordingly.
Credit.last.payments.sum(:payment_amount.to_f)
One thing you may not have considered is that the array ["75.00", "50.00", "25.00"] contains a bunch of strings.
If you were to sum them together like this:
["75.00", "50.00", "25.00"].sum
# or like this as one commenter suggested
["75.00", "50.00", "25.00"].reduce(&:+)
# or the long-handed version
["75.00", "50.00", "25.00"].reduce {|str, val| str + val }
You would actually get "75.0050.0025.00". This is because the individual strings in the array are getting concatenated together.
So in fact, you would need to convert the array to floats or integers first. This can be done like this:
floats = ["75.00", "50.00", "25.00"].collect(&:to_f)
# or the long-handed version
["75.00", "50.00", "25.00"].collect {|val| val.to_f }
Then you can sum the values:
sum = floats.sum
Edit:
I just tried summing a string column via ActiveRecord and got an exception ActiveRecord::StatementInvalid: TinyTds::Error: Operand data type nvarchar is invalid for sum operator.:.
payment_total = Credit.last.payments.sum(:payment_amount)
# returns ActiveRecord::StatementInvalid:
# TinyTds::Error: Operand data type nvarchar is invalid for sum
# operator.
Looks like that won't be an option for you. Although, you could change the datatype of the column so that it is something other than a string. If you change the column datatype then you will be able to use aggregate functions.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Folks, I'm trying to do the following.
I've got a array (NSArray) called 'specialLevels', that array looks like this:
specialLevels = #[#2, #4, #6, #9];
This should be a array of int's.
I also got the int 'currentLevel' (basic int no object).
And I want to check if the currentLevel is in de array of specialLevels.
I know the method 'containsObject' exists, but this won't work in my case.
What would you guys recommend to do in this case?
So I thought this, but it feels kinda strange imo:
if ([specialLevels containsObject:[NSNumber numberWithInt:currentLevel]]) {
// other code in here
}
You could alternatively write:
if ([specialLevels containsObject:#(currentLevel)]) {
// other code in here
}
which is more in keeping with the style of your other code.
specialLevels is not an array of ints. It is an array of NSNumber objects. #2, #4, #6, #8 each create an NSNumber instance equivalent to calling [[NSNumber numberWithInt:value]. When you call containsObject you also need to pass an NSNumber object so that containsObject can match the value (using isEqual:).
You can read about Objective-C literals here.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have two questions.
1) I need to create a dynamic structure, whose members are driven through an array.
For ex:
members = [:a, :b]
Config = Struct.new(members) #=> Struct.new(:a, :b)
FlatConfig = Struct.new(members) #=> Struct.new(:a, :b)
config = Config.new()
flat = FlatConfig.new()
After some days, If I need to add another member to these struct, then all I need to do is add a member in that members array (memebers = [:a, :b, :c]) and I don't need to tough the code further. Thus I am asking this. How to achieve this?
2) Now I need to build the values of flat Struct members by means of doing some manipulation on config struct member values.
For eg:
config.each{|configMember|
result = configMember.collect{|c| someArray.collect{|s| s + '--' + y}}
flat[":#{cofigMember}"] = result #=> Intent is to store result in same member as iterated through config struct.
}
How to achieve (1) and (2)?
Thanks in advance.
For your 1), use the splat operator:
Struct.new(*members)
I don't really understand your second question. Is "how can I access the same variable in two configs"?
config.members.each { |key|
configMember = config[key]
# do something
flat[key] = result
}