how to use Slice function for json format in ruby? - ruby

{
"Message": "Action completed. Completed the Request. One or more of the subsequent operations did not succeed. Please check the logs.",
"Details": null
}
from the above json response i want to print only "Action completed. Completed the Request"

Here is another approach using the slice function as mentioned in the question. I've used a regexp match to extract the part of the string interesting for you.
require "json"
data = JSON.parse('{
"Message": "Action completed. Completed the Request. One or more of the subsequent operations did not succeed. Please check the logs.",
"Details": null
}')
res = payload.inject('') { |r, (k, v)| r = v.slice(/^.+\..*\./) if k == :Message; r }
# => "Action completed. Completed the request."
As #andredurao said, there are multiple ways to achieve it and slice is not the only one.

There are many different ways to do this...
One of them is:
split the message data sentences (split)
get the two first items from split ([0..1])
join them back with a dot (join("."))
split the message data sentences, using the dots as separator:
require "json"
payload = '{
"Message": "Action completed. Completed the Request. One or more of the subsequent operations did not succeed. Please check the logs.",
"Details": null
}'
data = JSON.parse(payload)
puts data["Message"].split(".")[0..1].join(".") # "Action completed. Completed the Request"

Related

gorm use the find rerurn empty

I use the find method to find some records,but when I send the wrong condition.it should return the
ErrRecordNotFound,but it return a empty struct
var projectSetBudget domain.ProjectSetBudget
filter := &domain.ProjectSetBudget{}
filter.TenantID = tenantID
filter.ID = ProjectSetBudgetID
res := r.db.Where(filter).Find(&projectSetBudget)
i just print the info
zap.S().Info(errors.Is(res.Error, gorm.ErrRecordNotFound))
it print false
and return the empty struct
{
"ID": 0,
"CreatedAt": "0001-01-01T00:00:00Z",
"UpdatedAt": "0001-01-01T00:00:00Z",
"DeletedAt": null,
"title": "",
}
GORM provides First, Take, Last methods to retrieve a single object from the database, it adds LIMIT 1 condition when querying the database, and it will return the error ErrRecordNotFound if no record is found.
https://gorm.io/docs/query.html
only First, Take, Last methods but find
if you use First, Take, Last there will be ErrRecordNotFound
First, Take, Last have folow code, but find have not, find will find not only one, so you can know it found or not by count:
tx.Statement.RaiseErrorOnNotFound = true

How can I filter if any value of an array is contained in another array in rethinkdb/reql?

