repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.send_document | def send_document(params)
extra_params_validation = {
document: { required: true, class: [File, String] }
}
send_something(:document, params, extra_params_validation)
end | ruby | def send_document(params)
extra_params_validation = {
document: { required: true, class: [File, String] }
}
send_something(:document, params, extra_params_validation)
end | [
"def",
"send_document",
"(",
"params",
")",
"extra_params_validation",
"=",
"{",
"document",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"File",
",",
"String",
"]",
"}",
"}",
"send_something",
"(",
":document",
",",
"params",
",",
"extra_params_validation",
")",
"end"
] | Sends a document to a user or group chat.
@param [Hash] params hash of paramers to send to the sendDocument API operation.
@option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).
@option params [File,String] :document Required. File to send. You can either pass a file_id as String to resend a file that is already on the Telegram servers, or upload a new file using multipart/form-data.
@option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message
@option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.
@example
bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
my_secret_file = File.open("secrets.doc")
bot.send_document(chat_id: 123456789, document: my_secret_file)
@raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation
@raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down
@return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat | [
"Sends",
"a",
"document",
"to",
"a",
"user",
"or",
"group",
"chat",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L288-L294 | train |
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.send_sticker | def send_sticker(params)
extra_params_validation = {
sticker: { required: true, class: [File, String] }
}
send_something(:sticker, params, extra_params_validation)
end | ruby | def send_sticker(params)
extra_params_validation = {
sticker: { required: true, class: [File, String] }
}
send_something(:sticker, params, extra_params_validation)
end | [
"def",
"send_sticker",
"(",
"params",
")",
"extra_params_validation",
"=",
"{",
"sticker",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"File",
",",
"String",
"]",
"}",
"}",
"send_something",
"(",
":sticker",
",",
"params",
",",
"extra_params_validation",
")",
"end"
] | Send WebP images as stickers.
@param [Hash] params hash of paramers to send to the sendSticker API operation.
@option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).
@option params [File,String] :sticker Required. Sticker to send. You can either pass a file_id as String to resend a file that is already on the Telegram servers, or upload a new file using multipart/form-data.
@option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message
@option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.
@example
bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
sticker_file = File.open("my-sticker.webp")
bot.send_sticker(chat_id: 123456789, sticker: sticker_file)
@raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation
@raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down
@see #send_document
@return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat | [
"Send",
"WebP",
"images",
"as",
"stickers",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L314-L320 | train |
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.send_video | def send_video(params)
extra_params_validation = {
video: { required: true, class: [File, String] },
duration: { required: false, class: [Integer] },
caption: { required: false, class: [String] }
}
send_something(:video, params, extra_params_validation)
end | ruby | def send_video(params)
extra_params_validation = {
video: { required: true, class: [File, String] },
duration: { required: false, class: [Integer] },
caption: { required: false, class: [String] }
}
send_something(:video, params, extra_params_validation)
end | [
"def",
"send_video",
"(",
"params",
")",
"extra_params_validation",
"=",
"{",
"video",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"File",
",",
"String",
"]",
"}",
",",
"duration",
":",
"{",
"required",
":",
"false",
",",
"class",
":",
"[",
"Integer",
"]",
"}",
",",
"caption",
":",
"{",
"required",
":",
"false",
",",
"class",
":",
"[",
"String",
"]",
"}",
"}",
"send_something",
"(",
":video",
",",
"params",
",",
"extra_params_validation",
")",
"end"
] | Sends a video file to a user or group chat.
At this moment, Telegram only support mp4 videos. If you need to send other formats you must use #send_document.
@param [Hash] params hash of paramers to send to the sendVideo API operation.
@option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).
@option params [File,String] :video Required. Video to send. You can either pass a file_id as String to resend a video that is already on the Telegram servers, or upload a new video file.
@option params [Integer] :duration Optional. Duration of sent video in seconds.
@option params [String] :caption Optional. Video caption (may also be used when resending videos by file_id).
@option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message
@option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.
@example
bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
my_video = File.open("foo.mp4")
bot.send_video(chat_id: 123456789, video: my_video)
@raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation
@raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down
@see #send_document
@return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat | [
"Sends",
"a",
"video",
"file",
"to",
"a",
"user",
"or",
"group",
"chat",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L344-L352 | train |
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.send_location | def send_location(params)
extra_params_validation = {
latitude: { required: true, class: [Float] },
longitude: { required: true, class: [Float] }
}
send_something(:location, params, extra_params_validation)
end | ruby | def send_location(params)
extra_params_validation = {
latitude: { required: true, class: [Float] },
longitude: { required: true, class: [Float] }
}
send_something(:location, params, extra_params_validation)
end | [
"def",
"send_location",
"(",
"params",
")",
"extra_params_validation",
"=",
"{",
"latitude",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"Float",
"]",
"}",
",",
"longitude",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"Float",
"]",
"}",
"}",
"send_something",
"(",
":location",
",",
"params",
",",
"extra_params_validation",
")",
"end"
] | Sends point on the map to a user or group chat.
@param [Hash] params hash of paramers to send to the sendAudio API operation.
@option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).
@option params [Float] :latitude Required. Latitude of location.
@option params [Float] :longitude Required. Longitude of location.
@option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message.
@option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.
@example
bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
bot.send_location(chat_id: 123456789, latitude: 38.775539, longitude: -4.829988)
@raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation
@raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down
@return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat | [
"Sends",
"point",
"on",
"the",
"map",
"to",
"a",
"user",
"or",
"group",
"chat",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L371-L378 | train |
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.send_chat_action | def send_chat_action(params)
params_validation = {
chat_id: { required: true, class: [Fixnum, String] },
action: { required: true, class: [String] }
}
api_request('sendChatAction', params, params_validation)
end | ruby | def send_chat_action(params)
params_validation = {
chat_id: { required: true, class: [Fixnum, String] },
action: { required: true, class: [String] }
}
api_request('sendChatAction', params, params_validation)
end | [
"def",
"send_chat_action",
"(",
"params",
")",
"params_validation",
"=",
"{",
"chat_id",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"Fixnum",
",",
"String",
"]",
"}",
",",
"action",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"String",
"]",
"}",
"}",
"api_request",
"(",
"'sendChatAction'",
",",
"params",
",",
"params_validation",
")",
"end"
] | Sends a status action to a user or group chat.
Used when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status).
@param [Hash] params hash of paramers to send to the sendChatAction API operation.
@option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).
@option params [String] :action Required. Type of action to broadcast. Choose one, depending on what the user is about to receive: "typing" for text messages, "upload_photo" for photos, "record_video" or "upload_video" for videos, "record_audio" or "upload_audio" for audio files, "upload_document" for general files, "find_location" for location data.
@example
bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
bot.send_chat_action(chat_id: 123456789, action: "typing")
@raise [Telegrammer::Errors::BadRequestError]
@raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down
@return [Telegrammer::ApiResponse] Response from the API. | [
"Sends",
"a",
"status",
"action",
"to",
"a",
"user",
"or",
"group",
"chat",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L396-L403 | train |
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.get_user_profile_photos | def get_user_profile_photos(params)
params_validation = {
user_id: { required: true, class: [Fixnum] },
offset: { required: false, class: [Fixnum] },
limit: { required: false, class: [Fixnum] }
}
response = api_request('getUserProfilePhotos', params, params_validation)
Telegrammer::DataTypes::UserProfilePhotos.new(response.result).to_h
end | ruby | def get_user_profile_photos(params)
params_validation = {
user_id: { required: true, class: [Fixnum] },
offset: { required: false, class: [Fixnum] },
limit: { required: false, class: [Fixnum] }
}
response = api_request('getUserProfilePhotos', params, params_validation)
Telegrammer::DataTypes::UserProfilePhotos.new(response.result).to_h
end | [
"def",
"get_user_profile_photos",
"(",
"params",
")",
"params_validation",
"=",
"{",
"user_id",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"Fixnum",
"]",
"}",
",",
"offset",
":",
"{",
"required",
":",
"false",
",",
"class",
":",
"[",
"Fixnum",
"]",
"}",
",",
"limit",
":",
"{",
"required",
":",
"false",
",",
"class",
":",
"[",
"Fixnum",
"]",
"}",
"}",
"response",
"=",
"api_request",
"(",
"'getUserProfilePhotos'",
",",
"params",
",",
"params_validation",
")",
"Telegrammer",
"::",
"DataTypes",
"::",
"UserProfilePhotos",
".",
"new",
"(",
"response",
".",
"result",
")",
".",
"to_h",
"end"
] | Get a list of profile pictures for a user.
@param [Hash] params hash of paramers to send to the getUserProfilePhotos API operation.
@option params [Integer] :user_id Required. Unique identifier of the target user.
@option params [Integer] :offset Optional. Sequential number of the first photo to be returned. By default, all photos are returned.
@option params [Integer] :limit Optional. Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100.
@example
bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
bot.get_user_profile_photos(user_id: 123456789)
@raise [Telegrammer::Errors::BadRequestError]
@raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down
@return [Telegrammer::DataTypes::UserProfilePhotos] Message object sent to the user or group chat | [
"Get",
"a",
"list",
"of",
"profile",
"pictures",
"for",
"a",
"user",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L420-L430 | train |
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.get_file | def get_file(params)
params_validation = {
file_id: { required: true, class: [String] }
}
response = api_request("getFile", params, params_validation)
file_object = Telegrammer::DataTypes::File.new(response.result)
"#{API_ENDPOINT}/file/bot#{@api_token}/#{file_object.file_path}"
end | ruby | def get_file(params)
params_validation = {
file_id: { required: true, class: [String] }
}
response = api_request("getFile", params, params_validation)
file_object = Telegrammer::DataTypes::File.new(response.result)
"#{API_ENDPOINT}/file/bot#{@api_token}/#{file_object.file_path}"
end | [
"def",
"get_file",
"(",
"params",
")",
"params_validation",
"=",
"{",
"file_id",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"String",
"]",
"}",
"}",
"response",
"=",
"api_request",
"(",
"\"getFile\"",
",",
"params",
",",
"params_validation",
")",
"file_object",
"=",
"Telegrammer",
"::",
"DataTypes",
"::",
"File",
".",
"new",
"(",
"response",
".",
"result",
")",
"\"#{API_ENDPOINT}/file/bot#{@api_token}/#{file_object.file_path}\"",
"end"
] | Get basic info about a file and prepare it for downloading.
@param [Hash] params hash of paramers to send to the getFile API operation.
@option params [String] :file_id Required. File identifier to get info about.
@example
bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
bot.get_file(file_id: 123456789)
@raise [Telegrammer::Errors::BadRequestError]
@raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down
@return [String] URL of the file (valid for one hour) or BadRequestError if the file_id is wrong | [
"Get",
"basic",
"info",
"about",
"a",
"file",
"and",
"prepare",
"it",
"for",
"downloading",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L445-L454 | train |
mayoral/telegrammer | lib/telegrammer/bot.rb | Telegrammer.Bot.answer_inline_query | def answer_inline_query(params)
params_validation = {
inline_query_id: { required: true, class: [String] },
results: { required: true, class: [Array] },
cache_time: { required: false, class: [Fixnum] },
is_personal: { required: false, class: [TrueClass, FalseClass] },
next_offset: { required: false, class: [String] }
}
response = api_request("answerInlineQuery", params, params_validation)
end | ruby | def answer_inline_query(params)
params_validation = {
inline_query_id: { required: true, class: [String] },
results: { required: true, class: [Array] },
cache_time: { required: false, class: [Fixnum] },
is_personal: { required: false, class: [TrueClass, FalseClass] },
next_offset: { required: false, class: [String] }
}
response = api_request("answerInlineQuery", params, params_validation)
end | [
"def",
"answer_inline_query",
"(",
"params",
")",
"params_validation",
"=",
"{",
"inline_query_id",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"String",
"]",
"}",
",",
"results",
":",
"{",
"required",
":",
"true",
",",
"class",
":",
"[",
"Array",
"]",
"}",
",",
"cache_time",
":",
"{",
"required",
":",
"false",
",",
"class",
":",
"[",
"Fixnum",
"]",
"}",
",",
"is_personal",
":",
"{",
"required",
":",
"false",
",",
"class",
":",
"[",
"TrueClass",
",",
"FalseClass",
"]",
"}",
",",
"next_offset",
":",
"{",
"required",
":",
"false",
",",
"class",
":",
"[",
"String",
"]",
"}",
"}",
"response",
"=",
"api_request",
"(",
"\"answerInlineQuery\"",
",",
"params",
",",
"params_validation",
")",
"end"
] | Answer an inline query. On success, True is returned. No more than 50 results per query are allowed.
@param [Hash] params hash of paramers to send to the answerInlineQuery API operation.
@option params [String] :inline_query_id Required. Unique identifier for the answered query
@option params [Array] :results Required. An array of InlineQueryResults objects for the inline query
@option params [Fixnum] :cache_time Optional. The maximum amount of time the result of the inline query may be cached on the server
@option params [TrueClass,FalseClass] :is_personal Optional. Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query
@option params [String] :next_offset Optional. Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes.
@example
bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
bot.get_updates do |update|
if update.is_a?(Telegrammer::DataTypes::InlineQuery)
inline_query = message.inline_query
if inline_query
results = the_search_in_my_app(inline_query.query)
bot.answer_inline_query(
inline_query_id: "my-internal-query-id",
results: results
)
end
end
end
@raise [Telegrammer::Errors::BadRequestError]
@raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down
@return [TrueClass] True if all was OK | [
"Answer",
"an",
"inline",
"query",
".",
"On",
"success",
"True",
"is",
"returned",
".",
"No",
"more",
"than",
"50",
"results",
"per",
"query",
"are",
"allowed",
"."
] | be85007a647fcebec7e0b5ed1ff86f4dd924a62a | https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L489-L499 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/distance_matrix.rb | GoogleMapsService::Apis.DistanceMatrix.distance_matrix | def distance_matrix(origins, destinations,
mode: nil, language: nil, avoid: nil, units: nil,
departure_time: nil, arrival_time: nil, transit_mode: nil,
transit_routing_preference: nil)
params = {
origins: GoogleMapsService::Convert.waypoints(origins),
destinations: GoogleMapsService::Convert.waypoints(destinations)
}
params[:language] = language if language
params[:mode] = GoogleMapsService::Validator.travel_mode(mode) if mode
params[:avoid] = GoogleMapsService::Validator.avoid(avoid) if avoid
params[:units] = units if units
params[:departure_time] = GoogleMapsService::Convert.time(departure_time) if departure_time
params[:arrival_time] = GoogleMapsService::Convert.time(arrival_time) if arrival_time
if departure_time and arrival_time
raise ArgumentError, 'Should not specify both departure_time and arrival_time.'
end
params[:transit_mode] = GoogleMapsService::Convert.join_list('|', transit_mode) if transit_mode
params[:transit_routing_preference] = transit_routing_preference if transit_routing_preference
return get('/maps/api/distancematrix/json', params)
end | ruby | def distance_matrix(origins, destinations,
mode: nil, language: nil, avoid: nil, units: nil,
departure_time: nil, arrival_time: nil, transit_mode: nil,
transit_routing_preference: nil)
params = {
origins: GoogleMapsService::Convert.waypoints(origins),
destinations: GoogleMapsService::Convert.waypoints(destinations)
}
params[:language] = language if language
params[:mode] = GoogleMapsService::Validator.travel_mode(mode) if mode
params[:avoid] = GoogleMapsService::Validator.avoid(avoid) if avoid
params[:units] = units if units
params[:departure_time] = GoogleMapsService::Convert.time(departure_time) if departure_time
params[:arrival_time] = GoogleMapsService::Convert.time(arrival_time) if arrival_time
if departure_time and arrival_time
raise ArgumentError, 'Should not specify both departure_time and arrival_time.'
end
params[:transit_mode] = GoogleMapsService::Convert.join_list('|', transit_mode) if transit_mode
params[:transit_routing_preference] = transit_routing_preference if transit_routing_preference
return get('/maps/api/distancematrix/json', params)
end | [
"def",
"distance_matrix",
"(",
"origins",
",",
"destinations",
",",
"mode",
":",
"nil",
",",
"language",
":",
"nil",
",",
"avoid",
":",
"nil",
",",
"units",
":",
"nil",
",",
"departure_time",
":",
"nil",
",",
"arrival_time",
":",
"nil",
",",
"transit_mode",
":",
"nil",
",",
"transit_routing_preference",
":",
"nil",
")",
"params",
"=",
"{",
"origins",
":",
"GoogleMapsService",
"::",
"Convert",
".",
"waypoints",
"(",
"origins",
")",
",",
"destinations",
":",
"GoogleMapsService",
"::",
"Convert",
".",
"waypoints",
"(",
"destinations",
")",
"}",
"params",
"[",
":language",
"]",
"=",
"language",
"if",
"language",
"params",
"[",
":mode",
"]",
"=",
"GoogleMapsService",
"::",
"Validator",
".",
"travel_mode",
"(",
"mode",
")",
"if",
"mode",
"params",
"[",
":avoid",
"]",
"=",
"GoogleMapsService",
"::",
"Validator",
".",
"avoid",
"(",
"avoid",
")",
"if",
"avoid",
"params",
"[",
":units",
"]",
"=",
"units",
"if",
"units",
"params",
"[",
":departure_time",
"]",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"time",
"(",
"departure_time",
")",
"if",
"departure_time",
"params",
"[",
":arrival_time",
"]",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"time",
"(",
"arrival_time",
")",
"if",
"arrival_time",
"if",
"departure_time",
"and",
"arrival_time",
"raise",
"ArgumentError",
",",
"'Should not specify both departure_time and arrival_time.'",
"end",
"params",
"[",
":transit_mode",
"]",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"join_list",
"(",
"'|'",
",",
"transit_mode",
")",
"if",
"transit_mode",
"params",
"[",
":transit_routing_preference",
"]",
"=",
"transit_routing_preference",
"if",
"transit_routing_preference",
"return",
"get",
"(",
"'/maps/api/distancematrix/json'",
",",
"params",
")",
"end"
] | Gets travel distance and time for a matrix of origins and destinations.
@example Simple distance matrix
origins = ["Perth, Australia", "Sydney, Australia",
"Melbourne, Australia", "Adelaide, Australia",
"Brisbane, Australia", "Darwin, Australia",
"Hobart, Australia", "Canberra, Australia"]
destinations = ["Uluru, Australia",
"Kakadu, Australia",
"Blue Mountains, Australia",
"Bungle Bungles, Australia",
"The Pinnacles, Australia"]
matrix = client.distance_matrix(origins, destinations)
@example Complex distance matrix
origins = ["Bobcaygeon ON", [41.43206, -81.38992]]
destinations = [[43.012486, -83.6964149], {lat: 42.8863855, lng: -78.8781627}]
matrix = client.distance_matrix(origins, destinations,
mode: 'driving',
language: 'en-AU',
avoid: 'tolls',
units: 'imperial')
@param [Array] origins One or more addresses and/or lat/lon pairs,
from which to calculate distance and time. If you pass an address
as a string, the service will geocode the string and convert it to
a lat/lon coordinate to calculate directions.
@param [Array] destinations One or more addresses and/or lat/lon pairs, to
which to calculate distance and time. If you pass an address as a
string, the service will geocode the string and convert it to a
lat/lon coordinate to calculate directions.
@param [String] mode Specifies the mode of transport to use when calculating
directions. Valid values are `driving`, `walking`, `transit` or `bicycling`.
@param [String] language The language in which to return results.
@param [String] avoid Indicates that the calculated route(s) should avoid the
indicated features. Valid values are `tolls`, `highways` or `ferries`.
@param [String] units Specifies the unit system to use when displaying results.
Valid values are `metric` or `imperial`.
@param [Integer, DateTime] departure_time Specifies the desired time of departure.
@param [Integer, DateTime] arrival_time Specifies the desired time of arrival for transit
directions. Note: you can not specify both `departure_time` and `arrival_time`.
@param [String, Array<String>] transit_mode Specifies one or more preferred modes of transit.
This parameter may only be specified for requests where the mode is
transit. Valid values are `bus`, `subway`, `train`, `tram`, or `rail`.
`rail` is equivalent to `["train", "tram", "subway"]`.
@param [String] transit_routing_preference Specifies preferences for transit
requests. Valid values are `less_walking` or `fewer_transfers`.
@return [Hash] Matrix of distances. Results are returned in rows, each row
containing one origin paired with each destination. | [
"Gets",
"travel",
"distance",
"and",
"time",
"for",
"a",
"matrix",
"of",
"origins",
"and",
"destinations",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/distance_matrix.rb#L58-L83 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/convert.rb | GoogleMapsService.Convert.components | def components(arg)
if arg.kind_of?(Hash)
arg = arg.sort.map { |k, v| "#{k}:#{v}" }
return arg.join("|")
end
raise ArgumentError, "Expected a Hash for components, but got #{arg.class}"
end | ruby | def components(arg)
if arg.kind_of?(Hash)
arg = arg.sort.map { |k, v| "#{k}:#{v}" }
return arg.join("|")
end
raise ArgumentError, "Expected a Hash for components, but got #{arg.class}"
end | [
"def",
"components",
"(",
"arg",
")",
"if",
"arg",
".",
"kind_of?",
"(",
"Hash",
")",
"arg",
"=",
"arg",
".",
"sort",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"\"#{k}:#{v}\"",
"}",
"return",
"arg",
".",
"join",
"(",
"\"|\"",
")",
"end",
"raise",
"ArgumentError",
",",
"\"Expected a Hash for components, but got #{arg.class}\"",
"end"
] | Converts a dict of components to the format expected by the Google Maps
server.
@example
>> GoogleMapsService::Convert.components({"country": "US", "postal_code": "94043"})
=> "country:US|postal_code:94043"
@param [Hash] arg The component filter.
@return [String] | [
"Converts",
"a",
"dict",
"of",
"components",
"to",
"the",
"format",
"expected",
"by",
"the",
"Google",
"Maps",
"server",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/convert.rb#L94-L101 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/convert.rb | GoogleMapsService.Convert.waypoint | def waypoint(waypoint)
if waypoint.kind_of?(String)
return waypoint
end
return GoogleMapsService::Convert.latlng(waypoint)
end | ruby | def waypoint(waypoint)
if waypoint.kind_of?(String)
return waypoint
end
return GoogleMapsService::Convert.latlng(waypoint)
end | [
"def",
"waypoint",
"(",
"waypoint",
")",
"if",
"waypoint",
".",
"kind_of?",
"(",
"String",
")",
"return",
"waypoint",
"end",
"return",
"GoogleMapsService",
"::",
"Convert",
".",
"latlng",
"(",
"waypoint",
")",
"end"
] | Converts a waypoints to the format expected by the Google Maps server.
Accept two representation of waypoint:
1. String: Name of place or comma-separated lat/lon pair.
2. Hash/Array: Lat/lon pair.
@param [Array, String, Hash] waypoint Path.
@return [String] | [
"Converts",
"a",
"waypoints",
"to",
"the",
"format",
"expected",
"by",
"the",
"Google",
"Maps",
"server",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/convert.rb#L149-L154 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/geocoding.rb | GoogleMapsService::Apis.Geocoding.reverse_geocode | def reverse_geocode(latlng, location_type: nil, result_type: nil, language: nil)
params = {
latlng: GoogleMapsService::Convert.latlng(latlng)
}
params[:result_type] = GoogleMapsService::Convert.join_list('|', result_type) if result_type
params[:location_type] = GoogleMapsService::Convert.join_list('|', location_type) if location_type
params[:language] = language if language
return get('/maps/api/geocode/json', params)[:results]
end | ruby | def reverse_geocode(latlng, location_type: nil, result_type: nil, language: nil)
params = {
latlng: GoogleMapsService::Convert.latlng(latlng)
}
params[:result_type] = GoogleMapsService::Convert.join_list('|', result_type) if result_type
params[:location_type] = GoogleMapsService::Convert.join_list('|', location_type) if location_type
params[:language] = language if language
return get('/maps/api/geocode/json', params)[:results]
end | [
"def",
"reverse_geocode",
"(",
"latlng",
",",
"location_type",
":",
"nil",
",",
"result_type",
":",
"nil",
",",
"language",
":",
"nil",
")",
"params",
"=",
"{",
"latlng",
":",
"GoogleMapsService",
"::",
"Convert",
".",
"latlng",
"(",
"latlng",
")",
"}",
"params",
"[",
":result_type",
"]",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"join_list",
"(",
"'|'",
",",
"result_type",
")",
"if",
"result_type",
"params",
"[",
":location_type",
"]",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"join_list",
"(",
"'|'",
",",
"location_type",
")",
"if",
"location_type",
"params",
"[",
":language",
"]",
"=",
"language",
"if",
"language",
"return",
"get",
"(",
"'/maps/api/geocode/json'",
",",
"params",
")",
"[",
":results",
"]",
"end"
] | Reverse geocoding is the process of converting geographic coordinates into a
human-readable address.
@example Simple lat/lon pair
client.reverse_geocode({lat: 40.714224, lng: -73.961452})
@example Multiple parameters
client.reverse_geocode([40.714224, -73.961452],
location_type: ['ROOFTOP', 'RANGE_INTERPOLATED'],
result_type: ['street_address', 'route'],
language: 'es')
@param [Hash, Array] latlng The latitude/longitude value for which you wish to obtain
the closest, human-readable address.
@param [String, Array<String>] location_type One or more location types to restrict results to.
@param [String, Array<String>] result_type One or more address types to restrict results to.
@param [String] language The language in which to return results.
@return [Array] Array of reverse geocoding results. | [
"Reverse",
"geocoding",
"is",
"the",
"process",
"of",
"converting",
"geographic",
"coordinates",
"into",
"a",
"human",
"-",
"readable",
"address",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/geocoding.rb#L72-L82 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/time_zone.rb | GoogleMapsService::Apis.TimeZone.timezone | def timezone(location, timestamp: Time.now, language: nil)
location = GoogleMapsService::Convert.latlng(location)
timestamp = GoogleMapsService::Convert.time(timestamp)
params = {
location: location,
timestamp: timestamp
}
params[:language] = language if language
return get('/maps/api/timezone/json', params)
end | ruby | def timezone(location, timestamp: Time.now, language: nil)
location = GoogleMapsService::Convert.latlng(location)
timestamp = GoogleMapsService::Convert.time(timestamp)
params = {
location: location,
timestamp: timestamp
}
params[:language] = language if language
return get('/maps/api/timezone/json', params)
end | [
"def",
"timezone",
"(",
"location",
",",
"timestamp",
":",
"Time",
".",
"now",
",",
"language",
":",
"nil",
")",
"location",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"latlng",
"(",
"location",
")",
"timestamp",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"time",
"(",
"timestamp",
")",
"params",
"=",
"{",
"location",
":",
"location",
",",
"timestamp",
":",
"timestamp",
"}",
"params",
"[",
":language",
"]",
"=",
"language",
"if",
"language",
"return",
"get",
"(",
"'/maps/api/timezone/json'",
",",
"params",
")",
"end"
] | Get time zone for a location on the earth, as well as that location's
time offset from UTC.
@example Current time zone
timezone = client.timezone([39.603481, -119.682251])
@example Time zone at certain time
timezone = client.timezone([39.603481, -119.682251], timestamp: Time.at(1608))
@param [Hash, Array] location The latitude/longitude value representing the location to
look up.
@param [Integer, DateTime] timestamp Timestamp specifies the desired time as seconds since
midnight, January 1, 1970 UTC. The Time Zone API uses the timestamp to
determine whether or not Daylight Savings should be applied. Times
before 1970 can be expressed as negative values. Optional. Defaults to
`Time.now`.
@param [String] language The language in which to return results.
@return [Hash] Time zone object. | [
"Get",
"time",
"zone",
"for",
"a",
"location",
"on",
"the",
"earth",
"as",
"well",
"as",
"that",
"location",
"s",
"time",
"offset",
"from",
"UTC",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/time_zone.rb#L27-L39 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/url.rb | GoogleMapsService.Url.sign_hmac | def sign_hmac(secret, payload)
secret = secret.encode('ASCII')
payload = payload.encode('ASCII')
# Decode the private key
raw_key = Base64.urlsafe_decode64(secret)
# Create a signature using the private key and the URL
digest = OpenSSL::Digest.new('sha1')
raw_signature = OpenSSL::HMAC.digest(digest, raw_key, payload)
# Encode the signature into base64 for url use form.
signature = Base64.urlsafe_encode64(raw_signature)
return signature
end | ruby | def sign_hmac(secret, payload)
secret = secret.encode('ASCII')
payload = payload.encode('ASCII')
# Decode the private key
raw_key = Base64.urlsafe_decode64(secret)
# Create a signature using the private key and the URL
digest = OpenSSL::Digest.new('sha1')
raw_signature = OpenSSL::HMAC.digest(digest, raw_key, payload)
# Encode the signature into base64 for url use form.
signature = Base64.urlsafe_encode64(raw_signature)
return signature
end | [
"def",
"sign_hmac",
"(",
"secret",
",",
"payload",
")",
"secret",
"=",
"secret",
".",
"encode",
"(",
"'ASCII'",
")",
"payload",
"=",
"payload",
".",
"encode",
"(",
"'ASCII'",
")",
"raw_key",
"=",
"Base64",
".",
"urlsafe_decode64",
"(",
"secret",
")",
"digest",
"=",
"OpenSSL",
"::",
"Digest",
".",
"new",
"(",
"'sha1'",
")",
"raw_signature",
"=",
"OpenSSL",
"::",
"HMAC",
".",
"digest",
"(",
"digest",
",",
"raw_key",
",",
"payload",
")",
"signature",
"=",
"Base64",
".",
"urlsafe_encode64",
"(",
"raw_signature",
")",
"return",
"signature",
"end"
] | Returns a base64-encoded HMAC-SHA1 signature of a given string.
@param [String] secret The key used for the signature, base64 encoded.
@param [String] payload The payload to sign.
@return [String] Base64-encoded HMAC-SHA1 signature | [
"Returns",
"a",
"base64",
"-",
"encoded",
"HMAC",
"-",
"SHA1",
"signature",
"of",
"a",
"given",
"string",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/url.rb#L16-L30 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/url.rb | GoogleMapsService.Url.unquote_unreserved | def unquote_unreserved(uri)
parts = uri.split('%')
(1..parts.length-1).each do |i|
h = parts[i][0..1]
if h =~ /^([\h]{2})(.*)/ and c = $1.to_i(16).chr and UNRESERVED_SET.include?(c)
parts[i] = c + $2
else
parts[i] = '%' + parts[i]
end
end
parts.join
end | ruby | def unquote_unreserved(uri)
parts = uri.split('%')
(1..parts.length-1).each do |i|
h = parts[i][0..1]
if h =~ /^([\h]{2})(.*)/ and c = $1.to_i(16).chr and UNRESERVED_SET.include?(c)
parts[i] = c + $2
else
parts[i] = '%' + parts[i]
end
end
parts.join
end | [
"def",
"unquote_unreserved",
"(",
"uri",
")",
"parts",
"=",
"uri",
".",
"split",
"(",
"'%'",
")",
"(",
"1",
"..",
"parts",
".",
"length",
"-",
"1",
")",
".",
"each",
"do",
"|",
"i",
"|",
"h",
"=",
"parts",
"[",
"i",
"]",
"[",
"0",
"..",
"1",
"]",
"if",
"h",
"=~",
"/",
"\\h",
"/",
"and",
"c",
"=",
"$1",
".",
"to_i",
"(",
"16",
")",
".",
"chr",
"and",
"UNRESERVED_SET",
".",
"include?",
"(",
"c",
")",
"parts",
"[",
"i",
"]",
"=",
"c",
"+",
"$2",
"else",
"parts",
"[",
"i",
"]",
"=",
"'%'",
"+",
"parts",
"[",
"i",
"]",
"end",
"end",
"parts",
".",
"join",
"end"
] | Un-escape any percent-escape sequences in a URI that are unreserved
characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
@param [String] uri
@return [String] | [
"Un",
"-",
"escape",
"any",
"percent",
"-",
"escape",
"sequences",
"in",
"a",
"URI",
"that",
"are",
"unreserved",
"characters",
".",
"This",
"leaves",
"all",
"reserved",
"illegal",
"and",
"non",
"-",
"ASCII",
"bytes",
"encoded",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/url.rb#L45-L59 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/client.rb | GoogleMapsService.Client.new_client | def new_client
client = Hurley::Client.new
client.request_options.query_class = Hurley::Query::Flat
client.request_options.redirection_limit = 0
client.header[:user_agent] = user_agent
client.connection = @connection if @connection
@request_options.each_pair {|key, value| client.request_options[key] = value } if @request_options
@ssl_options.each_pair {|key, value| client.ssl_options[key] = value } if @ssl_options
client
end | ruby | def new_client
client = Hurley::Client.new
client.request_options.query_class = Hurley::Query::Flat
client.request_options.redirection_limit = 0
client.header[:user_agent] = user_agent
client.connection = @connection if @connection
@request_options.each_pair {|key, value| client.request_options[key] = value } if @request_options
@ssl_options.each_pair {|key, value| client.ssl_options[key] = value } if @ssl_options
client
end | [
"def",
"new_client",
"client",
"=",
"Hurley",
"::",
"Client",
".",
"new",
"client",
".",
"request_options",
".",
"query_class",
"=",
"Hurley",
"::",
"Query",
"::",
"Flat",
"client",
".",
"request_options",
".",
"redirection_limit",
"=",
"0",
"client",
".",
"header",
"[",
":user_agent",
"]",
"=",
"user_agent",
"client",
".",
"connection",
"=",
"@connection",
"if",
"@connection",
"@request_options",
".",
"each_pair",
"{",
"|",
"key",
",",
"value",
"|",
"client",
".",
"request_options",
"[",
"key",
"]",
"=",
"value",
"}",
"if",
"@request_options",
"@ssl_options",
".",
"each_pair",
"{",
"|",
"key",
",",
"value",
"|",
"client",
".",
"ssl_options",
"[",
"key",
"]",
"=",
"value",
"}",
"if",
"@ssl_options",
"client",
"end"
] | Create a new HTTP client.
@return [Hurley::Client] | [
"Create",
"a",
"new",
"HTTP",
"client",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/client.rb#L141-L152 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/client.rb | GoogleMapsService.Client.get | def get(path, params, base_url: DEFAULT_BASE_URL, accepts_client_id: true, custom_response_decoder: nil)
url = base_url + generate_auth_url(path, params, accepts_client_id)
Retriable.retriable timeout: @retry_timeout, on: RETRIABLE_ERRORS do |try|
begin
request_query_ticket
response = client.get url
ensure
release_query_ticket
end
return custom_response_decoder.call(response) if custom_response_decoder
decode_response_body(response)
end
end | ruby | def get(path, params, base_url: DEFAULT_BASE_URL, accepts_client_id: true, custom_response_decoder: nil)
url = base_url + generate_auth_url(path, params, accepts_client_id)
Retriable.retriable timeout: @retry_timeout, on: RETRIABLE_ERRORS do |try|
begin
request_query_ticket
response = client.get url
ensure
release_query_ticket
end
return custom_response_decoder.call(response) if custom_response_decoder
decode_response_body(response)
end
end | [
"def",
"get",
"(",
"path",
",",
"params",
",",
"base_url",
":",
"DEFAULT_BASE_URL",
",",
"accepts_client_id",
":",
"true",
",",
"custom_response_decoder",
":",
"nil",
")",
"url",
"=",
"base_url",
"+",
"generate_auth_url",
"(",
"path",
",",
"params",
",",
"accepts_client_id",
")",
"Retriable",
".",
"retriable",
"timeout",
":",
"@retry_timeout",
",",
"on",
":",
"RETRIABLE_ERRORS",
"do",
"|",
"try",
"|",
"begin",
"request_query_ticket",
"response",
"=",
"client",
".",
"get",
"url",
"ensure",
"release_query_ticket",
"end",
"return",
"custom_response_decoder",
".",
"call",
"(",
"response",
")",
"if",
"custom_response_decoder",
"decode_response_body",
"(",
"response",
")",
"end",
"end"
] | Make API call.
@param [String] path Url path.
@param [String] params Request parameters.
@param [String] base_url Base Google Maps Web Service API endpoint url.
@param [Boolean] accepts_client_id Sign the request using API {#keys} instead of {#client_id}.
@param [Method] custom_response_decoder Custom method to decode raw API response.
@return [Object] Decoded response body. | [
"Make",
"API",
"call",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/client.rb#L171-L185 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/client.rb | GoogleMapsService.Client.generate_auth_url | def generate_auth_url(path, params, accepts_client_id)
# Deterministic ordering through sorting by key.
# Useful for tests, and in the future, any caching.
if params.kind_of?(Hash)
params = params.sort
else
params = params.dup
end
if accepts_client_id and @client_id and @client_secret
params << ["client", @client_id]
path = [path, GoogleMapsService::Url.urlencode_params(params)].join("?")
sig = GoogleMapsService::Url.sign_hmac(@client_secret, path)
return path + "&signature=" + sig
end
if @key
params << ["key", @key]
return path + "?" + GoogleMapsService::Url.urlencode_params(params)
end
raise ArgumentError, "Must provide API key for this API. It does not accept enterprise credentials."
end | ruby | def generate_auth_url(path, params, accepts_client_id)
# Deterministic ordering through sorting by key.
# Useful for tests, and in the future, any caching.
if params.kind_of?(Hash)
params = params.sort
else
params = params.dup
end
if accepts_client_id and @client_id and @client_secret
params << ["client", @client_id]
path = [path, GoogleMapsService::Url.urlencode_params(params)].join("?")
sig = GoogleMapsService::Url.sign_hmac(@client_secret, path)
return path + "&signature=" + sig
end
if @key
params << ["key", @key]
return path + "?" + GoogleMapsService::Url.urlencode_params(params)
end
raise ArgumentError, "Must provide API key for this API. It does not accept enterprise credentials."
end | [
"def",
"generate_auth_url",
"(",
"path",
",",
"params",
",",
"accepts_client_id",
")",
"if",
"params",
".",
"kind_of?",
"(",
"Hash",
")",
"params",
"=",
"params",
".",
"sort",
"else",
"params",
"=",
"params",
".",
"dup",
"end",
"if",
"accepts_client_id",
"and",
"@client_id",
"and",
"@client_secret",
"params",
"<<",
"[",
"\"client\"",
",",
"@client_id",
"]",
"path",
"=",
"[",
"path",
",",
"GoogleMapsService",
"::",
"Url",
".",
"urlencode_params",
"(",
"params",
")",
"]",
".",
"join",
"(",
"\"?\"",
")",
"sig",
"=",
"GoogleMapsService",
"::",
"Url",
".",
"sign_hmac",
"(",
"@client_secret",
",",
"path",
")",
"return",
"path",
"+",
"\"&signature=\"",
"+",
"sig",
"end",
"if",
"@key",
"params",
"<<",
"[",
"\"key\"",
",",
"@key",
"]",
"return",
"path",
"+",
"\"?\"",
"+",
"GoogleMapsService",
"::",
"Url",
".",
"urlencode_params",
"(",
"params",
")",
"end",
"raise",
"ArgumentError",
",",
"\"Must provide API key for this API. It does not accept enterprise credentials.\"",
"end"
] | Returns the path and query string portion of the request URL,
first adding any necessary parameters.
@param [String] path The path portion of the URL.
@param [Hash] params URL parameters.
@param [Boolean] accepts_client_id Sign the request using API {#keys} instead of {#client_id}.
@return [String] | [
"Returns",
"the",
"path",
"and",
"query",
"string",
"portion",
"of",
"the",
"request",
"URL",
"first",
"adding",
"any",
"necessary",
"parameters",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/client.rb#L213-L236 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/client.rb | GoogleMapsService.Client.decode_response_body | def decode_response_body(response)
check_response_status_code(response)
body = MultiJson.load(response.body, :symbolize_keys => true)
check_body_error(response, body)
body
end | ruby | def decode_response_body(response)
check_response_status_code(response)
body = MultiJson.load(response.body, :symbolize_keys => true)
check_body_error(response, body)
body
end | [
"def",
"decode_response_body",
"(",
"response",
")",
"check_response_status_code",
"(",
"response",
")",
"body",
"=",
"MultiJson",
".",
"load",
"(",
"response",
".",
"body",
",",
":symbolize_keys",
"=>",
"true",
")",
"check_body_error",
"(",
"response",
",",
"body",
")",
"body",
"end"
] | Extract and parse body response as hash. Throw an error if there is something wrong with the response.
@param [Hurley::Response] response Web API response.
@return [Hash] Response body as hash. The hash key will be symbolized. | [
"Extract",
"and",
"parse",
"body",
"response",
"as",
"hash",
".",
"Throw",
"an",
"error",
"if",
"there",
"is",
"something",
"wrong",
"with",
"the",
"response",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/client.rb#L243-L248 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/client.rb | GoogleMapsService.Client.check_response_status_code | def check_response_status_code(response)
case response.status_code
when 200..300
# Do-nothing
when 301, 302, 303, 307
raise GoogleMapsService::Error::RedirectError.new(response), sprintf('Redirect to %s', response.header[:location])
when 401
raise GoogleMapsService::Error::ClientError.new(response), 'Unauthorized'
when 304, 400, 402...500
raise GoogleMapsService::Error::ClientError.new(response), 'Invalid request'
when 500..600
raise GoogleMapsService::Error::ServerError.new(response), 'Server error'
end
end | ruby | def check_response_status_code(response)
case response.status_code
when 200..300
# Do-nothing
when 301, 302, 303, 307
raise GoogleMapsService::Error::RedirectError.new(response), sprintf('Redirect to %s', response.header[:location])
when 401
raise GoogleMapsService::Error::ClientError.new(response), 'Unauthorized'
when 304, 400, 402...500
raise GoogleMapsService::Error::ClientError.new(response), 'Invalid request'
when 500..600
raise GoogleMapsService::Error::ServerError.new(response), 'Server error'
end
end | [
"def",
"check_response_status_code",
"(",
"response",
")",
"case",
"response",
".",
"status_code",
"when",
"200",
"..",
"300",
"when",
"301",
",",
"302",
",",
"303",
",",
"307",
"raise",
"GoogleMapsService",
"::",
"Error",
"::",
"RedirectError",
".",
"new",
"(",
"response",
")",
",",
"sprintf",
"(",
"'Redirect to %s'",
",",
"response",
".",
"header",
"[",
":location",
"]",
")",
"when",
"401",
"raise",
"GoogleMapsService",
"::",
"Error",
"::",
"ClientError",
".",
"new",
"(",
"response",
")",
",",
"'Unauthorized'",
"when",
"304",
",",
"400",
",",
"402",
"...",
"500",
"raise",
"GoogleMapsService",
"::",
"Error",
"::",
"ClientError",
".",
"new",
"(",
"response",
")",
",",
"'Invalid request'",
"when",
"500",
"..",
"600",
"raise",
"GoogleMapsService",
"::",
"Error",
"::",
"ServerError",
".",
"new",
"(",
"response",
")",
",",
"'Server error'",
"end",
"end"
] | Check HTTP response status code. Raise error if the status is not 2xx.
@param [Hurley::Response] response Web API response. | [
"Check",
"HTTP",
"response",
"status",
"code",
".",
"Raise",
"error",
"if",
"the",
"status",
"is",
"not",
"2xx",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/client.rb#L253-L266 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/directions.rb | GoogleMapsService::Apis.Directions.directions | def directions(origin, destination,
mode: nil, waypoints: nil, alternatives: false, avoid: nil,
language: nil, units: nil, region: nil, departure_time: nil,
arrival_time: nil, optimize_waypoints: false, transit_mode: nil,
transit_routing_preference: nil)
params = {
origin: GoogleMapsService::Convert.waypoint(origin),
destination: GoogleMapsService::Convert.waypoint(destination)
}
params[:mode] = GoogleMapsService::Validator.travel_mode(mode) if mode
if waypoints = waypoints
waypoints = GoogleMapsService::Convert.as_list(waypoints)
waypoints = waypoints.map { |waypoint| GoogleMapsService::Convert.waypoint(waypoint) }
waypoints = ['optimize:true'] + waypoints if optimize_waypoints
params[:waypoints] = GoogleMapsService::Convert.join_list("|", waypoints)
end
params[:alternatives] = 'true' if alternatives
params[:avoid] = GoogleMapsService::Convert.join_list('|', avoid) if avoid
params[:language] = language if language
params[:units] = units if units
params[:region] = region if region
params[:departure_time] = GoogleMapsService::Convert.time(departure_time) if departure_time
params[:arrival_time] = GoogleMapsService::Convert.time(arrival_time) if arrival_time
if departure_time and arrival_time
raise ArgumentError, 'Should not specify both departure_time and arrival_time.'
end
params[:transit_mode] = GoogleMapsService::Convert.join_list("|", transit_mode) if transit_mode
params[:transit_routing_preference] = transit_routing_preference if transit_routing_preference
return get('/maps/api/directions/json', params)[:routes]
end | ruby | def directions(origin, destination,
mode: nil, waypoints: nil, alternatives: false, avoid: nil,
language: nil, units: nil, region: nil, departure_time: nil,
arrival_time: nil, optimize_waypoints: false, transit_mode: nil,
transit_routing_preference: nil)
params = {
origin: GoogleMapsService::Convert.waypoint(origin),
destination: GoogleMapsService::Convert.waypoint(destination)
}
params[:mode] = GoogleMapsService::Validator.travel_mode(mode) if mode
if waypoints = waypoints
waypoints = GoogleMapsService::Convert.as_list(waypoints)
waypoints = waypoints.map { |waypoint| GoogleMapsService::Convert.waypoint(waypoint) }
waypoints = ['optimize:true'] + waypoints if optimize_waypoints
params[:waypoints] = GoogleMapsService::Convert.join_list("|", waypoints)
end
params[:alternatives] = 'true' if alternatives
params[:avoid] = GoogleMapsService::Convert.join_list('|', avoid) if avoid
params[:language] = language if language
params[:units] = units if units
params[:region] = region if region
params[:departure_time] = GoogleMapsService::Convert.time(departure_time) if departure_time
params[:arrival_time] = GoogleMapsService::Convert.time(arrival_time) if arrival_time
if departure_time and arrival_time
raise ArgumentError, 'Should not specify both departure_time and arrival_time.'
end
params[:transit_mode] = GoogleMapsService::Convert.join_list("|", transit_mode) if transit_mode
params[:transit_routing_preference] = transit_routing_preference if transit_routing_preference
return get('/maps/api/directions/json', params)[:routes]
end | [
"def",
"directions",
"(",
"origin",
",",
"destination",
",",
"mode",
":",
"nil",
",",
"waypoints",
":",
"nil",
",",
"alternatives",
":",
"false",
",",
"avoid",
":",
"nil",
",",
"language",
":",
"nil",
",",
"units",
":",
"nil",
",",
"region",
":",
"nil",
",",
"departure_time",
":",
"nil",
",",
"arrival_time",
":",
"nil",
",",
"optimize_waypoints",
":",
"false",
",",
"transit_mode",
":",
"nil",
",",
"transit_routing_preference",
":",
"nil",
")",
"params",
"=",
"{",
"origin",
":",
"GoogleMapsService",
"::",
"Convert",
".",
"waypoint",
"(",
"origin",
")",
",",
"destination",
":",
"GoogleMapsService",
"::",
"Convert",
".",
"waypoint",
"(",
"destination",
")",
"}",
"params",
"[",
":mode",
"]",
"=",
"GoogleMapsService",
"::",
"Validator",
".",
"travel_mode",
"(",
"mode",
")",
"if",
"mode",
"if",
"waypoints",
"=",
"waypoints",
"waypoints",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"as_list",
"(",
"waypoints",
")",
"waypoints",
"=",
"waypoints",
".",
"map",
"{",
"|",
"waypoint",
"|",
"GoogleMapsService",
"::",
"Convert",
".",
"waypoint",
"(",
"waypoint",
")",
"}",
"waypoints",
"=",
"[",
"'optimize:true'",
"]",
"+",
"waypoints",
"if",
"optimize_waypoints",
"params",
"[",
":waypoints",
"]",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"join_list",
"(",
"\"|\"",
",",
"waypoints",
")",
"end",
"params",
"[",
":alternatives",
"]",
"=",
"'true'",
"if",
"alternatives",
"params",
"[",
":avoid",
"]",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"join_list",
"(",
"'|'",
",",
"avoid",
")",
"if",
"avoid",
"params",
"[",
":language",
"]",
"=",
"language",
"if",
"language",
"params",
"[",
":units",
"]",
"=",
"units",
"if",
"units",
"params",
"[",
":region",
"]",
"=",
"region",
"if",
"region",
"params",
"[",
":departure_time",
"]",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"time",
"(",
"departure_time",
")",
"if",
"departure_time",
"params",
"[",
":arrival_time",
"]",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"time",
"(",
"arrival_time",
")",
"if",
"arrival_time",
"if",
"departure_time",
"and",
"arrival_time",
"raise",
"ArgumentError",
",",
"'Should not specify both departure_time and arrival_time.'",
"end",
"params",
"[",
":transit_mode",
"]",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"join_list",
"(",
"\"|\"",
",",
"transit_mode",
")",
"if",
"transit_mode",
"params",
"[",
":transit_routing_preference",
"]",
"=",
"transit_routing_preference",
"if",
"transit_routing_preference",
"return",
"get",
"(",
"'/maps/api/directions/json'",
",",
"params",
")",
"[",
":routes",
"]",
"end"
] | Get directions between an origin point and a destination point.
@example Simple directions
routes = client.directions('Sydney', 'Melbourne')
@example Complex bicycling directions
routes = client.directions('Sydney', 'Melbourne',
mode: 'bicycling',
avoid: ['highways', 'tolls', 'ferries'],
units: 'metric',
region: 'au')
@example Public transportation directions
an_hour_from_now = Time.now - (1.0/24)
routes = client.directions('Sydney Town Hall', 'Parramatta, NSW',
mode: 'transit',
arrival_time: an_hour_from_now)
@example Walking with alternative routes
routes = client.directions('Sydney Town Hall', 'Parramatta, NSW',
mode: 'walking',
alternatives: true)
@param [String, Hash, Array] origin The address or latitude/longitude value from which you wish
to calculate directions.
@param [String, Hash, Array] destination The address or latitude/longitude value from which
you wish to calculate directions.
@param [String] mode Specifies the mode of transport to use when calculating
directions. One of `driving`, `walking`, `bicycling` or `transit`.
@param [Array<String>, Array<Hash>, Array<Array>] waypoints Specifies an array of waypoints. Waypoints alter a
route by routing it through the specified location(s).
@param [Boolean] alternatives If True, more than one route may be returned in the
response.
@param [Array, String] avoid Indicates that the calculated route(s) should avoid the
indicated features.
@param [String] language The language in which to return results.
@param [String] units Specifies the unit system to use when displaying results.
`metric` or `imperial`.
@param [String] region The region code, specified as a ccTLD (_top-level domain_)
two-character value.
@param [Integer, DateTime] departure_time Specifies the desired time of departure.
@param [Integer, DateTime] arrival_time Specifies the desired time of arrival for transit
directions. Note: you can not specify both `departure_time` and
`arrival_time`.
@param [Boolean] optimize_waypoints Optimize the provided route by rearranging the
waypoints in a more efficient order.
@param [String, Array<String>] transit_mode Specifies one or more preferred modes of transit.
This parameter may only be specified for requests where the mode is
transit. Valid values are `bus`, `subway`, `train`, `tram` or `rail`.
`rail` is equivalent to `["train", "tram", "subway"]`.
@param [String] transit_routing_preference Specifies preferences for transit
requests. Valid values are `less_walking` or `fewer_transfers`.
@return [Array] Array of routes. | [
"Get",
"directions",
"between",
"an",
"origin",
"point",
"and",
"a",
"destination",
"point",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/directions.rb#L62-L99 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/elevation.rb | GoogleMapsService::Apis.Elevation.elevation_along_path | def elevation_along_path(path, samples)
if path.kind_of?(String)
path = "enc:%s" % path
else
path = GoogleMapsService::Convert.waypoints(path)
end
params = {
path: path,
samples: samples
}
return get('/maps/api/elevation/json', params)[:results]
end | ruby | def elevation_along_path(path, samples)
if path.kind_of?(String)
path = "enc:%s" % path
else
path = GoogleMapsService::Convert.waypoints(path)
end
params = {
path: path,
samples: samples
}
return get('/maps/api/elevation/json', params)[:results]
end | [
"def",
"elevation_along_path",
"(",
"path",
",",
"samples",
")",
"if",
"path",
".",
"kind_of?",
"(",
"String",
")",
"path",
"=",
"\"enc:%s\"",
"%",
"path",
"else",
"path",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"waypoints",
"(",
"path",
")",
"end",
"params",
"=",
"{",
"path",
":",
"path",
",",
"samples",
":",
"samples",
"}",
"return",
"get",
"(",
"'/maps/api/elevation/json'",
",",
"params",
")",
"[",
":results",
"]",
"end"
] | Provides elevation data sampled along a path on the surface of the earth.
@example Elevation along path
locations = [[40.714728, -73.998672], [-34.397, 150.644]]
results = client.elevation_along_path(locations, 5)
@param [String, Array] path A encoded polyline string, or a list of
latitude/longitude pairs from which you wish to calculate
elevation data.
@param [Integer] samples The number of sample points along a path for which to
return elevation data.
@return [Array] Array of elevation data responses | [
"Provides",
"elevation",
"data",
"sampled",
"along",
"a",
"path",
"on",
"the",
"surface",
"of",
"the",
"earth",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/elevation.rb#L43-L56 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/roads.rb | GoogleMapsService::Apis.Roads.snap_to_roads | def snap_to_roads(path, interpolate: false)
path = GoogleMapsService::Convert.waypoints(path)
params = {
path: path
}
params[:interpolate] = 'true' if interpolate
return get('/v1/snapToRoads', params,
base_url: ROADS_BASE_URL,
accepts_client_id: false,
custom_response_decoder: method(:extract_roads_body))[:snappedPoints]
end | ruby | def snap_to_roads(path, interpolate: false)
path = GoogleMapsService::Convert.waypoints(path)
params = {
path: path
}
params[:interpolate] = 'true' if interpolate
return get('/v1/snapToRoads', params,
base_url: ROADS_BASE_URL,
accepts_client_id: false,
custom_response_decoder: method(:extract_roads_body))[:snappedPoints]
end | [
"def",
"snap_to_roads",
"(",
"path",
",",
"interpolate",
":",
"false",
")",
"path",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"waypoints",
"(",
"path",
")",
"params",
"=",
"{",
"path",
":",
"path",
"}",
"params",
"[",
":interpolate",
"]",
"=",
"'true'",
"if",
"interpolate",
"return",
"get",
"(",
"'/v1/snapToRoads'",
",",
"params",
",",
"base_url",
":",
"ROADS_BASE_URL",
",",
"accepts_client_id",
":",
"false",
",",
"custom_response_decoder",
":",
"method",
"(",
":extract_roads_body",
")",
")",
"[",
":snappedPoints",
"]",
"end"
] | Snaps a path to the most likely roads travelled.
Takes up to 100 GPS points collected along a route, and returns a similar
set of data with the points snapped to the most likely roads the vehicle
was traveling along.
@example Single point snap
results = client.snap_to_roads([40.714728, -73.998672])
@example Multi points snap
path = [
[-33.8671, 151.20714],
[-33.86708, 151.20683000000002],
[-33.867070000000005, 151.20674000000002],
[-33.86703, 151.20625]
]
results = client.snap_to_roads(path, interpolate: true)
@param [Array] path The path to be snapped. Array of latitude/longitude pairs.
@param [Boolean] interpolate Whether to interpolate a path to include all points
forming the full road-geometry. When true, additional interpolated
points will also be returned, resulting in a path that smoothly
follows the geometry of the road, even around corners and through
tunnels. Interpolated paths may contain more points than the
original path.
@return [Array] Array of snapped points. | [
"Snaps",
"a",
"path",
"to",
"the",
"most",
"likely",
"roads",
"travelled",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/roads.rb#L38-L51 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/roads.rb | GoogleMapsService::Apis.Roads.nearest_roads | def nearest_roads(points)
points = GoogleMapsService::Convert.waypoints(points)
params = {
points: points
}
return get('/v1/nearestRoads', params,
base_url: ROADS_BASE_URL,
accepts_client_id: false,
custom_response_decoder: method(:extract_roads_body))[:snappedPoints]
end | ruby | def nearest_roads(points)
points = GoogleMapsService::Convert.waypoints(points)
params = {
points: points
}
return get('/v1/nearestRoads', params,
base_url: ROADS_BASE_URL,
accepts_client_id: false,
custom_response_decoder: method(:extract_roads_body))[:snappedPoints]
end | [
"def",
"nearest_roads",
"(",
"points",
")",
"points",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"waypoints",
"(",
"points",
")",
"params",
"=",
"{",
"points",
":",
"points",
"}",
"return",
"get",
"(",
"'/v1/nearestRoads'",
",",
"params",
",",
"base_url",
":",
"ROADS_BASE_URL",
",",
"accepts_client_id",
":",
"false",
",",
"custom_response_decoder",
":",
"method",
"(",
":extract_roads_body",
")",
")",
"[",
":snappedPoints",
"]",
"end"
] | Returns the nearest road segments for provided points.
The points passed do not need to be part of a continuous path.
@example Single point snap
results = client.nearest_roads([40.714728, -73.998672])
@example Multi points snap
points = [
[-33.8671, 151.20714],
[-33.86708, 151.20683000000002],
[-33.867070000000005, 151.20674000000002],
[-33.86703, 151.20625]
]
results = client.nearest_roads(points)
@param [Array] points The points to be used for nearest road segment lookup. Array of latitude/longitude pairs
which do not need to be a part of continuous part.
Takes up to 100 independent coordinates, and returns the closest road segment for each point.
@return [Array] Array of snapped points. | [
"Returns",
"the",
"nearest",
"road",
"segments",
"for",
"provided",
"points",
".",
"The",
"points",
"passed",
"do",
"not",
"need",
"to",
"be",
"part",
"of",
"a",
"continuous",
"path",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/roads.rb#L128-L139 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/apis/roads.rb | GoogleMapsService::Apis.Roads.extract_roads_body | def extract_roads_body(response)
begin
body = MultiJson.load(response.body, :symbolize_keys => true)
rescue
unless response.status_code == 200
check_response_status_code(response)
end
raise GoogleMapsService::Error::ApiError.new(response), 'Received a malformed response.'
end
check_roads_body_error(response, body)
unless response.status_code == 200
raise GoogleMapsService::Error::ApiError.new(response)
end
return body
end | ruby | def extract_roads_body(response)
begin
body = MultiJson.load(response.body, :symbolize_keys => true)
rescue
unless response.status_code == 200
check_response_status_code(response)
end
raise GoogleMapsService::Error::ApiError.new(response), 'Received a malformed response.'
end
check_roads_body_error(response, body)
unless response.status_code == 200
raise GoogleMapsService::Error::ApiError.new(response)
end
return body
end | [
"def",
"extract_roads_body",
"(",
"response",
")",
"begin",
"body",
"=",
"MultiJson",
".",
"load",
"(",
"response",
".",
"body",
",",
":symbolize_keys",
"=>",
"true",
")",
"rescue",
"unless",
"response",
".",
"status_code",
"==",
"200",
"check_response_status_code",
"(",
"response",
")",
"end",
"raise",
"GoogleMapsService",
"::",
"Error",
"::",
"ApiError",
".",
"new",
"(",
"response",
")",
",",
"'Received a malformed response.'",
"end",
"check_roads_body_error",
"(",
"response",
",",
"body",
")",
"unless",
"response",
".",
"status_code",
"==",
"200",
"raise",
"GoogleMapsService",
"::",
"Error",
"::",
"ApiError",
".",
"new",
"(",
"response",
")",
"end",
"return",
"body",
"end"
] | Extracts a result from a Roads API HTTP response. | [
"Extracts",
"a",
"result",
"from",
"a",
"Roads",
"API",
"HTTP",
"response",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/roads.rb#L145-L161 | train |
edwardsamuel/google-maps-services-ruby | lib/google_maps_service/polyline.rb | GoogleMapsService.Polyline.encode | def encode(points)
last_lat = last_lng = 0
result = ""
points.each do |point|
ll = GoogleMapsService::Convert.normalize_latlng(point)
lat = (ll[0] * 1e5).round.to_i
lng = (ll[1] * 1e5).round.to_i
d_lat = lat - last_lat
d_lng = lng - last_lng
[d_lat, d_lng].each do |v|
v = (v < 0) ? ~(v << 1) : (v << 1)
while v >= 0x20
result += ((0x20 | (v & 0x1f)) + 63).chr
v >>= 5
end
result += (v + 63).chr
end
last_lat = lat
last_lng = lng
end
result
end | ruby | def encode(points)
last_lat = last_lng = 0
result = ""
points.each do |point|
ll = GoogleMapsService::Convert.normalize_latlng(point)
lat = (ll[0] * 1e5).round.to_i
lng = (ll[1] * 1e5).round.to_i
d_lat = lat - last_lat
d_lng = lng - last_lng
[d_lat, d_lng].each do |v|
v = (v < 0) ? ~(v << 1) : (v << 1)
while v >= 0x20
result += ((0x20 | (v & 0x1f)) + 63).chr
v >>= 5
end
result += (v + 63).chr
end
last_lat = lat
last_lng = lng
end
result
end | [
"def",
"encode",
"(",
"points",
")",
"last_lat",
"=",
"last_lng",
"=",
"0",
"result",
"=",
"\"\"",
"points",
".",
"each",
"do",
"|",
"point",
"|",
"ll",
"=",
"GoogleMapsService",
"::",
"Convert",
".",
"normalize_latlng",
"(",
"point",
")",
"lat",
"=",
"(",
"ll",
"[",
"0",
"]",
"*",
"1e5",
")",
".",
"round",
".",
"to_i",
"lng",
"=",
"(",
"ll",
"[",
"1",
"]",
"*",
"1e5",
")",
".",
"round",
".",
"to_i",
"d_lat",
"=",
"lat",
"-",
"last_lat",
"d_lng",
"=",
"lng",
"-",
"last_lng",
"[",
"d_lat",
",",
"d_lng",
"]",
".",
"each",
"do",
"|",
"v",
"|",
"v",
"=",
"(",
"v",
"<",
"0",
")",
"?",
"~",
"(",
"v",
"<<",
"1",
")",
":",
"(",
"v",
"<<",
"1",
")",
"while",
"v",
">=",
"0x20",
"result",
"+=",
"(",
"(",
"0x20",
"|",
"(",
"v",
"&",
"0x1f",
")",
")",
"+",
"63",
")",
".",
"chr",
"v",
">>=",
"5",
"end",
"result",
"+=",
"(",
"v",
"+",
"63",
")",
".",
"chr",
"end",
"last_lat",
"=",
"lat",
"last_lng",
"=",
"lng",
"end",
"result",
"end"
] | Encodes a list of points into a polyline string.
See the developer docs for a detailed description of this encoding:
https://developers.google.com/maps/documentation/utilities/polylinealgorithm
@param [Array<Hash>, Array<Array>] points A list of lat/lng pairs.
@return [String] | [
"Encodes",
"a",
"list",
"of",
"points",
"into",
"a",
"polyline",
"string",
"."
] | 46746fd72e90c75855baa88aee04e41c84ff32c9 | https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/polyline.rb#L63-L88 | train |
mongoid/mongoid_fulltext | lib/mongoid/full_text_search.rb | Mongoid::FullTextSearch.ClassMethods.map_query_filters | def map_query_filters(filters)
Hash[filters.map do |key, value|
case value
when Hash then
if value.key? :any then format_query_filter('$in', key, value[:any])
elsif value.key? :all then format_query_filter('$all', key, value[:all])
else raise UnknownFilterQueryOperator, value.keys.join(','), caller end
else format_query_filter('$all', key, value)
end
end]
end | ruby | def map_query_filters(filters)
Hash[filters.map do |key, value|
case value
when Hash then
if value.key? :any then format_query_filter('$in', key, value[:any])
elsif value.key? :all then format_query_filter('$all', key, value[:all])
else raise UnknownFilterQueryOperator, value.keys.join(','), caller end
else format_query_filter('$all', key, value)
end
end]
end | [
"def",
"map_query_filters",
"(",
"filters",
")",
"Hash",
"[",
"filters",
".",
"map",
"do",
"|",
"key",
",",
"value",
"|",
"case",
"value",
"when",
"Hash",
"then",
"if",
"value",
".",
"key?",
":any",
"then",
"format_query_filter",
"(",
"'$in'",
",",
"key",
",",
"value",
"[",
":any",
"]",
")",
"elsif",
"value",
".",
"key?",
":all",
"then",
"format_query_filter",
"(",
"'$all'",
",",
"key",
",",
"value",
"[",
":all",
"]",
")",
"else",
"raise",
"UnknownFilterQueryOperator",
",",
"value",
".",
"keys",
".",
"join",
"(",
"','",
")",
",",
"caller",
"end",
"else",
"format_query_filter",
"(",
"'$all'",
",",
"key",
",",
"value",
")",
"end",
"end",
"]",
"end"
] | Take a list of filters to be mapped so they can update the query
used upon the fulltext search of the ngrams | [
"Take",
"a",
"list",
"of",
"filters",
"to",
"be",
"mapped",
"so",
"they",
"can",
"update",
"the",
"query",
"used",
"upon",
"the",
"fulltext",
"search",
"of",
"the",
"ngrams"
] | 3d212b0eaec2b93b54d9514603bc24b3b2594104 | https://github.com/mongoid/mongoid_fulltext/blob/3d212b0eaec2b93b54d9514603bc24b3b2594104/lib/mongoid/full_text_search.rb#L300-L310 | train |
copiousfreetime/stickler | lib/stickler/spec_lite.rb | Stickler.SpecLite.=~ | def =~(other)
other = coerce( other )
return (other and
self.name == other.name and
self.version.to_s == other.version.to_s and
self.platform_string == other.platform_string )
end | ruby | def =~(other)
other = coerce( other )
return (other and
self.name == other.name and
self.version.to_s == other.version.to_s and
self.platform_string == other.platform_string )
end | [
"def",
"=~",
"(",
"other",
")",
"other",
"=",
"coerce",
"(",
"other",
")",
"return",
"(",
"other",
"and",
"self",
".",
"name",
"==",
"other",
".",
"name",
"and",
"self",
".",
"version",
".",
"to_s",
"==",
"other",
".",
"version",
".",
"to_s",
"and",
"self",
".",
"platform_string",
"==",
"other",
".",
"platform_string",
")",
"end"
] | Lets be comparable!
See if another Spec is the same as this spec | [
"Lets",
"be",
"comparable!"
] | 9c9ef5b2287c0be071da0a233e2b262e98c878e5 | https://github.com/copiousfreetime/stickler/blob/9c9ef5b2287c0be071da0a233e2b262e98c878e5/lib/stickler/spec_lite.rb#L85-L91 | train |
copiousfreetime/stickler | lib/stickler/repository/remote_mirror.rb | ::Stickler::Repository.RemoteMirror.mirror | def mirror( spec, upstream_host )
raise Stickler::Repository::Error, "gem #{spec.full_name} already exists in remote repository" if remote_gem_file_exist?( spec )
resource_request( mirror_resource( spec, upstream_host ) )
end | ruby | def mirror( spec, upstream_host )
raise Stickler::Repository::Error, "gem #{spec.full_name} already exists in remote repository" if remote_gem_file_exist?( spec )
resource_request( mirror_resource( spec, upstream_host ) )
end | [
"def",
"mirror",
"(",
"spec",
",",
"upstream_host",
")",
"raise",
"Stickler",
"::",
"Repository",
"::",
"Error",
",",
"\"gem #{spec.full_name} already exists in remote repository\"",
"if",
"remote_gem_file_exist?",
"(",
"spec",
")",
"resource_request",
"(",
"mirror_resource",
"(",
"spec",
",",
"upstream_host",
")",
")",
"end"
] | Tell the remote repoistory to mirror the given gem from an upstream
repository | [
"Tell",
"the",
"remote",
"repoistory",
"to",
"mirror",
"the",
"given",
"gem",
"from",
"an",
"upstream",
"repository"
] | 9c9ef5b2287c0be071da0a233e2b262e98c878e5 | https://github.com/copiousfreetime/stickler/blob/9c9ef5b2287c0be071da0a233e2b262e98c878e5/lib/stickler/repository/remote_mirror.rb#L14-L17 | train |
copiousfreetime/stickler | lib/stickler/middleware/index.rb | Stickler::Middleware.Index.marshalled_specs | def marshalled_specs( spec_a )
a = spec_a.collect { |s| s.to_rubygems_a }
marshal( optimize_specs( a ) )
end | ruby | def marshalled_specs( spec_a )
a = spec_a.collect { |s| s.to_rubygems_a }
marshal( optimize_specs( a ) )
end | [
"def",
"marshalled_specs",
"(",
"spec_a",
")",
"a",
"=",
"spec_a",
".",
"collect",
"{",
"|",
"s",
"|",
"s",
".",
"to_rubygems_a",
"}",
"marshal",
"(",
"optimize_specs",
"(",
"a",
")",
")",
"end"
] | Convert to the array format used by gem servers
everywhere | [
"Convert",
"to",
"the",
"array",
"format",
"used",
"by",
"gem",
"servers",
"everywhere"
] | 9c9ef5b2287c0be071da0a233e2b262e98c878e5 | https://github.com/copiousfreetime/stickler/blob/9c9ef5b2287c0be071da0a233e2b262e98c878e5/lib/stickler/middleware/index.rb#L153-L156 | train |
copiousfreetime/stickler | lib/stickler/client.rb | Stickler.Client.parser | def parser
me = self # scoping forces this
@parser ||= Trollop::Parser.new do
banner me.class.banner
opt :server, "The gem or stickler server URL", :type => :string, :default => Client.config.server
opt :debug, "Output debug information for the server interaction", :default => false
end
end | ruby | def parser
me = self # scoping forces this
@parser ||= Trollop::Parser.new do
banner me.class.banner
opt :server, "The gem or stickler server URL", :type => :string, :default => Client.config.server
opt :debug, "Output debug information for the server interaction", :default => false
end
end | [
"def",
"parser",
"me",
"=",
"self",
"@parser",
"||=",
"Trollop",
"::",
"Parser",
".",
"new",
"do",
"banner",
"me",
".",
"class",
".",
"banner",
"opt",
":server",
",",
"\"The gem or stickler server URL\"",
",",
":type",
"=>",
":string",
",",
":default",
"=>",
"Client",
".",
"config",
".",
"server",
"opt",
":debug",
",",
"\"Output debug information for the server interaction\"",
",",
":default",
"=>",
"false",
"end",
"end"
] | Create a new client
Takes an argv like array as a parameter. | [
"Create",
"a",
"new",
"client"
] | 9c9ef5b2287c0be071da0a233e2b262e98c878e5 | https://github.com/copiousfreetime/stickler/blob/9c9ef5b2287c0be071da0a233e2b262e98c878e5/lib/stickler/client.rb#L21-L28 | train |
janko/flickr-objects | lib/flickr/attributes.rb | Flickr.Attribute.find_value | def find_value(context)
locations.each do |location|
begin
value = context.instance_exec(&location)
next if value.nil?
return value
rescue
end
end
nil
end | ruby | def find_value(context)
locations.each do |location|
begin
value = context.instance_exec(&location)
next if value.nil?
return value
rescue
end
end
nil
end | [
"def",
"find_value",
"(",
"context",
")",
"locations",
".",
"each",
"do",
"|",
"location",
"|",
"begin",
"value",
"=",
"context",
".",
"instance_exec",
"(",
"&",
"location",
")",
"next",
"if",
"value",
".",
"nil?",
"return",
"value",
"rescue",
"end",
"end",
"nil",
"end"
] | Finds attribute value in the JSON response by looking at the given locations. | [
"Finds",
"attribute",
"value",
"in",
"the",
"JSON",
"response",
"by",
"looking",
"at",
"the",
"given",
"locations",
"."
] | dd25554e0002e76f4045542a9abdcdb754a94df6 | https://github.com/janko/flickr-objects/blob/dd25554e0002e76f4045542a9abdcdb754a94df6/lib/flickr/attributes.rb#L79-L90 | train |
janko/flickr-objects | lib/flickr/attributes.rb | Flickr.AttributeSet.add_locations | def add_locations(hash)
hash.each do |attribute_name, locations|
find(attribute_name).add_locations(locations)
end
end | ruby | def add_locations(hash)
hash.each do |attribute_name, locations|
find(attribute_name).add_locations(locations)
end
end | [
"def",
"add_locations",
"(",
"hash",
")",
"hash",
".",
"each",
"do",
"|",
"attribute_name",
",",
"locations",
"|",
"find",
"(",
"attribute_name",
")",
".",
"add_locations",
"(",
"locations",
")",
"end",
"end"
] | Shorthand for adding locations to multiple attributes at once. | [
"Shorthand",
"for",
"adding",
"locations",
"to",
"multiple",
"attributes",
"at",
"once",
"."
] | dd25554e0002e76f4045542a9abdcdb754a94df6 | https://github.com/janko/flickr-objects/blob/dd25554e0002e76f4045542a9abdcdb754a94df6/lib/flickr/attributes.rb#L187-L191 | train |
janko/flickr-objects | spec/support/helpers.rb | Helpers.ClassMethods.record_api_methods | def record_api_methods
before do
stub_const("Flickr::Client::Data", Class.new(Flickr::Client::Data) do
def do_request(http_method, flickr_method, params = {})
VCR.use_cassette(flickr_method) { super }
end
end)
stub_const("Flickr::Client::Upload", Class.new(Flickr::Client::Upload) do
def do_request(http_method, path, params = {})
if VCR.send(:cassettes).empty?
VCR.use_cassette(path) { super }
else
super
end
end
end)
end
end | ruby | def record_api_methods
before do
stub_const("Flickr::Client::Data", Class.new(Flickr::Client::Data) do
def do_request(http_method, flickr_method, params = {})
VCR.use_cassette(flickr_method) { super }
end
end)
stub_const("Flickr::Client::Upload", Class.new(Flickr::Client::Upload) do
def do_request(http_method, path, params = {})
if VCR.send(:cassettes).empty?
VCR.use_cassette(path) { super }
else
super
end
end
end)
end
end | [
"def",
"record_api_methods",
"before",
"do",
"stub_const",
"(",
"\"Flickr::Client::Data\"",
",",
"Class",
".",
"new",
"(",
"Flickr",
"::",
"Client",
"::",
"Data",
")",
"do",
"def",
"do_request",
"(",
"http_method",
",",
"flickr_method",
",",
"params",
"=",
"{",
"}",
")",
"VCR",
".",
"use_cassette",
"(",
"flickr_method",
")",
"{",
"super",
"}",
"end",
"end",
")",
"stub_const",
"(",
"\"Flickr::Client::Upload\"",
",",
"Class",
".",
"new",
"(",
"Flickr",
"::",
"Client",
"::",
"Upload",
")",
"do",
"def",
"do_request",
"(",
"http_method",
",",
"path",
",",
"params",
"=",
"{",
"}",
")",
"if",
"VCR",
".",
"send",
"(",
":cassettes",
")",
".",
"empty?",
"VCR",
".",
"use_cassette",
"(",
"path",
")",
"{",
"super",
"}",
"else",
"super",
"end",
"end",
"end",
")",
"end",
"end"
] | Wraps a VCR cassette around API calls with the same name as the Flickr
method called. For example, the cassette for `Flickr.sets.create` will
be called "flickr.photosets.create". Because we repeat the same API calls
in different examples, we can just reuse those VCR cassettes rather than
recording new ones. | [
"Wraps",
"a",
"VCR",
"cassette",
"around",
"API",
"calls",
"with",
"the",
"same",
"name",
"as",
"the",
"Flickr",
"method",
"called",
".",
"For",
"example",
"the",
"cassette",
"for",
"Flickr",
".",
"sets",
".",
"create",
"will",
"be",
"called",
"flickr",
".",
"photosets",
".",
"create",
".",
"Because",
"we",
"repeat",
"the",
"same",
"API",
"calls",
"in",
"different",
"examples",
"we",
"can",
"just",
"reuse",
"those",
"VCR",
"cassettes",
"rather",
"than",
"recording",
"new",
"ones",
"."
] | dd25554e0002e76f4045542a9abdcdb754a94df6 | https://github.com/janko/flickr-objects/blob/dd25554e0002e76f4045542a9abdcdb754a94df6/spec/support/helpers.rb#L30-L48 | train |
janko/flickr-objects | lib/flickr/object.rb | Flickr.Object.inspect | def inspect
attribute_values = self.class.attributes
.inject({}) { |hash, attribute| hash.update(attribute.name => send(attribute.name)) }
.reject { |name, value| value.nil? or (value.respond_to?(:empty?) and value.empty?) }
attributes = attribute_values
.map { |name, value| "#{name}=#{value.inspect}" }
.join(" ")
class_name = self.class.name
hex_code = "0x#{(object_id >> 1).to_s(16)}"
"#<#{class_name}:#{hex_code} #{attributes}>"
end | ruby | def inspect
attribute_values = self.class.attributes
.inject({}) { |hash, attribute| hash.update(attribute.name => send(attribute.name)) }
.reject { |name, value| value.nil? or (value.respond_to?(:empty?) and value.empty?) }
attributes = attribute_values
.map { |name, value| "#{name}=#{value.inspect}" }
.join(" ")
class_name = self.class.name
hex_code = "0x#{(object_id >> 1).to_s(16)}"
"#<#{class_name}:#{hex_code} #{attributes}>"
end | [
"def",
"inspect",
"attribute_values",
"=",
"self",
".",
"class",
".",
"attributes",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"hash",
",",
"attribute",
"|",
"hash",
".",
"update",
"(",
"attribute",
".",
"name",
"=>",
"send",
"(",
"attribute",
".",
"name",
")",
")",
"}",
".",
"reject",
"{",
"|",
"name",
",",
"value",
"|",
"value",
".",
"nil?",
"or",
"(",
"value",
".",
"respond_to?",
"(",
":empty?",
")",
"and",
"value",
".",
"empty?",
")",
"}",
"attributes",
"=",
"attribute_values",
".",
"map",
"{",
"|",
"name",
",",
"value",
"|",
"\"#{name}=#{value.inspect}\"",
"}",
".",
"join",
"(",
"\" \"",
")",
"class_name",
"=",
"self",
".",
"class",
".",
"name",
"hex_code",
"=",
"\"0x#{(object_id >> 1).to_s(16)}\"",
"\"#<#{class_name}:#{hex_code} #{attributes}>\"",
"end"
] | Displays all the attributes and their values. | [
"Displays",
"all",
"the",
"attributes",
"and",
"their",
"values",
"."
] | dd25554e0002e76f4045542a9abdcdb754a94df6 | https://github.com/janko/flickr-objects/blob/dd25554e0002e76f4045542a9abdcdb754a94df6/lib/flickr/object.rb#L85-L97 | train |
janko/flickr-objects | lib/flickr/sanitized_file.rb | Flickr.SanitizedFile.sanitize! | def sanitize!
if rails_file?
@file = @original
@content_type = @original.content_type
@path = @original.tempfile
elsif sinatra_file?
@file = @original[:tempfile]
@content_type = @original[:type]
@path = @original[:tempfile].path
elsif io?
@file = @original
@content_type = @original.content_type if @original.respond_to?(:content_type)
@path = @original.path if @original.respond_to?(:path)
elsif string?
@file = File.open(@original)
@content_type = nil
@path = @original
else
raise ArgumentError, "invalid file format"
end
end | ruby | def sanitize!
if rails_file?
@file = @original
@content_type = @original.content_type
@path = @original.tempfile
elsif sinatra_file?
@file = @original[:tempfile]
@content_type = @original[:type]
@path = @original[:tempfile].path
elsif io?
@file = @original
@content_type = @original.content_type if @original.respond_to?(:content_type)
@path = @original.path if @original.respond_to?(:path)
elsif string?
@file = File.open(@original)
@content_type = nil
@path = @original
else
raise ArgumentError, "invalid file format"
end
end | [
"def",
"sanitize!",
"if",
"rails_file?",
"@file",
"=",
"@original",
"@content_type",
"=",
"@original",
".",
"content_type",
"@path",
"=",
"@original",
".",
"tempfile",
"elsif",
"sinatra_file?",
"@file",
"=",
"@original",
"[",
":tempfile",
"]",
"@content_type",
"=",
"@original",
"[",
":type",
"]",
"@path",
"=",
"@original",
"[",
":tempfile",
"]",
".",
"path",
"elsif",
"io?",
"@file",
"=",
"@original",
"@content_type",
"=",
"@original",
".",
"content_type",
"if",
"@original",
".",
"respond_to?",
"(",
":content_type",
")",
"@path",
"=",
"@original",
".",
"path",
"if",
"@original",
".",
"respond_to?",
"(",
":path",
")",
"elsif",
"string?",
"@file",
"=",
"File",
".",
"open",
"(",
"@original",
")",
"@content_type",
"=",
"nil",
"@path",
"=",
"@original",
"else",
"raise",
"ArgumentError",
",",
"\"invalid file format\"",
"end",
"end"
] | Extracts the tempfile, content type and path. | [
"Extracts",
"the",
"tempfile",
"content",
"type",
"and",
"path",
"."
] | dd25554e0002e76f4045542a9abdcdb754a94df6 | https://github.com/janko/flickr-objects/blob/dd25554e0002e76f4045542a9abdcdb754a94df6/lib/flickr/sanitized_file.rb#L30-L50 | train |
dei79/jquery-modal-rails | lib/jquery/modal/helpers/link_helpers.rb | Jquery.Helpers.link_to_modal | def link_to_modal(*args, &block)
if block_given?
options = args.first || {}
html_options = args.second
block_result = capture(&block)
link_to_modal(block_result, options, html_options)
else
name = args[0]
options = args[1] || {}
html_options = args[2] || {}
# extend the html_options
html_options[:rel] = "modal:open"
if (html_options.has_key?(:remote))
if (html_options[:remote] == true)
html_options[:rel] = "modal:open:ajaxpost"
end
# remove the remote tag
html_options.delete(:remote)
end
# check if we have an id
html_options[:id] = UUIDTools::UUID.random_create().to_s unless html_options.has_key?(:id)
# perform the normal link_to operation
html_link = link_to(name, options, html_options)
# emit both
html_link.html_safe
end
end | ruby | def link_to_modal(*args, &block)
if block_given?
options = args.first || {}
html_options = args.second
block_result = capture(&block)
link_to_modal(block_result, options, html_options)
else
name = args[0]
options = args[1] || {}
html_options = args[2] || {}
# extend the html_options
html_options[:rel] = "modal:open"
if (html_options.has_key?(:remote))
if (html_options[:remote] == true)
html_options[:rel] = "modal:open:ajaxpost"
end
# remove the remote tag
html_options.delete(:remote)
end
# check if we have an id
html_options[:id] = UUIDTools::UUID.random_create().to_s unless html_options.has_key?(:id)
# perform the normal link_to operation
html_link = link_to(name, options, html_options)
# emit both
html_link.html_safe
end
end | [
"def",
"link_to_modal",
"(",
"*",
"args",
",",
"&",
"block",
")",
"if",
"block_given?",
"options",
"=",
"args",
".",
"first",
"||",
"{",
"}",
"html_options",
"=",
"args",
".",
"second",
"block_result",
"=",
"capture",
"(",
"&",
"block",
")",
"link_to_modal",
"(",
"block_result",
",",
"options",
",",
"html_options",
")",
"else",
"name",
"=",
"args",
"[",
"0",
"]",
"options",
"=",
"args",
"[",
"1",
"]",
"||",
"{",
"}",
"html_options",
"=",
"args",
"[",
"2",
"]",
"||",
"{",
"}",
"html_options",
"[",
":rel",
"]",
"=",
"\"modal:open\"",
"if",
"(",
"html_options",
".",
"has_key?",
"(",
":remote",
")",
")",
"if",
"(",
"html_options",
"[",
":remote",
"]",
"==",
"true",
")",
"html_options",
"[",
":rel",
"]",
"=",
"\"modal:open:ajaxpost\"",
"end",
"html_options",
".",
"delete",
"(",
":remote",
")",
"end",
"html_options",
"[",
":id",
"]",
"=",
"UUIDTools",
"::",
"UUID",
".",
"random_create",
"(",
")",
".",
"to_s",
"unless",
"html_options",
".",
"has_key?",
"(",
":id",
")",
"html_link",
"=",
"link_to",
"(",
"name",
",",
"options",
",",
"html_options",
")",
"html_link",
".",
"html_safe",
"end",
"end"
] | Creates a link tag to a given url or path and ensures that the linke will be rendered
as jquery modal dialog
==== Signatures
link_to(body, url, html_options = {})
link_to(body, url) | [
"Creates",
"a",
"link",
"tag",
"to",
"a",
"given",
"url",
"or",
"path",
"and",
"ensures",
"that",
"the",
"linke",
"will",
"be",
"rendered",
"as",
"jquery",
"modal",
"dialog"
] | 9aa5e120131108577cfeb9600dde7343d95a034f | https://github.com/dei79/jquery-modal-rails/blob/9aa5e120131108577cfeb9600dde7343d95a034f/lib/jquery/modal/helpers/link_helpers.rb#L12-L43 | train |
ashmaroli/jekyll-data | lib/jekyll-data/reader.rb | JekyllData.Reader.read_theme_data | def read_theme_data
if @theme.data_path
#
# show contents of "<theme>/_data/" dir being read while degugging.
inspect_theme_data
theme_data = ThemeDataReader.new(site).read(site.config["data_dir"])
@site.data = Jekyll::Utils.deep_merge_hashes(theme_data, @site.data)
#
# show contents of merged site.data hash while debugging with
# additional --show-data switch.
inspect_merged_hash if site.config["show-data"] && site.config["verbose"]
end
end | ruby | def read_theme_data
if @theme.data_path
#
# show contents of "<theme>/_data/" dir being read while degugging.
inspect_theme_data
theme_data = ThemeDataReader.new(site).read(site.config["data_dir"])
@site.data = Jekyll::Utils.deep_merge_hashes(theme_data, @site.data)
#
# show contents of merged site.data hash while debugging with
# additional --show-data switch.
inspect_merged_hash if site.config["show-data"] && site.config["verbose"]
end
end | [
"def",
"read_theme_data",
"if",
"@theme",
".",
"data_path",
"inspect_theme_data",
"theme_data",
"=",
"ThemeDataReader",
".",
"new",
"(",
"site",
")",
".",
"read",
"(",
"site",
".",
"config",
"[",
"\"data_dir\"",
"]",
")",
"@site",
".",
"data",
"=",
"Jekyll",
"::",
"Utils",
".",
"deep_merge_hashes",
"(",
"theme_data",
",",
"@site",
".",
"data",
")",
"inspect_merged_hash",
"if",
"site",
".",
"config",
"[",
"\"show-data\"",
"]",
"&&",
"site",
".",
"config",
"[",
"\"verbose\"",
"]",
"end",
"end"
] | Read data files within a theme gem and add them to internal data
Returns a hash appended with new data | [
"Read",
"data",
"files",
"within",
"a",
"theme",
"gem",
"and",
"add",
"them",
"to",
"internal",
"data"
] | 7fb2b51db67c864c9e596a759c0df46efc78c86d | https://github.com/ashmaroli/jekyll-data/blob/7fb2b51db67c864c9e596a759c0df46efc78c86d/lib/jekyll-data/reader.rb#L25-L37 | train |
ashmaroli/jekyll-data | lib/jekyll-data/reader.rb | JekyllData.Reader.inspect_inner_hash | def inspect_inner_hash(hash)
hash.each do |key, value|
if value.is_a? Array
print_label key
extract_hashes_and_print value
elsif value.is_a? Hash
print_subkey_and_value key, value
else
print_hash key, value
end
end
end | ruby | def inspect_inner_hash(hash)
hash.each do |key, value|
if value.is_a? Array
print_label key
extract_hashes_and_print value
elsif value.is_a? Hash
print_subkey_and_value key, value
else
print_hash key, value
end
end
end | [
"def",
"inspect_inner_hash",
"(",
"hash",
")",
"hash",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"is_a?",
"Array",
"print_label",
"key",
"extract_hashes_and_print",
"value",
"elsif",
"value",
".",
"is_a?",
"Hash",
"print_subkey_and_value",
"key",
",",
"value",
"else",
"print_hash",
"key",
",",
"value",
"end",
"end",
"end"
] | Analyse deeper hashes and extract contents to output | [
"Analyse",
"deeper",
"hashes",
"and",
"extract",
"contents",
"to",
"output"
] | 7fb2b51db67c864c9e596a759c0df46efc78c86d | https://github.com/ashmaroli/jekyll-data/blob/7fb2b51db67c864c9e596a759c0df46efc78c86d/lib/jekyll-data/reader.rb#L98-L109 | train |
ashmaroli/jekyll-data | lib/jekyll-data/reader.rb | JekyllData.Reader.print_subkey_and_value | def print_subkey_and_value(key, value)
print_label key
value.each do |subkey, val|
if val.is_a? Hash
print_inner_subkey subkey
inspect_inner_hash val
elsif val.is_a? Array
print_inner_subkey subkey
extract_hashes_and_print val
elsif val.is_a? String
print_hash subkey, val
end
end
end | ruby | def print_subkey_and_value(key, value)
print_label key
value.each do |subkey, val|
if val.is_a? Hash
print_inner_subkey subkey
inspect_inner_hash val
elsif val.is_a? Array
print_inner_subkey subkey
extract_hashes_and_print val
elsif val.is_a? String
print_hash subkey, val
end
end
end | [
"def",
"print_subkey_and_value",
"(",
"key",
",",
"value",
")",
"print_label",
"key",
"value",
".",
"each",
"do",
"|",
"subkey",
",",
"val",
"|",
"if",
"val",
".",
"is_a?",
"Hash",
"print_inner_subkey",
"subkey",
"inspect_inner_hash",
"val",
"elsif",
"val",
".",
"is_a?",
"Array",
"print_inner_subkey",
"subkey",
"extract_hashes_and_print",
"val",
"elsif",
"val",
".",
"is_a?",
"String",
"print_hash",
"subkey",
",",
"val",
"end",
"end",
"end"
] | Prints label, keys and values of mappings | [
"Prints",
"label",
"keys",
"and",
"values",
"of",
"mappings"
] | 7fb2b51db67c864c9e596a759c0df46efc78c86d | https://github.com/ashmaroli/jekyll-data/blob/7fb2b51db67c864c9e596a759c0df46efc78c86d/lib/jekyll-data/reader.rb#L176-L189 | train |
RubyDevInc/paho.mqtt.ruby | lib/paho_mqtt/connection_helper.rb | PahoMqtt.ConnectionHelper.should_send_ping? | def should_send_ping?(now, keep_alive, last_packet_received_at)
last_pingreq_sent_at = @sender.last_pingreq_sent_at
last_pingresp_received_at = @handler.last_pingresp_received_at
if !last_pingreq_sent_at || (last_pingresp_received_at && (last_pingreq_sent_at <= last_pingresp_received_at))
next_pingreq_at = [@sender.last_packet_sent_at, last_packet_received_at].min + (keep_alive * 0.7).ceil
return next_pingreq_at <= now
end
end | ruby | def should_send_ping?(now, keep_alive, last_packet_received_at)
last_pingreq_sent_at = @sender.last_pingreq_sent_at
last_pingresp_received_at = @handler.last_pingresp_received_at
if !last_pingreq_sent_at || (last_pingresp_received_at && (last_pingreq_sent_at <= last_pingresp_received_at))
next_pingreq_at = [@sender.last_packet_sent_at, last_packet_received_at].min + (keep_alive * 0.7).ceil
return next_pingreq_at <= now
end
end | [
"def",
"should_send_ping?",
"(",
"now",
",",
"keep_alive",
",",
"last_packet_received_at",
")",
"last_pingreq_sent_at",
"=",
"@sender",
".",
"last_pingreq_sent_at",
"last_pingresp_received_at",
"=",
"@handler",
".",
"last_pingresp_received_at",
"if",
"!",
"last_pingreq_sent_at",
"||",
"(",
"last_pingresp_received_at",
"&&",
"(",
"last_pingreq_sent_at",
"<=",
"last_pingresp_received_at",
")",
")",
"next_pingreq_at",
"=",
"[",
"@sender",
".",
"last_packet_sent_at",
",",
"last_packet_received_at",
"]",
".",
"min",
"+",
"(",
"keep_alive",
"*",
"0.7",
")",
".",
"ceil",
"return",
"next_pingreq_at",
"<=",
"now",
"end",
"end"
] | Would return 'true' if ping requset should be sent and 'nil' if not | [
"Would",
"return",
"true",
"if",
"ping",
"requset",
"should",
"be",
"sent",
"and",
"nil",
"if",
"not"
] | 1a3a14ac5b646132829fb0f38c794cae503989d2 | https://github.com/RubyDevInc/paho.mqtt.ruby/blob/1a3a14ac5b646132829fb0f38c794cae503989d2/lib/paho_mqtt/connection_helper.rb#L147-L154 | train |
morgoth/picasa | lib/picasa/utils.rb | Picasa.Utils.array_wrap | def array_wrap(object)
if object.nil?
[]
elsif object.respond_to?(:to_ary)
object.to_ary || [object]
else
[object]
end
end | ruby | def array_wrap(object)
if object.nil?
[]
elsif object.respond_to?(:to_ary)
object.to_ary || [object]
else
[object]
end
end | [
"def",
"array_wrap",
"(",
"object",
")",
"if",
"object",
".",
"nil?",
"[",
"]",
"elsif",
"object",
".",
"respond_to?",
"(",
":to_ary",
")",
"object",
".",
"to_ary",
"||",
"[",
"object",
"]",
"else",
"[",
"object",
"]",
"end",
"end"
] | Ported from activesupport gem | [
"Ported",
"from",
"activesupport",
"gem"
] | 94672fab0baa24eb2db9c6aba5b03920be9f98f2 | https://github.com/morgoth/picasa/blob/94672fab0baa24eb2db9c6aba5b03920be9f98f2/lib/picasa/utils.rb#L26-L34 | train |
coderanger/rspec-command | lib/rspec_command/match_fixture.rb | RSpecCommand.MatchFixture.failure_message | def failure_message
matching_files = @fixture.files & @local.files
fixture_only_files = @fixture.files - @local.files
local_only_files = @local.files - @fixture.files
buf = "expected fixture #{@fixture.path} to match files:\n"
(@fixture.files | @local.files).sort.each do |file|
if matching_files.include?(file)
local_file = @local.absolute(file)
fixture_file = @fixture.absolute(file)
if File.directory?(local_file) && File.directory?(fixture_file)
# Do nothing
elsif File.directory?(fixture_file)
buf << " #{file} should be a directory\n"
elsif File.directory?(local_file)
buf << " #{file} should not be a directory"
else
actual = IO.read(local_file)
expected = IO.read(fixture_file)
if actual != expected
# Show a diff
buf << " #{file} does not match fixture:"
buf << differ.diff(actual, expected).split(/\n/).map {|line| ' '+line }.join("\n")
end
end
elsif fixture_only_files.include?(file)
buf << " #{file} is not found\n"
elsif local_only_files.include?(file)
buf << " #{file} should not exist\n"
end
end
buf
end | ruby | def failure_message
matching_files = @fixture.files & @local.files
fixture_only_files = @fixture.files - @local.files
local_only_files = @local.files - @fixture.files
buf = "expected fixture #{@fixture.path} to match files:\n"
(@fixture.files | @local.files).sort.each do |file|
if matching_files.include?(file)
local_file = @local.absolute(file)
fixture_file = @fixture.absolute(file)
if File.directory?(local_file) && File.directory?(fixture_file)
# Do nothing
elsif File.directory?(fixture_file)
buf << " #{file} should be a directory\n"
elsif File.directory?(local_file)
buf << " #{file} should not be a directory"
else
actual = IO.read(local_file)
expected = IO.read(fixture_file)
if actual != expected
# Show a diff
buf << " #{file} does not match fixture:"
buf << differ.diff(actual, expected).split(/\n/).map {|line| ' '+line }.join("\n")
end
end
elsif fixture_only_files.include?(file)
buf << " #{file} is not found\n"
elsif local_only_files.include?(file)
buf << " #{file} should not exist\n"
end
end
buf
end | [
"def",
"failure_message",
"matching_files",
"=",
"@fixture",
".",
"files",
"&",
"@local",
".",
"files",
"fixture_only_files",
"=",
"@fixture",
".",
"files",
"-",
"@local",
".",
"files",
"local_only_files",
"=",
"@local",
".",
"files",
"-",
"@fixture",
".",
"files",
"buf",
"=",
"\"expected fixture #{@fixture.path} to match files:\\n\"",
"(",
"@fixture",
".",
"files",
"|",
"@local",
".",
"files",
")",
".",
"sort",
".",
"each",
"do",
"|",
"file",
"|",
"if",
"matching_files",
".",
"include?",
"(",
"file",
")",
"local_file",
"=",
"@local",
".",
"absolute",
"(",
"file",
")",
"fixture_file",
"=",
"@fixture",
".",
"absolute",
"(",
"file",
")",
"if",
"File",
".",
"directory?",
"(",
"local_file",
")",
"&&",
"File",
".",
"directory?",
"(",
"fixture_file",
")",
"elsif",
"File",
".",
"directory?",
"(",
"fixture_file",
")",
"buf",
"<<",
"\" #{file} should be a directory\\n\"",
"elsif",
"File",
".",
"directory?",
"(",
"local_file",
")",
"buf",
"<<",
"\" #{file} should not be a directory\"",
"else",
"actual",
"=",
"IO",
".",
"read",
"(",
"local_file",
")",
"expected",
"=",
"IO",
".",
"read",
"(",
"fixture_file",
")",
"if",
"actual",
"!=",
"expected",
"buf",
"<<",
"\" #{file} does not match fixture:\"",
"buf",
"<<",
"differ",
".",
"diff",
"(",
"actual",
",",
"expected",
")",
".",
"split",
"(",
"/",
"\\n",
"/",
")",
".",
"map",
"{",
"|",
"line",
"|",
"' '",
"+",
"line",
"}",
".",
"join",
"(",
"\"\\n\"",
")",
"end",
"end",
"elsif",
"fixture_only_files",
".",
"include?",
"(",
"file",
")",
"buf",
"<<",
"\" #{file} is not found\\n\"",
"elsif",
"local_only_files",
".",
"include?",
"(",
"file",
")",
"buf",
"<<",
"\" #{file} should not exist\\n\"",
"end",
"end",
"buf",
"end"
] | Callback fro RSpec. Returns a human-readable failure message.
@return [String] | [
"Callback",
"fro",
"RSpec",
".",
"Returns",
"a",
"human",
"-",
"readable",
"failure",
"message",
"."
] | 3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9 | https://github.com/coderanger/rspec-command/blob/3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9/lib/rspec_command/match_fixture.rb#L51-L82 | train |
coderanger/rspec-command | lib/rspec_command/match_fixture.rb | RSpecCommand.MatchFixture.file_content_match? | def file_content_match?
@fixture.full_files.zip(@local.full_files).all? do |fixture_file, local_file|
if File.directory?(fixture_file)
File.directory?(local_file)
else
!File.directory?(local_file) && IO.read(fixture_file) == IO.read(local_file)
end
end
end | ruby | def file_content_match?
@fixture.full_files.zip(@local.full_files).all? do |fixture_file, local_file|
if File.directory?(fixture_file)
File.directory?(local_file)
else
!File.directory?(local_file) && IO.read(fixture_file) == IO.read(local_file)
end
end
end | [
"def",
"file_content_match?",
"@fixture",
".",
"full_files",
".",
"zip",
"(",
"@local",
".",
"full_files",
")",
".",
"all?",
"do",
"|",
"fixture_file",
",",
"local_file",
"|",
"if",
"File",
".",
"directory?",
"(",
"fixture_file",
")",
"File",
".",
"directory?",
"(",
"local_file",
")",
"else",
"!",
"File",
".",
"directory?",
"(",
"local_file",
")",
"&&",
"IO",
".",
"read",
"(",
"fixture_file",
")",
"==",
"IO",
".",
"read",
"(",
"local_file",
")",
"end",
"end",
"end"
] | Do the file contents match?
@return [Boolean] | [
"Do",
"the",
"file",
"contents",
"match?"
] | 3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9 | https://github.com/coderanger/rspec-command/blob/3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9/lib/rspec_command/match_fixture.rb#L96-L104 | train |
coderanger/rspec-command | lib/rspec_command.rb | RSpecCommand.ClassMethods.file | def file(path, content=nil, &block)
raise "file path should be relative the the temporary directory." if path == File.expand_path(path)
before do
content = instance_eval(&block) if block
dest_path = File.join(temp_path, path)
FileUtils.mkdir_p(File.dirname(dest_path))
IO.write(dest_path, content)
end
end | ruby | def file(path, content=nil, &block)
raise "file path should be relative the the temporary directory." if path == File.expand_path(path)
before do
content = instance_eval(&block) if block
dest_path = File.join(temp_path, path)
FileUtils.mkdir_p(File.dirname(dest_path))
IO.write(dest_path, content)
end
end | [
"def",
"file",
"(",
"path",
",",
"content",
"=",
"nil",
",",
"&",
"block",
")",
"raise",
"\"file path should be relative the the temporary directory.\"",
"if",
"path",
"==",
"File",
".",
"expand_path",
"(",
"path",
")",
"before",
"do",
"content",
"=",
"instance_eval",
"(",
"&",
"block",
")",
"if",
"block",
"dest_path",
"=",
"File",
".",
"join",
"(",
"temp_path",
",",
"path",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"File",
".",
"dirname",
"(",
"dest_path",
")",
")",
"IO",
".",
"write",
"(",
"dest_path",
",",
"content",
")",
"end",
"end"
] | Create a file in the temporary directory for this example.
@param path [String] Path within the temporary directory to write to.
@param content [String] File data to write.
@param block [Proc] Optional block to return file data to write.
@example
describe 'myapp' do
command 'myapp read data.txt'
file 'data.txt', <<-EOH
a thing
EOH
its(:exitstatus) { is_expected.to eq 0 }
end | [
"Create",
"a",
"file",
"in",
"the",
"temporary",
"directory",
"for",
"this",
"example",
"."
] | 3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9 | https://github.com/coderanger/rspec-command/blob/3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9/lib/rspec_command.rb#L298-L306 | train |
coderanger/rspec-command | lib/rspec_command.rb | RSpecCommand.ClassMethods.fixture_file | def fixture_file(path, dest=nil)
raise "file path should be relative the the temporary directory." if path == File.expand_path(path)
before do |example|
fixture_path = find_fixture(example.file_path, path)
dest_path = dest ? File.join(temp_path, dest) : temp_path
FileUtils.mkdir_p(dest_path)
file_list = MatchFixture::FileList.new(fixture_path)
file_list.files.each do |file|
abs = file_list.absolute(file)
if File.directory?(abs)
FileUtils.mkdir_p(File.join(dest_path, file))
else
FileUtils.copy(abs , File.join(dest_path, file), preserve: true)
end
end
end
end | ruby | def fixture_file(path, dest=nil)
raise "file path should be relative the the temporary directory." if path == File.expand_path(path)
before do |example|
fixture_path = find_fixture(example.file_path, path)
dest_path = dest ? File.join(temp_path, dest) : temp_path
FileUtils.mkdir_p(dest_path)
file_list = MatchFixture::FileList.new(fixture_path)
file_list.files.each do |file|
abs = file_list.absolute(file)
if File.directory?(abs)
FileUtils.mkdir_p(File.join(dest_path, file))
else
FileUtils.copy(abs , File.join(dest_path, file), preserve: true)
end
end
end
end | [
"def",
"fixture_file",
"(",
"path",
",",
"dest",
"=",
"nil",
")",
"raise",
"\"file path should be relative the the temporary directory.\"",
"if",
"path",
"==",
"File",
".",
"expand_path",
"(",
"path",
")",
"before",
"do",
"|",
"example",
"|",
"fixture_path",
"=",
"find_fixture",
"(",
"example",
".",
"file_path",
",",
"path",
")",
"dest_path",
"=",
"dest",
"?",
"File",
".",
"join",
"(",
"temp_path",
",",
"dest",
")",
":",
"temp_path",
"FileUtils",
".",
"mkdir_p",
"(",
"dest_path",
")",
"file_list",
"=",
"MatchFixture",
"::",
"FileList",
".",
"new",
"(",
"fixture_path",
")",
"file_list",
".",
"files",
".",
"each",
"do",
"|",
"file",
"|",
"abs",
"=",
"file_list",
".",
"absolute",
"(",
"file",
")",
"if",
"File",
".",
"directory?",
"(",
"abs",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"File",
".",
"join",
"(",
"dest_path",
",",
"file",
")",
")",
"else",
"FileUtils",
".",
"copy",
"(",
"abs",
",",
"File",
".",
"join",
"(",
"dest_path",
",",
"file",
")",
",",
"preserve",
":",
"true",
")",
"end",
"end",
"end",
"end"
] | Copy fixture data from the spec folder to the temporary directory for this
example.
@param path [String] Path of the fixture to copy.
@param dest [String] Optional destination path. By default the destination
is the same as path.
@example
describe 'myapp' do
command 'myapp run test/'
fixture_file 'test'
its(:exitstatus) { is_expected.to eq 0 }
end | [
"Copy",
"fixture",
"data",
"from",
"the",
"spec",
"folder",
"to",
"the",
"temporary",
"directory",
"for",
"this",
"example",
"."
] | 3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9 | https://github.com/coderanger/rspec-command/blob/3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9/lib/rspec_command.rb#L320-L336 | train |
coderanger/rspec-command | lib/rspec_command.rb | RSpecCommand.ClassMethods.environment | def environment(variables)
before do
variables.each do |key, value|
if value.nil?
_environment.delete(key.to_s)
else
_environment[key.to_s] = value.to_s
end
end
end
end | ruby | def environment(variables)
before do
variables.each do |key, value|
if value.nil?
_environment.delete(key.to_s)
else
_environment[key.to_s] = value.to_s
end
end
end
end | [
"def",
"environment",
"(",
"variables",
")",
"before",
"do",
"variables",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"nil?",
"_environment",
".",
"delete",
"(",
"key",
".",
"to_s",
")",
"else",
"_environment",
"[",
"key",
".",
"to_s",
"]",
"=",
"value",
".",
"to_s",
"end",
"end",
"end",
"end"
] | Set an environment variable for this example.
@param variables [Hash] Key/value pairs to set.
@example
describe 'myapp' do
command 'myapp show'
environment DEBUG: true
its(:stderr) { is_expected.to include('[debug]') }
end | [
"Set",
"an",
"environment",
"variable",
"for",
"this",
"example",
"."
] | 3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9 | https://github.com/coderanger/rspec-command/blob/3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9/lib/rspec_command.rb#L347-L357 | train |
cheezy/data_magic | lib/data_magic/standard_translation.rb | DataMagic.StandardTranslation.randomize | def randomize(value)
case value
when Array then value[rand(value.size)]
when Range then rand((value.last+1) - value.first) + value.first
else value
end
end | ruby | def randomize(value)
case value
when Array then value[rand(value.size)]
when Range then rand((value.last+1) - value.first) + value.first
else value
end
end | [
"def",
"randomize",
"(",
"value",
")",
"case",
"value",
"when",
"Array",
"then",
"value",
"[",
"rand",
"(",
"value",
".",
"size",
")",
"]",
"when",
"Range",
"then",
"rand",
"(",
"(",
"value",
".",
"last",
"+",
"1",
")",
"-",
"value",
".",
"first",
")",
"+",
"value",
".",
"first",
"else",
"value",
"end",
"end"
] | return a random value from an array or range | [
"return",
"a",
"random",
"value",
"from",
"an",
"array",
"or",
"range"
] | ac0dc18b319bf3974f9a79704a7636dbf55059ae | https://github.com/cheezy/data_magic/blob/ac0dc18b319bf3974f9a79704a7636dbf55059ae/lib/data_magic/standard_translation.rb#L236-L242 | train |
cheezy/data_magic | lib/data_magic/standard_translation.rb | DataMagic.StandardTranslation.sequential | def sequential(value)
index = index_variable_for(value)
index = (index ? index + 1 : 0)
index = 0 if index == value.length
set_index_variable(value, index)
value[index]
end | ruby | def sequential(value)
index = index_variable_for(value)
index = (index ? index + 1 : 0)
index = 0 if index == value.length
set_index_variable(value, index)
value[index]
end | [
"def",
"sequential",
"(",
"value",
")",
"index",
"=",
"index_variable_for",
"(",
"value",
")",
"index",
"=",
"(",
"index",
"?",
"index",
"+",
"1",
":",
"0",
")",
"index",
"=",
"0",
"if",
"index",
"==",
"value",
".",
"length",
"set_index_variable",
"(",
"value",
",",
"index",
")",
"value",
"[",
"index",
"]",
"end"
] | return an element from the array. The first request will return
the first element, the second request will return the second,
and so forth. | [
"return",
"an",
"element",
"from",
"the",
"array",
".",
"The",
"first",
"request",
"will",
"return",
"the",
"first",
"element",
"the",
"second",
"request",
"will",
"return",
"the",
"second",
"and",
"so",
"forth",
"."
] | ac0dc18b319bf3974f9a79704a7636dbf55059ae | https://github.com/cheezy/data_magic/blob/ac0dc18b319bf3974f9a79704a7636dbf55059ae/lib/data_magic/standard_translation.rb#L250-L256 | train |
matiasgagliano/action_access | lib/action_access/keeper.rb | ActionAccess.Keeper.let | def let(clearance_level, actions, resource, options = {})
clearance_level = clearance_level.to_s.singularize.to_sym
actions = Array(actions).map(&:to_sym)
controller = get_controller_name(resource, options)
@rules[controller] ||= {}
@rules[controller][clearance_level] ||= []
@rules[controller][clearance_level] += actions
@rules[controller][clearance_level].uniq!
return nil
end | ruby | def let(clearance_level, actions, resource, options = {})
clearance_level = clearance_level.to_s.singularize.to_sym
actions = Array(actions).map(&:to_sym)
controller = get_controller_name(resource, options)
@rules[controller] ||= {}
@rules[controller][clearance_level] ||= []
@rules[controller][clearance_level] += actions
@rules[controller][clearance_level].uniq!
return nil
end | [
"def",
"let",
"(",
"clearance_level",
",",
"actions",
",",
"resource",
",",
"options",
"=",
"{",
"}",
")",
"clearance_level",
"=",
"clearance_level",
".",
"to_s",
".",
"singularize",
".",
"to_sym",
"actions",
"=",
"Array",
"(",
"actions",
")",
".",
"map",
"(",
"&",
":to_sym",
")",
"controller",
"=",
"get_controller_name",
"(",
"resource",
",",
"options",
")",
"@rules",
"[",
"controller",
"]",
"||=",
"{",
"}",
"@rules",
"[",
"controller",
"]",
"[",
"clearance_level",
"]",
"||=",
"[",
"]",
"@rules",
"[",
"controller",
"]",
"[",
"clearance_level",
"]",
"+=",
"actions",
"@rules",
"[",
"controller",
"]",
"[",
"clearance_level",
"]",
".",
"uniq!",
"return",
"nil",
"end"
] | Set clearance to perform actions over a resource.
Clearance level and resource can be either plural or singular.
== Examples:
let :user, :show, :profile
let :user, :show, @profile
let :user, :show, ProfilesController
# Any user can can access 'profiles#show'.
let :admins, [:edit, :update], :articles, namespace: :admin
let :admins, [:edit, :update], @admin_article
let :admins, [:edit, :update], Admin::ArticlesController
# Admins can access 'admin/articles#edit' and 'admin/articles#update'. | [
"Set",
"clearance",
"to",
"perform",
"actions",
"over",
"a",
"resource",
".",
"Clearance",
"level",
"and",
"resource",
"can",
"be",
"either",
"plural",
"or",
"singular",
"."
] | aa1db07489943e2d5f281fd76257884f52de9766 | https://github.com/matiasgagliano/action_access/blob/aa1db07489943e2d5f281fd76257884f52de9766/lib/action_access/keeper.rb#L24-L33 | train |
matiasgagliano/action_access | lib/action_access/keeper.rb | ActionAccess.Keeper.lets? | def lets?(clearance_level, action, resource, options = {})
clearance_level = clearance_level.to_s.singularize.to_sym
action = action.to_sym
controller = get_controller_name(resource, options)
# Load the controller to ensure its rules are loaded (lazy loading rules).
controller.constantize.new
rules = @rules[controller]
return false unless rules
# Check rules
Array(rules[:all]).include?(:all) ||
Array(rules[:all]).include?(action) ||
Array(rules[clearance_level]).include?(:all) ||
Array(rules[clearance_level]).include?(action)
end | ruby | def lets?(clearance_level, action, resource, options = {})
clearance_level = clearance_level.to_s.singularize.to_sym
action = action.to_sym
controller = get_controller_name(resource, options)
# Load the controller to ensure its rules are loaded (lazy loading rules).
controller.constantize.new
rules = @rules[controller]
return false unless rules
# Check rules
Array(rules[:all]).include?(:all) ||
Array(rules[:all]).include?(action) ||
Array(rules[clearance_level]).include?(:all) ||
Array(rules[clearance_level]).include?(action)
end | [
"def",
"lets?",
"(",
"clearance_level",
",",
"action",
",",
"resource",
",",
"options",
"=",
"{",
"}",
")",
"clearance_level",
"=",
"clearance_level",
".",
"to_s",
".",
"singularize",
".",
"to_sym",
"action",
"=",
"action",
".",
"to_sym",
"controller",
"=",
"get_controller_name",
"(",
"resource",
",",
"options",
")",
"controller",
".",
"constantize",
".",
"new",
"rules",
"=",
"@rules",
"[",
"controller",
"]",
"return",
"false",
"unless",
"rules",
"Array",
"(",
"rules",
"[",
":all",
"]",
")",
".",
"include?",
"(",
":all",
")",
"||",
"Array",
"(",
"rules",
"[",
":all",
"]",
")",
".",
"include?",
"(",
"action",
")",
"||",
"Array",
"(",
"rules",
"[",
"clearance_level",
"]",
")",
".",
"include?",
"(",
":all",
")",
"||",
"Array",
"(",
"rules",
"[",
"clearance_level",
"]",
")",
".",
"include?",
"(",
"action",
")",
"end"
] | Check if a given clearance level allows to perform an action on a resource.
Clearance level and resource can be either plural or singular.
== Examples:
lets? :users, :create, :profiles
lets? :users, :create, @profile
lets? :users, :create, ProfilesController
# True if users are allowed to access 'profiles#create'.
lets? :admin, :edit, :article, namespace: :admin
lets? :admin, :edit, @admin_article
lets? :admin, :edit, Admin::ArticlesController
# True if any admin is allowed to access 'admin/articles#edit'. | [
"Check",
"if",
"a",
"given",
"clearance",
"level",
"allows",
"to",
"perform",
"an",
"action",
"on",
"a",
"resource",
".",
"Clearance",
"level",
"and",
"resource",
"can",
"be",
"either",
"plural",
"or",
"singular",
"."
] | aa1db07489943e2d5f281fd76257884f52de9766 | https://github.com/matiasgagliano/action_access/blob/aa1db07489943e2d5f281fd76257884f52de9766/lib/action_access/keeper.rb#L50-L65 | train |
matiasgagliano/action_access | lib/action_access/controller_additions.rb | ActionAccess.ControllerAdditions.validate_access! | def validate_access!
action = self.action_name
clearance_levels = Array(current_clearance_levels)
authorized = clearance_levels.any? { |c| keeper.lets? c, action, self.class }
not_authorized! unless authorized
end | ruby | def validate_access!
action = self.action_name
clearance_levels = Array(current_clearance_levels)
authorized = clearance_levels.any? { |c| keeper.lets? c, action, self.class }
not_authorized! unless authorized
end | [
"def",
"validate_access!",
"action",
"=",
"self",
".",
"action_name",
"clearance_levels",
"=",
"Array",
"(",
"current_clearance_levels",
")",
"authorized",
"=",
"clearance_levels",
".",
"any?",
"{",
"|",
"c",
"|",
"keeper",
".",
"lets?",
"c",
",",
"action",
",",
"self",
".",
"class",
"}",
"not_authorized!",
"unless",
"authorized",
"end"
] | Validate access to the current route. | [
"Validate",
"access",
"to",
"the",
"current",
"route",
"."
] | aa1db07489943e2d5f281fd76257884f52de9766 | https://github.com/matiasgagliano/action_access/blob/aa1db07489943e2d5f281fd76257884f52de9766/lib/action_access/controller_additions.rb#L86-L91 | train |
matiasgagliano/action_access | lib/action_access/controller_additions.rb | ActionAccess.ControllerAdditions.not_authorized! | def not_authorized!(*args)
options = args.extract_options!
message = options[:message] ||
I18n.t('action_access.redirection_message', default: 'Not authorized.')
path = options[:path] || unauthorized_access_redirection_path
redirect_to path, alert: message
end | ruby | def not_authorized!(*args)
options = args.extract_options!
message = options[:message] ||
I18n.t('action_access.redirection_message', default: 'Not authorized.')
path = options[:path] || unauthorized_access_redirection_path
redirect_to path, alert: message
end | [
"def",
"not_authorized!",
"(",
"*",
"args",
")",
"options",
"=",
"args",
".",
"extract_options!",
"message",
"=",
"options",
"[",
":message",
"]",
"||",
"I18n",
".",
"t",
"(",
"'action_access.redirection_message'",
",",
"default",
":",
"'Not authorized.'",
")",
"path",
"=",
"options",
"[",
":path",
"]",
"||",
"unauthorized_access_redirection_path",
"redirect_to",
"path",
",",
"alert",
":",
"message",
"end"
] | Redirect if not authorized.
May be used inside action methods for finer control. | [
"Redirect",
"if",
"not",
"authorized",
".",
"May",
"be",
"used",
"inside",
"action",
"methods",
"for",
"finer",
"control",
"."
] | aa1db07489943e2d5f281fd76257884f52de9766 | https://github.com/matiasgagliano/action_access/blob/aa1db07489943e2d5f281fd76257884f52de9766/lib/action_access/controller_additions.rb#L95-L101 | train |
matiasgagliano/action_access | lib/action_access/user_utilities.rb | ActionAccess.UserUtilities.can? | def can?(action, resource, options = {})
keeper = ActionAccess::Keeper.instance
clearance_levels = Array(clearance_levels())
clearance_levels.any? { |c| keeper.lets? c, action, resource, options }
end | ruby | def can?(action, resource, options = {})
keeper = ActionAccess::Keeper.instance
clearance_levels = Array(clearance_levels())
clearance_levels.any? { |c| keeper.lets? c, action, resource, options }
end | [
"def",
"can?",
"(",
"action",
",",
"resource",
",",
"options",
"=",
"{",
"}",
")",
"keeper",
"=",
"ActionAccess",
"::",
"Keeper",
".",
"instance",
"clearance_levels",
"=",
"Array",
"(",
"clearance_levels",
"(",
")",
")",
"clearance_levels",
".",
"any?",
"{",
"|",
"c",
"|",
"keeper",
".",
"lets?",
"c",
",",
"action",
",",
"resource",
",",
"options",
"}",
"end"
] | Check if the user is authorized to perform a given action.
Resource can be either plural or singular.
== Examples:
user.can? :show, :articles
user.can? :show, @article
user.can? :show, ArticlesController
# True if any of the user's clearance levels allows to access 'articles#show'
user.can? :edit, :articles, namespace: :admin
user.can? :edit, @admin_article
user.can? :edit, Admin::ArticlesController
# True if any of the user's clearance levels allows to access 'admin/articles#edit' | [
"Check",
"if",
"the",
"user",
"is",
"authorized",
"to",
"perform",
"a",
"given",
"action",
".",
"Resource",
"can",
"be",
"either",
"plural",
"or",
"singular",
"."
] | aa1db07489943e2d5f281fd76257884f52de9766 | https://github.com/matiasgagliano/action_access/blob/aa1db07489943e2d5f281fd76257884f52de9766/lib/action_access/user_utilities.rb#L18-L22 | train |
ssut/telegram-rb | lib/telegram/models.rb | Telegram.TelegramBase.send_image | def send_image(path, refer, &callback)
if @type == 'encr_chat'
logger.warn("Currently telegram-cli has a bug with send_typing, then prevent this for safety")
return
end
fail_back(&callback) if not File.exist?(path)
@client.send_photo(targetize, path, &callback)
end | ruby | def send_image(path, refer, &callback)
if @type == 'encr_chat'
logger.warn("Currently telegram-cli has a bug with send_typing, then prevent this for safety")
return
end
fail_back(&callback) if not File.exist?(path)
@client.send_photo(targetize, path, &callback)
end | [
"def",
"send_image",
"(",
"path",
",",
"refer",
",",
"&",
"callback",
")",
"if",
"@type",
"==",
"'encr_chat'",
"logger",
".",
"warn",
"(",
"\"Currently telegram-cli has a bug with send_typing, then prevent this for safety\"",
")",
"return",
"end",
"fail_back",
"(",
"&",
"callback",
")",
"if",
"not",
"File",
".",
"exist?",
"(",
"path",
")",
"@client",
".",
"send_photo",
"(",
"targetize",
",",
"path",
",",
"&",
"callback",
")",
"end"
] | Send an image
@param [String] path The absoulte path of the image you want to send
@param [TelegramMessage] refer referral of the method call
@param [Block] callback Callback block that will be called when finished
@since [0.1.1] | [
"Send",
"an",
"image"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/models.rb#L93-L100 | train |
ssut/telegram-rb | lib/telegram/models.rb | Telegram.TelegramBase.send_image_url | def send_image_url(url, opt, refer, &callback)
begin
opt = {} if opt.nil?
http = EM::HttpRequest.new(url, :connect_timeout => 2, :inactivity_timeout => 5).get opt
file = Tempfile.new(['image', 'jpg'])
http.stream { |chunk|
file.write(chunk)
}
http.callback {
file.close
type = FastImage.type(file.path)
if %i(jpeg png gif).include?(type)
send_image(file.path, refer, &callback)
else
fail_back(&callback)
end
}
rescue Exception => e
logger.error("An error occurred during the image downloading: #{e.inspect} #{e.backtrace}")
fail_back(&callback)
end
end | ruby | def send_image_url(url, opt, refer, &callback)
begin
opt = {} if opt.nil?
http = EM::HttpRequest.new(url, :connect_timeout => 2, :inactivity_timeout => 5).get opt
file = Tempfile.new(['image', 'jpg'])
http.stream { |chunk|
file.write(chunk)
}
http.callback {
file.close
type = FastImage.type(file.path)
if %i(jpeg png gif).include?(type)
send_image(file.path, refer, &callback)
else
fail_back(&callback)
end
}
rescue Exception => e
logger.error("An error occurred during the image downloading: #{e.inspect} #{e.backtrace}")
fail_back(&callback)
end
end | [
"def",
"send_image_url",
"(",
"url",
",",
"opt",
",",
"refer",
",",
"&",
"callback",
")",
"begin",
"opt",
"=",
"{",
"}",
"if",
"opt",
".",
"nil?",
"http",
"=",
"EM",
"::",
"HttpRequest",
".",
"new",
"(",
"url",
",",
":connect_timeout",
"=>",
"2",
",",
":inactivity_timeout",
"=>",
"5",
")",
".",
"get",
"opt",
"file",
"=",
"Tempfile",
".",
"new",
"(",
"[",
"'image'",
",",
"'jpg'",
"]",
")",
"http",
".",
"stream",
"{",
"|",
"chunk",
"|",
"file",
".",
"write",
"(",
"chunk",
")",
"}",
"http",
".",
"callback",
"{",
"file",
".",
"close",
"type",
"=",
"FastImage",
".",
"type",
"(",
"file",
".",
"path",
")",
"if",
"%i(",
"jpeg",
"png",
"gif",
")",
".",
"include?",
"(",
"type",
")",
"send_image",
"(",
"file",
".",
"path",
",",
"refer",
",",
"&",
"callback",
")",
"else",
"fail_back",
"(",
"&",
"callback",
")",
"end",
"}",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"error",
"(",
"\"An error occurred during the image downloading: #{e.inspect} #{e.backtrace}\"",
")",
"fail_back",
"(",
"&",
"callback",
")",
"end",
"end"
] | Send an image with given url, not implemen
@param [String] url The URL of the image you want to send
@param [TelegramMessage] refer referral of the method call
@param [Block] callback Callback block that will be called when finished
@since [0.1.1] | [
"Send",
"an",
"image",
"with",
"given",
"url",
"not",
"implemen"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/models.rb#L108-L129 | train |
ssut/telegram-rb | lib/telegram/models.rb | Telegram.TelegramBase.send_video | def send_video(path, refer, &callback)
fail_back(&callback) if not File.exist?(path)
@client.send_video(targetize, path, &callback)
end | ruby | def send_video(path, refer, &callback)
fail_back(&callback) if not File.exist?(path)
@client.send_video(targetize, path, &callback)
end | [
"def",
"send_video",
"(",
"path",
",",
"refer",
",",
"&",
"callback",
")",
"fail_back",
"(",
"&",
"callback",
")",
"if",
"not",
"File",
".",
"exist?",
"(",
"path",
")",
"@client",
".",
"send_video",
"(",
"targetize",
",",
"path",
",",
"&",
"callback",
")",
"end"
] | Send a video
@param [String] path The absoulte path of the video you want to send
@param [TelegramMessage] refer referral of the method call
@param [Block] callback Callback block that will be called when finished
@since [0.1.1] | [
"Send",
"a",
"video"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/models.rb#L137-L140 | train |
ssut/telegram-rb | lib/telegram/models.rb | Telegram.TelegramMessage.reply | def reply(type, content, target=nil, &callback)
target = @target if target.nil?
case type
when :text
target.send_message(content, self, &callback)
when :image
option = nil
content, option = content if content.class == Array
if content.include?('http')
target.method(:send_image_url).call(content, option, self, &callback)
else
target.method(:send_image).call(content, self, &callback)
end
when :video
target.send_video(content, self, &callback)
end
end | ruby | def reply(type, content, target=nil, &callback)
target = @target if target.nil?
case type
when :text
target.send_message(content, self, &callback)
when :image
option = nil
content, option = content if content.class == Array
if content.include?('http')
target.method(:send_image_url).call(content, option, self, &callback)
else
target.method(:send_image).call(content, self, &callback)
end
when :video
target.send_video(content, self, &callback)
end
end | [
"def",
"reply",
"(",
"type",
",",
"content",
",",
"target",
"=",
"nil",
",",
"&",
"callback",
")",
"target",
"=",
"@target",
"if",
"target",
".",
"nil?",
"case",
"type",
"when",
":text",
"target",
".",
"send_message",
"(",
"content",
",",
"self",
",",
"&",
"callback",
")",
"when",
":image",
"option",
"=",
"nil",
"content",
",",
"option",
"=",
"content",
"if",
"content",
".",
"class",
"==",
"Array",
"if",
"content",
".",
"include?",
"(",
"'http'",
")",
"target",
".",
"method",
"(",
":send_image_url",
")",
".",
"call",
"(",
"content",
",",
"option",
",",
"self",
",",
"&",
"callback",
")",
"else",
"target",
".",
"method",
"(",
":send_image",
")",
".",
"call",
"(",
"content",
",",
"self",
",",
"&",
"callback",
")",
"end",
"when",
":video",
"target",
".",
"send_video",
"(",
"content",
",",
"self",
",",
"&",
"callback",
")",
"end",
"end"
] | Reply a message to the chat
@param [Symbol] type Type of the message (either of :text, :sticker, :image)
@param [String] content Content to send a message
@param [TelegramChat] target Specify a TelegramChat to send
@param [TelegramContact] target Specify a TelegramContact to send
@param [Block] callback Callback block that will be called when finished
@since [0.1.0] | [
"Reply",
"a",
"message",
"to",
"the",
"chat"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/models.rb#L334-L351 | train |
ssut/telegram-rb | lib/telegram/api.rb | Telegram.API.update! | def update!(&cb)
done = false
EM.synchrony do
multi = EM::Synchrony::Multi.new
multi.add :profile, update_profile!
multi.add :contacts, update_contacts!
multi.add :chats, update_chats!
multi.perform
done = true
end
check_done = Proc.new {
if done
@starts_at = Time.now
cb.call unless cb.nil?
logger.info("Successfully loaded all information")
else
EM.next_tick(&check_done)
end
}
EM.add_timer(0, &check_done)
end | ruby | def update!(&cb)
done = false
EM.synchrony do
multi = EM::Synchrony::Multi.new
multi.add :profile, update_profile!
multi.add :contacts, update_contacts!
multi.add :chats, update_chats!
multi.perform
done = true
end
check_done = Proc.new {
if done
@starts_at = Time.now
cb.call unless cb.nil?
logger.info("Successfully loaded all information")
else
EM.next_tick(&check_done)
end
}
EM.add_timer(0, &check_done)
end | [
"def",
"update!",
"(",
"&",
"cb",
")",
"done",
"=",
"false",
"EM",
".",
"synchrony",
"do",
"multi",
"=",
"EM",
"::",
"Synchrony",
"::",
"Multi",
".",
"new",
"multi",
".",
"add",
":profile",
",",
"update_profile!",
"multi",
".",
"add",
":contacts",
",",
"update_contacts!",
"multi",
".",
"add",
":chats",
",",
"update_chats!",
"multi",
".",
"perform",
"done",
"=",
"true",
"end",
"check_done",
"=",
"Proc",
".",
"new",
"{",
"if",
"done",
"@starts_at",
"=",
"Time",
".",
"now",
"cb",
".",
"call",
"unless",
"cb",
".",
"nil?",
"logger",
".",
"info",
"(",
"\"Successfully loaded all information\"",
")",
"else",
"EM",
".",
"next_tick",
"(",
"&",
"check_done",
")",
"end",
"}",
"EM",
".",
"add_timer",
"(",
"0",
",",
"&",
"check_done",
")",
"end"
] | Update user profile, contacts and chats
@api private | [
"Update",
"user",
"profile",
"contacts",
"and",
"chats"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L11-L32 | train |
ssut/telegram-rb | lib/telegram/api.rb | Telegram.API.update_profile! | def update_profile!
assert!
callback = Callback.new
@profile = nil
@connection.communicate('get_self') do |success, data|
if success
callback.trigger(:success)
contact = TelegramContact.pick_or_new(self, data)
@contacts << contact unless self.contacts.include?(contact)
@profile = contact
else
raise "Couldn't fetch the user profile."
end
end
callback
end | ruby | def update_profile!
assert!
callback = Callback.new
@profile = nil
@connection.communicate('get_self') do |success, data|
if success
callback.trigger(:success)
contact = TelegramContact.pick_or_new(self, data)
@contacts << contact unless self.contacts.include?(contact)
@profile = contact
else
raise "Couldn't fetch the user profile."
end
end
callback
end | [
"def",
"update_profile!",
"assert!",
"callback",
"=",
"Callback",
".",
"new",
"@profile",
"=",
"nil",
"@connection",
".",
"communicate",
"(",
"'get_self'",
")",
"do",
"|",
"success",
",",
"data",
"|",
"if",
"success",
"callback",
".",
"trigger",
"(",
":success",
")",
"contact",
"=",
"TelegramContact",
".",
"pick_or_new",
"(",
"self",
",",
"data",
")",
"@contacts",
"<<",
"contact",
"unless",
"self",
".",
"contacts",
".",
"include?",
"(",
"contact",
")",
"@profile",
"=",
"contact",
"else",
"raise",
"\"Couldn't fetch the user profile.\"",
"end",
"end",
"callback",
"end"
] | Update user profile
@api private | [
"Update",
"user",
"profile"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L37-L52 | train |
ssut/telegram-rb | lib/telegram/api.rb | Telegram.API.update_contacts! | def update_contacts!
assert!
callback = Callback.new
@contacts = []
@connection.communicate('contact_list') do |success, data|
if success and data.class == Array
callback.trigger(:success)
data.each { |contact|
contact = TelegramContact.pick_or_new(self, contact)
@contacts << contact unless self.contacts.include?(contact)
}
else
raise "Couldn't fetch the contact list."
end
end
callback
end | ruby | def update_contacts!
assert!
callback = Callback.new
@contacts = []
@connection.communicate('contact_list') do |success, data|
if success and data.class == Array
callback.trigger(:success)
data.each { |contact|
contact = TelegramContact.pick_or_new(self, contact)
@contacts << contact unless self.contacts.include?(contact)
}
else
raise "Couldn't fetch the contact list."
end
end
callback
end | [
"def",
"update_contacts!",
"assert!",
"callback",
"=",
"Callback",
".",
"new",
"@contacts",
"=",
"[",
"]",
"@connection",
".",
"communicate",
"(",
"'contact_list'",
")",
"do",
"|",
"success",
",",
"data",
"|",
"if",
"success",
"and",
"data",
".",
"class",
"==",
"Array",
"callback",
".",
"trigger",
"(",
":success",
")",
"data",
".",
"each",
"{",
"|",
"contact",
"|",
"contact",
"=",
"TelegramContact",
".",
"pick_or_new",
"(",
"self",
",",
"contact",
")",
"@contacts",
"<<",
"contact",
"unless",
"self",
".",
"contacts",
".",
"include?",
"(",
"contact",
")",
"}",
"else",
"raise",
"\"Couldn't fetch the contact list.\"",
"end",
"end",
"callback",
"end"
] | Update user contacts
@api private | [
"Update",
"user",
"contacts"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L57-L73 | train |
ssut/telegram-rb | lib/telegram/api.rb | Telegram.API.update_chats! | def update_chats!
assert!
callback = Callback.new
collected = 0
collect_done = Proc.new do |id, data, count|
collected += 1
@chats << TelegramChat.new(self, data)
callback.trigger(:success) if collected == count
end
collect = Proc.new do |id, count|
@connection.communicate(['chat_info', "chat\##{id}"]) do |success, data|
collect_done.call(id, data, count) if success
end
end
@chats = []
@connection.communicate('dialog_list') do |success, data|
if success and data.class == Array
chatsize = data.count { |chat| chat['peer_type'] == 'chat' }
data.each do |chat|
if chat['peer_type'] == 'chat'
collect.call(chat['peer_id'], chatsize)
elsif chat['peer_type'] == 'user'
@chats << TelegramChat.new(self, chat)
end
end
callback.trigger(:success) if chatsize == 0
else
raise "Couldn't fetch the dialog(chat) list."
end
end
callback
end | ruby | def update_chats!
assert!
callback = Callback.new
collected = 0
collect_done = Proc.new do |id, data, count|
collected += 1
@chats << TelegramChat.new(self, data)
callback.trigger(:success) if collected == count
end
collect = Proc.new do |id, count|
@connection.communicate(['chat_info', "chat\##{id}"]) do |success, data|
collect_done.call(id, data, count) if success
end
end
@chats = []
@connection.communicate('dialog_list') do |success, data|
if success and data.class == Array
chatsize = data.count { |chat| chat['peer_type'] == 'chat' }
data.each do |chat|
if chat['peer_type'] == 'chat'
collect.call(chat['peer_id'], chatsize)
elsif chat['peer_type'] == 'user'
@chats << TelegramChat.new(self, chat)
end
end
callback.trigger(:success) if chatsize == 0
else
raise "Couldn't fetch the dialog(chat) list."
end
end
callback
end | [
"def",
"update_chats!",
"assert!",
"callback",
"=",
"Callback",
".",
"new",
"collected",
"=",
"0",
"collect_done",
"=",
"Proc",
".",
"new",
"do",
"|",
"id",
",",
"data",
",",
"count",
"|",
"collected",
"+=",
"1",
"@chats",
"<<",
"TelegramChat",
".",
"new",
"(",
"self",
",",
"data",
")",
"callback",
".",
"trigger",
"(",
":success",
")",
"if",
"collected",
"==",
"count",
"end",
"collect",
"=",
"Proc",
".",
"new",
"do",
"|",
"id",
",",
"count",
"|",
"@connection",
".",
"communicate",
"(",
"[",
"'chat_info'",
",",
"\"chat\\##{id}\"",
"]",
")",
"do",
"|",
"success",
",",
"data",
"|",
"collect_done",
".",
"call",
"(",
"id",
",",
"data",
",",
"count",
")",
"if",
"success",
"end",
"end",
"@chats",
"=",
"[",
"]",
"@connection",
".",
"communicate",
"(",
"'dialog_list'",
")",
"do",
"|",
"success",
",",
"data",
"|",
"if",
"success",
"and",
"data",
".",
"class",
"==",
"Array",
"chatsize",
"=",
"data",
".",
"count",
"{",
"|",
"chat",
"|",
"chat",
"[",
"'peer_type'",
"]",
"==",
"'chat'",
"}",
"data",
".",
"each",
"do",
"|",
"chat",
"|",
"if",
"chat",
"[",
"'peer_type'",
"]",
"==",
"'chat'",
"collect",
".",
"call",
"(",
"chat",
"[",
"'peer_id'",
"]",
",",
"chatsize",
")",
"elsif",
"chat",
"[",
"'peer_type'",
"]",
"==",
"'user'",
"@chats",
"<<",
"TelegramChat",
".",
"new",
"(",
"self",
",",
"chat",
")",
"end",
"end",
"callback",
".",
"trigger",
"(",
":success",
")",
"if",
"chatsize",
"==",
"0",
"else",
"raise",
"\"Couldn't fetch the dialog(chat) list.\"",
"end",
"end",
"callback",
"end"
] | Update user chats
@api private | [
"Update",
"user",
"chats"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L78-L111 | train |
ssut/telegram-rb | lib/telegram/api.rb | Telegram.API.send_contact | def send_contact(peer, phone, first_name, last_name)
assert!
@connection.communicate(['send_contact', peer, phone, first_name, last_name])
end | ruby | def send_contact(peer, phone, first_name, last_name)
assert!
@connection.communicate(['send_contact', peer, phone, first_name, last_name])
end | [
"def",
"send_contact",
"(",
"peer",
",",
"phone",
",",
"first_name",
",",
"last_name",
")",
"assert!",
"@connection",
".",
"communicate",
"(",
"[",
"'send_contact'",
",",
"peer",
",",
"phone",
",",
"first_name",
",",
"last_name",
"]",
")",
"end"
] | Send contact to peer chat
@param [String] peer Target chat to which contact will be send
@param [String] contact phone number
@param [String] contact first name
@param [String] contact last name
@example
telegram.send_contact('chat#1234567', '9329232332', 'Foo', 'Bar') | [
"Send",
"contact",
"to",
"peer",
"chat"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L202-L205 | train |
ssut/telegram-rb | lib/telegram/api.rb | Telegram.API.download_attachment | def download_attachment(type, seq, &callback)
assert!
raise "Type mismatch" unless %w(photo video audio).include?(type)
@connection.communicate(["load_#{type.to_s}", seq], &callback)
end | ruby | def download_attachment(type, seq, &callback)
assert!
raise "Type mismatch" unless %w(photo video audio).include?(type)
@connection.communicate(["load_#{type.to_s}", seq], &callback)
end | [
"def",
"download_attachment",
"(",
"type",
",",
"seq",
",",
"&",
"callback",
")",
"assert!",
"raise",
"\"Type mismatch\"",
"unless",
"%w(",
"photo",
"video",
"audio",
")",
".",
"include?",
"(",
"type",
")",
"@connection",
".",
"communicate",
"(",
"[",
"\"load_#{type.to_s}\"",
",",
"seq",
"]",
",",
"&",
"callback",
")",
"end"
] | Download an attachment from a message
@param [type] type The type of an attachment (:photo, :video, :audio)
@param [String] seq Message sequence number
@param [Block] callback Callback block that will be called when finished
@yieldparam [Bool] success The result of the request (true or false)
@yieldparam [Hash] data The raw data of the request
@since [0.1.1] | [
"Download",
"an",
"attachment",
"from",
"a",
"message"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L305-L309 | train |
ssut/telegram-rb | lib/telegram/events.rb | Telegram.Event.format_message | def format_message
message = Message.new
message.id = @id
message.text = @raw_data['text'] ||= ''
media = @raw_data['media']
message.type = media ? media['type'] : 'text'
message.raw_from = @raw_data['from']['peer_id']
message.from_type = @raw_data['from']['peer_type']
message.raw_to = @raw_data['to']['peer_id']
message.to_type = @raw_data['to']['peer_type']
from = @client.contacts.find { |c| c.id == message.raw_from }
to = @client.contacts.find { |c| c.id == message.raw_to }
to = @client.chats.find { |c| c.id == message.raw_to } if to.nil?
message.from = from
message.to = to
@message = message
if @message.from.nil?
user = @raw_data['from']
user = TelegramContact.pick_or_new(@client, user)
@client.contacts << user unless @client.contacts.include?(user)
@message.from = user
end
if @message.to.nil?
type = @raw_data['to']['peer_type']
case type
when 'chat', 'encr_chat'
chat = TelegramChat.pick_or_new(@client, @raw_data['to'])
@client.chats << chat unless @client.chats.include?(chat)
if type == 'encr_chat' then
@message.to = chat
else
@message.from = chat
end
when 'user'
user = TelegramContact.pick_or_new(@client, @raw_data['to'])
@client.contacts << user unless @client.contacts.include?(user)
@message.to = user
end
end
end | ruby | def format_message
message = Message.new
message.id = @id
message.text = @raw_data['text'] ||= ''
media = @raw_data['media']
message.type = media ? media['type'] : 'text'
message.raw_from = @raw_data['from']['peer_id']
message.from_type = @raw_data['from']['peer_type']
message.raw_to = @raw_data['to']['peer_id']
message.to_type = @raw_data['to']['peer_type']
from = @client.contacts.find { |c| c.id == message.raw_from }
to = @client.contacts.find { |c| c.id == message.raw_to }
to = @client.chats.find { |c| c.id == message.raw_to } if to.nil?
message.from = from
message.to = to
@message = message
if @message.from.nil?
user = @raw_data['from']
user = TelegramContact.pick_or_new(@client, user)
@client.contacts << user unless @client.contacts.include?(user)
@message.from = user
end
if @message.to.nil?
type = @raw_data['to']['peer_type']
case type
when 'chat', 'encr_chat'
chat = TelegramChat.pick_or_new(@client, @raw_data['to'])
@client.chats << chat unless @client.chats.include?(chat)
if type == 'encr_chat' then
@message.to = chat
else
@message.from = chat
end
when 'user'
user = TelegramContact.pick_or_new(@client, @raw_data['to'])
@client.contacts << user unless @client.contacts.include?(user)
@message.to = user
end
end
end | [
"def",
"format_message",
"message",
"=",
"Message",
".",
"new",
"message",
".",
"id",
"=",
"@id",
"message",
".",
"text",
"=",
"@raw_data",
"[",
"'text'",
"]",
"||=",
"''",
"media",
"=",
"@raw_data",
"[",
"'media'",
"]",
"message",
".",
"type",
"=",
"media",
"?",
"media",
"[",
"'type'",
"]",
":",
"'text'",
"message",
".",
"raw_from",
"=",
"@raw_data",
"[",
"'from'",
"]",
"[",
"'peer_id'",
"]",
"message",
".",
"from_type",
"=",
"@raw_data",
"[",
"'from'",
"]",
"[",
"'peer_type'",
"]",
"message",
".",
"raw_to",
"=",
"@raw_data",
"[",
"'to'",
"]",
"[",
"'peer_id'",
"]",
"message",
".",
"to_type",
"=",
"@raw_data",
"[",
"'to'",
"]",
"[",
"'peer_type'",
"]",
"from",
"=",
"@client",
".",
"contacts",
".",
"find",
"{",
"|",
"c",
"|",
"c",
".",
"id",
"==",
"message",
".",
"raw_from",
"}",
"to",
"=",
"@client",
".",
"contacts",
".",
"find",
"{",
"|",
"c",
"|",
"c",
".",
"id",
"==",
"message",
".",
"raw_to",
"}",
"to",
"=",
"@client",
".",
"chats",
".",
"find",
"{",
"|",
"c",
"|",
"c",
".",
"id",
"==",
"message",
".",
"raw_to",
"}",
"if",
"to",
".",
"nil?",
"message",
".",
"from",
"=",
"from",
"message",
".",
"to",
"=",
"to",
"@message",
"=",
"message",
"if",
"@message",
".",
"from",
".",
"nil?",
"user",
"=",
"@raw_data",
"[",
"'from'",
"]",
"user",
"=",
"TelegramContact",
".",
"pick_or_new",
"(",
"@client",
",",
"user",
")",
"@client",
".",
"contacts",
"<<",
"user",
"unless",
"@client",
".",
"contacts",
".",
"include?",
"(",
"user",
")",
"@message",
".",
"from",
"=",
"user",
"end",
"if",
"@message",
".",
"to",
".",
"nil?",
"type",
"=",
"@raw_data",
"[",
"'to'",
"]",
"[",
"'peer_type'",
"]",
"case",
"type",
"when",
"'chat'",
",",
"'encr_chat'",
"chat",
"=",
"TelegramChat",
".",
"pick_or_new",
"(",
"@client",
",",
"@raw_data",
"[",
"'to'",
"]",
")",
"@client",
".",
"chats",
"<<",
"chat",
"unless",
"@client",
".",
"chats",
".",
"include?",
"(",
"chat",
")",
"if",
"type",
"==",
"'encr_chat'",
"then",
"@message",
".",
"to",
"=",
"chat",
"else",
"@message",
".",
"from",
"=",
"chat",
"end",
"when",
"'user'",
"user",
"=",
"TelegramContact",
".",
"pick_or_new",
"(",
"@client",
",",
"@raw_data",
"[",
"'to'",
"]",
")",
"@client",
".",
"contacts",
"<<",
"user",
"unless",
"@client",
".",
"contacts",
".",
"include?",
"(",
"user",
")",
"@message",
".",
"to",
"=",
"user",
"end",
"end",
"end"
] | Process raw data in which event type is message given.
@return [void]
@api private | [
"Process",
"raw",
"data",
"in",
"which",
"event",
"type",
"is",
"message",
"given",
"."
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/events.rb#L161-L206 | train |
ssut/telegram-rb | lib/telegram/connection.rb | Telegram.Connection.communicate | def communicate(*messages, &callback)
@available = false
@data = ''
@callback = callback
messages = messages.first if messages.size == 1 and messages.first.is_a?(Array)
messages = messages.join(' ') << "\n"
send_data(messages)
end | ruby | def communicate(*messages, &callback)
@available = false
@data = ''
@callback = callback
messages = messages.first if messages.size == 1 and messages.first.is_a?(Array)
messages = messages.join(' ') << "\n"
send_data(messages)
end | [
"def",
"communicate",
"(",
"*",
"messages",
",",
"&",
"callback",
")",
"@available",
"=",
"false",
"@data",
"=",
"''",
"@callback",
"=",
"callback",
"messages",
"=",
"messages",
".",
"first",
"if",
"messages",
".",
"size",
"==",
"1",
"and",
"messages",
".",
"first",
".",
"is_a?",
"(",
"Array",
")",
"messages",
"=",
"messages",
".",
"join",
"(",
"' '",
")",
"<<",
"\"\\n\"",
"send_data",
"(",
"messages",
")",
"end"
] | Communicate telegram-rb with telegram-cli connection
@param [Array<String>] messages Messages that will be sent
@yieldparam [Block] callback Callback block that will be called when finished | [
"Communicate",
"telegram",
"-",
"rb",
"with",
"telegram",
"-",
"cli",
"connection"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/connection.rb#L31-L38 | train |
ssut/telegram-rb | lib/telegram/connection.rb | Telegram.Connection.receive_data | def receive_data(data)
@data << data
return unless data.index("\n\n")
begin
result = _receive_data(@data)
rescue
raise
result = nil
end
@callback.call(!result.nil?, result) unless @callback.nil?
@callback = nil
@available = true
end | ruby | def receive_data(data)
@data << data
return unless data.index("\n\n")
begin
result = _receive_data(@data)
rescue
raise
result = nil
end
@callback.call(!result.nil?, result) unless @callback.nil?
@callback = nil
@available = true
end | [
"def",
"receive_data",
"(",
"data",
")",
"@data",
"<<",
"data",
"return",
"unless",
"data",
".",
"index",
"(",
"\"\\n\\n\"",
")",
"begin",
"result",
"=",
"_receive_data",
"(",
"@data",
")",
"rescue",
"raise",
"result",
"=",
"nil",
"end",
"@callback",
".",
"call",
"(",
"!",
"result",
".",
"nil?",
",",
"result",
")",
"unless",
"@callback",
".",
"nil?",
"@callback",
"=",
"nil",
"@available",
"=",
"true",
"end"
] | This method will be called by EventMachine when data arrived
then parse given data and execute callback method if exists
@api private | [
"This",
"method",
"will",
"be",
"called",
"by",
"EventMachine",
"when",
"data",
"arrived",
"then",
"parse",
"given",
"data",
"and",
"execute",
"callback",
"method",
"if",
"exists"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/connection.rb#L80-L93 | train |
ssut/telegram-rb | lib/telegram/connection_pool.rb | Telegram.ConnectionPool.acquire | def acquire(&callback)
acq = Proc.new {
conn = self.find { |conn| conn.available? }
if not conn.nil? and conn.connected?
callback.call(conn)
else
logger.warn("Failed to acquire available connection, retry after 0.1 second")
EM.add_timer(0.1, &acq)
end
}
EM.add_timer(0, &acq)
end | ruby | def acquire(&callback)
acq = Proc.new {
conn = self.find { |conn| conn.available? }
if not conn.nil? and conn.connected?
callback.call(conn)
else
logger.warn("Failed to acquire available connection, retry after 0.1 second")
EM.add_timer(0.1, &acq)
end
}
EM.add_timer(0, &acq)
end | [
"def",
"acquire",
"(",
"&",
"callback",
")",
"acq",
"=",
"Proc",
".",
"new",
"{",
"conn",
"=",
"self",
".",
"find",
"{",
"|",
"conn",
"|",
"conn",
".",
"available?",
"}",
"if",
"not",
"conn",
".",
"nil?",
"and",
"conn",
".",
"connected?",
"callback",
".",
"call",
"(",
"conn",
")",
"else",
"logger",
".",
"warn",
"(",
"\"Failed to acquire available connection, retry after 0.1 second\"",
")",
"EM",
".",
"add_timer",
"(",
"0.1",
",",
"&",
"acq",
")",
"end",
"}",
"EM",
".",
"add_timer",
"(",
"0",
",",
"&",
"acq",
")",
"end"
] | Acquire available connection
@see Connection
@param [Block] callback This block will be called when successfully acquired a connection
@yieldparam [Connection] connection acquired connection | [
"Acquire",
"available",
"connection"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/connection_pool.rb#L43-L54 | train |
ssut/telegram-rb | lib/telegram/client.rb | Telegram.Client.execute | def execute
cli_arguments = Telegram::CLIArguments.new(@config)
command = "'#{@config.daemon}' #{cli_arguments.to_s}"
@stdout = IO.popen(command, 'a+')
initialize_stdout_reading
end | ruby | def execute
cli_arguments = Telegram::CLIArguments.new(@config)
command = "'#{@config.daemon}' #{cli_arguments.to_s}"
@stdout = IO.popen(command, 'a+')
initialize_stdout_reading
end | [
"def",
"execute",
"cli_arguments",
"=",
"Telegram",
"::",
"CLIArguments",
".",
"new",
"(",
"@config",
")",
"command",
"=",
"\"'#{@config.daemon}' #{cli_arguments.to_s}\"",
"@stdout",
"=",
"IO",
".",
"popen",
"(",
"command",
",",
"'a+'",
")",
"initialize_stdout_reading",
"end"
] | Initialize Telegram Client
@yieldparam [Block] block
@yield [config] Given configuration struct to the block
Execute telegram-cli daemon and wait for the response
@api private | [
"Initialize",
"Telegram",
"Client"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/client.rb#L82-L87 | train |
ssut/telegram-rb | lib/telegram/client.rb | Telegram.Client.poll | def poll
logger.info("Start polling for events")
while (data = @stdout.gets)
begin
brace = data.index('{')
data = data[brace..-2]
data = Oj.load(data, mode: :compat)
@events << data
rescue
end
end
end | ruby | def poll
logger.info("Start polling for events")
while (data = @stdout.gets)
begin
brace = data.index('{')
data = data[brace..-2]
data = Oj.load(data, mode: :compat)
@events << data
rescue
end
end
end | [
"def",
"poll",
"logger",
".",
"info",
"(",
"\"Start polling for events\"",
")",
"while",
"(",
"data",
"=",
"@stdout",
".",
"gets",
")",
"begin",
"brace",
"=",
"data",
".",
"index",
"(",
"'{'",
")",
"data",
"=",
"data",
"[",
"brace",
"..",
"-",
"2",
"]",
"data",
"=",
"Oj",
".",
"load",
"(",
"data",
",",
"mode",
":",
":compat",
")",
"@events",
"<<",
"data",
"rescue",
"end",
"end",
"end"
] | Do the long-polling from stdout of the telegram-cli
@api private | [
"Do",
"the",
"long",
"-",
"polling",
"from",
"stdout",
"of",
"the",
"telegram",
"-",
"cli"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/client.rb#L92-L103 | train |
ssut/telegram-rb | lib/telegram/client.rb | Telegram.Client.connect | def connect(&block)
logger.info("Trying to start telegram-cli and then connect")
@connect_callback = block
process_data
EM.defer(method(:execute), method(:create_pool), method(:execution_failed))
end | ruby | def connect(&block)
logger.info("Trying to start telegram-cli and then connect")
@connect_callback = block
process_data
EM.defer(method(:execute), method(:create_pool), method(:execution_failed))
end | [
"def",
"connect",
"(",
"&",
"block",
")",
"logger",
".",
"info",
"(",
"\"Trying to start telegram-cli and then connect\"",
")",
"@connect_callback",
"=",
"block",
"process_data",
"EM",
".",
"defer",
"(",
"method",
"(",
":execute",
")",
",",
"method",
"(",
":create_pool",
")",
",",
"method",
"(",
":execution_failed",
")",
")",
"end"
] | Start telegram-cli daemon
@yield This block will be executed when all connections have responded | [
"Start",
"telegram",
"-",
"cli",
"daemon"
] | 2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2 | https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/client.rb#L144-L149 | train |
bpot/poseidon | lib/poseidon/message_set.rb | Poseidon.MessageSet.flatten | def flatten
messages = struct.messages.map do |message|
if message.compressed?
s = message.decompressed_value
MessageSet.read_without_size(Protocol::ResponseBuffer.new(s)).flatten
else
message
end
end.flatten
end | ruby | def flatten
messages = struct.messages.map do |message|
if message.compressed?
s = message.decompressed_value
MessageSet.read_without_size(Protocol::ResponseBuffer.new(s)).flatten
else
message
end
end.flatten
end | [
"def",
"flatten",
"messages",
"=",
"struct",
".",
"messages",
".",
"map",
"do",
"|",
"message",
"|",
"if",
"message",
".",
"compressed?",
"s",
"=",
"message",
".",
"decompressed_value",
"MessageSet",
".",
"read_without_size",
"(",
"Protocol",
"::",
"ResponseBuffer",
".",
"new",
"(",
"s",
")",
")",
".",
"flatten",
"else",
"message",
"end",
"end",
".",
"flatten",
"end"
] | Builds an array of Message objects from the MessageStruct objects.
Decompressing messages if necessary.
@return [Array<Message>] | [
"Builds",
"an",
"array",
"of",
"Message",
"objects",
"from",
"the",
"MessageStruct",
"objects",
".",
"Decompressing",
"messages",
"if",
"necessary",
"."
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/message_set.rb#L59-L68 | train |
bpot/poseidon | lib/poseidon/messages_for_broker.rb | Poseidon.MessagesForBroker.add | def add(message, partition_id)
@messages << message
@topics[message.topic] ||= {}
@topics[message.topic][partition_id] ||= []
@topics[message.topic][partition_id] << message
end | ruby | def add(message, partition_id)
@messages << message
@topics[message.topic] ||= {}
@topics[message.topic][partition_id] ||= []
@topics[message.topic][partition_id] << message
end | [
"def",
"add",
"(",
"message",
",",
"partition_id",
")",
"@messages",
"<<",
"message",
"@topics",
"[",
"message",
".",
"topic",
"]",
"||=",
"{",
"}",
"@topics",
"[",
"message",
".",
"topic",
"]",
"[",
"partition_id",
"]",
"||=",
"[",
"]",
"@topics",
"[",
"message",
".",
"topic",
"]",
"[",
"partition_id",
"]",
"<<",
"message",
"end"
] | Add a messages for this broker | [
"Add",
"a",
"messages",
"for",
"this",
"broker"
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/messages_for_broker.rb#L14-L20 | train |
bpot/poseidon | lib/poseidon/messages_for_broker.rb | Poseidon.MessagesForBroker.build_protocol_objects | def build_protocol_objects(compression_config)
@topics.map do |topic, messages_by_partition|
codec = compression_config.compression_codec_for_topic(topic)
messages_for_partitions = messages_by_partition.map do |partition, messages|
message_set = MessageSet.new(messages)
if codec
Protocol::MessagesForPartition.new(partition, message_set.compress(codec))
else
Protocol::MessagesForPartition.new(partition, message_set)
end
end
Protocol::MessagesForTopic.new(topic, messages_for_partitions)
end
end | ruby | def build_protocol_objects(compression_config)
@topics.map do |topic, messages_by_partition|
codec = compression_config.compression_codec_for_topic(topic)
messages_for_partitions = messages_by_partition.map do |partition, messages|
message_set = MessageSet.new(messages)
if codec
Protocol::MessagesForPartition.new(partition, message_set.compress(codec))
else
Protocol::MessagesForPartition.new(partition, message_set)
end
end
Protocol::MessagesForTopic.new(topic, messages_for_partitions)
end
end | [
"def",
"build_protocol_objects",
"(",
"compression_config",
")",
"@topics",
".",
"map",
"do",
"|",
"topic",
",",
"messages_by_partition",
"|",
"codec",
"=",
"compression_config",
".",
"compression_codec_for_topic",
"(",
"topic",
")",
"messages_for_partitions",
"=",
"messages_by_partition",
".",
"map",
"do",
"|",
"partition",
",",
"messages",
"|",
"message_set",
"=",
"MessageSet",
".",
"new",
"(",
"messages",
")",
"if",
"codec",
"Protocol",
"::",
"MessagesForPartition",
".",
"new",
"(",
"partition",
",",
"message_set",
".",
"compress",
"(",
"codec",
")",
")",
"else",
"Protocol",
"::",
"MessagesForPartition",
".",
"new",
"(",
"partition",
",",
"message_set",
")",
"end",
"end",
"Protocol",
"::",
"MessagesForTopic",
".",
"new",
"(",
"topic",
",",
"messages_for_partitions",
")",
"end",
"end"
] | Build protocol objects for this broker! | [
"Build",
"protocol",
"objects",
"for",
"this",
"broker!"
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/messages_for_broker.rb#L23-L37 | train |
bpot/poseidon | lib/poseidon/messages_to_send_batch.rb | Poseidon.MessagesToSendBatch.messages_for_brokers | def messages_for_brokers
messages_for_broker_ids = {}
@messages.each do |message|
partition_id, broker_id = @message_conductor.destination(message.topic,
message.key)
# Create a nested hash to group messages by broker_id, topic, partition.
messages_for_broker_ids[broker_id] ||= MessagesForBroker.new(broker_id)
messages_for_broker_ids[broker_id].add(message, partition_id)
end
messages_for_broker_ids.values
end | ruby | def messages_for_brokers
messages_for_broker_ids = {}
@messages.each do |message|
partition_id, broker_id = @message_conductor.destination(message.topic,
message.key)
# Create a nested hash to group messages by broker_id, topic, partition.
messages_for_broker_ids[broker_id] ||= MessagesForBroker.new(broker_id)
messages_for_broker_ids[broker_id].add(message, partition_id)
end
messages_for_broker_ids.values
end | [
"def",
"messages_for_brokers",
"messages_for_broker_ids",
"=",
"{",
"}",
"@messages",
".",
"each",
"do",
"|",
"message",
"|",
"partition_id",
",",
"broker_id",
"=",
"@message_conductor",
".",
"destination",
"(",
"message",
".",
"topic",
",",
"message",
".",
"key",
")",
"messages_for_broker_ids",
"[",
"broker_id",
"]",
"||=",
"MessagesForBroker",
".",
"new",
"(",
"broker_id",
")",
"messages_for_broker_ids",
"[",
"broker_id",
"]",
".",
"add",
"(",
"message",
",",
"partition_id",
")",
"end",
"messages_for_broker_ids",
".",
"values",
"end"
] | Groups messages by broker and preps them for transmission.
@return [Array<MessagesForBroker>] | [
"Groups",
"messages",
"by",
"broker",
"and",
"preps",
"them",
"for",
"transmission",
"."
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/messages_to_send_batch.rb#L13-L25 | train |
bpot/poseidon | lib/poseidon/connection.rb | Poseidon.Connection.produce | def produce(required_acks, timeout, messages_for_topics)
ensure_connected
req = ProduceRequest.new( request_common(:produce),
required_acks,
timeout,
messages_for_topics)
send_request(req)
if required_acks != 0
read_response(ProduceResponse)
else
true
end
end | ruby | def produce(required_acks, timeout, messages_for_topics)
ensure_connected
req = ProduceRequest.new( request_common(:produce),
required_acks,
timeout,
messages_for_topics)
send_request(req)
if required_acks != 0
read_response(ProduceResponse)
else
true
end
end | [
"def",
"produce",
"(",
"required_acks",
",",
"timeout",
",",
"messages_for_topics",
")",
"ensure_connected",
"req",
"=",
"ProduceRequest",
".",
"new",
"(",
"request_common",
"(",
":produce",
")",
",",
"required_acks",
",",
"timeout",
",",
"messages_for_topics",
")",
"send_request",
"(",
"req",
")",
"if",
"required_acks",
"!=",
"0",
"read_response",
"(",
"ProduceResponse",
")",
"else",
"true",
"end",
"end"
] | Execute a produce call
@param [Integer] required_acks
@param [Integer] timeout
@param [Array<Protocol::MessagesForTopics>] messages_for_topics Messages to send
@return [ProduceResponse] | [
"Execute",
"a",
"produce",
"call"
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/connection.rb#L49-L61 | train |
bpot/poseidon | lib/poseidon/connection.rb | Poseidon.Connection.fetch | def fetch(max_wait_time, min_bytes, topic_fetches)
ensure_connected
req = FetchRequest.new( request_common(:fetch),
REPLICA_ID,
max_wait_time,
min_bytes,
topic_fetches)
send_request(req)
read_response(FetchResponse)
end | ruby | def fetch(max_wait_time, min_bytes, topic_fetches)
ensure_connected
req = FetchRequest.new( request_common(:fetch),
REPLICA_ID,
max_wait_time,
min_bytes,
topic_fetches)
send_request(req)
read_response(FetchResponse)
end | [
"def",
"fetch",
"(",
"max_wait_time",
",",
"min_bytes",
",",
"topic_fetches",
")",
"ensure_connected",
"req",
"=",
"FetchRequest",
".",
"new",
"(",
"request_common",
"(",
":fetch",
")",
",",
"REPLICA_ID",
",",
"max_wait_time",
",",
"min_bytes",
",",
"topic_fetches",
")",
"send_request",
"(",
"req",
")",
"read_response",
"(",
"FetchResponse",
")",
"end"
] | Execute a fetch call
@param [Integer] max_wait_time
@param [Integer] min_bytes
@param [Integer] topic_fetches | [
"Execute",
"a",
"fetch",
"call"
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/connection.rb#L68-L77 | train |
bpot/poseidon | lib/poseidon/connection.rb | Poseidon.Connection.topic_metadata | def topic_metadata(topic_names)
ensure_connected
req = MetadataRequest.new( request_common(:metadata),
topic_names)
send_request(req)
read_response(MetadataResponse)
end | ruby | def topic_metadata(topic_names)
ensure_connected
req = MetadataRequest.new( request_common(:metadata),
topic_names)
send_request(req)
read_response(MetadataResponse)
end | [
"def",
"topic_metadata",
"(",
"topic_names",
")",
"ensure_connected",
"req",
"=",
"MetadataRequest",
".",
"new",
"(",
"request_common",
"(",
":metadata",
")",
",",
"topic_names",
")",
"send_request",
"(",
"req",
")",
"read_response",
"(",
"MetadataResponse",
")",
"end"
] | Fetch metadata for +topic_names+
@param [Enumberable<String>] topic_names
A list of topics to retrive metadata for
@return [TopicMetadataResponse] metadata for the topics | [
"Fetch",
"metadata",
"for",
"+",
"topic_names",
"+"
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/connection.rb#L93-L99 | train |
bpot/poseidon | lib/poseidon/cluster_metadata.rb | Poseidon.ClusterMetadata.update | def update(topic_metadata_response)
update_brokers(topic_metadata_response.brokers)
update_topics(topic_metadata_response.topics)
@last_refreshed_at = Time.now
nil
end | ruby | def update(topic_metadata_response)
update_brokers(topic_metadata_response.brokers)
update_topics(topic_metadata_response.topics)
@last_refreshed_at = Time.now
nil
end | [
"def",
"update",
"(",
"topic_metadata_response",
")",
"update_brokers",
"(",
"topic_metadata_response",
".",
"brokers",
")",
"update_topics",
"(",
"topic_metadata_response",
".",
"topics",
")",
"@last_refreshed_at",
"=",
"Time",
".",
"now",
"nil",
"end"
] | Update what we know about the cluter based on MetadataResponse
@param [MetadataResponse] topic_metadata_response
@return nil | [
"Update",
"what",
"we",
"know",
"about",
"the",
"cluter",
"based",
"on",
"MetadataResponse"
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/cluster_metadata.rb#L18-L24 | train |
bpot/poseidon | lib/poseidon/message_conductor.rb | Poseidon.MessageConductor.destination | def destination(topic, key = nil)
topic_metadata = topic_metadatas[topic]
if topic_metadata && topic_metadata.leader_available?
partition_id = determine_partition(topic_metadata, key)
broker_id = topic_metadata.partition_leader(partition_id) || NO_BROKER
else
partition_id = NO_PARTITION
broker_id = NO_BROKER
end
return partition_id, broker_id
end | ruby | def destination(topic, key = nil)
topic_metadata = topic_metadatas[topic]
if topic_metadata && topic_metadata.leader_available?
partition_id = determine_partition(topic_metadata, key)
broker_id = topic_metadata.partition_leader(partition_id) || NO_BROKER
else
partition_id = NO_PARTITION
broker_id = NO_BROKER
end
return partition_id, broker_id
end | [
"def",
"destination",
"(",
"topic",
",",
"key",
"=",
"nil",
")",
"topic_metadata",
"=",
"topic_metadatas",
"[",
"topic",
"]",
"if",
"topic_metadata",
"&&",
"topic_metadata",
".",
"leader_available?",
"partition_id",
"=",
"determine_partition",
"(",
"topic_metadata",
",",
"key",
")",
"broker_id",
"=",
"topic_metadata",
".",
"partition_leader",
"(",
"partition_id",
")",
"||",
"NO_BROKER",
"else",
"partition_id",
"=",
"NO_PARTITION",
"broker_id",
"=",
"NO_BROKER",
"end",
"return",
"partition_id",
",",
"broker_id",
"end"
] | Create a new message conductor
@param [Hash<String,TopicMetadata>] topics_metadata
Metadata for all topics this conductor may receive.
@param [Object] partitioner
Custom partitioner
Determines which partition a message should be sent to.
@param [String] topic
Topic we are sending this message to
@param [Object] key
Key for this message, may be nil
@return [Integer,Integer]
partition_id and broker_id to which this message should be sent | [
"Create",
"a",
"new",
"message",
"conductor"
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/message_conductor.rb#L30-L41 | train |
bpot/poseidon | lib/poseidon/partition_consumer.rb | Poseidon.PartitionConsumer.fetch | def fetch(options = {})
fetch_max_wait = options.delete(:max_wait_ms) || max_wait_ms
fetch_max_bytes = options.delete(:max_bytes) || max_bytes
fetch_min_bytes = options.delete(:min_bytes) || min_bytes
if options.keys.any?
raise ArgumentError, "Unknown options: #{options.keys.inspect}"
end
topic_fetches = build_topic_fetch_request(fetch_max_bytes)
fetch_response = @connection.fetch(fetch_max_wait, fetch_min_bytes, topic_fetches)
topic_response = fetch_response.topic_fetch_responses.first
partition_response = topic_response.partition_fetch_responses.first
unless partition_response.error == Errors::NO_ERROR_CODE
if @offset < 0 &&
Errors::ERROR_CODES[partition_response.error] == Errors::OffsetOutOfRange
@offset = :earliest_offset
return fetch(options)
end
raise Errors::ERROR_CODES[partition_response.error]
else
@highwater_mark = partition_response.highwater_mark_offset
messages = partition_response.message_set.flatten.map do |m|
FetchedMessage.new(topic_response.topic, m.value, m.key, m.offset)
end
if messages.any?
@offset = messages.last.offset + 1
end
messages
end
end | ruby | def fetch(options = {})
fetch_max_wait = options.delete(:max_wait_ms) || max_wait_ms
fetch_max_bytes = options.delete(:max_bytes) || max_bytes
fetch_min_bytes = options.delete(:min_bytes) || min_bytes
if options.keys.any?
raise ArgumentError, "Unknown options: #{options.keys.inspect}"
end
topic_fetches = build_topic_fetch_request(fetch_max_bytes)
fetch_response = @connection.fetch(fetch_max_wait, fetch_min_bytes, topic_fetches)
topic_response = fetch_response.topic_fetch_responses.first
partition_response = topic_response.partition_fetch_responses.first
unless partition_response.error == Errors::NO_ERROR_CODE
if @offset < 0 &&
Errors::ERROR_CODES[partition_response.error] == Errors::OffsetOutOfRange
@offset = :earliest_offset
return fetch(options)
end
raise Errors::ERROR_CODES[partition_response.error]
else
@highwater_mark = partition_response.highwater_mark_offset
messages = partition_response.message_set.flatten.map do |m|
FetchedMessage.new(topic_response.topic, m.value, m.key, m.offset)
end
if messages.any?
@offset = messages.last.offset + 1
end
messages
end
end | [
"def",
"fetch",
"(",
"options",
"=",
"{",
"}",
")",
"fetch_max_wait",
"=",
"options",
".",
"delete",
"(",
":max_wait_ms",
")",
"||",
"max_wait_ms",
"fetch_max_bytes",
"=",
"options",
".",
"delete",
"(",
":max_bytes",
")",
"||",
"max_bytes",
"fetch_min_bytes",
"=",
"options",
".",
"delete",
"(",
":min_bytes",
")",
"||",
"min_bytes",
"if",
"options",
".",
"keys",
".",
"any?",
"raise",
"ArgumentError",
",",
"\"Unknown options: #{options.keys.inspect}\"",
"end",
"topic_fetches",
"=",
"build_topic_fetch_request",
"(",
"fetch_max_bytes",
")",
"fetch_response",
"=",
"@connection",
".",
"fetch",
"(",
"fetch_max_wait",
",",
"fetch_min_bytes",
",",
"topic_fetches",
")",
"topic_response",
"=",
"fetch_response",
".",
"topic_fetch_responses",
".",
"first",
"partition_response",
"=",
"topic_response",
".",
"partition_fetch_responses",
".",
"first",
"unless",
"partition_response",
".",
"error",
"==",
"Errors",
"::",
"NO_ERROR_CODE",
"if",
"@offset",
"<",
"0",
"&&",
"Errors",
"::",
"ERROR_CODES",
"[",
"partition_response",
".",
"error",
"]",
"==",
"Errors",
"::",
"OffsetOutOfRange",
"@offset",
"=",
":earliest_offset",
"return",
"fetch",
"(",
"options",
")",
"end",
"raise",
"Errors",
"::",
"ERROR_CODES",
"[",
"partition_response",
".",
"error",
"]",
"else",
"@highwater_mark",
"=",
"partition_response",
".",
"highwater_mark_offset",
"messages",
"=",
"partition_response",
".",
"message_set",
".",
"flatten",
".",
"map",
"do",
"|",
"m",
"|",
"FetchedMessage",
".",
"new",
"(",
"topic_response",
".",
"topic",
",",
"m",
".",
"value",
",",
"m",
".",
"key",
",",
"m",
".",
"offset",
")",
"end",
"if",
"messages",
".",
"any?",
"@offset",
"=",
"messages",
".",
"last",
".",
"offset",
"+",
"1",
"end",
"messages",
"end",
"end"
] | Create a new consumer which reads the specified topic and partition from
the host.
@param [String] client_id Used to identify this client should be unique.
@param [String] host
@param [Integer] port
@param [String] topic Topic to read from
@param [Integer] partition Partitions are zero indexed.
@param [Integer,Symbol] offset
Offset to start reading from. A negative offset can also be passed.
There are a couple special offsets which can be passed as symbols:
:earliest_offset Start reading from the first offset the server has.
:latest_offset Start reading from the latest offset the server has.
@param [Hash] options
Theses options can all be overridden in each individual fetch command.
@option options [Integer] :max_bytes
Maximum number of bytes to fetch
Default: 1048576 (1MB)
@option options [Integer] :max_wait_ms
How long to block until the server sends us data.
NOTE: This is only enforced if min_bytes is > 0.
Default: 100 (100ms)
@option options [Integer] :min_bytes
Smallest amount of data the server should send us.
Default: 1 (Send us data as soon as it is ready)
@option options [Integer] :socket_timeout_ms
How long to wait for reply from server. Should be higher than max_wait_ms.
Default: 10000 (10s)
@api public
Fetch messages from the broker.
@param [Hash] options
@option options [Integer] :max_bytes
Maximum number of bytes to fetch
@option options [Integer] :max_wait_ms
How long to block until the server sends us data.
@option options [Integer] :min_bytes
Smallest amount of data the server should send us.
@api public | [
"Create",
"a",
"new",
"consumer",
"which",
"reads",
"the",
"specified",
"topic",
"and",
"partition",
"from",
"the",
"host",
"."
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/partition_consumer.rb#L100-L132 | train |
bpot/poseidon | lib/poseidon/producer.rb | Poseidon.Producer.send_messages | def send_messages(messages)
raise Errors::ProducerShutdownError if @shutdown
if !messages.respond_to?(:each)
raise ArgumentError, "messages must respond to #each"
end
@producer.send_messages(convert_to_messages_objects(messages))
end | ruby | def send_messages(messages)
raise Errors::ProducerShutdownError if @shutdown
if !messages.respond_to?(:each)
raise ArgumentError, "messages must respond to #each"
end
@producer.send_messages(convert_to_messages_objects(messages))
end | [
"def",
"send_messages",
"(",
"messages",
")",
"raise",
"Errors",
"::",
"ProducerShutdownError",
"if",
"@shutdown",
"if",
"!",
"messages",
".",
"respond_to?",
"(",
":each",
")",
"raise",
"ArgumentError",
",",
"\"messages must respond to #each\"",
"end",
"@producer",
".",
"send_messages",
"(",
"convert_to_messages_objects",
"(",
"messages",
")",
")",
"end"
] | Returns a new Producer.
@param [Array<String>] brokers An array of brokers in the form "host1:port1"
@param [String] client_id A client_id used to indentify the producer.
@param [Hash] options
@option options [:sync / :async] :type (:sync)
Whether we should send messages right away or queue them and send
them in the background.
@option options [:gzip / :snappy / :none] :compression_codec (:none)
Type of compression to use.
@option options [Enumberable<String>] :compressed_topics (nil)
Topics to compress. If this is not specified we will compress all
topics provided that +:compression_codec+ is set.
@option options [Integer: Milliseconds] :metadata_refresh_interval_ms (600_000)
How frequently we should update the topic metadata in milliseconds.
@option options [#call, nil] :partitioner
Object which partitions messages based on key.
Responds to #call(key, partition_count).
@option options [Integer] :max_send_retries (3)
Number of times to retry sending of messages to a leader.
@option options [Integer] :retry_backoff_ms (100)
The amount of time (in milliseconds) to wait before refreshing the metadata
after we are unable to send messages.
Number of times to retry sending of messages to a leader.
@option options [Integer] :required_acks (0)
The number of acks required per request.
@option options [Integer] :ack_timeout_ms (1500)
How long the producer waits for acks.
@option options [Integer] :socket_timeout_ms] (10000)
How long the producer socket waits for any reply from server.
@api public
Send messages to the cluster. Raises an exception if the producer fails to send the messages.
@param [Enumerable<MessageToSend>] messages
Messages must have a +topic+ set and may have a +key+ set.
@return [Boolean]
@api public | [
"Returns",
"a",
"new",
"Producer",
"."
] | bfbf084ea21af2a31350ad5f58d8ef5dc30b948e | https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/producer.rb#L157-L164 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.size | def size
size = size_from_java
size ||= size_from_win_api
size ||= size_from_ioctl
size ||= size_from_io_console
size ||= size_from_readline
size ||= size_from_tput
size ||= size_from_stty
size ||= size_from_env
size ||= size_from_ansicon
size || DEFAULT_SIZE
end | ruby | def size
size = size_from_java
size ||= size_from_win_api
size ||= size_from_ioctl
size ||= size_from_io_console
size ||= size_from_readline
size ||= size_from_tput
size ||= size_from_stty
size ||= size_from_env
size ||= size_from_ansicon
size || DEFAULT_SIZE
end | [
"def",
"size",
"size",
"=",
"size_from_java",
"size",
"||=",
"size_from_win_api",
"size",
"||=",
"size_from_ioctl",
"size",
"||=",
"size_from_io_console",
"size",
"||=",
"size_from_readline",
"size",
"||=",
"size_from_tput",
"size",
"||=",
"size_from_stty",
"size",
"||=",
"size_from_env",
"size",
"||=",
"size_from_ansicon",
"size",
"||",
"DEFAULT_SIZE",
"end"
] | Get terminal rows and columns
@return [Array[Integer, Integer]]
return rows & columns
@api public | [
"Get",
"terminal",
"rows",
"and",
"columns"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L39-L50 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.size_from_win_api | def size_from_win_api(verbose: nil)
require 'fiddle'
kernel32 = Fiddle::Handle.new('kernel32')
get_std_handle = Fiddle::Function.new(kernel32['GetStdHandle'],
[-Fiddle::TYPE_INT], Fiddle::TYPE_INT)
get_console_buffer_info = Fiddle::Function.new(
kernel32['GetConsoleScreenBufferInfo'],
[Fiddle::TYPE_LONG, Fiddle::TYPE_VOIDP], Fiddle::TYPE_INT)
format = 'SSSSSssssSS'
buffer = ([0] * format.size).pack(format)
stdout_handle = get_std_handle.(STDOUT_HANDLE)
get_console_buffer_info.(stdout_handle, buffer)
_, _, _, _, _, left, top, right, bottom, = buffer.unpack(format)
size = [bottom - top + 1, right - left + 1]
return size if nonzero_column?(size[1] - 1)
rescue LoadError
warn 'no native fiddle module found' if verbose
rescue Fiddle::DLError
# non windows platform or no kernel32 lib
end | ruby | def size_from_win_api(verbose: nil)
require 'fiddle'
kernel32 = Fiddle::Handle.new('kernel32')
get_std_handle = Fiddle::Function.new(kernel32['GetStdHandle'],
[-Fiddle::TYPE_INT], Fiddle::TYPE_INT)
get_console_buffer_info = Fiddle::Function.new(
kernel32['GetConsoleScreenBufferInfo'],
[Fiddle::TYPE_LONG, Fiddle::TYPE_VOIDP], Fiddle::TYPE_INT)
format = 'SSSSSssssSS'
buffer = ([0] * format.size).pack(format)
stdout_handle = get_std_handle.(STDOUT_HANDLE)
get_console_buffer_info.(stdout_handle, buffer)
_, _, _, _, _, left, top, right, bottom, = buffer.unpack(format)
size = [bottom - top + 1, right - left + 1]
return size if nonzero_column?(size[1] - 1)
rescue LoadError
warn 'no native fiddle module found' if verbose
rescue Fiddle::DLError
# non windows platform or no kernel32 lib
end | [
"def",
"size_from_win_api",
"(",
"verbose",
":",
"nil",
")",
"require",
"'fiddle'",
"kernel32",
"=",
"Fiddle",
"::",
"Handle",
".",
"new",
"(",
"'kernel32'",
")",
"get_std_handle",
"=",
"Fiddle",
"::",
"Function",
".",
"new",
"(",
"kernel32",
"[",
"'GetStdHandle'",
"]",
",",
"[",
"-",
"Fiddle",
"::",
"TYPE_INT",
"]",
",",
"Fiddle",
"::",
"TYPE_INT",
")",
"get_console_buffer_info",
"=",
"Fiddle",
"::",
"Function",
".",
"new",
"(",
"kernel32",
"[",
"'GetConsoleScreenBufferInfo'",
"]",
",",
"[",
"Fiddle",
"::",
"TYPE_LONG",
",",
"Fiddle",
"::",
"TYPE_VOIDP",
"]",
",",
"Fiddle",
"::",
"TYPE_INT",
")",
"format",
"=",
"'SSSSSssssSS'",
"buffer",
"=",
"(",
"[",
"0",
"]",
"*",
"format",
".",
"size",
")",
".",
"pack",
"(",
"format",
")",
"stdout_handle",
"=",
"get_std_handle",
".",
"(",
"STDOUT_HANDLE",
")",
"get_console_buffer_info",
".",
"(",
"stdout_handle",
",",
"buffer",
")",
"_",
",",
"_",
",",
"_",
",",
"_",
",",
"_",
",",
"left",
",",
"top",
",",
"right",
",",
"bottom",
",",
"=",
"buffer",
".",
"unpack",
"(",
"format",
")",
"size",
"=",
"[",
"bottom",
"-",
"top",
"+",
"1",
",",
"right",
"-",
"left",
"+",
"1",
"]",
"return",
"size",
"if",
"nonzero_column?",
"(",
"size",
"[",
"1",
"]",
"-",
"1",
")",
"rescue",
"LoadError",
"warn",
"'no native fiddle module found'",
"if",
"verbose",
"rescue",
"Fiddle",
"::",
"DLError",
"end"
] | Determine terminal size with a Windows native API
@return [nil, Array[Integer, Integer]]
@api private | [
"Determine",
"terminal",
"size",
"with",
"a",
"Windows",
"native",
"API"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L80-L102 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.size_from_java | def size_from_java(verbose: nil)
return unless jruby?
require 'java'
java_import 'jline.TerminalFactory'
terminal = TerminalFactory.get
size = [terminal.get_height, terminal.get_width]
return size if nonzero_column?(size[1])
rescue
warn 'failed to import java terminal package' if verbose
end | ruby | def size_from_java(verbose: nil)
return unless jruby?
require 'java'
java_import 'jline.TerminalFactory'
terminal = TerminalFactory.get
size = [terminal.get_height, terminal.get_width]
return size if nonzero_column?(size[1])
rescue
warn 'failed to import java terminal package' if verbose
end | [
"def",
"size_from_java",
"(",
"verbose",
":",
"nil",
")",
"return",
"unless",
"jruby?",
"require",
"'java'",
"java_import",
"'jline.TerminalFactory'",
"terminal",
"=",
"TerminalFactory",
".",
"get",
"size",
"=",
"[",
"terminal",
".",
"get_height",
",",
"terminal",
".",
"get_width",
"]",
"return",
"size",
"if",
"nonzero_column?",
"(",
"size",
"[",
"1",
"]",
")",
"rescue",
"warn",
"'failed to import java terminal package'",
"if",
"verbose",
"end"
] | Determine terminal size on jruby using native Java libs
@return [nil, Array[Integer, Integer]]
@api private | [
"Determine",
"terminal",
"size",
"on",
"jruby",
"using",
"native",
"Java",
"libs"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L110-L119 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.size_from_ioctl | def size_from_ioctl
return if jruby?
return unless @output.respond_to?(:ioctl)
format = 'SSSS'
buffer = ([0] * format.size).pack(format)
if ioctl?(TIOCGWINSZ, buffer) || ioctl?(TIOCGWINSZ_PPC, buffer)
rows, cols, = buffer.unpack(format)[0..1]
return [rows, cols] if nonzero_column?(cols)
end
end | ruby | def size_from_ioctl
return if jruby?
return unless @output.respond_to?(:ioctl)
format = 'SSSS'
buffer = ([0] * format.size).pack(format)
if ioctl?(TIOCGWINSZ, buffer) || ioctl?(TIOCGWINSZ_PPC, buffer)
rows, cols, = buffer.unpack(format)[0..1]
return [rows, cols] if nonzero_column?(cols)
end
end | [
"def",
"size_from_ioctl",
"return",
"if",
"jruby?",
"return",
"unless",
"@output",
".",
"respond_to?",
"(",
":ioctl",
")",
"format",
"=",
"'SSSS'",
"buffer",
"=",
"(",
"[",
"0",
"]",
"*",
"format",
".",
"size",
")",
".",
"pack",
"(",
"format",
")",
"if",
"ioctl?",
"(",
"TIOCGWINSZ",
",",
"buffer",
")",
"||",
"ioctl?",
"(",
"TIOCGWINSZ_PPC",
",",
"buffer",
")",
"rows",
",",
"cols",
",",
"=",
"buffer",
".",
"unpack",
"(",
"format",
")",
"[",
"0",
"..",
"1",
"]",
"return",
"[",
"rows",
",",
"cols",
"]",
"if",
"nonzero_column?",
"(",
"cols",
")",
"end",
"end"
] | Read terminal size from Unix ioctl
@return [nil, Array[Integer, Integer]]
@api private | [
"Read",
"terminal",
"size",
"from",
"Unix",
"ioctl"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L156-L166 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.size_from_readline | def size_from_readline
if defined?(Readline) && Readline.respond_to?(:get_screen_size)
size = Readline.get_screen_size
size if nonzero_column?(size[1])
end
rescue NotImplementedError
end | ruby | def size_from_readline
if defined?(Readline) && Readline.respond_to?(:get_screen_size)
size = Readline.get_screen_size
size if nonzero_column?(size[1])
end
rescue NotImplementedError
end | [
"def",
"size_from_readline",
"if",
"defined?",
"(",
"Readline",
")",
"&&",
"Readline",
".",
"respond_to?",
"(",
":get_screen_size",
")",
"size",
"=",
"Readline",
".",
"get_screen_size",
"size",
"if",
"nonzero_column?",
"(",
"size",
"[",
"1",
"]",
")",
"end",
"rescue",
"NotImplementedError",
"end"
] | Detect screen size using Readline
@api private | [
"Detect",
"screen",
"size",
"using",
"Readline"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L182-L188 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.size_from_tput | def size_from_tput
return unless @output.tty?
lines = run_command('tput', 'lines').to_i
cols = run_command('tput', 'cols').to_i
[lines, cols] if nonzero_column?(lines)
rescue IOError, SystemCallError
end | ruby | def size_from_tput
return unless @output.tty?
lines = run_command('tput', 'lines').to_i
cols = run_command('tput', 'cols').to_i
[lines, cols] if nonzero_column?(lines)
rescue IOError, SystemCallError
end | [
"def",
"size_from_tput",
"return",
"unless",
"@output",
".",
"tty?",
"lines",
"=",
"run_command",
"(",
"'tput'",
",",
"'lines'",
")",
".",
"to_i",
"cols",
"=",
"run_command",
"(",
"'tput'",
",",
"'cols'",
")",
".",
"to_i",
"[",
"lines",
",",
"cols",
"]",
"if",
"nonzero_column?",
"(",
"lines",
")",
"rescue",
"IOError",
",",
"SystemCallError",
"end"
] | Detect terminal size from tput utility
@api private | [
"Detect",
"terminal",
"size",
"from",
"tput",
"utility"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L194-L200 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.size_from_stty | def size_from_stty
return unless @output.tty?
out = run_command('stty', 'size')
return unless out
size = out.split.map(&:to_i)
size if nonzero_column?(size[1])
rescue IOError, SystemCallError
end | ruby | def size_from_stty
return unless @output.tty?
out = run_command('stty', 'size')
return unless out
size = out.split.map(&:to_i)
size if nonzero_column?(size[1])
rescue IOError, SystemCallError
end | [
"def",
"size_from_stty",
"return",
"unless",
"@output",
".",
"tty?",
"out",
"=",
"run_command",
"(",
"'stty'",
",",
"'size'",
")",
"return",
"unless",
"out",
"size",
"=",
"out",
".",
"split",
".",
"map",
"(",
"&",
":to_i",
")",
"size",
"if",
"nonzero_column?",
"(",
"size",
"[",
"1",
"]",
")",
"rescue",
"IOError",
",",
"SystemCallError",
"end"
] | Detect terminal size from stty utility
@api private | [
"Detect",
"terminal",
"size",
"from",
"stty",
"utility"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L206-L213 | train |
piotrmurach/tty-screen | lib/tty/screen.rb | TTY.Screen.run_command | def run_command(*args)
require 'tempfile'
out = Tempfile.new('tty-screen')
result = system(*args, out: out.path, err: File::NULL)
return if result.nil?
out.rewind
out.read
ensure
out.close if out
end | ruby | def run_command(*args)
require 'tempfile'
out = Tempfile.new('tty-screen')
result = system(*args, out: out.path, err: File::NULL)
return if result.nil?
out.rewind
out.read
ensure
out.close if out
end | [
"def",
"run_command",
"(",
"*",
"args",
")",
"require",
"'tempfile'",
"out",
"=",
"Tempfile",
".",
"new",
"(",
"'tty-screen'",
")",
"result",
"=",
"system",
"(",
"*",
"args",
",",
"out",
":",
"out",
".",
"path",
",",
"err",
":",
"File",
"::",
"NULL",
")",
"return",
"if",
"result",
".",
"nil?",
"out",
".",
"rewind",
"out",
".",
"read",
"ensure",
"out",
".",
"close",
"if",
"out",
"end"
] | Runs command silently capturing the output
@api private | [
"Runs",
"command",
"silently",
"capturing",
"the",
"output"
] | 282ae528974059c16090212dbcfb4a3d5aa3bbeb | https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L246-L255 | train |
jpmckinney/multi_mail | lib/multi_mail/service.rb | MultiMail.Service.validate_options | def validate_options(options, raise_error_if_unrecognized = true)
keys = []
for key, value in options
unless value.nil?
keys << key
end
end
missing = requirements - keys
unless missing.empty?
raise ArgumentError, "Missing required arguments: #{missing.map(&:to_s).sort.join(', ')}"
end
if !recognizes.empty? && raise_error_if_unrecognized
unrecognized = options.keys - requirements - recognized
unless unrecognized.empty?
raise ArgumentError, "Unrecognized arguments: #{unrecognized.map(&:to_s).sort.join(', ')}"
end
end
end | ruby | def validate_options(options, raise_error_if_unrecognized = true)
keys = []
for key, value in options
unless value.nil?
keys << key
end
end
missing = requirements - keys
unless missing.empty?
raise ArgumentError, "Missing required arguments: #{missing.map(&:to_s).sort.join(', ')}"
end
if !recognizes.empty? && raise_error_if_unrecognized
unrecognized = options.keys - requirements - recognized
unless unrecognized.empty?
raise ArgumentError, "Unrecognized arguments: #{unrecognized.map(&:to_s).sort.join(', ')}"
end
end
end | [
"def",
"validate_options",
"(",
"options",
",",
"raise_error_if_unrecognized",
"=",
"true",
")",
"keys",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"options",
"unless",
"value",
".",
"nil?",
"keys",
"<<",
"key",
"end",
"end",
"missing",
"=",
"requirements",
"-",
"keys",
"unless",
"missing",
".",
"empty?",
"raise",
"ArgumentError",
",",
"\"Missing required arguments: #{missing.map(&:to_s).sort.join(', ')}\"",
"end",
"if",
"!",
"recognizes",
".",
"empty?",
"&&",
"raise_error_if_unrecognized",
"unrecognized",
"=",
"options",
".",
"keys",
"-",
"requirements",
"-",
"recognized",
"unless",
"unrecognized",
".",
"empty?",
"raise",
"ArgumentError",
",",
"\"Unrecognized arguments: #{unrecognized.map(&:to_s).sort.join(', ')}\"",
"end",
"end",
"end"
] | Ensures that required arguments are present and that optional arguments
are recognized.
@param [Hash] options arguments
@raise [ArgumentError] if it can't find a required argument or can't
recognize an optional argument
@see Fog::Service::validate_options | [
"Ensures",
"that",
"required",
"arguments",
"are",
"present",
"and",
"that",
"optional",
"arguments",
"are",
"recognized",
"."
] | 4c9d7310633c1034afbef0dab873e89a8c608d00 | https://github.com/jpmckinney/multi_mail/blob/4c9d7310633c1034afbef0dab873e89a8c608d00/lib/multi_mail/service.rb#L45-L64 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_at_rule | def consume_at_rule(input = @tokens)
rule = {}
rule[:tokens] = input.collect do
rule[:name] = input.consume[:value]
rule[:prelude] = []
while token = input.consume
node = token[:node]
if node == :comment # Non-standard.
next
elsif node == :semicolon
break
elsif node === :'{'
# Note: The spec says the block should _be_ the consumed simple
# block, but Simon Sapin's CSS parsing tests and tinycss2 expect
# only the _value_ of the consumed simple block here. I assume I'm
# interpreting the spec too literally, so I'm going with the
# tinycss2 behavior.
rule[:block] = consume_simple_block(input)[:value]
break
elsif node == :simple_block && token[:start] == '{'
# Note: The spec says the block should _be_ the simple block, but
# Simon Sapin's CSS parsing tests and tinycss2 expect only the
# _value_ of the simple block here. I assume I'm interpreting the
# spec too literally, so I'm going with the tinycss2 behavior.
rule[:block] = token[:value]
break
else
input.reconsume
rule[:prelude] << consume_component_value(input)
end
end
end
create_node(:at_rule, rule)
end | ruby | def consume_at_rule(input = @tokens)
rule = {}
rule[:tokens] = input.collect do
rule[:name] = input.consume[:value]
rule[:prelude] = []
while token = input.consume
node = token[:node]
if node == :comment # Non-standard.
next
elsif node == :semicolon
break
elsif node === :'{'
# Note: The spec says the block should _be_ the consumed simple
# block, but Simon Sapin's CSS parsing tests and tinycss2 expect
# only the _value_ of the consumed simple block here. I assume I'm
# interpreting the spec too literally, so I'm going with the
# tinycss2 behavior.
rule[:block] = consume_simple_block(input)[:value]
break
elsif node == :simple_block && token[:start] == '{'
# Note: The spec says the block should _be_ the simple block, but
# Simon Sapin's CSS parsing tests and tinycss2 expect only the
# _value_ of the simple block here. I assume I'm interpreting the
# spec too literally, so I'm going with the tinycss2 behavior.
rule[:block] = token[:value]
break
else
input.reconsume
rule[:prelude] << consume_component_value(input)
end
end
end
create_node(:at_rule, rule)
end | [
"def",
"consume_at_rule",
"(",
"input",
"=",
"@tokens",
")",
"rule",
"=",
"{",
"}",
"rule",
"[",
":tokens",
"]",
"=",
"input",
".",
"collect",
"do",
"rule",
"[",
":name",
"]",
"=",
"input",
".",
"consume",
"[",
":value",
"]",
"rule",
"[",
":prelude",
"]",
"=",
"[",
"]",
"while",
"token",
"=",
"input",
".",
"consume",
"node",
"=",
"token",
"[",
":node",
"]",
"if",
"node",
"==",
":comment",
"next",
"elsif",
"node",
"==",
":semicolon",
"break",
"elsif",
"node",
"===",
":'",
"'",
"rule",
"[",
":block",
"]",
"=",
"consume_simple_block",
"(",
"input",
")",
"[",
":value",
"]",
"break",
"elsif",
"node",
"==",
":simple_block",
"&&",
"token",
"[",
":start",
"]",
"==",
"'{'",
"rule",
"[",
":block",
"]",
"=",
"token",
"[",
":value",
"]",
"break",
"else",
"input",
".",
"reconsume",
"rule",
"[",
":prelude",
"]",
"<<",
"consume_component_value",
"(",
"input",
")",
"end",
"end",
"end",
"create_node",
"(",
":at_rule",
",",
"rule",
")",
"end"
] | Initializes a parser based on the given _input_, which may be a CSS string
or an array of tokens.
See {Tokenizer#initialize} for _options_.
Consumes an at-rule and returns it.
5.4.2. http://dev.w3.org/csswg/css-syntax-3/#consume-at-rule | [
"Initializes",
"a",
"parser",
"based",
"on",
"the",
"given",
"_input_",
"which",
"may",
"be",
"a",
"CSS",
"string",
"or",
"an",
"array",
"of",
"tokens",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L137-L178 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_component_value | def consume_component_value(input = @tokens)
return nil unless token = input.consume
case token[:node]
when :'{', :'[', :'('
consume_simple_block(input)
when :function
if token.key?(:name)
# This is a parsed function, not a function token. This step isn't
# mentioned in the spec, but it's necessary to avoid re-parsing
# functions that have already been parsed.
token
else
consume_function(input)
end
else
token
end
end | ruby | def consume_component_value(input = @tokens)
return nil unless token = input.consume
case token[:node]
when :'{', :'[', :'('
consume_simple_block(input)
when :function
if token.key?(:name)
# This is a parsed function, not a function token. This step isn't
# mentioned in the spec, but it's necessary to avoid re-parsing
# functions that have already been parsed.
token
else
consume_function(input)
end
else
token
end
end | [
"def",
"consume_component_value",
"(",
"input",
"=",
"@tokens",
")",
"return",
"nil",
"unless",
"token",
"=",
"input",
".",
"consume",
"case",
"token",
"[",
":node",
"]",
"when",
":'",
"'",
",",
":'",
"'",
",",
":'",
"'",
"consume_simple_block",
"(",
"input",
")",
"when",
":function",
"if",
"token",
".",
"key?",
"(",
":name",
")",
"token",
"else",
"consume_function",
"(",
"input",
")",
"end",
"else",
"token",
"end",
"end"
] | Consumes a component value and returns it, or `nil` if there are no more
tokens.
5.4.6. http://dev.w3.org/csswg/css-syntax-3/#consume-a-component-value | [
"Consumes",
"a",
"component",
"value",
"and",
"returns",
"it",
"or",
"nil",
"if",
"there",
"are",
"no",
"more",
"tokens",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L184-L204 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_declaration | def consume_declaration(input = @tokens)
declaration = {}
value = []
declaration[:tokens] = input.collect do
declaration[:name] = input.consume[:value]
next_token = input.peek
while next_token && next_token[:node] == :whitespace
input.consume
next_token = input.peek
end
unless next_token && next_token[:node] == :colon
# Parse error.
#
# Note: The spec explicitly says to return nothing here, but Simon
# Sapin's CSS parsing tests expect an error node.
return create_node(:error, :value => 'invalid')
end
input.consume
until input.peek.nil?
value << consume_component_value(input)
end
end
# Look for !important.
important_tokens = value.reject {|token|
node = token[:node]
node == :whitespace || node == :comment || node == :semicolon
}.last(2)
if important_tokens.size == 2 &&
important_tokens[0][:node] == :delim &&
important_tokens[0][:value] == '!' &&
important_tokens[1][:node] == :ident &&
important_tokens[1][:value].downcase == 'important'
declaration[:important] = true
excl_index = value.index(important_tokens[0])
# Technically the spec doesn't require us to trim trailing tokens after
# the !important, but Simon Sapin's CSS parsing tests expect it and
# tinycss2 does it, so we'll go along with the cool kids.
value.slice!(excl_index, value.size - excl_index)
else
declaration[:important] = false
end
declaration[:value] = value
create_node(:declaration, declaration)
end | ruby | def consume_declaration(input = @tokens)
declaration = {}
value = []
declaration[:tokens] = input.collect do
declaration[:name] = input.consume[:value]
next_token = input.peek
while next_token && next_token[:node] == :whitespace
input.consume
next_token = input.peek
end
unless next_token && next_token[:node] == :colon
# Parse error.
#
# Note: The spec explicitly says to return nothing here, but Simon
# Sapin's CSS parsing tests expect an error node.
return create_node(:error, :value => 'invalid')
end
input.consume
until input.peek.nil?
value << consume_component_value(input)
end
end
# Look for !important.
important_tokens = value.reject {|token|
node = token[:node]
node == :whitespace || node == :comment || node == :semicolon
}.last(2)
if important_tokens.size == 2 &&
important_tokens[0][:node] == :delim &&
important_tokens[0][:value] == '!' &&
important_tokens[1][:node] == :ident &&
important_tokens[1][:value].downcase == 'important'
declaration[:important] = true
excl_index = value.index(important_tokens[0])
# Technically the spec doesn't require us to trim trailing tokens after
# the !important, but Simon Sapin's CSS parsing tests expect it and
# tinycss2 does it, so we'll go along with the cool kids.
value.slice!(excl_index, value.size - excl_index)
else
declaration[:important] = false
end
declaration[:value] = value
create_node(:declaration, declaration)
end | [
"def",
"consume_declaration",
"(",
"input",
"=",
"@tokens",
")",
"declaration",
"=",
"{",
"}",
"value",
"=",
"[",
"]",
"declaration",
"[",
":tokens",
"]",
"=",
"input",
".",
"collect",
"do",
"declaration",
"[",
":name",
"]",
"=",
"input",
".",
"consume",
"[",
":value",
"]",
"next_token",
"=",
"input",
".",
"peek",
"while",
"next_token",
"&&",
"next_token",
"[",
":node",
"]",
"==",
":whitespace",
"input",
".",
"consume",
"next_token",
"=",
"input",
".",
"peek",
"end",
"unless",
"next_token",
"&&",
"next_token",
"[",
":node",
"]",
"==",
":colon",
"return",
"create_node",
"(",
":error",
",",
":value",
"=>",
"'invalid'",
")",
"end",
"input",
".",
"consume",
"until",
"input",
".",
"peek",
".",
"nil?",
"value",
"<<",
"consume_component_value",
"(",
"input",
")",
"end",
"end",
"important_tokens",
"=",
"value",
".",
"reject",
"{",
"|",
"token",
"|",
"node",
"=",
"token",
"[",
":node",
"]",
"node",
"==",
":whitespace",
"||",
"node",
"==",
":comment",
"||",
"node",
"==",
":semicolon",
"}",
".",
"last",
"(",
"2",
")",
"if",
"important_tokens",
".",
"size",
"==",
"2",
"&&",
"important_tokens",
"[",
"0",
"]",
"[",
":node",
"]",
"==",
":delim",
"&&",
"important_tokens",
"[",
"0",
"]",
"[",
":value",
"]",
"==",
"'!'",
"&&",
"important_tokens",
"[",
"1",
"]",
"[",
":node",
"]",
"==",
":ident",
"&&",
"important_tokens",
"[",
"1",
"]",
"[",
":value",
"]",
".",
"downcase",
"==",
"'important'",
"declaration",
"[",
":important",
"]",
"=",
"true",
"excl_index",
"=",
"value",
".",
"index",
"(",
"important_tokens",
"[",
"0",
"]",
")",
"value",
".",
"slice!",
"(",
"excl_index",
",",
"value",
".",
"size",
"-",
"excl_index",
")",
"else",
"declaration",
"[",
":important",
"]",
"=",
"false",
"end",
"declaration",
"[",
":value",
"]",
"=",
"value",
"create_node",
"(",
":declaration",
",",
"declaration",
")",
"end"
] | Consumes a declaration and returns it, or `nil` on parse error.
5.4.5. http://dev.w3.org/csswg/css-syntax-3/#consume-a-declaration | [
"Consumes",
"a",
"declaration",
"and",
"returns",
"it",
"or",
"nil",
"on",
"parse",
"error",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L209-L263 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_declarations | def consume_declarations(input = @tokens, options = {})
declarations = []
while token = input.consume
case token[:node]
# Non-standard: Preserve comments, semicolons, and whitespace.
when :comment, :semicolon, :whitespace
declarations << token unless options[:strict]
when :at_keyword
# When parsing a style rule, this is a parse error. Otherwise it's
# not.
input.reconsume
declarations << consume_at_rule(input)
when :ident
decl_tokens = [token]
while next_token = input.peek
break if next_token[:node] == :semicolon
decl_tokens << consume_component_value(input)
end
if decl = consume_declaration(TokenScanner.new(decl_tokens))
declarations << decl
end
else
# Parse error (invalid property name, etc.).
#
# Note: The spec doesn't say we should append anything to the list of
# declarations here, but Simon Sapin's CSS parsing tests expect an
# error node.
declarations << create_node(:error, :value => 'invalid')
input.reconsume
while next_token = input.peek
break if next_token[:node] == :semicolon
consume_component_value(input)
end
end
end
declarations
end | ruby | def consume_declarations(input = @tokens, options = {})
declarations = []
while token = input.consume
case token[:node]
# Non-standard: Preserve comments, semicolons, and whitespace.
when :comment, :semicolon, :whitespace
declarations << token unless options[:strict]
when :at_keyword
# When parsing a style rule, this is a parse error. Otherwise it's
# not.
input.reconsume
declarations << consume_at_rule(input)
when :ident
decl_tokens = [token]
while next_token = input.peek
break if next_token[:node] == :semicolon
decl_tokens << consume_component_value(input)
end
if decl = consume_declaration(TokenScanner.new(decl_tokens))
declarations << decl
end
else
# Parse error (invalid property name, etc.).
#
# Note: The spec doesn't say we should append anything to the list of
# declarations here, but Simon Sapin's CSS parsing tests expect an
# error node.
declarations << create_node(:error, :value => 'invalid')
input.reconsume
while next_token = input.peek
break if next_token[:node] == :semicolon
consume_component_value(input)
end
end
end
declarations
end | [
"def",
"consume_declarations",
"(",
"input",
"=",
"@tokens",
",",
"options",
"=",
"{",
"}",
")",
"declarations",
"=",
"[",
"]",
"while",
"token",
"=",
"input",
".",
"consume",
"case",
"token",
"[",
":node",
"]",
"when",
":comment",
",",
":semicolon",
",",
":whitespace",
"declarations",
"<<",
"token",
"unless",
"options",
"[",
":strict",
"]",
"when",
":at_keyword",
"input",
".",
"reconsume",
"declarations",
"<<",
"consume_at_rule",
"(",
"input",
")",
"when",
":ident",
"decl_tokens",
"=",
"[",
"token",
"]",
"while",
"next_token",
"=",
"input",
".",
"peek",
"break",
"if",
"next_token",
"[",
":node",
"]",
"==",
":semicolon",
"decl_tokens",
"<<",
"consume_component_value",
"(",
"input",
")",
"end",
"if",
"decl",
"=",
"consume_declaration",
"(",
"TokenScanner",
".",
"new",
"(",
"decl_tokens",
")",
")",
"declarations",
"<<",
"decl",
"end",
"else",
"declarations",
"<<",
"create_node",
"(",
":error",
",",
":value",
"=>",
"'invalid'",
")",
"input",
".",
"reconsume",
"while",
"next_token",
"=",
"input",
".",
"peek",
"break",
"if",
"next_token",
"[",
":node",
"]",
"==",
":semicolon",
"consume_component_value",
"(",
"input",
")",
"end",
"end",
"end",
"declarations",
"end"
] | Consumes a list of declarations and returns them.
By default, the returned list may include `:comment`, `:semicolon`, and
`:whitespace` nodes, which is non-standard.
Options:
* **:strict** - Set to `true` to exclude non-standard `:comment`,
`:semicolon`, and `:whitespace` nodes.
5.4.4. http://dev.w3.org/csswg/css-syntax/#consume-a-list-of-declarations | [
"Consumes",
"a",
"list",
"of",
"declarations",
"and",
"returns",
"them",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L276-L321 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_function | def consume_function(input = @tokens)
function = {
:name => input.current[:value],
:value => [],
:tokens => [input.current] # Non-standard, used for serialization.
}
function[:tokens].concat(input.collect {
while token = input.consume
case token[:node]
when :')'
break
# Non-standard.
when :comment
next
else
input.reconsume
function[:value] << consume_component_value(input)
end
end
})
create_node(:function, function)
end | ruby | def consume_function(input = @tokens)
function = {
:name => input.current[:value],
:value => [],
:tokens => [input.current] # Non-standard, used for serialization.
}
function[:tokens].concat(input.collect {
while token = input.consume
case token[:node]
when :')'
break
# Non-standard.
when :comment
next
else
input.reconsume
function[:value] << consume_component_value(input)
end
end
})
create_node(:function, function)
end | [
"def",
"consume_function",
"(",
"input",
"=",
"@tokens",
")",
"function",
"=",
"{",
":name",
"=>",
"input",
".",
"current",
"[",
":value",
"]",
",",
":value",
"=>",
"[",
"]",
",",
":tokens",
"=>",
"[",
"input",
".",
"current",
"]",
"}",
"function",
"[",
":tokens",
"]",
".",
"concat",
"(",
"input",
".",
"collect",
"{",
"while",
"token",
"=",
"input",
".",
"consume",
"case",
"token",
"[",
":node",
"]",
"when",
":'",
"'",
"break",
"when",
":comment",
"next",
"else",
"input",
".",
"reconsume",
"function",
"[",
":value",
"]",
"<<",
"consume_component_value",
"(",
"input",
")",
"end",
"end",
"}",
")",
"create_node",
"(",
":function",
",",
"function",
")",
"end"
] | Consumes a function and returns it.
5.4.8. http://dev.w3.org/csswg/css-syntax-3/#consume-a-function | [
"Consumes",
"a",
"function",
"and",
"returns",
"it",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L326-L351 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_qualified_rule | def consume_qualified_rule(input = @tokens)
rule = {:prelude => []}
rule[:tokens] = input.collect do
while true
unless token = input.consume
# Parse error.
#
# Note: The spec explicitly says to return nothing here, but Simon
# Sapin's CSS parsing tests expect an error node.
return create_node(:error, :value => 'invalid')
end
if token[:node] == :'{'
# Note: The spec says the block should _be_ the consumed simple
# block, but Simon Sapin's CSS parsing tests and tinycss2 expect
# only the _value_ of the consumed simple block here. I assume I'm
# interpreting the spec too literally, so I'm going with the
# tinycss2 behavior.
rule[:block] = consume_simple_block(input)[:value]
break
elsif token[:node] == :simple_block && token[:start] == '{'
# Note: The spec says the block should _be_ the simple block, but
# Simon Sapin's CSS parsing tests and tinycss2 expect only the
# _value_ of the simple block here. I assume I'm interpreting the
# spec too literally, so I'm going with the tinycss2 behavior.
rule[:block] = token[:value]
break
else
input.reconsume
rule[:prelude] << consume_component_value(input)
end
end
end
create_node(:qualified_rule, rule)
end | ruby | def consume_qualified_rule(input = @tokens)
rule = {:prelude => []}
rule[:tokens] = input.collect do
while true
unless token = input.consume
# Parse error.
#
# Note: The spec explicitly says to return nothing here, but Simon
# Sapin's CSS parsing tests expect an error node.
return create_node(:error, :value => 'invalid')
end
if token[:node] == :'{'
# Note: The spec says the block should _be_ the consumed simple
# block, but Simon Sapin's CSS parsing tests and tinycss2 expect
# only the _value_ of the consumed simple block here. I assume I'm
# interpreting the spec too literally, so I'm going with the
# tinycss2 behavior.
rule[:block] = consume_simple_block(input)[:value]
break
elsif token[:node] == :simple_block && token[:start] == '{'
# Note: The spec says the block should _be_ the simple block, but
# Simon Sapin's CSS parsing tests and tinycss2 expect only the
# _value_ of the simple block here. I assume I'm interpreting the
# spec too literally, so I'm going with the tinycss2 behavior.
rule[:block] = token[:value]
break
else
input.reconsume
rule[:prelude] << consume_component_value(input)
end
end
end
create_node(:qualified_rule, rule)
end | [
"def",
"consume_qualified_rule",
"(",
"input",
"=",
"@tokens",
")",
"rule",
"=",
"{",
":prelude",
"=>",
"[",
"]",
"}",
"rule",
"[",
":tokens",
"]",
"=",
"input",
".",
"collect",
"do",
"while",
"true",
"unless",
"token",
"=",
"input",
".",
"consume",
"return",
"create_node",
"(",
":error",
",",
":value",
"=>",
"'invalid'",
")",
"end",
"if",
"token",
"[",
":node",
"]",
"==",
":'",
"'",
"rule",
"[",
":block",
"]",
"=",
"consume_simple_block",
"(",
"input",
")",
"[",
":value",
"]",
"break",
"elsif",
"token",
"[",
":node",
"]",
"==",
":simple_block",
"&&",
"token",
"[",
":start",
"]",
"==",
"'{'",
"rule",
"[",
":block",
"]",
"=",
"token",
"[",
":value",
"]",
"break",
"else",
"input",
".",
"reconsume",
"rule",
"[",
":prelude",
"]",
"<<",
"consume_component_value",
"(",
"input",
")",
"end",
"end",
"end",
"create_node",
"(",
":qualified_rule",
",",
"rule",
")",
"end"
] | Consumes a qualified rule and returns it, or `nil` if a parse error
occurs.
5.4.3. http://dev.w3.org/csswg/css-syntax-3/#consume-a-qualified-rule | [
"Consumes",
"a",
"qualified",
"rule",
"and",
"returns",
"it",
"or",
"nil",
"if",
"a",
"parse",
"error",
"occurs",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L357-L393 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_rules | def consume_rules(flags = {})
rules = []
while token = @tokens.consume
case token[:node]
# Non-standard. Spec says to discard comments and whitespace, but we
# keep them so we can serialize faithfully.
when :comment, :whitespace
rules << token
when :cdc, :cdo
unless flags[:top_level]
@tokens.reconsume
rule = consume_qualified_rule
rules << rule if rule
end
when :at_keyword
@tokens.reconsume
rule = consume_at_rule
rules << rule if rule
else
@tokens.reconsume
rule = consume_qualified_rule
rules << rule if rule
end
end
rules
end | ruby | def consume_rules(flags = {})
rules = []
while token = @tokens.consume
case token[:node]
# Non-standard. Spec says to discard comments and whitespace, but we
# keep them so we can serialize faithfully.
when :comment, :whitespace
rules << token
when :cdc, :cdo
unless flags[:top_level]
@tokens.reconsume
rule = consume_qualified_rule
rules << rule if rule
end
when :at_keyword
@tokens.reconsume
rule = consume_at_rule
rules << rule if rule
else
@tokens.reconsume
rule = consume_qualified_rule
rules << rule if rule
end
end
rules
end | [
"def",
"consume_rules",
"(",
"flags",
"=",
"{",
"}",
")",
"rules",
"=",
"[",
"]",
"while",
"token",
"=",
"@tokens",
".",
"consume",
"case",
"token",
"[",
":node",
"]",
"when",
":comment",
",",
":whitespace",
"rules",
"<<",
"token",
"when",
":cdc",
",",
":cdo",
"unless",
"flags",
"[",
":top_level",
"]",
"@tokens",
".",
"reconsume",
"rule",
"=",
"consume_qualified_rule",
"rules",
"<<",
"rule",
"if",
"rule",
"end",
"when",
":at_keyword",
"@tokens",
".",
"reconsume",
"rule",
"=",
"consume_at_rule",
"rules",
"<<",
"rule",
"if",
"rule",
"else",
"@tokens",
".",
"reconsume",
"rule",
"=",
"consume_qualified_rule",
"rules",
"<<",
"rule",
"if",
"rule",
"end",
"end",
"rules",
"end"
] | Consumes a list of rules and returns them.
5.4.1. http://dev.w3.org/csswg/css-syntax/#consume-a-list-of-rules | [
"Consumes",
"a",
"list",
"of",
"rules",
"and",
"returns",
"them",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L398-L428 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.consume_simple_block | def consume_simple_block(input = @tokens)
start_token = input.current[:node]
end_token = BLOCK_END_TOKENS[start_token]
block = {
:start => start_token.to_s,
:end => end_token.to_s,
:value => [],
:tokens => [input.current] # Non-standard. Used for serialization.
}
block[:tokens].concat(input.collect do
while token = input.consume
break if token[:node] == end_token
input.reconsume
block[:value] << consume_component_value(input)
end
end)
create_node(:simple_block, block)
end | ruby | def consume_simple_block(input = @tokens)
start_token = input.current[:node]
end_token = BLOCK_END_TOKENS[start_token]
block = {
:start => start_token.to_s,
:end => end_token.to_s,
:value => [],
:tokens => [input.current] # Non-standard. Used for serialization.
}
block[:tokens].concat(input.collect do
while token = input.consume
break if token[:node] == end_token
input.reconsume
block[:value] << consume_component_value(input)
end
end)
create_node(:simple_block, block)
end | [
"def",
"consume_simple_block",
"(",
"input",
"=",
"@tokens",
")",
"start_token",
"=",
"input",
".",
"current",
"[",
":node",
"]",
"end_token",
"=",
"BLOCK_END_TOKENS",
"[",
"start_token",
"]",
"block",
"=",
"{",
":start",
"=>",
"start_token",
".",
"to_s",
",",
":end",
"=>",
"end_token",
".",
"to_s",
",",
":value",
"=>",
"[",
"]",
",",
":tokens",
"=>",
"[",
"input",
".",
"current",
"]",
"}",
"block",
"[",
":tokens",
"]",
".",
"concat",
"(",
"input",
".",
"collect",
"do",
"while",
"token",
"=",
"input",
".",
"consume",
"break",
"if",
"token",
"[",
":node",
"]",
"==",
"end_token",
"input",
".",
"reconsume",
"block",
"[",
":value",
"]",
"<<",
"consume_component_value",
"(",
"input",
")",
"end",
"end",
")",
"create_node",
"(",
":simple_block",
",",
"block",
")",
"end"
] | Consumes and returns a simple block associated with the current input
token.
5.4.7. http://dev.w3.org/csswg/css-syntax/#consume-a-simple-block | [
"Consumes",
"and",
"returns",
"a",
"simple",
"block",
"associated",
"with",
"the",
"current",
"input",
"token",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L434-L455 | train |
rgrove/crass | lib/crass/parser.rb | Crass.Parser.parse_component_value | def parse_component_value(input = @tokens)
input = TokenScanner.new(input) unless input.is_a?(TokenScanner)
while input.peek && input.peek[:node] == :whitespace
input.consume
end
if input.peek.nil?
return create_node(:error, :value => 'empty')
end
value = consume_component_value(input)
while input.peek && input.peek[:node] == :whitespace
input.consume
end
if input.peek.nil?
value
else
create_node(:error, :value => 'extra-input')
end
end | ruby | def parse_component_value(input = @tokens)
input = TokenScanner.new(input) unless input.is_a?(TokenScanner)
while input.peek && input.peek[:node] == :whitespace
input.consume
end
if input.peek.nil?
return create_node(:error, :value => 'empty')
end
value = consume_component_value(input)
while input.peek && input.peek[:node] == :whitespace
input.consume
end
if input.peek.nil?
value
else
create_node(:error, :value => 'extra-input')
end
end | [
"def",
"parse_component_value",
"(",
"input",
"=",
"@tokens",
")",
"input",
"=",
"TokenScanner",
".",
"new",
"(",
"input",
")",
"unless",
"input",
".",
"is_a?",
"(",
"TokenScanner",
")",
"while",
"input",
".",
"peek",
"&&",
"input",
".",
"peek",
"[",
":node",
"]",
"==",
":whitespace",
"input",
".",
"consume",
"end",
"if",
"input",
".",
"peek",
".",
"nil?",
"return",
"create_node",
"(",
":error",
",",
":value",
"=>",
"'empty'",
")",
"end",
"value",
"=",
"consume_component_value",
"(",
"input",
")",
"while",
"input",
".",
"peek",
"&&",
"input",
".",
"peek",
"[",
":node",
"]",
"==",
":whitespace",
"input",
".",
"consume",
"end",
"if",
"input",
".",
"peek",
".",
"nil?",
"value",
"else",
"create_node",
"(",
":error",
",",
":value",
"=>",
"'extra-input'",
")",
"end",
"end"
] | Parses a single component value and returns it.
5.3.7. http://dev.w3.org/csswg/css-syntax-3/#parse-a-component-value | [
"Parses",
"a",
"single",
"component",
"value",
"and",
"returns",
"it",
"."
] | 074e56f2a9f10bb873fa8e708ef58a065d4281a2 | https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L483-L505 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.