I am using embed.ly API, but when using example code i just get a long string of data and not an object i can access the different parts of, here is my code:
embedly_api = Embedly::API.new :key => 'HIDDEN', :user_agent => 'Mozilla/5.0 (compatible; mytestapp/1.0; my#email.com)'
url = 'http://www.guardian.co.uk/media/2011/jan/21/andy-coulson-phone-hacking-statement'
obj = embedly_api.oembed :url => url
obj[0].marshal_dump
The obj[0] returns:
{:provider_url=>"http://www.guardian.co.uk/", :description=>"11.25am: Andy Coulson, the the director of communications at No 10, is to make a \"personal statement\". He has been under pressure in recent months over the phone-hacking scandal, with a slew of revelations in a number of civil court cases that appeared to bring the scandal closer to his door.", :title=>"Andy Coulson resigns – as it happened", :url=>"http://www.guardian.co.uk/media/2011/jan/21/andy-coulson-phone-hacking-statement", :thumbnail_width=>140, :thumbnail_url=>"https://static-secure.guim.co.uk/sys-images/Guardian/Pix/pictures/2011/1/14/1295010840306/Andy-Coulson-003.jpg", :version=>"1.0", :provider_name=>"Guardian", :type=>"link", :thumbnail_height=>84}
What i want is to access obj[0].provider_url, description and so on... how?
obj[0][:provider_url]
should do the trick.
Related
I took this to the Godot Reddit first, but honestly it's not much help imo. A lot of questions go unanswered there. So here I am.
As the title says, Im making a quest system in godot 2d using nested dictionaries. Ive seen people use Nodes, Classes or otherwise for their quest systems, and a few dictionary based ones out there. I chose dictionaries as I know them the best(still isnt a whole lot, or i probably wouldnt be here asking this lol) And my quest system is set up like so:
QuestBase --> QuestHandler --> PlayerData
QuestBase is a giant dictionary of all available quests in the game.
PlayerData is a giant dictionary of all the player stats(including active, completed, or failed quests)
and QuestHandler takes a questName in a function to Copy the quest(questName) from QuestBase dict into the PlayerData.quests_active dict.(quests_active is a dictionary of quests(also dictionaries) inside of the PlayerData dictionary lol) But i cant seem to get it to work. I've done it a couple different ways now, including the way the Godot documentation states on how to add Dinctionaries into dictionaries. Please help, this is the error I get from QuestHandler:
Invalid set index 'tutorialQuest' (on base: 'Nil') with value of type 'Dictionary'
QuestBase:
var storyQuests = {
"tutorialQuest":{
"name" : "Your First Steps",#Name of the Quest
"desc" : "Get to know your environment and learn the ropes.",#Description of the Quest
"level" : 1, #Required level before player can accept quest
"questType" : 0, #0=Story Quest || 1=Side Quest || 2=Repeateable Quest
"taskType": 0, #0=Progressive(task must be completed in order) || 1=Synchronous(tasks can be completed in any order, and all at once)
"tasks":{#Dictionary of Quest's Tasks
"task1":{
"text":"Talk to Bjorn",#Text to display in Quest log
"type":0,#0=Talk,1=Slay,2=Fetch,3=Deliver,4=Collect,5=Goto
"quantity":0,#Determines the amount to complete task for Slay, Fetch, and Collect
"target":"Bjorn",#Determines Who to talk to, or who to slay, or what to collect.
"completed":false#Is this task complete?
},
"task2":{
"text":"Talk to Bjorn",
"type":"Talk",
"target":"Bjorn",
"completed":false
},
"task3":{
"text":"Talk to Bjorn",
"type":"Talk",
"target":"Bjorn",
"completed":false
}
},
"itemReward":{
"items":["Sword", "Basic Elixer"],#Names of items to give
"amount":[1, 5]#Amount of each item to give, respectively.
},
"expReward":{
"skill":["Forestry","Smithing"],#Names of skills to add Exp to
"amount": [100,100] #Amount to add to each skill, respectively.
#1st number will increase first skill in "skill", etc...
},
"Complete":false,
"Failed":false
}
}
PlayerData:
var playerData = {
... irrelevant player data...
#Quests
"quests_active": {"blank":"blank"},
"quests_completed": {},
"quests_failed": {},
and Finally, Quest Handler:
func startQuest(questName: String):
var active_quests = PlayerData.playerData.get("quests_active")
if QuestBase.storyQuests.has(questName):
var questCopy = QuestBase.storyQuests.get(questName).duplicate(true)
PlayerData.playerData.get("quests_active")[questName] = questCopy #.quests_active.append(questCopy)
#print("Story Quest Started: " + PlayerData.playerData.QuestsActive.get(questName).get("name"))
elif QuestBase.sideQuests.has(questName):
var questCopy = QuestBase.sideQuests.get(questName).duplicate(true)
active_quests.append(questCopy)
#print("Side Quest Started: " + PlayerData.playerData.QuestsActive.get(questName).get("name"))
else:
print("Quest Doesn't Exist! Check Spelling!")
I am trying to update Dynamo Table using expression, I am trying to generate keys dynamically. The issue looks like if they key has space in it, expressions don't evaluate properly.
Following in my update implementation:
update_expression = 'SET {}'.format(','.join(f'#{p}=:{p}' for p in row_as_dict))
expression_attribute_values = {f':{p}': v for p, v in row_as_dict.items()}
expression_attribute_names = {f'#{p}': p for p in row_as_dict}
if result_set.get('Item') and result_set.get('Item').get(primary_key):
TABLE.update_item(
Key={
primary_key: row_as_dict[primary_key],
sort_key: row_as_dict[sort_key]
},
UpdateExpression=update_expression,
ExpressionAttributeValues=expression_attribute_values,
ExpressionAttributeNames=expression_attribute_names
)
if i print the values for update_expression and expression_attribute_values and expression_attribute_names i get following output.
update_expression
SET #Ref No=:Ref No,#FT/Hot=:FT/Hot,#Irfan watch List=:Irfan watch List,#F.Soahil watchList=:F.Soahil watchList,#HR Responible=:HR Responible,#Pipeline(Adv/Ref)=:Pipeline
(Adv/Ref),#Source=:Source,#Date Submitted=:Date Submitted,#Name=:Name,#Candidate Location=:Candidate Location,#Tech =:Tech ,#Current Company=:Current Company,#Exp=:Exp,#Position being considered for=:Position being considered for,#Proj. / Gen Hiring=:Proj. / Gen Hiring,#Comments / Latest Status / Next Step=:Comments / Latest Status / Next Step,#Status=:Status,#hiring status=:hiring status,#Link to Lever=:Link to Lever,#LinkedIn Link / Resume=:LinkedIn Link / Resume,#Interview Feedback Google Doc=:Interview Feedback Google Doc,#Email=:Email
expression_attribute_values
{':Ref No': '1', ':FT/Hot': 'NaN', ':Irfan watch List': 'NaN', ':F.Soahil watchList': 'NaN', ':HR Responible': 'Khurram', ':Pipeline\r\n(Adv/Ref)': 'Referred', ':Source': 'Usman Khan', ':Date Submitted': '17-Dec', ':Name': 'Asif Mahmood Mughal Zain', ':Candidate Location': 'ISL', ':Tech ': 'Spark. Hadoop\r\nSQL, Big Data', ':Current Company': 'Zain Telecom', ':Exp': '18+', ':Position being considered for': 'Senior SA', ':Proj. / Gen Hiring': 'General', ':Comments / Latest Status / Next Step': 'Muhammaf Naseer Recommneded\r\nAdeel Ashraf Recommended\r\nFaheem Khan Recommended\r\n\r\nAccepted offer.will join on 6 jan', ':Status': 'Joined', ':hiring status': 'Hired', ':Link to Lever': 'Link to Lever', ':LinkedIn Link / Resume': 'Asif Mehmood Mughal', ':Interview Feedback Google Doc': 'Link to Feedback', ':Email': 'some_email1#test.com'}
expression_attribute_names
{'#Ref No': 'Ref No', '#FT/Hot': 'FT/Hot', '#Irfan watch List': 'Irfan watch List', '#F.Soahil watchList': 'F.Soahil watchList', '#HR Responible': 'HR Responible', '#Pipeline\r\n(Adv/Ref)': 'Pipeline\r\n(Adv/Ref)', '#Source': 'Source', '#Date Submitted': 'Date Submitted', '#Name': 'Name', '#Candidate Location': 'Candidate Location', '#Tech ': 'Tech ', '#Current Company': 'Current Company', '#Exp': 'Exp', '#Position being considered for': 'Position being considered for', '#Proj. / Gen Hiring': 'Proj. / Gen Hiring', '#Comments / Latest Status / Next Step': 'Comments / Latest Status / Next Step', '#Status': 'Status', '#hiring status': 'hiring status', '#Link to Lever': 'Link to Lever', '#LinkedIn Link / Resume': 'LinkedIn Link / Resume', '#Interview Feedback Google Doc': 'Interview Feedback Google Doc', '#Email': 'Email'}
The Error generated is
An error occurred (ValidationException) when calling the UpdateItem operation: ExpressionAttributeValues contains invalid key: Syntax error; key: ":hiring status"
You can't have spaces in your attribute keys/values in the expression. So :hiring status needs to be something like :hiring_status.
Go Dynamof!
You might be very interested in dynamof. Its a library purposed to do exactly what your trying to do. At the very least you can take a peak and check out how it handles dynamically creating all the expressions.
I suggest you take a look at the args module.
It has the functions that do what your trying to do. The args module gets some help from another module (the request builder) in dynamof that is responsible for some preprocessing of the entire action's arguments so the args module's functions get an easy to use and parse RequestTree object.
Answer...
I would just use dynamof - but I'm biased. If you want to write it yourself, heres a little example on how its been done straight from dynamof.
def UpdateExpression(request: RequestTree):
def expression(attr):
if attr.func is not None:
return attr.func.expression(attr)
return f'{attr.alias} = {attr.key}'
key_expressions = [expression(key) for key in request.attributes.values]
key_expression = ', '.join(key_expressions)
return f'SET {key_expression}'
NOTE: The attr.alias is whats used to handle the special name cases - like spaces. Its set in the request builder module mentioned above.
disclaimer: I wrote dynamof
Say I have a GRPC order that looks like this when generated:
Google::Protobuf::DescriptorPool.generated_pool.build do
add_message "something.Order" do
optional :uuid, :string, 1
repeated :shipments, :message, 2, "something.Shipment"
...
end
end
So an Order has many shipments. When I create the order to send back as a response in the service... how do I create the many shipments?
Can I just do:
order = Order.find(request.id)
Something::Order.new(uuid: order.id, shipments: [order.shipments)
Or does it needs to be:
order = Order.find(request.id)
Something::Order.new(uuid: order.id, shipments: [order.shipments.attributes)
I get the latter from these docs
I'm not sure but it looks like the google-protobuf package is used here?
(https://github.com/google/protobuf).
If that's the case, I don't think the ruby-protobuf docs are relevant here.
For using Google::Protobuf here, it looks like you should be able to add an array of Shipment objects to the 'shipments' field of an 'Order' instance.
I am trying to figure out what is working and why the other way is not working for me.
At the moment I have a list of shops I use and I need to change the naming every time; so I have decided to go by the product_id which never changes, but my code is not working.
product_id <- vector()
This one is not working:
product_name[product_id == '40600000003'] <- 'my cool store']
but this one does work:
product_name[product_name == 'my#cool#Store'] <- 'my cool store'
Now, I am not sure what am I doing wrong, I tried to do:
if (product_id == '40600000003') {
product_name = 'my cool shop'
}
I have a list of 15 shops that I need to change the naming as they arrive in the wrong format from the api connection.
Try 40600000003 instead of '40600000003' it's more than likely reading your vector slots as int if it doesn't contain any characters
I am trying to get my console to print out a summation of all my Locations rate card pricing.
I am trying to complete this task through the console but getting a BigDecimal as the result. Stuck on how to convert this result into a legible string or integer.
Results:
Location.pluck(:rate_card).sum
=> "#<BigDecimal:7f7cf347edd0,'0.3091675E6',18(36)>"
In my Location 'index', to be able to see a dollar amount, I have this setup as:
<%= number_to_currency(location.rate_card, :precision => 2) %>
TIA
Location.each do |e|
puts e.rate_card.to_s.to_f.round(2)
end
You're seeing :rate_card returned as a BigDecimal because that's how it's defined in your database schema. If you were to issue Location.rate_card.class in a Rails console you'll see => BigDecimal.
As was mentioned by #Darby, you can use round. In a console, issue Location.pluck(:rate_card).sum.round(2) and that should show the desired result rounded properly.
Lastly, is there significance to the second part of your results? You show the code you're using to display the view code properly but I don't think it has bearing on your question.
A BigDecimal can be converted to a string like this.
pry(main)> b = BigDecimal.new('78.23')
=> #<BigDecimal:7ff0119cab68,'0.7823E2',18(18)>
[37] pry(main)> b.to_s
=> "0.7823E2"
You don't need to change this to a string first and then a float.
to_f is defined on a BigDecimal object.
[34] pry(main)> b.to_f
=> 78.23
There is also to_i and to_r for integers and rationals respectively.