I want to find any user who is member of a group I can manage (using the webinterface/javascript):
Users:
{
"id": 1
"member_in_groups": ["all", "de-south"]
},
{
"id": 2
"member_in_groups": ["all", "de-north"]
}
I tried:
r.db('mydb').table('users').filter(r.row('member_in_groups').map(function(p) {
return r.expr(['de-south']).contains(p);
}))
but always both users are returned. Which command do I have to use and how can I use an index for this (I read about multi-indexes in https://rethinkdb.com/docs/secondary-indexes/python/#multi-indexes but there only one value is searched for)?
I got the correct answer at the slack channel so posting it here if anyone else comes to this thread through googling:
First create a multi index as described in
https://rethinkdb.com/docs/secondary-indexes/javascript/, e. g.
r.db('<db-name>').table('<table-name>').indexCreate('<some-index-name>', {multi: true}).run()
(you can omit .run() if using the webadmin)
Then query the data with
r.db('<db-name>').table('<table-name>').getAll('de-north', 'de-west', {index:'<some-index-name>'}).distinct()

Debugging data structure errors in BigQuery

BigQuery often ends bq load with ambiguous
Waiting on <jobid> ... (68s) Current status: DONE
BigQuery error in load operation: Error processing job
'<jobid>': Too many errors
encountered. Limit is: {1}.
When I do bq --format=prettyjson show -j <jobid> to find out what's wrong, I get:
"status": {
"errorResult": {
"message": "Too many errors encountered. Limit is: {1}.",
"reason": "invalid"
},
"errors": [
{
"message": "Too many errors encountered. Limit is: {1}.",
"reason": "invalid"
}
],
"state": "DONE"
},
Which usually indicates that bq dislikes something about the data structure.
But how can I find out what is wrong? Which row or column bq exits on with error?
Update
Apparently, sometimes, bq returns "Failure details", where it says which column and line caused an error. But I couldn't replicate getting these details. They appear arbitrary on the same instance, data, and command.
I found a few options in bq help load to let the data pass through:
--[no]autodetect: Enable auto detection of schema and options for formats that are not self
describing like CSV and JSON.
--[no]ignore_unknown_values: Whether to allow and ignore extra, unrecognized values in CSV or
JSON import data.
--max_bad_records: Maximum number of bad records allowed before the entire job fails.
(default: '0')
(an integer)
They allow dropping bad values, but many rows may be lost. And I couldn't find where bq returns the number of dropped rows.

How to use multiple dimension and metric values in google adsense version api 1.4

When generating reports from google adsense management api v 1.4 can how listed here :
https://developers.google.com/adsense/management/v1.4/reference/accounts/reports/generate
I checked out the metrics and dimension given here :
https://developers.google.com/adsense/management/metrics-dimensions
I tried to pass these values in request and its working fine for me :
startDate=2015-07-07&
endDate=2015-07-12&
dimension=AD_UNIT_NAME&
metric=AD_REQUESTS_CTR
But how should i pass multiple metric values ?
for example if i want metric values :
AD_REQUESTS_RPM ,
AD_REQUESTS_RPM ,
CLICKS ,
EARNINGS etc
I tried to separate them with normal and url-encoded values of
":"
","
" " (space)
But nothing works for me , i am getting this error :
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalidParameter",
"message": "Invalid value 'AD_REQUESTS_CTR:AD_REQUESTS_RPM'. Values must match the following regular expression: '[a-zA-Z_]+'",
"locationType": "parameter",
"location": "metric[0]"
}
],
"code": 400,
"message": "Invalid value 'AD_REQUESTS_CTR:AD_REQUESTS_RPM'. Values must match the following regular expression: '[a-zA-Z_]+'"
}
}
so i found the solution to pass multiple metric and dimension value and i think its a really poor api design by google adsense team .
This is how it works :
GET https://www.googleapis.com/adsense/v1.4/accounts/pub-423423423432/reports?alt=json&
startDate=2015-07-07&
endDate=2015-07-12&
dimension=AD_UNIT_NAME&
metric=AD_REQUESTS_RPM&
metric=AD_REQUESTS_RPM&
metric=CLICKS&
metric=EARNINGS

GoogleCustom API number of results

How is possible to get more results then 10 with googlecoustom API? I think its just take results from 1st page... when I type to search more then 10 I get this error:
Here is request:
https://www.googleapis.com/customsearch/v1?q=Montenegro&cx=002715630024689775911%3Ajczmrpp_vpo&num=10&key={YOUR_API_KEY}
num=10 is number of results
400 Bad Request
- Show headers -
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalid",
"message": "Invalid Value"
}
],
"code": 400,
"message": "Invalid Value"
}
}
Well It is not possible to get more than 10 result from Google Custom Search API.
https://developers.google.com/custom-search/v1/using_rest#query-params
As You can see for num parameter you valid values are only between 1 and 10 inclusive.
To get more result you should make multiple calls. in each different call, increase the value of parameter 'start' by 10. That should do it
For first page result, use
https://www.googleapis.com/customsearch/v1?q=Montenegro&cx=002715630024689775911%3Ajczmrpp_vpo&num=10&start=1&key={YOUR_API_KEY}
This query asks google to provide 10 results starting from position 1. Now you can not ask google for more than 10 results at a time. So you have to query again asking for 10 result starting from 11. So In next query, keep num=10 and start=11. Now you can get all the results by changing start value.

Resources