I have a json data like below :
data :[
{
"application_number": 1274930,
"status": "Removed",
},
{
"application_number": 1550670,
"status": "Registered",
},
{
"application_number": 1562368,
"status": "Registered",
},
{
"application_number": 1625492,
"status": "Objected",
},
{
"application_number": 1644092,
"status": "Registered",
},
{
"application_number": 1691808,
"status": "Removed",
},
{
"application_number": 1726161,
"status": "Registered",
}
]
I want to get the unique values of status only. Something like this:
["Removed", "Objected", "Registered"]
I found a similar question and solution there was in javascript :- _.keys(_.countBy(data, function(data) { return data.name; }));
Is there a similar way in ruby to find this ?
you achieve this by following ways:
uniq_status = []
data.each do |tupple|
uniq_status << tupple['status'] if status.include?(tupple['status'])
end
uniq_tupple
#$> ["Removed", "Objected", "Registered"
data.collect{|tupple|tupple["status"]}.uniq
#$> ["Removed", "Objected", "Registered"
data.group_by {|tupple| tupple["status"]}.keys
#$> ["Removed", "Objected", "Registered"
data.uniq {|tupple| tupple["status"]}.collect{|tupple|tupple['status']}
#$> ["Removed", "Objected", "Registered"
I hope this will help you.
Related
I want to use elasticsearch configuration about mapping to display user location and his/her direction to admin in my web app. so I create an index in elasticsearch like:
{
"settings": {
"index": {
"number_of_shards": 5,
"number_of_replicas": 1
},
"analysis": {
"analyzer": {
"analyzer-name": {
"type": "custom",
"tokenizer": "keyword",
"filter": "lowercase"
}
}
}
},
"mappings": {
"properties": {
"driver_id": { "type": "integer" },
"email": { "type": "text" },
"location": { "type": "geo_point" },
"app-platform": { "type": "text" },
"app-version": { "type": "text" },
"created_at": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"}
}
}
}
and start to inserting user location to elasticsearch with this curl
{
"driver_id": 357,
"driver_email": "Andrew#mailinatior.com",
"location": {
"lat": 37.3,
"lon": 59.52
},
"created_at": "2021-06-04 00:09:00"
}
this structure came from user mobile to my elasticsearch, after that I wrote these services to fetch data for my web-end part of my designing:
module Api
module V1
module Drivers
module Elastic
class LiveLocation
include Peafowl
attribute :driver_id, ::Integer
def call
#driver = ::Driver.find(driver_id) if driver_id.present?
result = []
options = {
headers: {
'Content-Type' => 'application/json'
},
body: #driver.present? ? options_with_driver : options
}
begin
response = HTTParty.get(elasticseach_url.to_s, options)
records = JSON.parse(response.body)['hits']['hits']
if records.present?
records.group_by { |r| r['_source']['driver_id'] }.to_a.each do |record|
driver = ::Driver.where(id: record[0]).first
if driver.present?
location = record[1][0]['_source']['location']
app_platform = record[1][0]['_source']['app-platform']
app_version = record[1][0]['_source']['app-version']
result.push(driver_id: driver.id, driver_email: driver.profile.email, location: location, app_platform: app_platform, app_version: app_version)
end
end
end
rescue StandardError => error
Rails.logger.info "Error => #{error}"
result = []
end
context[:response] = result
end
def elasticseach_url
"#{ENV.fetch('ELASTICSEARCH_BASE_URL', 'http://127.0.0.1:9200')}/#{ENV.fetch('ELASTICSEARCH_DRIVER_POSITION_INDEX', 'live_location')}/_search"
end
def options
{
query: {
bool: {
filter: [
{
range: {
created_at: {
gte: (Time.now.beginning_of_day.strftime '%Y-%m-%d %H:%M:%S')
}
}
}
]
}
},
sort: [
{
created_at: {
order: 'desc'
}
}
]
}.to_json
end
def optinos_with_driver
{
query: {
bool: {
must: [
{
term: {
driver_id: {
value: #driver.id
}
}
}
],
filter: [
{
range: {
created_at: {
gte: (Time.now.beginning_of_day.strftime '%Y-%m-%d %H:%M:%S')
}
}
}
]
}
},
sort: [
{
created_at: {
order: 'desc'
}
}
]
}.to_json
end
end
end
end
end
end
this structure working perfectly but even if the user stops while elasticsearch saves his location but I need to filter user data that if the user stops for one hour in place elasticsearch understand and not saving data. Is it possible?
I use elsticsearch 7.1
and ruby 2.5
I know it's possible in kibana but I could not using kibana at this tim.
I am not sure if this can be done via a single ES query...
However you can use 2 queries:
one to check if the user's location's during the last hour is the same
Second same then don't insert
But i don't recommend that
What you could do:
Use REDIS or any in-mem cache to maintain the user's last geo-location duration
Basis that, update or skip update to Elastic Search
PS: I am not familiar with ES geo-location API
I am using graph API to add message rule which is forward a mail from user's inbox. Rule is getting added but mails are not forwarding to specified id.
Here are some details:
var data = {
"displayName": "From partner",
"sequence": 1,
"isEnabled": true,
"conditions": {
"isAutomaticForward": true
},
"actions": {
"forwardTo": [
{
"emailAddress": {
"name": "recipient name ",
"address": "email address"
}
}
],
"stopProcessingRules": true
}
}
axios.post("https://graph.microsoft.com/v1.0/users/{userId}/mailFolders/inbox/messageRules", data,
{
headers: {
"Authorization": "Bearer " + access_token
}
}
)
.then(response => {
console.log(response.data)
})
.catch(err => {
console.log(err.response)
})
Response is as expected but mails are not forwarding.
I tried the above payload, steps and it works for me!!
(1) Create a new rule using Graph API
POST https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messageRules
Content-type: application/json
{
"displayName": "From partner",
"sequence": 2,
"isAutomaticForward": true,
"actions": {
"forwardTo": [
{
"emailAddress": {
"name": "Alex Wilbur",
"address": "AlexW#contoso.onmicrosoft.com"
}
}
],
"stopProcessingRules": true
}
}
(2) Test whether the rule is working or not.
Result: It's working as expected
(3) Check that the above rule shows or not (as part of Outlook.office.com or Outlook UI's rule section)
Adding a snapshot that i captured from Outlook.office.com, mailbox settings!!
Im having a problem in getting Autopilot redirect to work
After redirecting to my POST url it stops saying anything.
Below is my code:
{
"actions": [
{
"collect": {
"name": "password_reset_collect",
"questions": [
{
"question": "I will perform password reset to your account. Do you wish to continue?",
"name": "continue",
"type": "Twilio.YES_NO"
}
],
"on_complete": {
"redirect": "https://88fb4b1a.ngrok.io/Voice/Post"
}
}
},
{
"remember": {
"action_query": "password_reset"
}
}
]
}
and in my POST url it returns JSON result using return Content() as follows
var response = "{\"actions\": [{\"say\": {\"speech\": \"Thank you! Have a good day\" }},{\"listen\": true }]}";
return Content(response, "application/json");
result:
{
"actions": [
{
"say": {
"speech": "Thank you! Have a good day"
}
},
{
"listen": true
}
]
}
It never say what I specified in the on JSON and the call end
What am I doing wrong?
Twilio developer evangelist here.
I'd try putting Remember before Collect, as mentioned on the Actions docs page.
With the following long controller action code
#available = Available.find(694)
#tareservation_id = 8943
#request_date_time = Time.now.utc.iso8601
#request_id = Time.now.to_i
#in_date = (Date.today + 24.days).strftime("%Y-%m-%d").to_s
#book = %Q|{
"booking": {
"currencyCode": "USD",
"languageCode": "es",
"paxNationality": "ES",
"clientRef": {
"value": \"#{#tareservation_id}\",
"mustBeUnique": true
},
"items": [
{
"itemNumber": 1,
"immediateConfirmationRequired": true,
"productCode": \"#{#available.product_code}\",
"leadPaxName":
{ "firstName": "Guy",
"lastName": "Test"
},
"product":
{
"period":
{
"start": "2018-08-27",
"quantity": 2
}
}
} ]
},
"requestAuditInfo":
{ "agentCode": "001",
"requestPassword": "pass",
"requestDateTime": \"#{#requestDateTime}\",
"requestID": #{#request_id} },
"versionNumber": "2.0"
}|
This then must be shipped off to the API as JSON in the body call
#result = HTTParty.post(
'https://test.com/search',
:body => JSON.parse(#book).to_json,
headers: {
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Connection' => 'Keep-Alive'
}
)
If the following block is removed:
,
"product":
{
"period":
{
"start": "2018-08-27",
"quantity": 2
}
}
in console JSON.parse(#start), parses properly. With the block JSON::ParserError: 784: unexpected token. Yet I fail to see what is incorrect here?
Is Rails handling of string for future JSON conversion really strict on syntax, particularly since there is interpretation of instance variables - both as strings and integers - and har returns involved? What would it be then? Or is there a safer solution to get out of what quickly becomes quicksand?
It turns out that pasting too many lines into the console (iTerm2, in this case) does something to the memory. 25 lines of code pasted in a single time is the maximum observered where behaviour is as expected.
I have to update multiple invideo promotion details for a particular channel.
My request is as follows:
var requestOptions={
part: 'invideoPromotion',
onBehalfOfContentOwner: 'contentOwner',
resource:{
id: channelId,
invideoPromotion: {
"defaultTiming": {
"offsetMs": 2000,
"type": "offsetFromStart"
},
"items": [
{
"promotedByContentOwner": true,
"timing":
{
"offsetMs":4000,
"duration" : 5000,
"type":"offsetFromStart"
},
"id":{
"videoId": videoid1,
"type": "video"
}
},
{
"promotedByContentOwner": true,
"timing":
{
"offsetMs":11000,
"duration" : 5000,
"type":"offsetFromStart"
},
"id":{
"videoId": videoId2,
"type": "video"
}
}
],
"position": {
"type": "corner",
"cornerPosition": "topLeft"
}
}
}
};
console.log(requestOptions);
var request = gapi.client.youtube.channels.update(requestOptions);
request.execute(function (response) {});
But when i try to execute this, I am getting error
0: {error:{code:500}, id:gapiRpc}
error: {code:500}
code: 500
id: "gapiRpc"
Even When I try to do this using the youtube api explorer
https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.channels.update ,
I am getting Internal server Error.
Can somebody let me know where I am going wrong.
You cannot promote more than one video. I also tried the same but getting an error "exceeded the number of promoted items". So you can only promote one video at a time.