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 |
---|---|---|---|---|---|---|---|---|---|---|---|
Origen-SDK/origen | lib/origen/features.rb | Origen.Features.feature | def feature(name = nil)
if !name
self.class.features.keys
else
if self.class.features.key?(name)
self.class.features[name]
else
fail "Feature #{name} does not exist!"
end
end
end | ruby | def feature(name = nil)
if !name
self.class.features.keys
else
if self.class.features.key?(name)
self.class.features[name]
else
fail "Feature #{name} does not exist!"
end
end
end | [
"def",
"feature",
"(",
"name",
"=",
"nil",
")",
"if",
"!",
"name",
"self",
".",
"class",
".",
"features",
".",
"keys",
"else",
"if",
"self",
".",
"class",
".",
"features",
".",
"key?",
"(",
"name",
")",
"self",
".",
"class",
".",
"features",
"[",
"name",
"]",
"else",
"fail",
"\"Feature #{name} does not exist!\"",
"end",
"end",
"end"
]
| Returns an array of the names of all associated features | [
"Returns",
"an",
"array",
"of",
"the",
"names",
"of",
"all",
"associated",
"features"
]
| f05e9dd190fcb90284084ba6e2bd4b0fe0c7f4ac | https://github.com/Origen-SDK/origen/blob/f05e9dd190fcb90284084ba6e2bd4b0fe0c7f4ac/lib/origen/features.rb#L91-L101 | train |
JoshCheek/ttt | lib/ttt/computer_player.rb | TTT.ComputerPlayer.imperative_move | def imperative_move
# if we can win *this turn*, then take it because
# it rates winning next turn the same as winning in 3 turns
game.available_moves.each do |move|
new_game = game.pristine_mark move
return move if new_game.over? && new_game.winner == player_number
end
# if we can block the opponent from winning *this turn*, then take it, because
# it rates losing this turn the same as losing in 3 turns
if moves_by_rating.all? { |move, rating, game| rating == -1 }
Game.winning_states do |position1, position2, position3|
a, b, c = board[position1-1, 1].to_i, board[position2-1, 1].to_i, board[position3-1, 1].to_i
if a + b + c == opponent_number * 2
return a.zero? ? position1 : b.zero? ? position2 : position3
end
end
end
end | ruby | def imperative_move
# if we can win *this turn*, then take it because
# it rates winning next turn the same as winning in 3 turns
game.available_moves.each do |move|
new_game = game.pristine_mark move
return move if new_game.over? && new_game.winner == player_number
end
# if we can block the opponent from winning *this turn*, then take it, because
# it rates losing this turn the same as losing in 3 turns
if moves_by_rating.all? { |move, rating, game| rating == -1 }
Game.winning_states do |position1, position2, position3|
a, b, c = board[position1-1, 1].to_i, board[position2-1, 1].to_i, board[position3-1, 1].to_i
if a + b + c == opponent_number * 2
return a.zero? ? position1 : b.zero? ? position2 : position3
end
end
end
end | [
"def",
"imperative_move",
"game",
".",
"available_moves",
".",
"each",
"do",
"|",
"move",
"|",
"new_game",
"=",
"game",
".",
"pristine_mark",
"move",
"return",
"move",
"if",
"new_game",
".",
"over?",
"&&",
"new_game",
".",
"winner",
"==",
"player_number",
"end",
"if",
"moves_by_rating",
".",
"all?",
"{",
"|",
"move",
",",
"rating",
",",
"game",
"|",
"rating",
"==",
"-",
"1",
"}",
"Game",
".",
"winning_states",
"do",
"|",
"position1",
",",
"position2",
",",
"position3",
"|",
"a",
",",
"b",
",",
"c",
"=",
"board",
"[",
"position1",
"-",
"1",
",",
"1",
"]",
".",
"to_i",
",",
"board",
"[",
"position2",
"-",
"1",
",",
"1",
"]",
".",
"to_i",
",",
"board",
"[",
"position3",
"-",
"1",
",",
"1",
"]",
".",
"to_i",
"if",
"a",
"+",
"b",
"+",
"c",
"==",
"opponent_number",
"*",
"2",
"return",
"a",
".",
"zero?",
"?",
"position1",
":",
"b",
".",
"zero?",
"?",
"position2",
":",
"position3",
"end",
"end",
"end",
"end"
]
| allows us to override ratings in cases where they make the robot look stupid | [
"allows",
"us",
"to",
"override",
"ratings",
"in",
"cases",
"where",
"they",
"make",
"the",
"robot",
"look",
"stupid"
]
| 1b10b6ac18ccf066d992abdc12ec6e43acf55f08 | https://github.com/JoshCheek/ttt/blob/1b10b6ac18ccf066d992abdc12ec6e43acf55f08/lib/ttt/computer_player.rb#L42-L60 | train |
lightstep/lightstep-tracer-ruby | lib/lightstep/tracer.rb | LightStep.Tracer.start_span | def start_span(operation_name, child_of: nil, references: nil, start_time: nil, tags: nil, ignore_active_scope: false)
if child_of.nil? && references.nil? && !ignore_active_scope
child_of = active_span
end
Span.new(
tracer: self,
operation_name: operation_name,
child_of: child_of,
references: references,
start_micros: start_time.nil? ? LightStep.micros(Time.now) : LightStep.micros(start_time),
tags: tags,
max_log_records: max_log_records,
)
end | ruby | def start_span(operation_name, child_of: nil, references: nil, start_time: nil, tags: nil, ignore_active_scope: false)
if child_of.nil? && references.nil? && !ignore_active_scope
child_of = active_span
end
Span.new(
tracer: self,
operation_name: operation_name,
child_of: child_of,
references: references,
start_micros: start_time.nil? ? LightStep.micros(Time.now) : LightStep.micros(start_time),
tags: tags,
max_log_records: max_log_records,
)
end | [
"def",
"start_span",
"(",
"operation_name",
",",
"child_of",
":",
"nil",
",",
"references",
":",
"nil",
",",
"start_time",
":",
"nil",
",",
"tags",
":",
"nil",
",",
"ignore_active_scope",
":",
"false",
")",
"if",
"child_of",
".",
"nil?",
"&&",
"references",
".",
"nil?",
"&&",
"!",
"ignore_active_scope",
"child_of",
"=",
"active_span",
"end",
"Span",
".",
"new",
"(",
"tracer",
":",
"self",
",",
"operation_name",
":",
"operation_name",
",",
"child_of",
":",
"child_of",
",",
"references",
":",
"references",
",",
"start_micros",
":",
"start_time",
".",
"nil?",
"?",
"LightStep",
".",
"micros",
"(",
"Time",
".",
"now",
")",
":",
"LightStep",
".",
"micros",
"(",
"start_time",
")",
",",
"tags",
":",
"tags",
",",
"max_log_records",
":",
"max_log_records",
",",
")",
"end"
]
| Starts a new span.
@param operation_name [String] The operation name for the Span
@param child_of [SpanContext] SpanContext that acts as a parent to
the newly-started Span. If a Span instance is provided, its
.span_context is automatically substituted.
@param references [Array<SpanContext>] An array of SpanContexts that
identify any parent SpanContexts of newly-started Span. If Spans
are provided, their .span_context is automatically substituted.
@param start_time [Time] When the Span started, if not now
@param tags [Hash] Tags to assign to the Span at start time
@param ignore_active_scope [Boolean] whether to create an implicit
References#CHILD_OF reference to the ScopeManager#active.
@return [Span] | [
"Starts",
"a",
"new",
"span",
"."
]
| 72f5669a4afabe81a3fb396cda61c47b7d01ec33 | https://github.com/lightstep/lightstep-tracer-ruby/blob/72f5669a4afabe81a3fb396cda61c47b7d01ec33/lib/lightstep/tracer.rb#L142-L156 | train |
lightstep/lightstep-tracer-ruby | lib/lightstep/tracer.rb | LightStep.Tracer.extract | def extract(format, carrier)
case format
when OpenTracing::FORMAT_TEXT_MAP
extract_from_text_map(carrier)
when OpenTracing::FORMAT_BINARY
warn 'Binary join format not yet implemented'
nil
when OpenTracing::FORMAT_RACK
extract_from_rack(carrier)
else
warn 'Unknown join format'
nil
end
end | ruby | def extract(format, carrier)
case format
when OpenTracing::FORMAT_TEXT_MAP
extract_from_text_map(carrier)
when OpenTracing::FORMAT_BINARY
warn 'Binary join format not yet implemented'
nil
when OpenTracing::FORMAT_RACK
extract_from_rack(carrier)
else
warn 'Unknown join format'
nil
end
end | [
"def",
"extract",
"(",
"format",
",",
"carrier",
")",
"case",
"format",
"when",
"OpenTracing",
"::",
"FORMAT_TEXT_MAP",
"extract_from_text_map",
"(",
"carrier",
")",
"when",
"OpenTracing",
"::",
"FORMAT_BINARY",
"warn",
"'Binary join format not yet implemented'",
"nil",
"when",
"OpenTracing",
"::",
"FORMAT_RACK",
"extract_from_rack",
"(",
"carrier",
")",
"else",
"warn",
"'Unknown join format'",
"nil",
"end",
"end"
]
| Extract a SpanContext from a carrier
@param format [OpenTracing::FORMAT_TEXT_MAP, OpenTracing::FORMAT_BINARY, OpenTracing::FORMAT_RACK]
@param carrier [Carrier] A carrier object of the type dictated by the specified `format`
@return [SpanContext] the extracted SpanContext or nil if none could be found | [
"Extract",
"a",
"SpanContext",
"from",
"a",
"carrier"
]
| 72f5669a4afabe81a3fb396cda61c47b7d01ec33 | https://github.com/lightstep/lightstep-tracer-ruby/blob/72f5669a4afabe81a3fb396cda61c47b7d01ec33/lib/lightstep/tracer.rb#L180-L193 | train |
lightstep/lightstep-tracer-ruby | lib/lightstep/span.rb | LightStep.Span.set_baggage | def set_baggage(baggage = {})
@context = SpanContext.new(
id: context.id,
trace_id: context.trace_id,
baggage: baggage
)
end | ruby | def set_baggage(baggage = {})
@context = SpanContext.new(
id: context.id,
trace_id: context.trace_id,
baggage: baggage
)
end | [
"def",
"set_baggage",
"(",
"baggage",
"=",
"{",
"}",
")",
"@context",
"=",
"SpanContext",
".",
"new",
"(",
"id",
":",
"context",
".",
"id",
",",
"trace_id",
":",
"context",
".",
"trace_id",
",",
"baggage",
":",
"baggage",
")",
"end"
]
| Set all baggage at once. This will reset the baggage to the given param.
@param baggage [Hash] new baggage for the span | [
"Set",
"all",
"baggage",
"at",
"once",
".",
"This",
"will",
"reset",
"the",
"baggage",
"to",
"the",
"given",
"param",
"."
]
| 72f5669a4afabe81a3fb396cda61c47b7d01ec33 | https://github.com/lightstep/lightstep-tracer-ruby/blob/72f5669a4afabe81a3fb396cda61c47b7d01ec33/lib/lightstep/span.rb#L93-L99 | train |
lightstep/lightstep-tracer-ruby | lib/lightstep/span.rb | LightStep.Span.to_h | def to_h
{
runtime_guid: tracer.guid,
span_guid: context.id,
trace_guid: context.trace_id,
span_name: operation_name,
attributes: tags.map {|key, value|
{Key: key.to_s, Value: value}
},
oldest_micros: start_micros,
youngest_micros: end_micros,
error_flag: false,
dropped_logs: dropped_logs_count,
log_records: log_records
}
end | ruby | def to_h
{
runtime_guid: tracer.guid,
span_guid: context.id,
trace_guid: context.trace_id,
span_name: operation_name,
attributes: tags.map {|key, value|
{Key: key.to_s, Value: value}
},
oldest_micros: start_micros,
youngest_micros: end_micros,
error_flag: false,
dropped_logs: dropped_logs_count,
log_records: log_records
}
end | [
"def",
"to_h",
"{",
"runtime_guid",
":",
"tracer",
".",
"guid",
",",
"span_guid",
":",
"context",
".",
"id",
",",
"trace_guid",
":",
"context",
".",
"trace_id",
",",
"span_name",
":",
"operation_name",
",",
"attributes",
":",
"tags",
".",
"map",
"{",
"|",
"key",
",",
"value",
"|",
"{",
"Key",
":",
"key",
".",
"to_s",
",",
"Value",
":",
"value",
"}",
"}",
",",
"oldest_micros",
":",
"start_micros",
",",
"youngest_micros",
":",
"end_micros",
",",
"error_flag",
":",
"false",
",",
"dropped_logs",
":",
"dropped_logs_count",
",",
"log_records",
":",
"log_records",
"}",
"end"
]
| Hash representation of a span | [
"Hash",
"representation",
"of",
"a",
"span"
]
| 72f5669a4afabe81a3fb396cda61c47b7d01ec33 | https://github.com/lightstep/lightstep-tracer-ruby/blob/72f5669a4afabe81a3fb396cda61c47b7d01ec33/lib/lightstep/span.rb#L154-L169 | train |
lightstep/lightstep-tracer-ruby | lib/lightstep/scope_manager.rb | LightStep.ScopeManager.activate | def activate(span:, finish_on_close: true)
return active if active && active.span == span
LightStep::Scope.new(manager: self, span: span, finish_on_close: finish_on_close).tap do |scope|
add_scope(scope)
end
end | ruby | def activate(span:, finish_on_close: true)
return active if active && active.span == span
LightStep::Scope.new(manager: self, span: span, finish_on_close: finish_on_close).tap do |scope|
add_scope(scope)
end
end | [
"def",
"activate",
"(",
"span",
":",
",",
"finish_on_close",
":",
"true",
")",
"return",
"active",
"if",
"active",
"&&",
"active",
".",
"span",
"==",
"span",
"LightStep",
"::",
"Scope",
".",
"new",
"(",
"manager",
":",
"self",
",",
"span",
":",
"span",
",",
"finish_on_close",
":",
"finish_on_close",
")",
".",
"tap",
"do",
"|",
"scope",
"|",
"add_scope",
"(",
"scope",
")",
"end",
"end"
]
| Make a span instance active.
@param span [Span] the Span that should become active
@param finish_on_close [Boolean] whether the Span should automatically be
finished when Scope#close is called
@return [Scope] instance to control the end of the active period for the
Span. It is a programming error to neglect to call Scope#close on the
returned instance. | [
"Make",
"a",
"span",
"instance",
"active",
"."
]
| 72f5669a4afabe81a3fb396cda61c47b7d01ec33 | https://github.com/lightstep/lightstep-tracer-ruby/blob/72f5669a4afabe81a3fb396cda61c47b7d01ec33/lib/lightstep/scope_manager.rb#L19-L24 | train |
NCSU-Libraries/lentil | lib/lentil/instagram_harvester.rb | Lentil.InstagramHarvester.configure_connection | def configure_connection(opts = {})
opts['client_id'] ||= Lentil::Engine::APP_CONFIG["instagram_client_id"]
opts['client_secret'] ||= Lentil::Engine::APP_CONFIG["instagram_client_secret"]
opts['access_token'] ||= Lentil::Engine::APP_CONFIG["instagram_access_token"] || nil
Instagram.configure do |config|
config.client_id = opts['client_id']
config.client_secret = opts['client_secret']
if (opts['access_token'])
config.access_token = opts['access_token']
end
end
end | ruby | def configure_connection(opts = {})
opts['client_id'] ||= Lentil::Engine::APP_CONFIG["instagram_client_id"]
opts['client_secret'] ||= Lentil::Engine::APP_CONFIG["instagram_client_secret"]
opts['access_token'] ||= Lentil::Engine::APP_CONFIG["instagram_access_token"] || nil
Instagram.configure do |config|
config.client_id = opts['client_id']
config.client_secret = opts['client_secret']
if (opts['access_token'])
config.access_token = opts['access_token']
end
end
end | [
"def",
"configure_connection",
"(",
"opts",
"=",
"{",
"}",
")",
"opts",
"[",
"'client_id'",
"]",
"||=",
"Lentil",
"::",
"Engine",
"::",
"APP_CONFIG",
"[",
"\"instagram_client_id\"",
"]",
"opts",
"[",
"'client_secret'",
"]",
"||=",
"Lentil",
"::",
"Engine",
"::",
"APP_CONFIG",
"[",
"\"instagram_client_secret\"",
"]",
"opts",
"[",
"'access_token'",
"]",
"||=",
"Lentil",
"::",
"Engine",
"::",
"APP_CONFIG",
"[",
"\"instagram_access_token\"",
"]",
"||",
"nil",
"Instagram",
".",
"configure",
"do",
"|",
"config",
"|",
"config",
".",
"client_id",
"=",
"opts",
"[",
"'client_id'",
"]",
"config",
".",
"client_secret",
"=",
"opts",
"[",
"'client_secret'",
"]",
"if",
"(",
"opts",
"[",
"'access_token'",
"]",
")",
"config",
".",
"access_token",
"=",
"opts",
"[",
"'access_token'",
"]",
"end",
"end",
"end"
]
| Configure the Instagram class in preparation requests.
@options opts [String] :client_id (Lentil::Engine::APP_CONFIG["instagram_client_id"]) The Instagram client ID
@options opts [String] :client_secret (Lentil::Engine::APP_CONFIG["instagram_client_secret"]) The Instagram client secret
@options opts [String] :access_token (nil) The optional Instagram client ID | [
"Configure",
"the",
"Instagram",
"class",
"in",
"preparation",
"requests",
"."
]
| c31775447a52db1781c05f6724ae293698527fe6 | https://github.com/NCSU-Libraries/lentil/blob/c31775447a52db1781c05f6724ae293698527fe6/lib/lentil/instagram_harvester.rb#L20-L33 | train |
NCSU-Libraries/lentil | lib/lentil/instagram_harvester.rb | Lentil.InstagramHarvester.configure_comment_connection | def configure_comment_connection(access_token = nil)
access_token ||= Lentil::Engine::APP_CONFIG["instagram_access_token"] || nil
raise "instagram_access_token must be defined as a parameter or in the application config" unless access_token
configure_connection({'access_token' => access_token})
end | ruby | def configure_comment_connection(access_token = nil)
access_token ||= Lentil::Engine::APP_CONFIG["instagram_access_token"] || nil
raise "instagram_access_token must be defined as a parameter or in the application config" unless access_token
configure_connection({'access_token' => access_token})
end | [
"def",
"configure_comment_connection",
"(",
"access_token",
"=",
"nil",
")",
"access_token",
"||=",
"Lentil",
"::",
"Engine",
"::",
"APP_CONFIG",
"[",
"\"instagram_access_token\"",
"]",
"||",
"nil",
"raise",
"\"instagram_access_token must be defined as a parameter or in the application config\"",
"unless",
"access_token",
"configure_connection",
"(",
"{",
"'access_token'",
"=>",
"access_token",
"}",
")",
"end"
]
| Configure the Instagram class in preparation for leaving comments
@param access_token = nil [String] Instagram access token for the writing account | [
"Configure",
"the",
"Instagram",
"class",
"in",
"preparation",
"for",
"leaving",
"comments"
]
| c31775447a52db1781c05f6724ae293698527fe6 | https://github.com/NCSU-Libraries/lentil/blob/c31775447a52db1781c05f6724ae293698527fe6/lib/lentil/instagram_harvester.rb#L40-L44 | train |
NCSU-Libraries/lentil | lib/lentil/instagram_harvester.rb | Lentil.InstagramHarvester.fetch_recent_images_by_tag | def fetch_recent_images_by_tag(tag = nil)
configure_connection
tag ||= Lentil::Engine::APP_CONFIG["default_image_search_tag"]
Instagram.tag_recent_media(tag, :count=>10)
end | ruby | def fetch_recent_images_by_tag(tag = nil)
configure_connection
tag ||= Lentil::Engine::APP_CONFIG["default_image_search_tag"]
Instagram.tag_recent_media(tag, :count=>10)
end | [
"def",
"fetch_recent_images_by_tag",
"(",
"tag",
"=",
"nil",
")",
"configure_connection",
"tag",
"||=",
"Lentil",
"::",
"Engine",
"::",
"APP_CONFIG",
"[",
"\"default_image_search_tag\"",
"]",
"Instagram",
".",
"tag_recent_media",
"(",
"tag",
",",
":count",
"=>",
"10",
")",
"end"
]
| Queries the Instagram API for recent images with a given tag.
@param [String] tag The tag to query by
@return [Hashie::Mash] The data returned by Instagram API | [
"Queries",
"the",
"Instagram",
"API",
"for",
"recent",
"images",
"with",
"a",
"given",
"tag",
"."
]
| c31775447a52db1781c05f6724ae293698527fe6 | https://github.com/NCSU-Libraries/lentil/blob/c31775447a52db1781c05f6724ae293698527fe6/lib/lentil/instagram_harvester.rb#L51-L55 | train |
NCSU-Libraries/lentil | lib/lentil/instagram_harvester.rb | Lentil.InstagramHarvester.extract_image_data | def extract_image_data(instagram_metadata)
{
url: instagram_metadata.link,
external_id: instagram_metadata.id,
large_url: instagram_metadata.images.standard_resolution.url,
name: instagram_metadata.caption && instagram_metadata.caption.text,
tags: instagram_metadata.tags,
user: instagram_metadata.user,
original_datetime: Time.at(instagram_metadata.created_time.to_i).to_datetime,
original_metadata: instagram_metadata,
media_type: instagram_metadata.type,
video_url: instagram_metadata.videos && instagram_metadata.videos.standard_resolution.url
}
end | ruby | def extract_image_data(instagram_metadata)
{
url: instagram_metadata.link,
external_id: instagram_metadata.id,
large_url: instagram_metadata.images.standard_resolution.url,
name: instagram_metadata.caption && instagram_metadata.caption.text,
tags: instagram_metadata.tags,
user: instagram_metadata.user,
original_datetime: Time.at(instagram_metadata.created_time.to_i).to_datetime,
original_metadata: instagram_metadata,
media_type: instagram_metadata.type,
video_url: instagram_metadata.videos && instagram_metadata.videos.standard_resolution.url
}
end | [
"def",
"extract_image_data",
"(",
"instagram_metadata",
")",
"{",
"url",
":",
"instagram_metadata",
".",
"link",
",",
"external_id",
":",
"instagram_metadata",
".",
"id",
",",
"large_url",
":",
"instagram_metadata",
".",
"images",
".",
"standard_resolution",
".",
"url",
",",
"name",
":",
"instagram_metadata",
".",
"caption",
"&&",
"instagram_metadata",
".",
"caption",
".",
"text",
",",
"tags",
":",
"instagram_metadata",
".",
"tags",
",",
"user",
":",
"instagram_metadata",
".",
"user",
",",
"original_datetime",
":",
"Time",
".",
"at",
"(",
"instagram_metadata",
".",
"created_time",
".",
"to_i",
")",
".",
"to_datetime",
",",
"original_metadata",
":",
"instagram_metadata",
",",
"media_type",
":",
"instagram_metadata",
".",
"type",
",",
"video_url",
":",
"instagram_metadata",
".",
"videos",
"&&",
"instagram_metadata",
".",
"videos",
".",
"standard_resolution",
".",
"url",
"}",
"end"
]
| Produce processed image metadata from Instagram metadata.
This metadata is accepted by the save_image method.
@param [Hashie::Mash] instagram_metadata The single image metadata returned by Instagram API
@return [Hash] processed image metadata | [
"Produce",
"processed",
"image",
"metadata",
"from",
"Instagram",
"metadata",
".",
"This",
"metadata",
"is",
"accepted",
"by",
"the",
"save_image",
"method",
"."
]
| c31775447a52db1781c05f6724ae293698527fe6 | https://github.com/NCSU-Libraries/lentil/blob/c31775447a52db1781c05f6724ae293698527fe6/lib/lentil/instagram_harvester.rb#L94-L107 | train |
NCSU-Libraries/lentil | lib/lentil/instagram_harvester.rb | Lentil.InstagramHarvester.save_image | def save_image(image_data)
instagram_service = Lentil::Service.where(:name => "Instagram").first
user_record = instagram_service.users.where(:user_name => image_data[:user][:username]).
first_or_create!({:full_name => image_data[:user][:full_name], :bio => image_data[:user][:bio]})
raise DuplicateImageError, "Duplicate image identifier" unless user_record.
images.where(:external_identifier => image_data[:external_id]).first.nil?
image_record = user_record.images.build({
:external_identifier => image_data[:external_id],
:description => image_data[:name],
:url => image_data[:url],
:long_url => image_data[:large_url],
:video_url => image_data[:video_url],
:original_datetime => image_data[:original_datetime],
:media_type => image_data[:media_type]
})
image_record.original_metadata = image_data[:original_metadata].to_hash
# Default to "All Rights Reserved" until we find out more about licenses
# FIXME: Set the default license in the app config
unless image_record.licenses.size > 0
image_record.licenses << Lentil::License.where(:short_name => "ARR").first
end
image_data[:tags].each {|tag| image_record.tags << Lentil::Tag.where(:name => tag).first_or_create}
user_record.save!
image_record.save!
image_record
end | ruby | def save_image(image_data)
instagram_service = Lentil::Service.where(:name => "Instagram").first
user_record = instagram_service.users.where(:user_name => image_data[:user][:username]).
first_or_create!({:full_name => image_data[:user][:full_name], :bio => image_data[:user][:bio]})
raise DuplicateImageError, "Duplicate image identifier" unless user_record.
images.where(:external_identifier => image_data[:external_id]).first.nil?
image_record = user_record.images.build({
:external_identifier => image_data[:external_id],
:description => image_data[:name],
:url => image_data[:url],
:long_url => image_data[:large_url],
:video_url => image_data[:video_url],
:original_datetime => image_data[:original_datetime],
:media_type => image_data[:media_type]
})
image_record.original_metadata = image_data[:original_metadata].to_hash
# Default to "All Rights Reserved" until we find out more about licenses
# FIXME: Set the default license in the app config
unless image_record.licenses.size > 0
image_record.licenses << Lentil::License.where(:short_name => "ARR").first
end
image_data[:tags].each {|tag| image_record.tags << Lentil::Tag.where(:name => tag).first_or_create}
user_record.save!
image_record.save!
image_record
end | [
"def",
"save_image",
"(",
"image_data",
")",
"instagram_service",
"=",
"Lentil",
"::",
"Service",
".",
"where",
"(",
":name",
"=>",
"\"Instagram\"",
")",
".",
"first",
"user_record",
"=",
"instagram_service",
".",
"users",
".",
"where",
"(",
":user_name",
"=>",
"image_data",
"[",
":user",
"]",
"[",
":username",
"]",
")",
".",
"first_or_create!",
"(",
"{",
":full_name",
"=>",
"image_data",
"[",
":user",
"]",
"[",
":full_name",
"]",
",",
":bio",
"=>",
"image_data",
"[",
":user",
"]",
"[",
":bio",
"]",
"}",
")",
"raise",
"DuplicateImageError",
",",
"\"Duplicate image identifier\"",
"unless",
"user_record",
".",
"images",
".",
"where",
"(",
":external_identifier",
"=>",
"image_data",
"[",
":external_id",
"]",
")",
".",
"first",
".",
"nil?",
"image_record",
"=",
"user_record",
".",
"images",
".",
"build",
"(",
"{",
":external_identifier",
"=>",
"image_data",
"[",
":external_id",
"]",
",",
":description",
"=>",
"image_data",
"[",
":name",
"]",
",",
":url",
"=>",
"image_data",
"[",
":url",
"]",
",",
":long_url",
"=>",
"image_data",
"[",
":large_url",
"]",
",",
":video_url",
"=>",
"image_data",
"[",
":video_url",
"]",
",",
":original_datetime",
"=>",
"image_data",
"[",
":original_datetime",
"]",
",",
":media_type",
"=>",
"image_data",
"[",
":media_type",
"]",
"}",
")",
"image_record",
".",
"original_metadata",
"=",
"image_data",
"[",
":original_metadata",
"]",
".",
"to_hash",
"unless",
"image_record",
".",
"licenses",
".",
"size",
">",
"0",
"image_record",
".",
"licenses",
"<<",
"Lentil",
"::",
"License",
".",
"where",
"(",
":short_name",
"=>",
"\"ARR\"",
")",
".",
"first",
"end",
"image_data",
"[",
":tags",
"]",
".",
"each",
"{",
"|",
"tag",
"|",
"image_record",
".",
"tags",
"<<",
"Lentil",
"::",
"Tag",
".",
"where",
"(",
":name",
"=>",
"tag",
")",
".",
"first_or_create",
"}",
"user_record",
".",
"save!",
"image_record",
".",
"save!",
"image_record",
"end"
]
| Takes return from Instagram API gem and adds image,
users, and tags to the database.
@raise [DuplicateImageError] This method does not accept duplicate external image IDs
@param [Hash] image_data processed Instagram image metadata
@return [Image] new Image object | [
"Takes",
"return",
"from",
"Instagram",
"API",
"gem",
"and",
"adds",
"image",
"users",
"and",
"tags",
"to",
"the",
"database",
"."
]
| c31775447a52db1781c05f6724ae293698527fe6 | https://github.com/NCSU-Libraries/lentil/blob/c31775447a52db1781c05f6724ae293698527fe6/lib/lentil/instagram_harvester.rb#L118-L151 | train |
NCSU-Libraries/lentil | lib/lentil/instagram_harvester.rb | Lentil.InstagramHarvester.save_instagram_load | def save_instagram_load(instagram_load, raise_dupes=false)
# Handle collections of images and individual images
images = instagram_load
if !images.kind_of?(Array)
images = [images]
end
images.collect {|image|
begin
save_image(extract_image_data(image))
rescue DuplicateImageError => e
raise e if raise_dupes
next
rescue => e
Rails.logger.error e.message
puts e.message
pp image
next
end
}.compact
end | ruby | def save_instagram_load(instagram_load, raise_dupes=false)
# Handle collections of images and individual images
images = instagram_load
if !images.kind_of?(Array)
images = [images]
end
images.collect {|image|
begin
save_image(extract_image_data(image))
rescue DuplicateImageError => e
raise e if raise_dupes
next
rescue => e
Rails.logger.error e.message
puts e.message
pp image
next
end
}.compact
end | [
"def",
"save_instagram_load",
"(",
"instagram_load",
",",
"raise_dupes",
"=",
"false",
")",
"images",
"=",
"instagram_load",
"if",
"!",
"images",
".",
"kind_of?",
"(",
"Array",
")",
"images",
"=",
"[",
"images",
"]",
"end",
"images",
".",
"collect",
"{",
"|",
"image",
"|",
"begin",
"save_image",
"(",
"extract_image_data",
"(",
"image",
")",
")",
"rescue",
"DuplicateImageError",
"=>",
"e",
"raise",
"e",
"if",
"raise_dupes",
"next",
"rescue",
"=>",
"e",
"Rails",
".",
"logger",
".",
"error",
"e",
".",
"message",
"puts",
"e",
".",
"message",
"pp",
"image",
"next",
"end",
"}",
".",
"compact",
"end"
]
| Takes return from Instagram API gem and adds all new images,
users, and tags to the database.
@param [Hashie::Mash] instagram_load The content returned by the Instagram gem
@param [Boolean] raise_dupes Whether to raise exceptions for duplicate images
@raise [DuplicateImageError] If there are duplicate images and raise_dupes is true
@return [Array] New image objects | [
"Takes",
"return",
"from",
"Instagram",
"API",
"gem",
"and",
"adds",
"all",
"new",
"images",
"users",
"and",
"tags",
"to",
"the",
"database",
"."
]
| c31775447a52db1781c05f6724ae293698527fe6 | https://github.com/NCSU-Libraries/lentil/blob/c31775447a52db1781c05f6724ae293698527fe6/lib/lentil/instagram_harvester.rb#L162-L183 | train |
NCSU-Libraries/lentil | lib/lentil/instagram_harvester.rb | Lentil.InstagramHarvester.harvest_image_data | def harvest_image_data(image)
response = Typhoeus.get(image.large_url(false), followlocation: true)
if response.success?
raise "Invalid content type: " + response.headers['Content-Type'] unless (response.headers['Content-Type'] == 'image/jpeg')
elsif response.timed_out?
raise "Request timed out"
elsif response.code == 0
raise "Could not get an HTTP response"
else
raise "HTTP request failed: " + response.code.to_s
end
response.body
end | ruby | def harvest_image_data(image)
response = Typhoeus.get(image.large_url(false), followlocation: true)
if response.success?
raise "Invalid content type: " + response.headers['Content-Type'] unless (response.headers['Content-Type'] == 'image/jpeg')
elsif response.timed_out?
raise "Request timed out"
elsif response.code == 0
raise "Could not get an HTTP response"
else
raise "HTTP request failed: " + response.code.to_s
end
response.body
end | [
"def",
"harvest_image_data",
"(",
"image",
")",
"response",
"=",
"Typhoeus",
".",
"get",
"(",
"image",
".",
"large_url",
"(",
"false",
")",
",",
"followlocation",
":",
"true",
")",
"if",
"response",
".",
"success?",
"raise",
"\"Invalid content type: \"",
"+",
"response",
".",
"headers",
"[",
"'Content-Type'",
"]",
"unless",
"(",
"response",
".",
"headers",
"[",
"'Content-Type'",
"]",
"==",
"'image/jpeg'",
")",
"elsif",
"response",
".",
"timed_out?",
"raise",
"\"Request timed out\"",
"elsif",
"response",
".",
"code",
"==",
"0",
"raise",
"\"Could not get an HTTP response\"",
"else",
"raise",
"\"HTTP request failed: \"",
"+",
"response",
".",
"code",
".",
"to_s",
"end",
"response",
".",
"body",
"end"
]
| Retrieve the binary image data for a given Image object
@param [Image] image An Image model object from the Instagram service
@raise [Exception] If there are request problems
@return [String] Binary image data | [
"Retrieve",
"the",
"binary",
"image",
"data",
"for",
"a",
"given",
"Image",
"object"
]
| c31775447a52db1781c05f6724ae293698527fe6 | https://github.com/NCSU-Libraries/lentil/blob/c31775447a52db1781c05f6724ae293698527fe6/lib/lentil/instagram_harvester.rb#L206-L220 | train |
NCSU-Libraries/lentil | lib/lentil/instagram_harvester.rb | Lentil.InstagramHarvester.harvest_video_data | def harvest_video_data(image)
response = Typhoeus.get(image.video_url, followlocation: true)
if response.success?
raise "Invalid content type: " + response.headers['Content-Type'] unless (response.headers['Content-Type'] == 'video/mp4')
elsif response.timed_out?
raise "Request timed out"
elsif response.code == 0
raise "Could not get an HTTP response"
else
raise "HTTP request failed: " + response.code.to_s
end
response.body
end | ruby | def harvest_video_data(image)
response = Typhoeus.get(image.video_url, followlocation: true)
if response.success?
raise "Invalid content type: " + response.headers['Content-Type'] unless (response.headers['Content-Type'] == 'video/mp4')
elsif response.timed_out?
raise "Request timed out"
elsif response.code == 0
raise "Could not get an HTTP response"
else
raise "HTTP request failed: " + response.code.to_s
end
response.body
end | [
"def",
"harvest_video_data",
"(",
"image",
")",
"response",
"=",
"Typhoeus",
".",
"get",
"(",
"image",
".",
"video_url",
",",
"followlocation",
":",
"true",
")",
"if",
"response",
".",
"success?",
"raise",
"\"Invalid content type: \"",
"+",
"response",
".",
"headers",
"[",
"'Content-Type'",
"]",
"unless",
"(",
"response",
".",
"headers",
"[",
"'Content-Type'",
"]",
"==",
"'video/mp4'",
")",
"elsif",
"response",
".",
"timed_out?",
"raise",
"\"Request timed out\"",
"elsif",
"response",
".",
"code",
"==",
"0",
"raise",
"\"Could not get an HTTP response\"",
"else",
"raise",
"\"HTTP request failed: \"",
"+",
"response",
".",
"code",
".",
"to_s",
"end",
"response",
".",
"body",
"end"
]
| Retrieve the binary video data for a given Image object
@param [Image] image An Image model object from the Instagram service
@raise [Exception] If there are request problems
@return [String] Binary video data | [
"Retrieve",
"the",
"binary",
"video",
"data",
"for",
"a",
"given",
"Image",
"object"
]
| c31775447a52db1781c05f6724ae293698527fe6 | https://github.com/NCSU-Libraries/lentil/blob/c31775447a52db1781c05f6724ae293698527fe6/lib/lentil/instagram_harvester.rb#L230-L244 | train |
NCSU-Libraries/lentil | lib/lentil/instagram_harvester.rb | Lentil.InstagramHarvester.leave_image_comment | def leave_image_comment(image, comment)
configure_comment_connection
Instagram.client.create_media_comment(image.external_identifier, comment)
end | ruby | def leave_image_comment(image, comment)
configure_comment_connection
Instagram.client.create_media_comment(image.external_identifier, comment)
end | [
"def",
"leave_image_comment",
"(",
"image",
",",
"comment",
")",
"configure_comment_connection",
"Instagram",
".",
"client",
".",
"create_media_comment",
"(",
"image",
".",
"external_identifier",
",",
"comment",
")",
"end"
]
| Leave a comment containing the donor agreement on an Instagram image
@param image [type] An Image model object from the Instagram service
@raise [Exception] If a comment submission fails
@authenticated true
@return [Hashie::Mash] Instagram response | [
"Leave",
"a",
"comment",
"containing",
"the",
"donor",
"agreement",
"on",
"an",
"Instagram",
"image"
]
| c31775447a52db1781c05f6724ae293698527fe6 | https://github.com/NCSU-Libraries/lentil/blob/c31775447a52db1781c05f6724ae293698527fe6/lib/lentil/instagram_harvester.rb#L275-L278 | train |
NCSU-Libraries/lentil | lib/lentil/popularity_calculator.rb | Lentil.PopularityCalculator.calculate_popularity | def calculate_popularity(image)
# A staff like is worth 10 points
if (image.staff_like === false)
staff_like_points = 0
else
staff_like_points = 10
end
# likes have diminishing returns
# 10 likes is 13 points
# 100 likes is 25 points
if image.like_votes_count > 0
like_vote_points = Math::log(image.like_votes_count, 1.5).round
else
like_vote_points = 0
end
# if an image has fewer than 5 battle rounds this is 0
# 5 or more and the points awarded is the win_pct/2
if image.win_pct and image.wins_count + image.losses_count > 4
battle_points = (image.win_pct/1.5).round
else
battle_points = 0
end
battle_points + like_vote_points + staff_like_points
end | ruby | def calculate_popularity(image)
# A staff like is worth 10 points
if (image.staff_like === false)
staff_like_points = 0
else
staff_like_points = 10
end
# likes have diminishing returns
# 10 likes is 13 points
# 100 likes is 25 points
if image.like_votes_count > 0
like_vote_points = Math::log(image.like_votes_count, 1.5).round
else
like_vote_points = 0
end
# if an image has fewer than 5 battle rounds this is 0
# 5 or more and the points awarded is the win_pct/2
if image.win_pct and image.wins_count + image.losses_count > 4
battle_points = (image.win_pct/1.5).round
else
battle_points = 0
end
battle_points + like_vote_points + staff_like_points
end | [
"def",
"calculate_popularity",
"(",
"image",
")",
"if",
"(",
"image",
".",
"staff_like",
"===",
"false",
")",
"staff_like_points",
"=",
"0",
"else",
"staff_like_points",
"=",
"10",
"end",
"if",
"image",
".",
"like_votes_count",
">",
"0",
"like_vote_points",
"=",
"Math",
"::",
"log",
"(",
"image",
".",
"like_votes_count",
",",
"1.5",
")",
".",
"round",
"else",
"like_vote_points",
"=",
"0",
"end",
"if",
"image",
".",
"win_pct",
"and",
"image",
".",
"wins_count",
"+",
"image",
".",
"losses_count",
">",
"4",
"battle_points",
"=",
"(",
"image",
".",
"win_pct",
"/",
"1.5",
")",
".",
"round",
"else",
"battle_points",
"=",
"0",
"end",
"battle_points",
"+",
"like_vote_points",
"+",
"staff_like_points",
"end"
]
| Takes image object and returns a popularity score
@param [object] image object with image data
@return [integer] popularity score of image | [
"Takes",
"image",
"object",
"and",
"returns",
"a",
"popularity",
"score"
]
| c31775447a52db1781c05f6724ae293698527fe6 | https://github.com/NCSU-Libraries/lentil/blob/c31775447a52db1781c05f6724ae293698527fe6/lib/lentil/popularity_calculator.rb#L9-L37 | train |
NCSU-Libraries/lentil | lib/lentil/popularity_calculator.rb | Lentil.PopularityCalculator.update_image_popularity_score | def update_image_popularity_score(image_to_update = :all)
def get_score_write_to_db(image)
popularity_score = calculate_popularity(image)
image.update_attribute(:popular_score, popularity_score)
end
if image_to_update == :all
images = Lentil::Image.find(image_to_update)
images.each do |image|
get_score_write_to_db(image)
end
elsif image_to_update.kind_of?(Integer)
image = Lentil::Image.find(image_to_update)
get_score_write_to_db(image)
end
end | ruby | def update_image_popularity_score(image_to_update = :all)
def get_score_write_to_db(image)
popularity_score = calculate_popularity(image)
image.update_attribute(:popular_score, popularity_score)
end
if image_to_update == :all
images = Lentil::Image.find(image_to_update)
images.each do |image|
get_score_write_to_db(image)
end
elsif image_to_update.kind_of?(Integer)
image = Lentil::Image.find(image_to_update)
get_score_write_to_db(image)
end
end | [
"def",
"update_image_popularity_score",
"(",
"image_to_update",
"=",
":all",
")",
"def",
"get_score_write_to_db",
"(",
"image",
")",
"popularity_score",
"=",
"calculate_popularity",
"(",
"image",
")",
"image",
".",
"update_attribute",
"(",
":popular_score",
",",
"popularity_score",
")",
"end",
"if",
"image_to_update",
"==",
":all",
"images",
"=",
"Lentil",
"::",
"Image",
".",
"find",
"(",
"image_to_update",
")",
"images",
".",
"each",
"do",
"|",
"image",
"|",
"get_score_write_to_db",
"(",
"image",
")",
"end",
"elsif",
"image_to_update",
".",
"kind_of?",
"(",
"Integer",
")",
"image",
"=",
"Lentil",
"::",
"Image",
".",
"find",
"(",
"image_to_update",
")",
"get_score_write_to_db",
"(",
"image",
")",
"end",
"end"
]
| Takes an image id and updates its popularity score
@param [integer] id of image to update defaults to :all
@return [boolean] success/failure of update | [
"Takes",
"an",
"image",
"id",
"and",
"updates",
"its",
"popularity",
"score"
]
| c31775447a52db1781c05f6724ae293698527fe6 | https://github.com/NCSU-Libraries/lentil/blob/c31775447a52db1781c05f6724ae293698527fe6/lib/lentil/popularity_calculator.rb#L44-L60 | train |
gaffneyc/usps | lib/usps/request/city_and_state_lookup.rb | USPS::Request.CityAndStateLookup.build | def build
super do |builder|
@zip_codes.each_with_index do |zip, i|
builder.tag!('ZipCode', :ID => i) do
builder.tag!('Zip5', zip)
end
end
end
end | ruby | def build
super do |builder|
@zip_codes.each_with_index do |zip, i|
builder.tag!('ZipCode', :ID => i) do
builder.tag!('Zip5', zip)
end
end
end
end | [
"def",
"build",
"super",
"do",
"|",
"builder",
"|",
"@zip_codes",
".",
"each_with_index",
"do",
"|",
"zip",
",",
"i",
"|",
"builder",
".",
"tag!",
"(",
"'ZipCode'",
",",
":ID",
"=>",
"i",
")",
"do",
"builder",
".",
"tag!",
"(",
"'Zip5'",
",",
"zip",
")",
"end",
"end",
"end",
"end"
]
| Given a list of zip codes, looks up what city and state they are associated with.
The USPS api is only capable of handling at most 5 zip codes per request. | [
"Given",
"a",
"list",
"of",
"zip",
"codes",
"looks",
"up",
"what",
"city",
"and",
"state",
"they",
"are",
"associated",
"with",
"."
]
| 77020c04a5207e0e0cbc7deab2024a1ec39ee738 | https://github.com/gaffneyc/usps/blob/77020c04a5207e0e0cbc7deab2024a1ec39ee738/lib/usps/request/city_and_state_lookup.rb#L22-L30 | train |
plexus/yaks | yaks/lib/yaks/configurable.rb | Yaks.Configurable.def_set | def def_set(*method_names)
method_names.each do |method_name|
define_singleton_method method_name do |arg = Undefined, &block|
if arg.equal?(Undefined)
unless block
raise ArgumentError, "setting #{method_name}: no value and no block given"
end
self.config = config.with(method_name => block)
else
if block
raise ArgumentError, "ambiguous invocation setting #{method_name}: give either a value or a block, not both."
end
self.config = config.with(method_name => arg)
end
end
end
end | ruby | def def_set(*method_names)
method_names.each do |method_name|
define_singleton_method method_name do |arg = Undefined, &block|
if arg.equal?(Undefined)
unless block
raise ArgumentError, "setting #{method_name}: no value and no block given"
end
self.config = config.with(method_name => block)
else
if block
raise ArgumentError, "ambiguous invocation setting #{method_name}: give either a value or a block, not both."
end
self.config = config.with(method_name => arg)
end
end
end
end | [
"def",
"def_set",
"(",
"*",
"method_names",
")",
"method_names",
".",
"each",
"do",
"|",
"method_name",
"|",
"define_singleton_method",
"method_name",
"do",
"|",
"arg",
"=",
"Undefined",
",",
"&",
"block",
"|",
"if",
"arg",
".",
"equal?",
"(",
"Undefined",
")",
"unless",
"block",
"raise",
"ArgumentError",
",",
"\"setting #{method_name}: no value and no block given\"",
"end",
"self",
".",
"config",
"=",
"config",
".",
"with",
"(",
"method_name",
"=>",
"block",
")",
"else",
"if",
"block",
"raise",
"ArgumentError",
",",
"\"ambiguous invocation setting #{method_name}: give either a value or a block, not both.\"",
"end",
"self",
".",
"config",
"=",
"config",
".",
"with",
"(",
"method_name",
"=>",
"arg",
")",
"end",
"end",
"end",
"end"
]
| Create a DSL method to set a certain config property. The
generated method will take either a plain value, or a block,
which will be captured and stored instead. | [
"Create",
"a",
"DSL",
"method",
"to",
"set",
"a",
"certain",
"config",
"property",
".",
"The",
"generated",
"method",
"will",
"take",
"either",
"a",
"plain",
"value",
"or",
"a",
"block",
"which",
"will",
"be",
"captured",
"and",
"stored",
"instead",
"."
]
| 75c41e5d9c56cbb12ec95385d725676175f04f06 | https://github.com/plexus/yaks/blob/75c41e5d9c56cbb12ec95385d725676175f04f06/yaks/lib/yaks/configurable.rb#L34-L50 | train |
plexus/yaks | yaks/lib/yaks/configurable.rb | Yaks.Configurable.def_forward | def def_forward(mappings, *names)
if mappings.instance_of? Hash
mappings.each do |method_name, target|
define_singleton_method method_name do |*args, &block|
self.config = config.public_send(target, *args, &block)
end
end
else
def_forward([mappings, *names].map{|name| {name => name}}.inject(:merge))
end
end | ruby | def def_forward(mappings, *names)
if mappings.instance_of? Hash
mappings.each do |method_name, target|
define_singleton_method method_name do |*args, &block|
self.config = config.public_send(target, *args, &block)
end
end
else
def_forward([mappings, *names].map{|name| {name => name}}.inject(:merge))
end
end | [
"def",
"def_forward",
"(",
"mappings",
",",
"*",
"names",
")",
"if",
"mappings",
".",
"instance_of?",
"Hash",
"mappings",
".",
"each",
"do",
"|",
"method_name",
",",
"target",
"|",
"define_singleton_method",
"method_name",
"do",
"|",
"*",
"args",
",",
"&",
"block",
"|",
"self",
".",
"config",
"=",
"config",
".",
"public_send",
"(",
"target",
",",
"*",
"args",
",",
"&",
"block",
")",
"end",
"end",
"else",
"def_forward",
"(",
"[",
"mappings",
",",
"*",
"names",
"]",
".",
"map",
"{",
"|",
"name",
"|",
"{",
"name",
"=>",
"name",
"}",
"}",
".",
"inject",
"(",
":merge",
")",
")",
"end",
"end"
]
| Forward a method to the config object. This assumes the method
will return an updated config instance.
Either takes a list of methods to forward, or a mapping (hash)
of source to destination method name. | [
"Forward",
"a",
"method",
"to",
"the",
"config",
"object",
".",
"This",
"assumes",
"the",
"method",
"will",
"return",
"an",
"updated",
"config",
"instance",
"."
]
| 75c41e5d9c56cbb12ec95385d725676175f04f06 | https://github.com/plexus/yaks/blob/75c41e5d9c56cbb12ec95385d725676175f04f06/yaks/lib/yaks/configurable.rb#L57-L67 | train |
plexus/yaks | yaks/lib/yaks/configurable.rb | Yaks.Configurable.def_add | def def_add(name, options)
old_verbose, $VERBOSE = $VERBOSE, false # skip method redefinition warning
define_singleton_method name do |*args, &block|
defaults = options.fetch(:defaults, {})
klass = options.fetch(:create)
if args.last.instance_of?(Hash)
args[-1] = defaults.merge(args[-1])
else
args << defaults
end
self.config = config.append_to(
options.fetch(:append_to),
klass.create(*args, &block)
)
end
ensure
$VERBOSE = old_verbose
end | ruby | def def_add(name, options)
old_verbose, $VERBOSE = $VERBOSE, false # skip method redefinition warning
define_singleton_method name do |*args, &block|
defaults = options.fetch(:defaults, {})
klass = options.fetch(:create)
if args.last.instance_of?(Hash)
args[-1] = defaults.merge(args[-1])
else
args << defaults
end
self.config = config.append_to(
options.fetch(:append_to),
klass.create(*args, &block)
)
end
ensure
$VERBOSE = old_verbose
end | [
"def",
"def_add",
"(",
"name",
",",
"options",
")",
"old_verbose",
",",
"$VERBOSE",
"=",
"$VERBOSE",
",",
"false",
"define_singleton_method",
"name",
"do",
"|",
"*",
"args",
",",
"&",
"block",
"|",
"defaults",
"=",
"options",
".",
"fetch",
"(",
":defaults",
",",
"{",
"}",
")",
"klass",
"=",
"options",
".",
"fetch",
"(",
":create",
")",
"if",
"args",
".",
"last",
".",
"instance_of?",
"(",
"Hash",
")",
"args",
"[",
"-",
"1",
"]",
"=",
"defaults",
".",
"merge",
"(",
"args",
"[",
"-",
"1",
"]",
")",
"else",
"args",
"<<",
"defaults",
"end",
"self",
".",
"config",
"=",
"config",
".",
"append_to",
"(",
"options",
".",
"fetch",
"(",
":append_to",
")",
",",
"klass",
".",
"create",
"(",
"*",
"args",
",",
"&",
"block",
")",
")",
"end",
"ensure",
"$VERBOSE",
"=",
"old_verbose",
"end"
]
| Generate a DSL method that creates a certain type of domain
object, and adds it to a list on the config.
def_add :fieldset, create: Fieldset, append_to: :fields
This will generate a `fieldset` method, which will call
`Fieldset.create`, and append the result to `config.fields` | [
"Generate",
"a",
"DSL",
"method",
"that",
"creates",
"a",
"certain",
"type",
"of",
"domain",
"object",
"and",
"adds",
"it",
"to",
"a",
"list",
"on",
"the",
"config",
"."
]
| 75c41e5d9c56cbb12ec95385d725676175f04f06 | https://github.com/plexus/yaks/blob/75c41e5d9c56cbb12ec95385d725676175f04f06/yaks/lib/yaks/configurable.rb#L76-L95 | train |
plexus/yaks | yaks/lib/yaks/default_policy.rb | Yaks.DefaultPolicy.derive_mapper_from_collection | def derive_mapper_from_collection(collection)
if m = collection.first
name = "#{m.class.name.split('::').last}CollectionMapper"
begin
return @options[:namespace].const_get(name)
rescue NameError # rubocop:disable Lint/HandleExceptions
end
end
begin
return @options[:namespace].const_get(:CollectionMapper)
rescue NameError # rubocop:disable Lint/HandleExceptions
end
CollectionMapper
end | ruby | def derive_mapper_from_collection(collection)
if m = collection.first
name = "#{m.class.name.split('::').last}CollectionMapper"
begin
return @options[:namespace].const_get(name)
rescue NameError # rubocop:disable Lint/HandleExceptions
end
end
begin
return @options[:namespace].const_get(:CollectionMapper)
rescue NameError # rubocop:disable Lint/HandleExceptions
end
CollectionMapper
end | [
"def",
"derive_mapper_from_collection",
"(",
"collection",
")",
"if",
"m",
"=",
"collection",
".",
"first",
"name",
"=",
"\"#{m.class.name.split('::').last}CollectionMapper\"",
"begin",
"return",
"@options",
"[",
":namespace",
"]",
".",
"const_get",
"(",
"name",
")",
"rescue",
"NameError",
"end",
"end",
"begin",
"return",
"@options",
"[",
":namespace",
"]",
".",
"const_get",
"(",
":CollectionMapper",
")",
"rescue",
"NameError",
"end",
"CollectionMapper",
"end"
]
| Derives a mapper from the given collection.
@param collection [Object]
@return [Class] A mapper, typically a subclass of Yaks::Mapper | [
"Derives",
"a",
"mapper",
"from",
"the",
"given",
"collection",
"."
]
| 75c41e5d9c56cbb12ec95385d725676175f04f06 | https://github.com/plexus/yaks/blob/75c41e5d9c56cbb12ec95385d725676175f04f06/yaks/lib/yaks/default_policy.rb#L41-L54 | train |
plexus/yaks | yaks/lib/yaks/default_policy.rb | Yaks.DefaultPolicy.derive_mapper_from_item | def derive_mapper_from_item(item)
klass = item.class
namespaces = klass.name.split("::")[0...-1]
begin
return build_mapper_class(namespaces, klass)
rescue NameError
klass = next_class_for_lookup(item, namespaces, klass)
retry if klass
end
raise_mapper_not_found(item)
end | ruby | def derive_mapper_from_item(item)
klass = item.class
namespaces = klass.name.split("::")[0...-1]
begin
return build_mapper_class(namespaces, klass)
rescue NameError
klass = next_class_for_lookup(item, namespaces, klass)
retry if klass
end
raise_mapper_not_found(item)
end | [
"def",
"derive_mapper_from_item",
"(",
"item",
")",
"klass",
"=",
"item",
".",
"class",
"namespaces",
"=",
"klass",
".",
"name",
".",
"split",
"(",
"\"::\"",
")",
"[",
"0",
"...",
"-",
"1",
"]",
"begin",
"return",
"build_mapper_class",
"(",
"namespaces",
",",
"klass",
")",
"rescue",
"NameError",
"klass",
"=",
"next_class_for_lookup",
"(",
"item",
",",
"namespaces",
",",
"klass",
")",
"retry",
"if",
"klass",
"end",
"raise_mapper_not_found",
"(",
"item",
")",
"end"
]
| Derives a mapper from the given item. This item should not
be a collection.
@param item [Object]
@return [Class] A mapper, typically a subclass of Yaks::Mapper
@raise [RuntimeError] only occurs when no mapper is found for the given item. | [
"Derives",
"a",
"mapper",
"from",
"the",
"given",
"item",
".",
"This",
"item",
"should",
"not",
"be",
"a",
"collection",
"."
]
| 75c41e5d9c56cbb12ec95385d725676175f04f06 | https://github.com/plexus/yaks/blob/75c41e5d9c56cbb12ec95385d725676175f04f06/yaks/lib/yaks/default_policy.rb#L63-L73 | train |
benedikt/mongoid-tree | lib/mongoid/tree.rb | Mongoid.Tree.root | def root
if parent_ids.present?
base_class.find(parent_ids.first)
else
self.root? ? self : self.parent.root
end
end | ruby | def root
if parent_ids.present?
base_class.find(parent_ids.first)
else
self.root? ? self : self.parent.root
end
end | [
"def",
"root",
"if",
"parent_ids",
".",
"present?",
"base_class",
".",
"find",
"(",
"parent_ids",
".",
"first",
")",
"else",
"self",
".",
"root?",
"?",
"self",
":",
"self",
".",
"parent",
".",
"root",
"end",
"end"
]
| Returns this document's root node. Returns `self` if the
current document is a root node
@example
node = Node.find(...)
node.root
@return [Mongoid::Document] The documents root node | [
"Returns",
"this",
"document",
"s",
"root",
"node",
".",
"Returns",
"self",
"if",
"the",
"current",
"document",
"is",
"a",
"root",
"node"
]
| 0970a945a16a1539511f6dd2017e78f1ba54d4bd | https://github.com/benedikt/mongoid-tree/blob/0970a945a16a1539511f6dd2017e78f1ba54d4bd/lib/mongoid/tree.rb#L277-L283 | train |
benedikt/mongoid-tree | lib/mongoid/tree.rb | Mongoid.Tree.nullify_children | def nullify_children
children.each do |c|
c.parent = c.parent_id = nil
c.save
end
end | ruby | def nullify_children
children.each do |c|
c.parent = c.parent_id = nil
c.save
end
end | [
"def",
"nullify_children",
"children",
".",
"each",
"do",
"|",
"c",
"|",
"c",
".",
"parent",
"=",
"c",
".",
"parent_id",
"=",
"nil",
"c",
".",
"save",
"end",
"end"
]
| Nullifies all children's parent_id
@return [undefined] | [
"Nullifies",
"all",
"children",
"s",
"parent_id"
]
| 0970a945a16a1539511f6dd2017e78f1ba54d4bd | https://github.com/benedikt/mongoid-tree/blob/0970a945a16a1539511f6dd2017e78f1ba54d4bd/lib/mongoid/tree.rb#L391-L396 | train |
benedikt/mongoid-tree | lib/mongoid/tree.rb | Mongoid.Tree.rearrange | def rearrange
if self.parent_id
self.parent_ids = parent.parent_ids + [self.parent_id]
else
self.parent_ids = []
end
self.depth = parent_ids.size
rearrange_children! if self.parent_ids_changed?
end | ruby | def rearrange
if self.parent_id
self.parent_ids = parent.parent_ids + [self.parent_id]
else
self.parent_ids = []
end
self.depth = parent_ids.size
rearrange_children! if self.parent_ids_changed?
end | [
"def",
"rearrange",
"if",
"self",
".",
"parent_id",
"self",
".",
"parent_ids",
"=",
"parent",
".",
"parent_ids",
"+",
"[",
"self",
".",
"parent_id",
"]",
"else",
"self",
".",
"parent_ids",
"=",
"[",
"]",
"end",
"self",
".",
"depth",
"=",
"parent_ids",
".",
"size",
"rearrange_children!",
"if",
"self",
".",
"parent_ids_changed?",
"end"
]
| Updates the parent_ids and marks the children for
rearrangement when the parent_ids changed
@private
@return [undefined] | [
"Updates",
"the",
"parent_ids",
"and",
"marks",
"the",
"children",
"for",
"rearrangement",
"when",
"the",
"parent_ids",
"changed"
]
| 0970a945a16a1539511f6dd2017e78f1ba54d4bd | https://github.com/benedikt/mongoid-tree/blob/0970a945a16a1539511f6dd2017e78f1ba54d4bd/lib/mongoid/tree.rb#L433-L443 | train |
intercom/cocoapods-mangle | lib/cocoapods_mangle/config.rb | CocoapodsMangle.Config.needs_update? | def needs_update?
return true unless File.exist?(@context.xcconfig_path)
xcconfig_hash = Xcodeproj::Config.new(File.new(@context.xcconfig_path)).to_hash
needs_update = xcconfig_hash[MANGLED_SPECS_CHECKSUM_XCCONFIG_KEY] != @context.specs_checksum
Pod::UI.message '- Mangling config already up to date' unless needs_update
needs_update
end | ruby | def needs_update?
return true unless File.exist?(@context.xcconfig_path)
xcconfig_hash = Xcodeproj::Config.new(File.new(@context.xcconfig_path)).to_hash
needs_update = xcconfig_hash[MANGLED_SPECS_CHECKSUM_XCCONFIG_KEY] != @context.specs_checksum
Pod::UI.message '- Mangling config already up to date' unless needs_update
needs_update
end | [
"def",
"needs_update?",
"return",
"true",
"unless",
"File",
".",
"exist?",
"(",
"@context",
".",
"xcconfig_path",
")",
"xcconfig_hash",
"=",
"Xcodeproj",
"::",
"Config",
".",
"new",
"(",
"File",
".",
"new",
"(",
"@context",
".",
"xcconfig_path",
")",
")",
".",
"to_hash",
"needs_update",
"=",
"xcconfig_hash",
"[",
"MANGLED_SPECS_CHECKSUM_XCCONFIG_KEY",
"]",
"!=",
"@context",
".",
"specs_checksum",
"Pod",
"::",
"UI",
".",
"message",
"'- Mangling config already up to date'",
"unless",
"needs_update",
"needs_update",
"end"
]
| Does the mangling xcconfig need to be updated?
@return [Truthy] Does the xcconfig need to be updated? | [
"Does",
"the",
"mangling",
"xcconfig",
"need",
"to",
"be",
"updated?"
]
| aaec3e68b578eb61185aa0895568a9316c24a05c | https://github.com/intercom/cocoapods-mangle/blob/aaec3e68b578eb61185aa0895568a9316c24a05c/lib/cocoapods_mangle/config.rb#L42-L48 | train |
intercom/cocoapods-mangle | lib/cocoapods_mangle/config.rb | CocoapodsMangle.Config.update_pod_xcconfigs_for_mangling! | def update_pod_xcconfigs_for_mangling!
Pod::UI.message '- Updating Pod xcconfig files' do
@context.pod_xcconfig_paths.each do |pod_xcconfig_path|
Pod::UI.message "- Updating '#{File.basename(pod_xcconfig_path)}'"
update_pod_xcconfig_for_mangling!(pod_xcconfig_path)
end
end
end | ruby | def update_pod_xcconfigs_for_mangling!
Pod::UI.message '- Updating Pod xcconfig files' do
@context.pod_xcconfig_paths.each do |pod_xcconfig_path|
Pod::UI.message "- Updating '#{File.basename(pod_xcconfig_path)}'"
update_pod_xcconfig_for_mangling!(pod_xcconfig_path)
end
end
end | [
"def",
"update_pod_xcconfigs_for_mangling!",
"Pod",
"::",
"UI",
".",
"message",
"'- Updating Pod xcconfig files'",
"do",
"@context",
".",
"pod_xcconfig_paths",
".",
"each",
"do",
"|",
"pod_xcconfig_path",
"|",
"Pod",
"::",
"UI",
".",
"message",
"\"- Updating '#{File.basename(pod_xcconfig_path)}'\"",
"update_pod_xcconfig_for_mangling!",
"(",
"pod_xcconfig_path",
")",
"end",
"end",
"end"
]
| Update all pod xcconfigs to use the mangling defines | [
"Update",
"all",
"pod",
"xcconfigs",
"to",
"use",
"the",
"mangling",
"defines"
]
| aaec3e68b578eb61185aa0895568a9316c24a05c | https://github.com/intercom/cocoapods-mangle/blob/aaec3e68b578eb61185aa0895568a9316c24a05c/lib/cocoapods_mangle/config.rb#L51-L58 | train |
intercom/cocoapods-mangle | lib/cocoapods_mangle/config.rb | CocoapodsMangle.Config.update_pod_xcconfig_for_mangling! | def update_pod_xcconfig_for_mangling!(pod_xcconfig_path)
mangle_xcconfig_include = "#include \"#{@context.xcconfig_path}\"\n"
gcc_preprocessor_defs = File.readlines(pod_xcconfig_path).select { |line| line =~ /GCC_PREPROCESSOR_DEFINITIONS/ }.first
gcc_preprocessor_defs.strip!
xcconfig_contents = File.read(pod_xcconfig_path)
# import the mangling config
new_xcconfig_contents = mangle_xcconfig_include + xcconfig_contents
# update GCC_PREPROCESSOR_DEFINITIONS to include mangling
new_xcconfig_contents.sub!(gcc_preprocessor_defs, gcc_preprocessor_defs + " $(#{MANGLING_DEFINES_XCCONFIG_KEY})")
File.open(pod_xcconfig_path, 'w') { |pod_xcconfig| pod_xcconfig.write(new_xcconfig_contents) }
end | ruby | def update_pod_xcconfig_for_mangling!(pod_xcconfig_path)
mangle_xcconfig_include = "#include \"#{@context.xcconfig_path}\"\n"
gcc_preprocessor_defs = File.readlines(pod_xcconfig_path).select { |line| line =~ /GCC_PREPROCESSOR_DEFINITIONS/ }.first
gcc_preprocessor_defs.strip!
xcconfig_contents = File.read(pod_xcconfig_path)
# import the mangling config
new_xcconfig_contents = mangle_xcconfig_include + xcconfig_contents
# update GCC_PREPROCESSOR_DEFINITIONS to include mangling
new_xcconfig_contents.sub!(gcc_preprocessor_defs, gcc_preprocessor_defs + " $(#{MANGLING_DEFINES_XCCONFIG_KEY})")
File.open(pod_xcconfig_path, 'w') { |pod_xcconfig| pod_xcconfig.write(new_xcconfig_contents) }
end | [
"def",
"update_pod_xcconfig_for_mangling!",
"(",
"pod_xcconfig_path",
")",
"mangle_xcconfig_include",
"=",
"\"#include \\\"#{@context.xcconfig_path}\\\"\\n\"",
"gcc_preprocessor_defs",
"=",
"File",
".",
"readlines",
"(",
"pod_xcconfig_path",
")",
".",
"select",
"{",
"|",
"line",
"|",
"line",
"=~",
"/",
"/",
"}",
".",
"first",
"gcc_preprocessor_defs",
".",
"strip!",
"xcconfig_contents",
"=",
"File",
".",
"read",
"(",
"pod_xcconfig_path",
")",
"new_xcconfig_contents",
"=",
"mangle_xcconfig_include",
"+",
"xcconfig_contents",
"new_xcconfig_contents",
".",
"sub!",
"(",
"gcc_preprocessor_defs",
",",
"gcc_preprocessor_defs",
"+",
"\" $(#{MANGLING_DEFINES_XCCONFIG_KEY})\"",
")",
"File",
".",
"open",
"(",
"pod_xcconfig_path",
",",
"'w'",
")",
"{",
"|",
"pod_xcconfig",
"|",
"pod_xcconfig",
".",
"write",
"(",
"new_xcconfig_contents",
")",
"}",
"end"
]
| Update a mangling config to use the mangling defines
@param [String] pod_xcconfig_path
Path to the pod xcconfig to update | [
"Update",
"a",
"mangling",
"config",
"to",
"use",
"the",
"mangling",
"defines"
]
| aaec3e68b578eb61185aa0895568a9316c24a05c | https://github.com/intercom/cocoapods-mangle/blob/aaec3e68b578eb61185aa0895568a9316c24a05c/lib/cocoapods_mangle/config.rb#L63-L75 | train |
HipByte/motion-cocoapods | lib/motion/project/cocoapods.rb | Motion::Project.CocoaPods.configure_project | def configure_project
if (xcconfig = self.pods_xcconfig_hash) && ldflags = xcconfig['OTHER_LDFLAGS']
@config.resources_dirs << resources_dir.to_s
frameworks = installed_frameworks[:pre_built]
if frameworks
@config.embedded_frameworks += frameworks
@config.embedded_frameworks.uniq!
end
if @use_frameworks
configure_project_frameworks
else
configure_project_static_libraries
end
end
end | ruby | def configure_project
if (xcconfig = self.pods_xcconfig_hash) && ldflags = xcconfig['OTHER_LDFLAGS']
@config.resources_dirs << resources_dir.to_s
frameworks = installed_frameworks[:pre_built]
if frameworks
@config.embedded_frameworks += frameworks
@config.embedded_frameworks.uniq!
end
if @use_frameworks
configure_project_frameworks
else
configure_project_static_libraries
end
end
end | [
"def",
"configure_project",
"if",
"(",
"xcconfig",
"=",
"self",
".",
"pods_xcconfig_hash",
")",
"&&",
"ldflags",
"=",
"xcconfig",
"[",
"'OTHER_LDFLAGS'",
"]",
"@config",
".",
"resources_dirs",
"<<",
"resources_dir",
".",
"to_s",
"frameworks",
"=",
"installed_frameworks",
"[",
":pre_built",
"]",
"if",
"frameworks",
"@config",
".",
"embedded_frameworks",
"+=",
"frameworks",
"@config",
".",
"embedded_frameworks",
".",
"uniq!",
"end",
"if",
"@use_frameworks",
"configure_project_frameworks",
"else",
"configure_project_static_libraries",
"end",
"end",
"end"
]
| Adds the Pods project to the RubyMotion config as a vendored project and | [
"Adds",
"the",
"Pods",
"project",
"to",
"the",
"RubyMotion",
"config",
"as",
"a",
"vendored",
"project",
"and"
]
| 005ffa50fdbe6074c7933e689d709e1a609f2a8a | https://github.com/HipByte/motion-cocoapods/blob/005ffa50fdbe6074c7933e689d709e1a609f2a8a/lib/motion/project/cocoapods.rb#L111-L127 | train |
HipByte/motion-cocoapods | lib/motion/project/cocoapods.rb | Motion::Project.CocoaPods.install! | def install!(update)
FileUtils.rm_rf(resources_dir)
pods_installer.update = update
pods_installer.installation_options.integrate_targets = false
pods_installer.install!
install_resources
copy_cocoapods_env_and_prefix_headers
end | ruby | def install!(update)
FileUtils.rm_rf(resources_dir)
pods_installer.update = update
pods_installer.installation_options.integrate_targets = false
pods_installer.install!
install_resources
copy_cocoapods_env_and_prefix_headers
end | [
"def",
"install!",
"(",
"update",
")",
"FileUtils",
".",
"rm_rf",
"(",
"resources_dir",
")",
"pods_installer",
".",
"update",
"=",
"update",
"pods_installer",
".",
"installation_options",
".",
"integrate_targets",
"=",
"false",
"pods_installer",
".",
"install!",
"install_resources",
"copy_cocoapods_env_and_prefix_headers",
"end"
]
| Performs a CocoaPods Installation.
For now we only support one Pods target, this will have to be expanded
once we work on more spec support.
Let RubyMotion re-generate the BridgeSupport file whenever the list of
installed pods changes. | [
"Performs",
"a",
"CocoaPods",
"Installation",
"."
]
| 005ffa50fdbe6074c7933e689d709e1a609f2a8a | https://github.com/HipByte/motion-cocoapods/blob/005ffa50fdbe6074c7933e689d709e1a609f2a8a/lib/motion/project/cocoapods.rb#L236-L244 | train |
HipByte/motion-cocoapods | lib/motion/project/cocoapods.rb | Motion::Project.CocoaPods.resources | def resources
resources = []
script = Pathname.new(@config.project_dir) + SUPPORT_FILES + "Pods-#{TARGET_NAME}-resources.sh"
return resources unless File.exist?(script)
File.open(script) { |f|
f.each_line do |line|
if matched = line.match(/install_resource\s+(.*)/)
path = (matched[1].strip)[1..-2]
if path.start_with?('${PODS_ROOT}')
path = path.sub('${PODS_ROOT}/', '')
end
if path.include?("$PODS_CONFIGURATION_BUILD_DIR")
path = File.join(".build", File.basename(path))
end
unless File.extname(path) == '.framework'
resources << Pathname.new(@config.project_dir) + PODS_ROOT + path
end
end
end
}
resources.uniq
end | ruby | def resources
resources = []
script = Pathname.new(@config.project_dir) + SUPPORT_FILES + "Pods-#{TARGET_NAME}-resources.sh"
return resources unless File.exist?(script)
File.open(script) { |f|
f.each_line do |line|
if matched = line.match(/install_resource\s+(.*)/)
path = (matched[1].strip)[1..-2]
if path.start_with?('${PODS_ROOT}')
path = path.sub('${PODS_ROOT}/', '')
end
if path.include?("$PODS_CONFIGURATION_BUILD_DIR")
path = File.join(".build", File.basename(path))
end
unless File.extname(path) == '.framework'
resources << Pathname.new(@config.project_dir) + PODS_ROOT + path
end
end
end
}
resources.uniq
end | [
"def",
"resources",
"resources",
"=",
"[",
"]",
"script",
"=",
"Pathname",
".",
"new",
"(",
"@config",
".",
"project_dir",
")",
"+",
"SUPPORT_FILES",
"+",
"\"Pods-#{TARGET_NAME}-resources.sh\"",
"return",
"resources",
"unless",
"File",
".",
"exist?",
"(",
"script",
")",
"File",
".",
"open",
"(",
"script",
")",
"{",
"|",
"f",
"|",
"f",
".",
"each_line",
"do",
"|",
"line",
"|",
"if",
"matched",
"=",
"line",
".",
"match",
"(",
"/",
"\\s",
"/",
")",
"path",
"=",
"(",
"matched",
"[",
"1",
"]",
".",
"strip",
")",
"[",
"1",
"..",
"-",
"2",
"]",
"if",
"path",
".",
"start_with?",
"(",
"'${PODS_ROOT}'",
")",
"path",
"=",
"path",
".",
"sub",
"(",
"'${PODS_ROOT}/'",
",",
"''",
")",
"end",
"if",
"path",
".",
"include?",
"(",
"\"$PODS_CONFIGURATION_BUILD_DIR\"",
")",
"path",
"=",
"File",
".",
"join",
"(",
"\".build\"",
",",
"File",
".",
"basename",
"(",
"path",
")",
")",
"end",
"unless",
"File",
".",
"extname",
"(",
"path",
")",
"==",
"'.framework'",
"resources",
"<<",
"Pathname",
".",
"new",
"(",
"@config",
".",
"project_dir",
")",
"+",
"PODS_ROOT",
"+",
"path",
"end",
"end",
"end",
"}",
"resources",
".",
"uniq",
"end"
]
| Do not copy `.framework` bundles, these should be handled through RM's
`embedded_frameworks` config attribute. | [
"Do",
"not",
"copy",
".",
"framework",
"bundles",
"these",
"should",
"be",
"handled",
"through",
"RM",
"s",
"embedded_frameworks",
"config",
"attribute",
"."
]
| 005ffa50fdbe6074c7933e689d709e1a609f2a8a | https://github.com/HipByte/motion-cocoapods/blob/005ffa50fdbe6074c7933e689d709e1a609f2a8a/lib/motion/project/cocoapods.rb#L500-L521 | train |
michaeledgar/laser | lib/laser/support/acts_as_struct.rb | Laser.ActsAsStruct.acts_as_struct | def acts_as_struct(*members)
include Comparable
extend InheritedAttributes
class_inheritable_array :current_members unless respond_to?(:current_members)
self.current_members ||= []
self.current_members.concat members
all_members = self.current_members
# Only add new members
attr_accessor *members
# NOT backwards compatible with a Struct's initializer. If you
# try to initialize the first argument to a Hash and don't provide
# other arguments, you trigger the hash extraction initializer instead
# of the positional initializer. That's a bad idea.
define_method :initialize do |*args|
if args.size == 1 && Hash === args.first
initialize_hash(args.first)
else
if args.size > all_members.size
raise ArgumentError.new("#{self.class} has #{all_members.size} members " +
"- you provided #{args.size}")
end
initialize_positional(args)
end
end
# Initializes by treating the input as key-value assignments.
define_method :initialize_hash do |hash|
hash.each { |k, v| send("#{k}=", v) }
end
private :initialize_hash
# Initialize by treating the input as positional arguments that
# line up with the struct members provided to acts_as_struct.
define_method :initialize_positional do |args|
args.each_with_index do |value, idx|
key = all_members[idx]
send("#{key}=", value)
end
end
private :initialize_positional
# Helper methods for keys/values.
define_method(:keys_and_values) { keys.zip(values) }
define_method(:values) { keys.map { |member| send member } }
define_method(:keys) { all_members }
define_method(:each) { |&blk| keys_and_values.each { |k, v| blk.call([k, v]) } }
define_method(:'<=>') do |other|
each do |key, value|
res = (value <=> other.send(key))
if res != 0
return res
end
end
0
end
end | ruby | def acts_as_struct(*members)
include Comparable
extend InheritedAttributes
class_inheritable_array :current_members unless respond_to?(:current_members)
self.current_members ||= []
self.current_members.concat members
all_members = self.current_members
# Only add new members
attr_accessor *members
# NOT backwards compatible with a Struct's initializer. If you
# try to initialize the first argument to a Hash and don't provide
# other arguments, you trigger the hash extraction initializer instead
# of the positional initializer. That's a bad idea.
define_method :initialize do |*args|
if args.size == 1 && Hash === args.first
initialize_hash(args.first)
else
if args.size > all_members.size
raise ArgumentError.new("#{self.class} has #{all_members.size} members " +
"- you provided #{args.size}")
end
initialize_positional(args)
end
end
# Initializes by treating the input as key-value assignments.
define_method :initialize_hash do |hash|
hash.each { |k, v| send("#{k}=", v) }
end
private :initialize_hash
# Initialize by treating the input as positional arguments that
# line up with the struct members provided to acts_as_struct.
define_method :initialize_positional do |args|
args.each_with_index do |value, idx|
key = all_members[idx]
send("#{key}=", value)
end
end
private :initialize_positional
# Helper methods for keys/values.
define_method(:keys_and_values) { keys.zip(values) }
define_method(:values) { keys.map { |member| send member } }
define_method(:keys) { all_members }
define_method(:each) { |&blk| keys_and_values.each { |k, v| blk.call([k, v]) } }
define_method(:'<=>') do |other|
each do |key, value|
res = (value <=> other.send(key))
if res != 0
return res
end
end
0
end
end | [
"def",
"acts_as_struct",
"(",
"*",
"members",
")",
"include",
"Comparable",
"extend",
"InheritedAttributes",
"class_inheritable_array",
":current_members",
"unless",
"respond_to?",
"(",
":current_members",
")",
"self",
".",
"current_members",
"||=",
"[",
"]",
"self",
".",
"current_members",
".",
"concat",
"members",
"all_members",
"=",
"self",
".",
"current_members",
"attr_accessor",
"*",
"members",
"define_method",
":initialize",
"do",
"|",
"*",
"args",
"|",
"if",
"args",
".",
"size",
"==",
"1",
"&&",
"Hash",
"===",
"args",
".",
"first",
"initialize_hash",
"(",
"args",
".",
"first",
")",
"else",
"if",
"args",
".",
"size",
">",
"all_members",
".",
"size",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"#{self.class} has #{all_members.size} members \"",
"+",
"\"- you provided #{args.size}\"",
")",
"end",
"initialize_positional",
"(",
"args",
")",
"end",
"end",
"define_method",
":initialize_hash",
"do",
"|",
"hash",
"|",
"hash",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"send",
"(",
"\"#{k}=\"",
",",
"v",
")",
"}",
"end",
"private",
":initialize_hash",
"define_method",
":initialize_positional",
"do",
"|",
"args",
"|",
"args",
".",
"each_with_index",
"do",
"|",
"value",
",",
"idx",
"|",
"key",
"=",
"all_members",
"[",
"idx",
"]",
"send",
"(",
"\"#{key}=\"",
",",
"value",
")",
"end",
"end",
"private",
":initialize_positional",
"define_method",
"(",
":keys_and_values",
")",
"{",
"keys",
".",
"zip",
"(",
"values",
")",
"}",
"define_method",
"(",
":values",
")",
"{",
"keys",
".",
"map",
"{",
"|",
"member",
"|",
"send",
"member",
"}",
"}",
"define_method",
"(",
":keys",
")",
"{",
"all_members",
"}",
"define_method",
"(",
":each",
")",
"{",
"|",
"&",
"blk",
"|",
"keys_and_values",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"blk",
".",
"call",
"(",
"[",
"k",
",",
"v",
"]",
")",
"}",
"}",
"define_method",
"(",
":'",
"'",
")",
"do",
"|",
"other",
"|",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"res",
"=",
"(",
"value",
"<=>",
"other",
".",
"send",
"(",
"key",
")",
")",
"if",
"res",
"!=",
"0",
"return",
"res",
"end",
"end",
"0",
"end",
"end"
]
| Mixes in struct behavior to the current class. | [
"Mixes",
"in",
"struct",
"behavior",
"to",
"the",
"current",
"class",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/support/acts_as_struct.rb#L8-L64 | train |
michaeledgar/laser | lib/laser/third_party/rgl/mutable.rb | RGL.MutableGraph.cycles | def cycles
g = self.clone
self.inject([]) do |acc, v|
acc = acc.concat(g.cycles_with_vertex(v))
g.remove_vertex(v); acc
end
end | ruby | def cycles
g = self.clone
self.inject([]) do |acc, v|
acc = acc.concat(g.cycles_with_vertex(v))
g.remove_vertex(v); acc
end
end | [
"def",
"cycles",
"g",
"=",
"self",
".",
"clone",
"self",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"acc",
",",
"v",
"|",
"acc",
"=",
"acc",
".",
"concat",
"(",
"g",
".",
"cycles_with_vertex",
"(",
"v",
")",
")",
"g",
".",
"remove_vertex",
"(",
"v",
")",
";",
"acc",
"end",
"end"
]
| Returns an array of all minimum cycles in a graph
This is not an efficient implementation O(n^4) and could
be done using Minimum Spanning Trees. Hint. Hint. | [
"Returns",
"an",
"array",
"of",
"all",
"minimum",
"cycles",
"in",
"a",
"graph"
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/third_party/rgl/mutable.rb#L108-L114 | train |
michaeledgar/laser | lib/laser/analysis/sexp_analysis.rb | Laser.Analysis.parse | def parse(body = self.body)
return PARSING_CACHE[body] if PARSING_CACHE[body]
pairs = Analysis.analyze_inputs([[file, body]])
PARSING_CACHE[body] = pairs[0][1]
end | ruby | def parse(body = self.body)
return PARSING_CACHE[body] if PARSING_CACHE[body]
pairs = Analysis.analyze_inputs([[file, body]])
PARSING_CACHE[body] = pairs[0][1]
end | [
"def",
"parse",
"(",
"body",
"=",
"self",
".",
"body",
")",
"return",
"PARSING_CACHE",
"[",
"body",
"]",
"if",
"PARSING_CACHE",
"[",
"body",
"]",
"pairs",
"=",
"Analysis",
".",
"analyze_inputs",
"(",
"[",
"[",
"file",
",",
"body",
"]",
"]",
")",
"PARSING_CACHE",
"[",
"body",
"]",
"=",
"pairs",
"[",
"0",
"]",
"[",
"1",
"]",
"end"
]
| Parses the given text.
@param [String] body (self.body) The text to parse
@return [Sexp, NilClass] the sexp representing the input text. | [
"Parses",
"the",
"given",
"text",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/analysis/sexp_analysis.rb#L19-L23 | train |
michaeledgar/laser | lib/laser/analysis/sexp_analysis.rb | Laser.Analysis.find_sexps | def find_sexps(type, tree = self.parse(self.body))
result = tree[0] == type ? [tree] : []
tree.each do |node|
result.concat find_sexps(type, node) if node.is_a?(Array)
end
result
end | ruby | def find_sexps(type, tree = self.parse(self.body))
result = tree[0] == type ? [tree] : []
tree.each do |node|
result.concat find_sexps(type, node) if node.is_a?(Array)
end
result
end | [
"def",
"find_sexps",
"(",
"type",
",",
"tree",
"=",
"self",
".",
"parse",
"(",
"self",
".",
"body",
")",
")",
"result",
"=",
"tree",
"[",
"0",
"]",
"==",
"type",
"?",
"[",
"tree",
"]",
":",
"[",
"]",
"tree",
".",
"each",
"do",
"|",
"node",
"|",
"result",
".",
"concat",
"find_sexps",
"(",
"type",
",",
"node",
")",
"if",
"node",
".",
"is_a?",
"(",
"Array",
")",
"end",
"result",
"end"
]
| Finds all sexps of the given type in the given Sexp tree.
@param [Symbol] type the type of sexp to search for
@param [Sexp] tree (self.parse(self.body)) The tree to search in. Leave
blank to search the entire body.
@return [Array<Sexp>] all sexps in the input tree (or whole body) that
are of the given type. | [
"Finds",
"all",
"sexps",
"of",
"the",
"given",
"type",
"in",
"the",
"given",
"Sexp",
"tree",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/analysis/sexp_analysis.rb#L32-L38 | train |
michaeledgar/laser | lib/laser/third_party/rgl/connected_components.rb | RGL.Graph.strongly_connected_components | def strongly_connected_components
raise NotDirectedError,
"strong_components only works for directed graphs." unless directed?
vis = TarjanSccVisitor.new(self)
depth_first_search(vis) { |v| }
vis
end | ruby | def strongly_connected_components
raise NotDirectedError,
"strong_components only works for directed graphs." unless directed?
vis = TarjanSccVisitor.new(self)
depth_first_search(vis) { |v| }
vis
end | [
"def",
"strongly_connected_components",
"raise",
"NotDirectedError",
",",
"\"strong_components only works for directed graphs.\"",
"unless",
"directed?",
"vis",
"=",
"TarjanSccVisitor",
".",
"new",
"(",
"self",
")",
"depth_first_search",
"(",
"vis",
")",
"{",
"|",
"v",
"|",
"}",
"vis",
"end"
]
| class TarjanSccVisitor
This is Tarjan's algorithm for strongly connected components, from his
paper "Depth first search and linear graph algorithms". It calculates
the components in a single application of DFS. We implement the
algorithm with the help of the DFSVisitor TarjanSccVisitor.
=== Definition
A _strongly connected component_ of a directed graph G=(V,E) is a
maximal set of vertices U which is in V, such that for every pair of
vertices u and v in U, we have both a path from u to v and a path
from v to u. That is to say, u and v are reachable from each other.
@Article{Tarjan:1972:DFS,
author = "R. E. Tarjan",
key = "Tarjan",
title = "Depth First Search and Linear Graph Algorithms",
journal = "SIAM Journal on Computing",
volume = "1",
number = "2",
pages = "146--160",
month = jun,
year = "1972",
CODEN = "SMJCAT",
ISSN = "0097-5397 (print), 1095-7111 (electronic)",
bibdate = "Thu Jan 23 09:56:44 1997",
bibsource = "Parallel/Multi.bib, Misc/Reverse.eng.bib",
}
The output of the algorithm is recorded in a TarjanSccVisitor _vis_.
vis.comp_map will contain numbers giving the component ID assigned to
each vertex. The number of components is vis.num_comp. | [
"class",
"TarjanSccVisitor",
"This",
"is",
"Tarjan",
"s",
"algorithm",
"for",
"strongly",
"connected",
"components",
"from",
"his",
"paper",
"Depth",
"first",
"search",
"and",
"linear",
"graph",
"algorithms",
".",
"It",
"calculates",
"the",
"components",
"in",
"a",
"single",
"application",
"of",
"DFS",
".",
"We",
"implement",
"the",
"algorithm",
"with",
"the",
"help",
"of",
"the",
"DFSVisitor",
"TarjanSccVisitor",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/third_party/rgl/connected_components.rb#L129-L135 | train |
michaeledgar/laser | lib/laser/third_party/rgl/base.rb | RGL.Graph.each_edge | def each_edge (&block)
if directed?
each_vertex { |u|
each_adjacent(u) { |v| yield u,v }
}
else
each_edge_aux(&block) # concrete graphs should to this better
end
end | ruby | def each_edge (&block)
if directed?
each_vertex { |u|
each_adjacent(u) { |v| yield u,v }
}
else
each_edge_aux(&block) # concrete graphs should to this better
end
end | [
"def",
"each_edge",
"(",
"&",
"block",
")",
"if",
"directed?",
"each_vertex",
"{",
"|",
"u",
"|",
"each_adjacent",
"(",
"u",
")",
"{",
"|",
"v",
"|",
"yield",
"u",
",",
"v",
"}",
"}",
"else",
"each_edge_aux",
"(",
"&",
"block",
")",
"end",
"end"
]
| The each_edge iterator should provide efficient access to all edges of the
graph. Its defines the EdgeListGraph concept.
This method must _not_ be defined by concrete graph classes, because it
can be implemented using each_vertex and each_adjacent. However for
undirected graph the function is inefficient because we must not yield
(v,u) if we already visited edge (u,v). | [
"The",
"each_edge",
"iterator",
"should",
"provide",
"efficient",
"access",
"to",
"all",
"edges",
"of",
"the",
"graph",
".",
"Its",
"defines",
"the",
"EdgeListGraph",
"concept",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/third_party/rgl/base.rb#L123-L131 | train |
michaeledgar/laser | lib/laser/runner.rb | Laser.Runner.handle_global_options | def handle_global_options(settings)
if settings[:"line-length"]
@using << Laser.LineLengthWarning(settings[:"line-length"])
end
if (only_name = settings[:only])
@fix = @using = Warning.concrete_warnings.select do |w|
classname = w.name && w.name.split('::').last
(classname && only_name.index(classname)) || (w.short_name && only_name.index(w.short_name))
end
end
if settings[:profile]
require 'benchmark'
require 'profile'
SETTINGS[:profile] = true
end
if settings[:include]
Laser::SETTINGS[:load_path] = settings[:include].reverse
end
ARGV.replace(['(stdin)']) if settings[:stdin]
end | ruby | def handle_global_options(settings)
if settings[:"line-length"]
@using << Laser.LineLengthWarning(settings[:"line-length"])
end
if (only_name = settings[:only])
@fix = @using = Warning.concrete_warnings.select do |w|
classname = w.name && w.name.split('::').last
(classname && only_name.index(classname)) || (w.short_name && only_name.index(w.short_name))
end
end
if settings[:profile]
require 'benchmark'
require 'profile'
SETTINGS[:profile] = true
end
if settings[:include]
Laser::SETTINGS[:load_path] = settings[:include].reverse
end
ARGV.replace(['(stdin)']) if settings[:stdin]
end | [
"def",
"handle_global_options",
"(",
"settings",
")",
"if",
"settings",
"[",
":\"",
"\"",
"]",
"@using",
"<<",
"Laser",
".",
"LineLengthWarning",
"(",
"settings",
"[",
":\"",
"\"",
"]",
")",
"end",
"if",
"(",
"only_name",
"=",
"settings",
"[",
":only",
"]",
")",
"@fix",
"=",
"@using",
"=",
"Warning",
".",
"concrete_warnings",
".",
"select",
"do",
"|",
"w",
"|",
"classname",
"=",
"w",
".",
"name",
"&&",
"w",
".",
"name",
".",
"split",
"(",
"'::'",
")",
".",
"last",
"(",
"classname",
"&&",
"only_name",
".",
"index",
"(",
"classname",
")",
")",
"||",
"(",
"w",
".",
"short_name",
"&&",
"only_name",
".",
"index",
"(",
"w",
".",
"short_name",
")",
")",
"end",
"end",
"if",
"settings",
"[",
":profile",
"]",
"require",
"'benchmark'",
"require",
"'profile'",
"SETTINGS",
"[",
":profile",
"]",
"=",
"true",
"end",
"if",
"settings",
"[",
":include",
"]",
"Laser",
"::",
"SETTINGS",
"[",
":load_path",
"]",
"=",
"settings",
"[",
":include",
"]",
".",
"reverse",
"end",
"ARGV",
".",
"replace",
"(",
"[",
"'(stdin)'",
"]",
")",
"if",
"settings",
"[",
":stdin",
"]",
"end"
]
| Processes the global options, which includes picking which warnings to
run against the source code. The settings provided determine what
modifies the runner's settings.
@param [Hash] settings the settings from the command-line to process.
@option settings :only (String) a list of warning names or short names
that will be the only warnings run. The names should be whitespace-delimited.
@option settings :"line-length" (Integer) a maximum line length to
generate a warning for. A common choice is 80/83. | [
"Processes",
"the",
"global",
"options",
"which",
"includes",
"picking",
"which",
"warnings",
"to",
"run",
"against",
"the",
"source",
"code",
".",
"The",
"settings",
"provided",
"determine",
"what",
"modifies",
"the",
"runner",
"s",
"settings",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/runner.rb#L42-L61 | train |
michaeledgar/laser | lib/laser/runner.rb | Laser.Runner.get_settings | def get_settings
warning_opts = get_warning_options
Trollop::options do
banner 'LASER: Lexically- and Semantically-Enriched Ruby'
opt :fix, 'Should errors be fixed in-line?', short: '-f'
opt :display, 'Should errors be displayed?', short: '-b', default: true
opt :'report-fixed', 'Should fixed errors be reported anyway?', short: '-r'
opt :'line-length', 'Warn at the given line length', short: '-l', type: :int
opt :only, 'Only consider the given warning (by short or full name)', short: '-O', type: :string
opt :stdin, 'Read Ruby code from standard input', short: '-s'
opt :'list-modules', 'Print the discovered, loaded modules'
opt :profile, 'Run the profiler during execution'
opt :include, 'specify $LOAD_PATH directory (may be used more than once)', short: '-I', multi: true
opt :S, 'look for scripts using PATH environment variable', short: '-S'
warning_opts.each { |warning| opt(*warning) }
end
end | ruby | def get_settings
warning_opts = get_warning_options
Trollop::options do
banner 'LASER: Lexically- and Semantically-Enriched Ruby'
opt :fix, 'Should errors be fixed in-line?', short: '-f'
opt :display, 'Should errors be displayed?', short: '-b', default: true
opt :'report-fixed', 'Should fixed errors be reported anyway?', short: '-r'
opt :'line-length', 'Warn at the given line length', short: '-l', type: :int
opt :only, 'Only consider the given warning (by short or full name)', short: '-O', type: :string
opt :stdin, 'Read Ruby code from standard input', short: '-s'
opt :'list-modules', 'Print the discovered, loaded modules'
opt :profile, 'Run the profiler during execution'
opt :include, 'specify $LOAD_PATH directory (may be used more than once)', short: '-I', multi: true
opt :S, 'look for scripts using PATH environment variable', short: '-S'
warning_opts.each { |warning| opt(*warning) }
end
end | [
"def",
"get_settings",
"warning_opts",
"=",
"get_warning_options",
"Trollop",
"::",
"options",
"do",
"banner",
"'LASER: Lexically- and Semantically-Enriched Ruby'",
"opt",
":fix",
",",
"'Should errors be fixed in-line?'",
",",
"short",
":",
"'-f'",
"opt",
":display",
",",
"'Should errors be displayed?'",
",",
"short",
":",
"'-b'",
",",
"default",
":",
"true",
"opt",
":'",
"'",
",",
"'Should fixed errors be reported anyway?'",
",",
"short",
":",
"'-r'",
"opt",
":'",
"'",
",",
"'Warn at the given line length'",
",",
"short",
":",
"'-l'",
",",
"type",
":",
":int",
"opt",
":only",
",",
"'Only consider the given warning (by short or full name)'",
",",
"short",
":",
"'-O'",
",",
"type",
":",
":string",
"opt",
":stdin",
",",
"'Read Ruby code from standard input'",
",",
"short",
":",
"'-s'",
"opt",
":'",
"'",
",",
"'Print the discovered, loaded modules'",
"opt",
":profile",
",",
"'Run the profiler during execution'",
"opt",
":include",
",",
"'specify $LOAD_PATH directory (may be used more than once)'",
",",
"short",
":",
"'-I'",
",",
"multi",
":",
"true",
"opt",
":S",
",",
"'look for scripts using PATH environment variable'",
",",
"short",
":",
"'-S'",
"warning_opts",
".",
"each",
"{",
"|",
"warning",
"|",
"opt",
"(",
"*",
"warning",
")",
"}",
"end",
"end"
]
| Parses the command-line options using Trollop
@return [Hash{Symbol => Object}] the settings entered by the user | [
"Parses",
"the",
"command",
"-",
"line",
"options",
"using",
"Trollop"
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/runner.rb#L66-L82 | train |
michaeledgar/laser | lib/laser/runner.rb | Laser.Runner.get_warning_options | def get_warning_options
all_options = Warning.all_warnings.inject({}) do |result, warning|
options = warning.options
options = [options] if options.any? && !options[0].is_a?(Array)
options.each do |option|
result[option.first] = option
end
result
end
all_options.values
end | ruby | def get_warning_options
all_options = Warning.all_warnings.inject({}) do |result, warning|
options = warning.options
options = [options] if options.any? && !options[0].is_a?(Array)
options.each do |option|
result[option.first] = option
end
result
end
all_options.values
end | [
"def",
"get_warning_options",
"all_options",
"=",
"Warning",
".",
"all_warnings",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"result",
",",
"warning",
"|",
"options",
"=",
"warning",
".",
"options",
"options",
"=",
"[",
"options",
"]",
"if",
"options",
".",
"any?",
"&&",
"!",
"options",
"[",
"0",
"]",
".",
"is_a?",
"(",
"Array",
")",
"options",
".",
"each",
"do",
"|",
"option",
"|",
"result",
"[",
"option",
".",
"first",
"]",
"=",
"option",
"end",
"result",
"end",
"all_options",
".",
"values",
"end"
]
| Gets all the options from the warning plugins and collects them
with overriding rules. The later the declaration is run, the higher the
priority the option has. | [
"Gets",
"all",
"the",
"options",
"from",
"the",
"warning",
"plugins",
"and",
"collects",
"them",
"with",
"overriding",
"rules",
".",
"The",
"later",
"the",
"declaration",
"is",
"run",
"the",
"higher",
"the",
"priority",
"the",
"option",
"has",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/runner.rb#L87-L97 | train |
michaeledgar/laser | lib/laser/runner.rb | Laser.Runner.print_modules | def print_modules
Analysis::LaserModule.all_modules.map do |mod|
result = []
result << if Analysis::LaserClass === mod && mod.superclass
then "#{mod.path} < #{mod.superclass.path}"
else mod.name
end
result
end.sort.flatten.each { |name| puts name }
end | ruby | def print_modules
Analysis::LaserModule.all_modules.map do |mod|
result = []
result << if Analysis::LaserClass === mod && mod.superclass
then "#{mod.path} < #{mod.superclass.path}"
else mod.name
end
result
end.sort.flatten.each { |name| puts name }
end | [
"def",
"print_modules",
"Analysis",
"::",
"LaserModule",
".",
"all_modules",
".",
"map",
"do",
"|",
"mod",
"|",
"result",
"=",
"[",
"]",
"result",
"<<",
"if",
"Analysis",
"::",
"LaserClass",
"===",
"mod",
"&&",
"mod",
".",
"superclass",
"then",
"\"#{mod.path} < #{mod.superclass.path}\"",
"else",
"mod",
".",
"name",
"end",
"result",
"end",
".",
"sort",
".",
"flatten",
".",
"each",
"{",
"|",
"name",
"|",
"puts",
"name",
"}",
"end"
]
| Prints the known modules after analysis. | [
"Prints",
"the",
"known",
"modules",
"after",
"analysis",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/runner.rb#L100-L109 | train |
michaeledgar/laser | lib/laser/runner.rb | Laser.Runner.convert_warning_list | def convert_warning_list(list)
list.map do |list|
case list
when :all then Warning.all_warnings
when :whitespace
[ExtraBlankLinesWarning, ExtraWhitespaceWarning,
OperatorSpacing, MisalignedUnindentationWarning]
else list
end
end.flatten
end | ruby | def convert_warning_list(list)
list.map do |list|
case list
when :all then Warning.all_warnings
when :whitespace
[ExtraBlankLinesWarning, ExtraWhitespaceWarning,
OperatorSpacing, MisalignedUnindentationWarning]
else list
end
end.flatten
end | [
"def",
"convert_warning_list",
"(",
"list",
")",
"list",
".",
"map",
"do",
"|",
"list",
"|",
"case",
"list",
"when",
":all",
"then",
"Warning",
".",
"all_warnings",
"when",
":whitespace",
"[",
"ExtraBlankLinesWarning",
",",
"ExtraWhitespaceWarning",
",",
"OperatorSpacing",
",",
"MisalignedUnindentationWarning",
"]",
"else",
"list",
"end",
"end",
".",
"flatten",
"end"
]
| Converts a list of warnings and symbol shortcuts for warnings to just a
list of warnings. | [
"Converts",
"a",
"list",
"of",
"warnings",
"and",
"symbol",
"shortcuts",
"for",
"warnings",
"to",
"just",
"a",
"list",
"of",
"warnings",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/runner.rb#L120-L130 | train |
michaeledgar/laser | lib/laser/runner.rb | Laser.Runner.collect_warnings | def collect_warnings(files, scanner)
full_list = files.map do |file|
data = file == '(stdin)' ? STDIN.read : File.read(file)
if scanner.settings[:fix]
scanner.settings[:output_file] = scanner.settings[:stdin] ? STDOUT : File.open(file, 'w')
end
results = scanner.scan(data, file)
if scanner.settings[:fix] && !scanner.settings[:stdin]
scanner.settings[:output_file].close
end
results
end
full_list.flatten
end | ruby | def collect_warnings(files, scanner)
full_list = files.map do |file|
data = file == '(stdin)' ? STDIN.read : File.read(file)
if scanner.settings[:fix]
scanner.settings[:output_file] = scanner.settings[:stdin] ? STDOUT : File.open(file, 'w')
end
results = scanner.scan(data, file)
if scanner.settings[:fix] && !scanner.settings[:stdin]
scanner.settings[:output_file].close
end
results
end
full_list.flatten
end | [
"def",
"collect_warnings",
"(",
"files",
",",
"scanner",
")",
"full_list",
"=",
"files",
".",
"map",
"do",
"|",
"file",
"|",
"data",
"=",
"file",
"==",
"'(stdin)'",
"?",
"STDIN",
".",
"read",
":",
"File",
".",
"read",
"(",
"file",
")",
"if",
"scanner",
".",
"settings",
"[",
":fix",
"]",
"scanner",
".",
"settings",
"[",
":output_file",
"]",
"=",
"scanner",
".",
"settings",
"[",
":stdin",
"]",
"?",
"STDOUT",
":",
"File",
".",
"open",
"(",
"file",
",",
"'w'",
")",
"end",
"results",
"=",
"scanner",
".",
"scan",
"(",
"data",
",",
"file",
")",
"if",
"scanner",
".",
"settings",
"[",
":fix",
"]",
"&&",
"!",
"scanner",
".",
"settings",
"[",
":stdin",
"]",
"scanner",
".",
"settings",
"[",
":output_file",
"]",
".",
"close",
"end",
"results",
"end",
"full_list",
".",
"flatten",
"end"
]
| Collects warnings from all the provided files by running them through
the scanner.
@param [Array<String>] files the files to scan. If (stdin) is in the
array, then data will be read from STDIN until EOF is reached.
@param [Scanner] scanner the scanner that will look for warnings
in the source text.
@return [Array<Warning>] a set of warnings, ordered by file. | [
"Collects",
"warnings",
"from",
"all",
"the",
"provided",
"files",
"by",
"running",
"them",
"through",
"the",
"scanner",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/runner.rb#L160-L173 | train |
michaeledgar/laser | lib/laser/runner.rb | Laser.Runner.display_warnings | def display_warnings(warnings, settings)
num_fixable = warnings.select { |warn| warn.fixable? }.size
num_total = warnings.size
results = "#{num_total} warnings found. #{num_fixable} are fixable."
puts results
puts '=' * results.size
warnings.each do |warning|
puts "#{warning.file}:#{warning.line_number} #{warning.name} " +
"(#{warning.severity}) - #{warning.desc}"
end
end | ruby | def display_warnings(warnings, settings)
num_fixable = warnings.select { |warn| warn.fixable? }.size
num_total = warnings.size
results = "#{num_total} warnings found. #{num_fixable} are fixable."
puts results
puts '=' * results.size
warnings.each do |warning|
puts "#{warning.file}:#{warning.line_number} #{warning.name} " +
"(#{warning.severity}) - #{warning.desc}"
end
end | [
"def",
"display_warnings",
"(",
"warnings",
",",
"settings",
")",
"num_fixable",
"=",
"warnings",
".",
"select",
"{",
"|",
"warn",
"|",
"warn",
".",
"fixable?",
"}",
".",
"size",
"num_total",
"=",
"warnings",
".",
"size",
"results",
"=",
"\"#{num_total} warnings found. #{num_fixable} are fixable.\"",
"puts",
"results",
"puts",
"'='",
"*",
"results",
".",
"size",
"warnings",
".",
"each",
"do",
"|",
"warning",
"|",
"puts",
"\"#{warning.file}:#{warning.line_number} #{warning.name} \"",
"+",
"\"(#{warning.severity}) - #{warning.desc}\"",
"end",
"end"
]
| Displays warnings using user-provided settings.
@param [Array<Warning>] warnings the warnings generated by the input
files, ordered by file
@param [Hash{Symbol => Object}] settings the user-set display settings | [
"Displays",
"warnings",
"using",
"user",
"-",
"provided",
"settings",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/runner.rb#L180-L192 | train |
michaeledgar/laser | lib/laser/third_party/rgl/traversal.rb | RGL.GraphVisitor.attach_distance_map | def attach_distance_map (map = Hash.new(0))
@dist_map = map
class << self
def handle_tree_edge (u, v)
super
@dist_map[v] = @dist_map[u] + 1
end
# Answer the distance to the start vertex.
def distance_to_root (v)
@dist_map[v]
end
end # class
end | ruby | def attach_distance_map (map = Hash.new(0))
@dist_map = map
class << self
def handle_tree_edge (u, v)
super
@dist_map[v] = @dist_map[u] + 1
end
# Answer the distance to the start vertex.
def distance_to_root (v)
@dist_map[v]
end
end # class
end | [
"def",
"attach_distance_map",
"(",
"map",
"=",
"Hash",
".",
"new",
"(",
"0",
")",
")",
"@dist_map",
"=",
"map",
"class",
"<<",
"self",
"def",
"handle_tree_edge",
"(",
"u",
",",
"v",
")",
"super",
"@dist_map",
"[",
"v",
"]",
"=",
"@dist_map",
"[",
"u",
"]",
"+",
"1",
"end",
"def",
"distance_to_root",
"(",
"v",
")",
"@dist_map",
"[",
"v",
"]",
"end",
"end",
"end"
]
| Attach a map to the visitor which records the distance of a visited
vertex to the start vertex.
This is similar to BGLs
distance_recorder[http://www.boost.org/libs/graph/doc/distance_recorder.html].
After the distance_map is attached, the visitor has a new method
distance_to_root, which answers the distance to the start vertex. | [
"Attach",
"a",
"map",
"to",
"the",
"visitor",
"which",
"records",
"the",
"distance",
"of",
"a",
"visited",
"vertex",
"to",
"the",
"start",
"vertex",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/third_party/rgl/traversal.rb#L99-L116 | train |
michaeledgar/laser | lib/laser/third_party/rgl/traversal.rb | RGL.Graph.bfs_search_tree_from | def bfs_search_tree_from (v)
require 'laser/third_party/rgl/adjacency'
bfs = bfs_iterator(v)
tree = DirectedAdjacencyGraph.new
bfs.set_tree_edge_event_handler { |from, to|
tree.add_edge(from, to)
}
bfs.set_to_end # does the search
tree
end | ruby | def bfs_search_tree_from (v)
require 'laser/third_party/rgl/adjacency'
bfs = bfs_iterator(v)
tree = DirectedAdjacencyGraph.new
bfs.set_tree_edge_event_handler { |from, to|
tree.add_edge(from, to)
}
bfs.set_to_end # does the search
tree
end | [
"def",
"bfs_search_tree_from",
"(",
"v",
")",
"require",
"'laser/third_party/rgl/adjacency'",
"bfs",
"=",
"bfs_iterator",
"(",
"v",
")",
"tree",
"=",
"DirectedAdjacencyGraph",
".",
"new",
"bfs",
".",
"set_tree_edge_event_handler",
"{",
"|",
"from",
",",
"to",
"|",
"tree",
".",
"add_edge",
"(",
"from",
",",
"to",
")",
"}",
"bfs",
".",
"set_to_end",
"tree",
"end"
]
| Returns a DirectedAdjacencyGraph, which represents a BFS search tree
starting at _v_. This method uses the tree_edge_event of BFSIterator
to record all tree edges of the search tree in the result. | [
"Returns",
"a",
"DirectedAdjacencyGraph",
"which",
"represents",
"a",
"BFS",
"search",
"tree",
"starting",
"at",
"_v_",
".",
"This",
"method",
"uses",
"the",
"tree_edge_event",
"of",
"BFSIterator",
"to",
"record",
"all",
"tree",
"edges",
"of",
"the",
"search",
"tree",
"in",
"the",
"result",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/third_party/rgl/traversal.rb#L237-L246 | train |
michaeledgar/laser | lib/laser/third_party/rgl/traversal.rb | RGL.Graph.depth_first_search | def depth_first_search (vis = DFSVisitor.new(self), &b)
each_vertex do |u|
unless vis.finished_vertex?(u)
vis.handle_start_vertex(u)
depth_first_visit(u, vis, &b)
end
end
end | ruby | def depth_first_search (vis = DFSVisitor.new(self), &b)
each_vertex do |u|
unless vis.finished_vertex?(u)
vis.handle_start_vertex(u)
depth_first_visit(u, vis, &b)
end
end
end | [
"def",
"depth_first_search",
"(",
"vis",
"=",
"DFSVisitor",
".",
"new",
"(",
"self",
")",
",",
"&",
"b",
")",
"each_vertex",
"do",
"|",
"u",
"|",
"unless",
"vis",
".",
"finished_vertex?",
"(",
"u",
")",
"vis",
".",
"handle_start_vertex",
"(",
"u",
")",
"depth_first_visit",
"(",
"u",
",",
"vis",
",",
"&",
"b",
")",
"end",
"end",
"end"
]
| Do a recursive DFS search on the whole graph. If a block is passed,
it is called on each _finish_vertex_ event. See
strongly_connected_components for an example usage. | [
"Do",
"a",
"recursive",
"DFS",
"search",
"on",
"the",
"whole",
"graph",
".",
"If",
"a",
"block",
"is",
"passed",
"it",
"is",
"called",
"on",
"each",
"_finish_vertex_",
"event",
".",
"See",
"strongly_connected_components",
"for",
"an",
"example",
"usage",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/third_party/rgl/traversal.rb#L299-L306 | train |
michaeledgar/laser | lib/laser/third_party/rgl/traversal.rb | RGL.Graph.depth_first_visit | def depth_first_visit (u, vis = DFSVisitor.new(self), &b)
vis.color_map[u] = :GRAY
vis.handle_examine_vertex(u)
each_adjacent(u) { |v|
vis.handle_examine_edge(u, v)
if vis.follow_edge?(u, v) # (u,v) is a tree edge
vis.handle_tree_edge(u, v) # also discovers v
vis.color_map[v] = :GRAY # color of v was :WHITE
depth_first_visit(v, vis, &b)
else # (u,v) is a non tree edge
if vis.color_map[v] == :GRAY
vis.handle_back_edge(u, v) # (u,v) has gray target
else
vis.handle_forward_edge(u, v) # (u,v) is a cross or forward edge
end
end
}
vis.color_map[u] = :BLACK
vis.handle_finish_vertex(u) # finish vertex
b.call(u)
end | ruby | def depth_first_visit (u, vis = DFSVisitor.new(self), &b)
vis.color_map[u] = :GRAY
vis.handle_examine_vertex(u)
each_adjacent(u) { |v|
vis.handle_examine_edge(u, v)
if vis.follow_edge?(u, v) # (u,v) is a tree edge
vis.handle_tree_edge(u, v) # also discovers v
vis.color_map[v] = :GRAY # color of v was :WHITE
depth_first_visit(v, vis, &b)
else # (u,v) is a non tree edge
if vis.color_map[v] == :GRAY
vis.handle_back_edge(u, v) # (u,v) has gray target
else
vis.handle_forward_edge(u, v) # (u,v) is a cross or forward edge
end
end
}
vis.color_map[u] = :BLACK
vis.handle_finish_vertex(u) # finish vertex
b.call(u)
end | [
"def",
"depth_first_visit",
"(",
"u",
",",
"vis",
"=",
"DFSVisitor",
".",
"new",
"(",
"self",
")",
",",
"&",
"b",
")",
"vis",
".",
"color_map",
"[",
"u",
"]",
"=",
":GRAY",
"vis",
".",
"handle_examine_vertex",
"(",
"u",
")",
"each_adjacent",
"(",
"u",
")",
"{",
"|",
"v",
"|",
"vis",
".",
"handle_examine_edge",
"(",
"u",
",",
"v",
")",
"if",
"vis",
".",
"follow_edge?",
"(",
"u",
",",
"v",
")",
"vis",
".",
"handle_tree_edge",
"(",
"u",
",",
"v",
")",
"vis",
".",
"color_map",
"[",
"v",
"]",
"=",
":GRAY",
"depth_first_visit",
"(",
"v",
",",
"vis",
",",
"&",
"b",
")",
"else",
"if",
"vis",
".",
"color_map",
"[",
"v",
"]",
"==",
":GRAY",
"vis",
".",
"handle_back_edge",
"(",
"u",
",",
"v",
")",
"else",
"vis",
".",
"handle_forward_edge",
"(",
"u",
",",
"v",
")",
"end",
"end",
"}",
"vis",
".",
"color_map",
"[",
"u",
"]",
"=",
":BLACK",
"vis",
".",
"handle_finish_vertex",
"(",
"u",
")",
"b",
".",
"call",
"(",
"u",
")",
"end"
]
| Start a depth first search at vertex _u_. The block _b_ is called on
each finish_vertex event. | [
"Start",
"a",
"depth",
"first",
"search",
"at",
"vertex",
"_u_",
".",
"The",
"block",
"_b_",
"is",
"called",
"on",
"each",
"finish_vertex",
"event",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/third_party/rgl/traversal.rb#L311-L331 | train |
michaeledgar/laser | lib/laser/scanner.rb | Laser.Scanner.scan | def scan(text, filename='(none)')
warnings = scan_for_file_warnings(text, filename)
text = filter_fixable(warnings).inject(text) do |text, warning|
warning.fix(text)
end
with_fixing_piped_to_output do
text.split(/\n/).each_with_index do |line, number|
warnings.concat process_line(line, number + 1, filename)
end
end
warnings += unused_method_warnings
warnings
end | ruby | def scan(text, filename='(none)')
warnings = scan_for_file_warnings(text, filename)
text = filter_fixable(warnings).inject(text) do |text, warning|
warning.fix(text)
end
with_fixing_piped_to_output do
text.split(/\n/).each_with_index do |line, number|
warnings.concat process_line(line, number + 1, filename)
end
end
warnings += unused_method_warnings
warnings
end | [
"def",
"scan",
"(",
"text",
",",
"filename",
"=",
"'(none)'",
")",
"warnings",
"=",
"scan_for_file_warnings",
"(",
"text",
",",
"filename",
")",
"text",
"=",
"filter_fixable",
"(",
"warnings",
")",
".",
"inject",
"(",
"text",
")",
"do",
"|",
"text",
",",
"warning",
"|",
"warning",
".",
"fix",
"(",
"text",
")",
"end",
"with_fixing_piped_to_output",
"do",
"text",
".",
"split",
"(",
"/",
"\\n",
"/",
")",
".",
"each_with_index",
"do",
"|",
"line",
",",
"number",
"|",
"warnings",
".",
"concat",
"process_line",
"(",
"line",
",",
"number",
"+",
"1",
",",
"filename",
")",
"end",
"end",
"warnings",
"+=",
"unused_method_warnings",
"warnings",
"end"
]
| Scans the text for warnings.
@param [String] text the input ruby file to scan
@return [Array[Laser::Warnings]] the warnings generated by the code.
If the code is clean, an empty array is returned. | [
"Scans",
"the",
"text",
"for",
"warnings",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/scanner.rb#L45-L57 | train |
michaeledgar/laser | lib/laser/scanner.rb | Laser.Scanner.process_line | def process_line(line, line_number, filename)
warnings = all_warnings_for_line(line, line_number, filename)
fix_input(warnings, line, line_number, filename) if @settings[:fix]
warnings
end | ruby | def process_line(line, line_number, filename)
warnings = all_warnings_for_line(line, line_number, filename)
fix_input(warnings, line, line_number, filename) if @settings[:fix]
warnings
end | [
"def",
"process_line",
"(",
"line",
",",
"line_number",
",",
"filename",
")",
"warnings",
"=",
"all_warnings_for_line",
"(",
"line",
",",
"line_number",
",",
"filename",
")",
"fix_input",
"(",
"warnings",
",",
"line",
",",
"line_number",
",",
"filename",
")",
"if",
"@settings",
"[",
":fix",
"]",
"warnings",
"end"
]
| Finds all matching warnings, and if the user wishes, fix a subset of them. | [
"Finds",
"all",
"matching",
"warnings",
"and",
"if",
"the",
"user",
"wishes",
"fix",
"a",
"subset",
"of",
"them",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/scanner.rb#L68-L72 | train |
michaeledgar/laser | lib/laser/scanner.rb | Laser.Scanner.fix_input | def fix_input(warnings, line, line_number, filename)
fixable_warnings = filter_fixable warnings
if fixable_warnings.size == 1
self.settings[:output_lines] << fixable_warnings.first.fix rescue line
elsif fixable_warnings.size > 1
new_text = fixable_warnings.first.fix rescue line
process_line(new_text, line_number, filename)
else
self.settings[:output_lines] << line
end
end | ruby | def fix_input(warnings, line, line_number, filename)
fixable_warnings = filter_fixable warnings
if fixable_warnings.size == 1
self.settings[:output_lines] << fixable_warnings.first.fix rescue line
elsif fixable_warnings.size > 1
new_text = fixable_warnings.first.fix rescue line
process_line(new_text, line_number, filename)
else
self.settings[:output_lines] << line
end
end | [
"def",
"fix_input",
"(",
"warnings",
",",
"line",
",",
"line_number",
",",
"filename",
")",
"fixable_warnings",
"=",
"filter_fixable",
"warnings",
"if",
"fixable_warnings",
".",
"size",
"==",
"1",
"self",
".",
"settings",
"[",
":output_lines",
"]",
"<<",
"fixable_warnings",
".",
"first",
".",
"fix",
"rescue",
"line",
"elsif",
"fixable_warnings",
".",
"size",
">",
"1",
"new_text",
"=",
"fixable_warnings",
".",
"first",
".",
"fix",
"rescue",
"line",
"process_line",
"(",
"new_text",
",",
"line_number",
",",
"filename",
")",
"else",
"self",
".",
"settings",
"[",
":output_lines",
"]",
"<<",
"line",
"end",
"end"
]
| Tries to fix the given line with a set of matching warnings for that line.
May recurse if there are multiple warnings on the same line. | [
"Tries",
"to",
"fix",
"the",
"given",
"line",
"with",
"a",
"set",
"of",
"matching",
"warnings",
"for",
"that",
"line",
".",
"May",
"recurse",
"if",
"there",
"are",
"multiple",
"warnings",
"on",
"the",
"same",
"line",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/scanner.rb#L76-L86 | train |
michaeledgar/laser | lib/laser/scanner.rb | Laser.Scanner.all_warnings_for_line | def all_warnings_for_line(line, line_number, filename)
new_warnings = check_for_indent_warnings!(line, filename)
new_warnings.concat scan_for_line_warnings(line, filename)
new_warnings.each {|warning| warning.line_number = line_number}
end | ruby | def all_warnings_for_line(line, line_number, filename)
new_warnings = check_for_indent_warnings!(line, filename)
new_warnings.concat scan_for_line_warnings(line, filename)
new_warnings.each {|warning| warning.line_number = line_number}
end | [
"def",
"all_warnings_for_line",
"(",
"line",
",",
"line_number",
",",
"filename",
")",
"new_warnings",
"=",
"check_for_indent_warnings!",
"(",
"line",
",",
"filename",
")",
"new_warnings",
".",
"concat",
"scan_for_line_warnings",
"(",
"line",
",",
"filename",
")",
"new_warnings",
".",
"each",
"{",
"|",
"warning",
"|",
"warning",
".",
"line_number",
"=",
"line_number",
"}",
"end"
]
| Returns all warnings that match the line | [
"Returns",
"all",
"warnings",
"that",
"match",
"the",
"line"
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/scanner.rb#L89-L93 | train |
michaeledgar/laser | lib/laser/scanner.rb | Laser.Scanner.check_for_indent_warnings! | def check_for_indent_warnings!(line, filename)
return [] if line == ""
indent_size = get_indent_size line
if indent_size > current_indent
self.indent_stack.push indent_size
elsif indent_size < current_indent
previous = self.indent_stack.pop
if indent_size != current_indent &&
using.include?(MisalignedUnindentationWarning)
warnings_to_check = [MisalignedUnindentationWarning.new(filename, line, current_indent)]
return filtered_warnings_from_line(line, warnings_to_check)
end
end
[]
end | ruby | def check_for_indent_warnings!(line, filename)
return [] if line == ""
indent_size = get_indent_size line
if indent_size > current_indent
self.indent_stack.push indent_size
elsif indent_size < current_indent
previous = self.indent_stack.pop
if indent_size != current_indent &&
using.include?(MisalignedUnindentationWarning)
warnings_to_check = [MisalignedUnindentationWarning.new(filename, line, current_indent)]
return filtered_warnings_from_line(line, warnings_to_check)
end
end
[]
end | [
"def",
"check_for_indent_warnings!",
"(",
"line",
",",
"filename",
")",
"return",
"[",
"]",
"if",
"line",
"==",
"\"\"",
"indent_size",
"=",
"get_indent_size",
"line",
"if",
"indent_size",
">",
"current_indent",
"self",
".",
"indent_stack",
".",
"push",
"indent_size",
"elsif",
"indent_size",
"<",
"current_indent",
"previous",
"=",
"self",
".",
"indent_stack",
".",
"pop",
"if",
"indent_size",
"!=",
"current_indent",
"&&",
"using",
".",
"include?",
"(",
"MisalignedUnindentationWarning",
")",
"warnings_to_check",
"=",
"[",
"MisalignedUnindentationWarning",
".",
"new",
"(",
"filename",
",",
"line",
",",
"current_indent",
")",
"]",
"return",
"filtered_warnings_from_line",
"(",
"line",
",",
"warnings_to_check",
")",
"end",
"end",
"[",
"]",
"end"
]
| Checks for new warnings based on indentation. | [
"Checks",
"for",
"new",
"warnings",
"based",
"on",
"indentation",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/scanner.rb#L101-L115 | train |
michaeledgar/laser | lib/laser/scanner.rb | Laser.Scanner.scan_for_line_warnings | def scan_for_line_warnings(line, filename)
warnings = scan_for_warnings(using & LineWarning.all_warnings, line, filename)
filtered_warnings_from_line(line, warnings)
end | ruby | def scan_for_line_warnings(line, filename)
warnings = scan_for_warnings(using & LineWarning.all_warnings, line, filename)
filtered_warnings_from_line(line, warnings)
end | [
"def",
"scan_for_line_warnings",
"(",
"line",
",",
"filename",
")",
"warnings",
"=",
"scan_for_warnings",
"(",
"using",
"&",
"LineWarning",
".",
"all_warnings",
",",
"line",
",",
"filename",
")",
"filtered_warnings_from_line",
"(",
"line",
",",
"warnings",
")",
"end"
]
| Goes through all line warning subclasses and checks if we got some new
warnings for a given line | [
"Goes",
"through",
"all",
"line",
"warning",
"subclasses",
"and",
"checks",
"if",
"we",
"got",
"some",
"new",
"warnings",
"for",
"a",
"given",
"line"
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/scanner.rb#L147-L150 | train |
michaeledgar/laser | lib/laser/analysis/lexical_analysis.rb | Laser.LexicalAnalysis.lex | def lex(body = self.body, token_class = Token)
return [] if body =~ /^#.*encoding.*/
Ripper.lex(body).map {|token| token_class.new(token) }
end | ruby | def lex(body = self.body, token_class = Token)
return [] if body =~ /^#.*encoding.*/
Ripper.lex(body).map {|token| token_class.new(token) }
end | [
"def",
"lex",
"(",
"body",
"=",
"self",
".",
"body",
",",
"token_class",
"=",
"Token",
")",
"return",
"[",
"]",
"if",
"body",
"=~",
"/",
"/",
"Ripper",
".",
"lex",
"(",
"body",
")",
".",
"map",
"{",
"|",
"token",
"|",
"token_class",
".",
"new",
"(",
"token",
")",
"}",
"end"
]
| Lexes the given text.
@param [String] body (self.body) The text to lex
@return [Array<Array<Integer, Integer>, Symbol, String>] A set of tokens
in Ripper's result format. Each token is an array of the form:
[[1, token_position], token_type, token_text]. I'm not exactly clear on
why the 1 is always there. At any rate - the result is an array of those
tokens. | [
"Lexes",
"the",
"given",
"text",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/analysis/lexical_analysis.rb#L31-L34 | train |
michaeledgar/laser | lib/laser/analysis/lexical_analysis.rb | Laser.LexicalAnalysis.find_token | def find_token(*args)
body, list = _extract_token_search_args(args)
# grr match comment with encoding in it
lexed = lex(body)
lexed.find.with_index do |tok, idx|
is_token = list.include?(tok.type)
is_not_symbol = idx == 0 || lexed[idx-1].type != :on_symbeg
is_token && is_not_symbol
end
end | ruby | def find_token(*args)
body, list = _extract_token_search_args(args)
# grr match comment with encoding in it
lexed = lex(body)
lexed.find.with_index do |tok, idx|
is_token = list.include?(tok.type)
is_not_symbol = idx == 0 || lexed[idx-1].type != :on_symbeg
is_token && is_not_symbol
end
end | [
"def",
"find_token",
"(",
"*",
"args",
")",
"body",
",",
"list",
"=",
"_extract_token_search_args",
"(",
"args",
")",
"lexed",
"=",
"lex",
"(",
"body",
")",
"lexed",
".",
"find",
".",
"with_index",
"do",
"|",
"tok",
",",
"idx",
"|",
"is_token",
"=",
"list",
".",
"include?",
"(",
"tok",
".",
"type",
")",
"is_not_symbol",
"=",
"idx",
"==",
"0",
"||",
"lexed",
"[",
"idx",
"-",
"1",
"]",
".",
"type",
"!=",
":on_symbeg",
"is_token",
"&&",
"is_not_symbol",
"end",
"end"
]
| Finds the first instance of a set of tokens in the body. If no text is
given to scan, then the full content is scanned.
@param [String] body (self.body) The first parameter is optional: the text
to search. This defaults to the full text.
@param [Symbol] token The rest of the arguments are tokens to search
for. Any number of tokens may be specified.
@return [Array] the token in the form returned by Ripper. See #lex. | [
"Finds",
"the",
"first",
"instance",
"of",
"a",
"set",
"of",
"tokens",
"in",
"the",
"body",
".",
"If",
"no",
"text",
"is",
"given",
"to",
"scan",
"then",
"the",
"full",
"content",
"is",
"scanned",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/analysis/lexical_analysis.rb#L114-L123 | train |
michaeledgar/laser | lib/laser/analysis/lexical_analysis.rb | Laser.LexicalAnalysis.split_on_keyword | def split_on_keyword(*args)
body, keywords = _extract_token_search_args(args)
token = find_keyword(body, *keywords)
return _split_body_with_raw_token(body, token)
end | ruby | def split_on_keyword(*args)
body, keywords = _extract_token_search_args(args)
token = find_keyword(body, *keywords)
return _split_body_with_raw_token(body, token)
end | [
"def",
"split_on_keyword",
"(",
"*",
"args",
")",
"body",
",",
"keywords",
"=",
"_extract_token_search_args",
"(",
"args",
")",
"token",
"=",
"find_keyword",
"(",
"body",
",",
"*",
"keywords",
")",
"return",
"_split_body_with_raw_token",
"(",
"body",
",",
"token",
")",
"end"
]
| Splits the body into two halfs based on the first appearance of a keyword.
@example
split_on_keyword('x = 5 unless y == 2', :unless)
# => ['x = 5 ', 'unless y == 2']
@param [String] body (self.body) The first parameter is optional: the text
to search. This defaults to the full text.
@param [Symbol] token The rest of the arguments are keywords to search
for. Any number of keywords may be specified.
@return [Array<String, String>] The body split by the keyword. | [
"Splits",
"the",
"body",
"into",
"two",
"halfs",
"based",
"on",
"the",
"first",
"appearance",
"of",
"a",
"keyword",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/analysis/lexical_analysis.rb#L135-L139 | train |
michaeledgar/laser | lib/laser/analysis/lexical_analysis.rb | Laser.LexicalAnalysis.split_on_token | def split_on_token(*args)
body, tokens = _extract_token_search_args(args)
token = find_token(body, *tokens)
return _split_body_with_raw_token(body, token)
end | ruby | def split_on_token(*args)
body, tokens = _extract_token_search_args(args)
token = find_token(body, *tokens)
return _split_body_with_raw_token(body, token)
end | [
"def",
"split_on_token",
"(",
"*",
"args",
")",
"body",
",",
"tokens",
"=",
"_extract_token_search_args",
"(",
"args",
")",
"token",
"=",
"find_token",
"(",
"body",
",",
"*",
"tokens",
")",
"return",
"_split_body_with_raw_token",
"(",
"body",
",",
"token",
")",
"end"
]
| Splits the body into two halfs based on the first appearance of a token.
@example
split_on_token('x = 5 unless y == 2', :on_kw)
# => ['x = 5 ', 'unless y == 2']
@param [String] body (self.body) The first parameter is optional: the text
to search. This defaults to the full text.
@param [Symbol] token The rest of the arguments are tokens to search
for. Any number of tokens may be specified.
@return [Array<String, String>] The body split by the token. | [
"Splits",
"the",
"body",
"into",
"two",
"halfs",
"based",
"on",
"the",
"first",
"appearance",
"of",
"a",
"token",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/analysis/lexical_analysis.rb#L151-L155 | train |
michaeledgar/laser | lib/laser/third_party/rgl/adjacency.rb | RGL.Graph.to_adjacency | def to_adjacency
result = (directed? ? DirectedAdjacencyGraph : AdjacencyGraph).new
each_vertex { |v| result.add_vertex(v) }
each_edge { |u,v| result.add_edge(u, v) }
result
end | ruby | def to_adjacency
result = (directed? ? DirectedAdjacencyGraph : AdjacencyGraph).new
each_vertex { |v| result.add_vertex(v) }
each_edge { |u,v| result.add_edge(u, v) }
result
end | [
"def",
"to_adjacency",
"result",
"=",
"(",
"directed?",
"?",
"DirectedAdjacencyGraph",
":",
"AdjacencyGraph",
")",
".",
"new",
"each_vertex",
"{",
"|",
"v",
"|",
"result",
".",
"add_vertex",
"(",
"v",
")",
"}",
"each_edge",
"{",
"|",
"u",
",",
"v",
"|",
"result",
".",
"add_edge",
"(",
"u",
",",
"v",
")",
"}",
"result",
"end"
]
| Convert a general graph to an AdjacencyGraph. If the graph is directed,
returns a DirectedAdjacencyGraph; otherwise, returns an AdjacencyGraph. | [
"Convert",
"a",
"general",
"graph",
"to",
"an",
"AdjacencyGraph",
".",
"If",
"the",
"graph",
"is",
"directed",
"returns",
"a",
"DirectedAdjacencyGraph",
";",
"otherwise",
"returns",
"an",
"AdjacencyGraph",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/third_party/rgl/adjacency.rb#L189-L194 | train |
michaeledgar/laser | lib/laser/third_party/rgl/adjacency.rb | RGL.DirectedAdjacencyGraph.initialize_copy | def initialize_copy(orig)
@vertex_dict = orig.instance_eval{@vertex_dict}.dup
@vertex_dict.keys.each do |v|
@vertex_dict[v] = @vertex_dict[v].dup
end
@predecessor_dict = orig.instance_eval{@predecessor_dict}.dup
@predecessor_dict.keys.each do |v|
@predecessor_dict[v] = @predecessor_dict[v].dup
end
end | ruby | def initialize_copy(orig)
@vertex_dict = orig.instance_eval{@vertex_dict}.dup
@vertex_dict.keys.each do |v|
@vertex_dict[v] = @vertex_dict[v].dup
end
@predecessor_dict = orig.instance_eval{@predecessor_dict}.dup
@predecessor_dict.keys.each do |v|
@predecessor_dict[v] = @predecessor_dict[v].dup
end
end | [
"def",
"initialize_copy",
"(",
"orig",
")",
"@vertex_dict",
"=",
"orig",
".",
"instance_eval",
"{",
"@vertex_dict",
"}",
".",
"dup",
"@vertex_dict",
".",
"keys",
".",
"each",
"do",
"|",
"v",
"|",
"@vertex_dict",
"[",
"v",
"]",
"=",
"@vertex_dict",
"[",
"v",
"]",
".",
"dup",
"end",
"@predecessor_dict",
"=",
"orig",
".",
"instance_eval",
"{",
"@predecessor_dict",
"}",
".",
"dup",
"@predecessor_dict",
".",
"keys",
".",
"each",
"do",
"|",
"v",
"|",
"@predecessor_dict",
"[",
"v",
"]",
"=",
"@predecessor_dict",
"[",
"v",
"]",
".",
"dup",
"end",
"end"
]
| Returns a new empty DirectedAdjacencyGraph which has as its edgelist
class the given class. The default edgelist class is Set, to ensure
set semantics for edges and vertices.
If other graphs are passed as parameters their vertices and edges are
added to the new graph.
Copy internal vertice_dict | [
"Returns",
"a",
"new",
"empty",
"DirectedAdjacencyGraph",
"which",
"has",
"as",
"its",
"edgelist",
"class",
"the",
"given",
"class",
".",
"The",
"default",
"edgelist",
"class",
"is",
"Set",
"to",
"ensure",
"set",
"semantics",
"for",
"edges",
"and",
"vertices",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/third_party/rgl/adjacency.rb#L49-L58 | train |
michaeledgar/laser | lib/laser/third_party/rgl/adjacency.rb | RGL.DirectedAdjacencyGraph.edgelist_class= | def edgelist_class=(klass)
@vertex_dict.keys.each do |v|
@vertex_dict[v] = klass.new @vertex_dict[v].to_a
end
@predecessor_dict.keys.each do |v|
@predecessor_dict[v] = klass.new @predecessor_dict[v].to_a
end
end | ruby | def edgelist_class=(klass)
@vertex_dict.keys.each do |v|
@vertex_dict[v] = klass.new @vertex_dict[v].to_a
end
@predecessor_dict.keys.each do |v|
@predecessor_dict[v] = klass.new @predecessor_dict[v].to_a
end
end | [
"def",
"edgelist_class",
"=",
"(",
"klass",
")",
"@vertex_dict",
".",
"keys",
".",
"each",
"do",
"|",
"v",
"|",
"@vertex_dict",
"[",
"v",
"]",
"=",
"klass",
".",
"new",
"@vertex_dict",
"[",
"v",
"]",
".",
"to_a",
"end",
"@predecessor_dict",
".",
"keys",
".",
"each",
"do",
"|",
"v",
"|",
"@predecessor_dict",
"[",
"v",
"]",
"=",
"klass",
".",
"new",
"@predecessor_dict",
"[",
"v",
"]",
".",
"to_a",
"end",
"end"
]
| Converts the adjacency list of each vertex to be of type _klass_. The
class is expected to have a new contructor which accepts an enumerable as
parameter. | [
"Converts",
"the",
"adjacency",
"list",
"of",
"each",
"vertex",
"to",
"be",
"of",
"type",
"_klass_",
".",
"The",
"class",
"is",
"expected",
"to",
"have",
"a",
"new",
"contructor",
"which",
"accepts",
"an",
"enumerable",
"as",
"parameter",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/third_party/rgl/adjacency.rb#L140-L147 | train |
michaeledgar/laser | lib/laser/support/module_extensions.rb | Laser.ModuleExtensions.opposite_method | def opposite_method(new_name, old_name)
define_method new_name do |*args, &blk|
!send(old_name, *args, &blk)
end
end | ruby | def opposite_method(new_name, old_name)
define_method new_name do |*args, &blk|
!send(old_name, *args, &blk)
end
end | [
"def",
"opposite_method",
"(",
"new_name",
",",
"old_name",
")",
"define_method",
"new_name",
"do",
"|",
"*",
"args",
",",
"&",
"blk",
"|",
"!",
"send",
"(",
"old_name",
",",
"*",
"args",
",",
"&",
"blk",
")",
"end",
"end"
]
| Creates a new method that returns the boolean negation of the
specified method. | [
"Creates",
"a",
"new",
"method",
"that",
"returns",
"the",
"boolean",
"negation",
"of",
"the",
"specified",
"method",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/support/module_extensions.rb#L9-L13 | train |
michaeledgar/laser | lib/laser/support/module_extensions.rb | Laser.ModuleExtensions.attr_accessor_with_default | def attr_accessor_with_default(name, val)
ivar_sym = "@#{name}"
define_method name do
unless instance_variable_defined?(ivar_sym)
instance_variable_set(ivar_sym, val)
end
instance_variable_get ivar_sym
end
attr_writer name
end | ruby | def attr_accessor_with_default(name, val)
ivar_sym = "@#{name}"
define_method name do
unless instance_variable_defined?(ivar_sym)
instance_variable_set(ivar_sym, val)
end
instance_variable_get ivar_sym
end
attr_writer name
end | [
"def",
"attr_accessor_with_default",
"(",
"name",
",",
"val",
")",
"ivar_sym",
"=",
"\"@#{name}\"",
"define_method",
"name",
"do",
"unless",
"instance_variable_defined?",
"(",
"ivar_sym",
")",
"instance_variable_set",
"(",
"ivar_sym",
",",
"val",
")",
"end",
"instance_variable_get",
"ivar_sym",
"end",
"attr_writer",
"name",
"end"
]
| Creates an attr_accessor that defaults to a certain value. | [
"Creates",
"an",
"attr_accessor",
"that",
"defaults",
"to",
"a",
"certain",
"value",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/support/module_extensions.rb#L16-L25 | train |
michaeledgar/laser | lib/laser/support/module_extensions.rb | Laser.ModuleExtensions.cattr_get_and_setter | def cattr_get_and_setter(*attrs)
attrs.each do |attr|
cattr_accessor attr
singleton_class.instance_eval do
alias_method "#{attr}_old_get".to_sym, attr
define_method attr do |*args, &blk|
if args.size > 0
send("#{attr}=", *args)
elsif blk != nil
send("#{attr}=", blk)
else
send("#{attr}_old_get")
end
end
end
end
end | ruby | def cattr_get_and_setter(*attrs)
attrs.each do |attr|
cattr_accessor attr
singleton_class.instance_eval do
alias_method "#{attr}_old_get".to_sym, attr
define_method attr do |*args, &blk|
if args.size > 0
send("#{attr}=", *args)
elsif blk != nil
send("#{attr}=", blk)
else
send("#{attr}_old_get")
end
end
end
end
end | [
"def",
"cattr_get_and_setter",
"(",
"*",
"attrs",
")",
"attrs",
".",
"each",
"do",
"|",
"attr",
"|",
"cattr_accessor",
"attr",
"singleton_class",
".",
"instance_eval",
"do",
"alias_method",
"\"#{attr}_old_get\"",
".",
"to_sym",
",",
"attr",
"define_method",
"attr",
"do",
"|",
"*",
"args",
",",
"&",
"blk",
"|",
"if",
"args",
".",
"size",
">",
"0",
"send",
"(",
"\"#{attr}=\"",
",",
"*",
"args",
")",
"elsif",
"blk",
"!=",
"nil",
"send",
"(",
"\"#{attr}=\"",
",",
"blk",
")",
"else",
"send",
"(",
"\"#{attr}_old_get\"",
")",
"end",
"end",
"end",
"end",
"end"
]
| Creates a DSL-friendly set-and-getter method. The method, when called with
no arguments, acts as a getter. When called with arguments, it acts as a
setter. Uses class instance variables - this is not for generating
instance methods.
@example
class A
cattr_get_and_setter :type
end
class B < A
type :silly
end
p B.type # => :silly | [
"Creates",
"a",
"DSL",
"-",
"friendly",
"set",
"-",
"and",
"-",
"getter",
"method",
".",
"The",
"method",
"when",
"called",
"with",
"no",
"arguments",
"acts",
"as",
"a",
"getter",
".",
"When",
"called",
"with",
"arguments",
"it",
"acts",
"as",
"a",
"setter",
".",
"Uses",
"class",
"instance",
"variables",
"-",
"this",
"is",
"not",
"for",
"generating",
"instance",
"methods",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/support/module_extensions.rb#L76-L92 | train |
michaeledgar/laser | lib/laser/third_party/rgl/dominators.rb | RGL.Graph.dominance_frontier | def dominance_frontier(start_node = self.enter, dom_tree)
vertices.inject(Hash.new { |h, k| h[k] = Set.new }) do |result, b|
preds = b.real_predecessors
if preds.size >= 2
preds.each do |p|
b_dominator = dom_tree[b].successors.first
break unless b_dominator
runner = dom_tree[p]
while runner && runner != b_dominator
result[runner] << b
runner = runner.successors.first
end
end
end
result
end
end | ruby | def dominance_frontier(start_node = self.enter, dom_tree)
vertices.inject(Hash.new { |h, k| h[k] = Set.new }) do |result, b|
preds = b.real_predecessors
if preds.size >= 2
preds.each do |p|
b_dominator = dom_tree[b].successors.first
break unless b_dominator
runner = dom_tree[p]
while runner && runner != b_dominator
result[runner] << b
runner = runner.successors.first
end
end
end
result
end
end | [
"def",
"dominance_frontier",
"(",
"start_node",
"=",
"self",
".",
"enter",
",",
"dom_tree",
")",
"vertices",
".",
"inject",
"(",
"Hash",
".",
"new",
"{",
"|",
"h",
",",
"k",
"|",
"h",
"[",
"k",
"]",
"=",
"Set",
".",
"new",
"}",
")",
"do",
"|",
"result",
",",
"b",
"|",
"preds",
"=",
"b",
".",
"real_predecessors",
"if",
"preds",
".",
"size",
">=",
"2",
"preds",
".",
"each",
"do",
"|",
"p",
"|",
"b_dominator",
"=",
"dom_tree",
"[",
"b",
"]",
".",
"successors",
".",
"first",
"break",
"unless",
"b_dominator",
"runner",
"=",
"dom_tree",
"[",
"p",
"]",
"while",
"runner",
"&&",
"runner",
"!=",
"b_dominator",
"result",
"[",
"runner",
"]",
"<<",
"b",
"runner",
"=",
"runner",
".",
"successors",
".",
"first",
"end",
"end",
"end",
"result",
"end",
"end"
]
| Returns the dominance frontier of the graph.
If the start node is not provided, it is assumed the receiver is a
ControlFlowGraph and has an #enter method.
return: Node => Set<Node> | [
"Returns",
"the",
"dominance",
"frontier",
"of",
"the",
"graph",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/third_party/rgl/dominators.rb#L55-L71 | train |
michaeledgar/laser | lib/laser/third_party/rgl/dominators.rb | RGL.Graph.dominator_set_intersect | def dominator_set_intersect(b1, b2, doms)
finger1, finger2 = b1, b2
while finger1.post_order_number != finger2.post_order_number
finger1 = doms[finger1] while finger1.post_order_number < finger2.post_order_number
finger2 = doms[finger2] while finger2.post_order_number < finger1.post_order_number
end
finger1
end | ruby | def dominator_set_intersect(b1, b2, doms)
finger1, finger2 = b1, b2
while finger1.post_order_number != finger2.post_order_number
finger1 = doms[finger1] while finger1.post_order_number < finger2.post_order_number
finger2 = doms[finger2] while finger2.post_order_number < finger1.post_order_number
end
finger1
end | [
"def",
"dominator_set_intersect",
"(",
"b1",
",",
"b2",
",",
"doms",
")",
"finger1",
",",
"finger2",
"=",
"b1",
",",
"b2",
"while",
"finger1",
".",
"post_order_number",
"!=",
"finger2",
".",
"post_order_number",
"finger1",
"=",
"doms",
"[",
"finger1",
"]",
"while",
"finger1",
".",
"post_order_number",
"<",
"finger2",
".",
"post_order_number",
"finger2",
"=",
"doms",
"[",
"finger2",
"]",
"while",
"finger2",
".",
"post_order_number",
"<",
"finger1",
".",
"post_order_number",
"end",
"finger1",
"end"
]
| performs a set intersection of the dominator tree. | [
"performs",
"a",
"set",
"intersection",
"of",
"the",
"dominator",
"tree",
"."
]
| 0e38780eb44466ae35f33d28ec75536a4f3a969b | https://github.com/michaeledgar/laser/blob/0e38780eb44466ae35f33d28ec75536a4f3a969b/lib/laser/third_party/rgl/dominators.rb#L96-L103 | train |
OSC/ood_core | lib/ood_core/cluster.rb | OodCore.Cluster.batch_connect_config | def batch_connect_config(template = nil)
if template
@batch_connect_config.fetch(template.to_sym, {}).to_h.symbolize_keys.merge(template: template.to_sym)
else
@batch_connect_config
end
end | ruby | def batch_connect_config(template = nil)
if template
@batch_connect_config.fetch(template.to_sym, {}).to_h.symbolize_keys.merge(template: template.to_sym)
else
@batch_connect_config
end
end | [
"def",
"batch_connect_config",
"(",
"template",
"=",
"nil",
")",
"if",
"template",
"@batch_connect_config",
".",
"fetch",
"(",
"template",
".",
"to_sym",
",",
"{",
"}",
")",
".",
"to_h",
".",
"symbolize_keys",
".",
"merge",
"(",
"template",
":",
"template",
".",
"to_sym",
")",
"else",
"@batch_connect_config",
"end",
"end"
]
| The batch connect template configuration used for this cluster
@param template [#to_sym, nil] the template type
@return [Hash] the batch connect configuration | [
"The",
"batch",
"connect",
"template",
"configuration",
"used",
"for",
"this",
"cluster"
]
| 11eb65be194a8a4c956b70fb8c78a715e763b1df | https://github.com/OSC/ood_core/blob/11eb65be194a8a4c956b70fb8c78a715e763b1df/lib/ood_core/cluster.rb#L92-L98 | train |
OSC/ood_core | lib/ood_core/cluster.rb | OodCore.Cluster.batch_connect_template | def batch_connect_template(context = {})
context = context.to_h.symbolize_keys
BatchConnect::Factory.build batch_connect_config(context[:template] || :basic).merge(context)
end | ruby | def batch_connect_template(context = {})
context = context.to_h.symbolize_keys
BatchConnect::Factory.build batch_connect_config(context[:template] || :basic).merge(context)
end | [
"def",
"batch_connect_template",
"(",
"context",
"=",
"{",
"}",
")",
"context",
"=",
"context",
".",
"to_h",
".",
"symbolize_keys",
"BatchConnect",
"::",
"Factory",
".",
"build",
"batch_connect_config",
"(",
"context",
"[",
":template",
"]",
"||",
":basic",
")",
".",
"merge",
"(",
"context",
")",
"end"
]
| Build a batch connect template from the respective configuration
@param context [#to_h] the context used for rendering the template
@return [BatchConnect::Template] the batch connect template | [
"Build",
"a",
"batch",
"connect",
"template",
"from",
"the",
"respective",
"configuration"
]
| 11eb65be194a8a4c956b70fb8c78a715e763b1df | https://github.com/OSC/ood_core/blob/11eb65be194a8a4c956b70fb8c78a715e763b1df/lib/ood_core/cluster.rb#L103-L106 | train |
OSC/ood_core | lib/ood_core/cluster.rb | OodCore.Cluster.custom_allow? | def custom_allow?(feature)
allow? &&
!custom_config(feature).empty? &&
build_acls(custom_config(feature).fetch(:acls, []).map(&:to_h)).all?(&:allow?)
end | ruby | def custom_allow?(feature)
allow? &&
!custom_config(feature).empty? &&
build_acls(custom_config(feature).fetch(:acls, []).map(&:to_h)).all?(&:allow?)
end | [
"def",
"custom_allow?",
"(",
"feature",
")",
"allow?",
"&&",
"!",
"custom_config",
"(",
"feature",
")",
".",
"empty?",
"&&",
"build_acls",
"(",
"custom_config",
"(",
"feature",
")",
".",
"fetch",
"(",
":acls",
",",
"[",
"]",
")",
".",
"map",
"(",
"&",
":to_h",
")",
")",
".",
"all?",
"(",
"&",
":allow?",
")",
"end"
]
| Whether the custom feature is allowed based on the ACLs
@return [Boolean] is this custom feature allowed | [
"Whether",
"the",
"custom",
"feature",
"is",
"allowed",
"based",
"on",
"the",
"ACLs"
]
| 11eb65be194a8a4c956b70fb8c78a715e763b1df | https://github.com/OSC/ood_core/blob/11eb65be194a8a4c956b70fb8c78a715e763b1df/lib/ood_core/cluster.rb#L117-L121 | train |
OSC/ood_core | lib/ood_core/cluster.rb | OodCore.Cluster.to_h | def to_h
{
id: id,
metadata: metadata_config,
login: login_config,
job: job_config,
custom: custom_config,
acls: acls_config,
batch_connect: batch_connect_config
}
end | ruby | def to_h
{
id: id,
metadata: metadata_config,
login: login_config,
job: job_config,
custom: custom_config,
acls: acls_config,
batch_connect: batch_connect_config
}
end | [
"def",
"to_h",
"{",
"id",
":",
"id",
",",
"metadata",
":",
"metadata_config",
",",
"login",
":",
"login_config",
",",
"job",
":",
"job_config",
",",
"custom",
":",
"custom_config",
",",
"acls",
":",
"acls_config",
",",
"batch_connect",
":",
"batch_connect_config",
"}",
"end"
]
| Convert object to hash
@return [Hash] the hash describing this object | [
"Convert",
"object",
"to",
"hash"
]
| 11eb65be194a8a4c956b70fb8c78a715e763b1df | https://github.com/OSC/ood_core/blob/11eb65be194a8a4c956b70fb8c78a715e763b1df/lib/ood_core/cluster.rb#L150-L160 | train |
OSC/ood_core | lib/ood_core/job/adapters/drmaa.rb | DRMAA.Session.run_bulk | def run_bulk(t, first, last, incr = 1)
retry_until { DRMAA.run_bulk_jobs(t.ptr, first, last, incr) }
end | ruby | def run_bulk(t, first, last, incr = 1)
retry_until { DRMAA.run_bulk_jobs(t.ptr, first, last, incr) }
end | [
"def",
"run_bulk",
"(",
"t",
",",
"first",
",",
"last",
",",
"incr",
"=",
"1",
")",
"retry_until",
"{",
"DRMAA",
".",
"run_bulk_jobs",
"(",
"t",
".",
"ptr",
",",
"first",
",",
"last",
",",
"incr",
")",
"}",
"end"
]
| submits bulk job described by JobTemplate 't'
and returns an array of job id strings | [
"submits",
"bulk",
"job",
"described",
"by",
"JobTemplate",
"t",
"and",
"returns",
"an",
"array",
"of",
"job",
"id",
"strings"
]
| 11eb65be194a8a4c956b70fb8c78a715e763b1df | https://github.com/OSC/ood_core/blob/11eb65be194a8a4c956b70fb8c78a715e763b1df/lib/ood_core/job/adapters/drmaa.rb#L756-L758 | train |
OSC/ood_core | lib/ood_core/job/adapters/drmaa.rb | DRMAA.Session.wait_each | def wait_each(timeout = -1)
if ! block_given?
ary = Array.new
end
while true
begin
info = DRMAA.wait(ANY_JOB, timeout)
rescue DRMAAInvalidJobError
break
end
if block_given?
yield info
else
ary << info
end
end
if ! block_given?
return ary
end
end | ruby | def wait_each(timeout = -1)
if ! block_given?
ary = Array.new
end
while true
begin
info = DRMAA.wait(ANY_JOB, timeout)
rescue DRMAAInvalidJobError
break
end
if block_given?
yield info
else
ary << info
end
end
if ! block_given?
return ary
end
end | [
"def",
"wait_each",
"(",
"timeout",
"=",
"-",
"1",
")",
"if",
"!",
"block_given?",
"ary",
"=",
"Array",
".",
"new",
"end",
"while",
"true",
"begin",
"info",
"=",
"DRMAA",
".",
"wait",
"(",
"ANY_JOB",
",",
"timeout",
")",
"rescue",
"DRMAAInvalidJobError",
"break",
"end",
"if",
"block_given?",
"yield",
"info",
"else",
"ary",
"<<",
"info",
"end",
"end",
"if",
"!",
"block_given?",
"return",
"ary",
"end",
"end"
]
| run block with JobInfo to finish for each waited session job
or return JobInfo array if no block was passed | [
"run",
"block",
"with",
"JobInfo",
"to",
"finish",
"for",
"each",
"waited",
"session",
"job",
"or",
"return",
"JobInfo",
"array",
"if",
"no",
"block",
"was",
"passed"
]
| 11eb65be194a8a4c956b70fb8c78a715e763b1df | https://github.com/OSC/ood_core/blob/11eb65be194a8a4c956b70fb8c78a715e763b1df/lib/ood_core/job/adapters/drmaa.rb#L772-L791 | train |
activerecord-hackery/meta_where | lib/meta_where/relation.rb | MetaWhere.Relation.predicate_visitor | def predicate_visitor
join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, association_joins, custom_joins)
MetaWhere::Visitors::Predicate.new(join_dependency)
end | ruby | def predicate_visitor
join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, association_joins, custom_joins)
MetaWhere::Visitors::Predicate.new(join_dependency)
end | [
"def",
"predicate_visitor",
"join_dependency",
"=",
"ActiveRecord",
"::",
"Associations",
"::",
"ClassMethods",
"::",
"JoinDependency",
".",
"new",
"(",
"@klass",
",",
"association_joins",
",",
"custom_joins",
")",
"MetaWhere",
"::",
"Visitors",
"::",
"Predicate",
".",
"new",
"(",
"join_dependency",
")",
"end"
]
| Very occasionally, we need to get a visitor for another relation, so it makes sense to factor
these out into a public method despite only being two lines long. | [
"Very",
"occasionally",
"we",
"need",
"to",
"get",
"a",
"visitor",
"for",
"another",
"relation",
"so",
"it",
"makes",
"sense",
"to",
"factor",
"these",
"out",
"into",
"a",
"public",
"method",
"despite",
"only",
"being",
"two",
"lines",
"long",
"."
]
| 12f2ee52eb3789ac50b0d77890122dd85b85da9b | https://github.com/activerecord-hackery/meta_where/blob/12f2ee52eb3789ac50b0d77890122dd85b85da9b/lib/meta_where/relation.rb#L116-L119 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.schedule_blast_from_template | def schedule_blast_from_template(template, list, schedule_time, options={})
post = options ? options : {}
post[:copy_template] = template
post[:list] = list
post[:schedule_time] = schedule_time
api_post(:blast, post)
end | ruby | def schedule_blast_from_template(template, list, schedule_time, options={})
post = options ? options : {}
post[:copy_template] = template
post[:list] = list
post[:schedule_time] = schedule_time
api_post(:blast, post)
end | [
"def",
"schedule_blast_from_template",
"(",
"template",
",",
"list",
",",
"schedule_time",
",",
"options",
"=",
"{",
"}",
")",
"post",
"=",
"options",
"?",
"options",
":",
"{",
"}",
"post",
"[",
":copy_template",
"]",
"=",
"template",
"post",
"[",
":list",
"]",
"=",
"list",
"post",
"[",
":schedule_time",
"]",
"=",
"schedule_time",
"api_post",
"(",
":blast",
",",
"post",
")",
"end"
]
| Schedule a mass mail blast from template | [
"Schedule",
"a",
"mass",
"mail",
"blast",
"from",
"template"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L108-L114 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.schedule_blast_from_blast | def schedule_blast_from_blast(blast_id, schedule_time, options={})
post = options ? options : {}
post[:copy_blast] = blast_id
#post[:name] = name
post[:schedule_time] = schedule_time
api_post(:blast, post)
end | ruby | def schedule_blast_from_blast(blast_id, schedule_time, options={})
post = options ? options : {}
post[:copy_blast] = blast_id
#post[:name] = name
post[:schedule_time] = schedule_time
api_post(:blast, post)
end | [
"def",
"schedule_blast_from_blast",
"(",
"blast_id",
",",
"schedule_time",
",",
"options",
"=",
"{",
"}",
")",
"post",
"=",
"options",
"?",
"options",
":",
"{",
"}",
"post",
"[",
":copy_blast",
"]",
"=",
"blast_id",
"post",
"[",
":schedule_time",
"]",
"=",
"schedule_time",
"api_post",
"(",
":blast",
",",
"post",
")",
"end"
]
| Schedule a mass mail blast from previous blast | [
"Schedule",
"a",
"mass",
"mail",
"blast",
"from",
"previous",
"blast"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L117-L123 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.update_blast | def update_blast(blast_id, name = nil, list = nil, schedule_time = nil, from_name = nil, from_email = nil, subject = nil, content_html = nil, content_text = nil, options = {})
data = options ? options : {}
data[:blast_id] = blast_id
if name != nil
data[:name] = name
end
if list != nil
data[:list] = list
end
if schedule_time != nil
data[:schedule_time] = schedule_time
end
if from_name != nil
data[:from_name] = from_name
end
if from_email != nil
data[:from_email] = from_email
end
if subject != nil
data[:subject] = subject
end
if content_html != nil
data[:content_html] = content_html
end
if content_text != nil
data[:content_text] = content_text
end
api_post(:blast, data)
end | ruby | def update_blast(blast_id, name = nil, list = nil, schedule_time = nil, from_name = nil, from_email = nil, subject = nil, content_html = nil, content_text = nil, options = {})
data = options ? options : {}
data[:blast_id] = blast_id
if name != nil
data[:name] = name
end
if list != nil
data[:list] = list
end
if schedule_time != nil
data[:schedule_time] = schedule_time
end
if from_name != nil
data[:from_name] = from_name
end
if from_email != nil
data[:from_email] = from_email
end
if subject != nil
data[:subject] = subject
end
if content_html != nil
data[:content_html] = content_html
end
if content_text != nil
data[:content_text] = content_text
end
api_post(:blast, data)
end | [
"def",
"update_blast",
"(",
"blast_id",
",",
"name",
"=",
"nil",
",",
"list",
"=",
"nil",
",",
"schedule_time",
"=",
"nil",
",",
"from_name",
"=",
"nil",
",",
"from_email",
"=",
"nil",
",",
"subject",
"=",
"nil",
",",
"content_html",
"=",
"nil",
",",
"content_text",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"data",
"=",
"options",
"?",
"options",
":",
"{",
"}",
"data",
"[",
":blast_id",
"]",
"=",
"blast_id",
"if",
"name",
"!=",
"nil",
"data",
"[",
":name",
"]",
"=",
"name",
"end",
"if",
"list",
"!=",
"nil",
"data",
"[",
":list",
"]",
"=",
"list",
"end",
"if",
"schedule_time",
"!=",
"nil",
"data",
"[",
":schedule_time",
"]",
"=",
"schedule_time",
"end",
"if",
"from_name",
"!=",
"nil",
"data",
"[",
":from_name",
"]",
"=",
"from_name",
"end",
"if",
"from_email",
"!=",
"nil",
"data",
"[",
":from_email",
"]",
"=",
"from_email",
"end",
"if",
"subject",
"!=",
"nil",
"data",
"[",
":subject",
"]",
"=",
"subject",
"end",
"if",
"content_html",
"!=",
"nil",
"data",
"[",
":content_html",
"]",
"=",
"content_html",
"end",
"if",
"content_text",
"!=",
"nil",
"data",
"[",
":content_text",
"]",
"=",
"content_text",
"end",
"api_post",
"(",
":blast",
",",
"data",
")",
"end"
]
| params
blast_id, Fixnum | String
name, String
list, String
schedule_time, String
from_name, String
from_email, String
subject, String
content_html, String
content_text, String
options, hash
updates existing blast | [
"params",
"blast_id",
"Fixnum",
"|",
"String",
"name",
"String",
"list",
"String",
"schedule_time",
"String",
"from_name",
"String",
"from_email",
"String",
"subject",
"String",
"content_html",
"String",
"content_text",
"String",
"options",
"hash"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L138-L166 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.stats_list | def stats_list(list = nil, date = nil)
data = {}
if list != nil
data[:list] = list
end
if date != nil
data[:date] = date
end
data[:stat] = 'list'
api_get(:stats, data)
end | ruby | def stats_list(list = nil, date = nil)
data = {}
if list != nil
data[:list] = list
end
if date != nil
data[:date] = date
end
data[:stat] = 'list'
api_get(:stats, data)
end | [
"def",
"stats_list",
"(",
"list",
"=",
"nil",
",",
"date",
"=",
"nil",
")",
"data",
"=",
"{",
"}",
"if",
"list",
"!=",
"nil",
"data",
"[",
":list",
"]",
"=",
"list",
"end",
"if",
"date",
"!=",
"nil",
"data",
"[",
":date",
"]",
"=",
"date",
"end",
"data",
"[",
":stat",
"]",
"=",
"'list'",
"api_get",
"(",
":stats",
",",
"data",
")",
"end"
]
| params
list, String
date, String
returns:
hash, response from server
Retrieve information about your subscriber counts on a particular list, on a particular day. | [
"params",
"list",
"String",
"date",
"String"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L411-L421 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.stats_blast | def stats_blast(blast_id = nil, start_date = nil, end_date = nil, options = {})
data = options
if blast_id != nil
data[:blast_id] = blast_id
end
if start_date != nil
data[:start_date] = start_date
end
if end_date != nil
data[:end_date] = end_date
end
data[:stat] = 'blast'
api_get(:stats, data)
end | ruby | def stats_blast(blast_id = nil, start_date = nil, end_date = nil, options = {})
data = options
if blast_id != nil
data[:blast_id] = blast_id
end
if start_date != nil
data[:start_date] = start_date
end
if end_date != nil
data[:end_date] = end_date
end
data[:stat] = 'blast'
api_get(:stats, data)
end | [
"def",
"stats_blast",
"(",
"blast_id",
"=",
"nil",
",",
"start_date",
"=",
"nil",
",",
"end_date",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"data",
"=",
"options",
"if",
"blast_id",
"!=",
"nil",
"data",
"[",
":blast_id",
"]",
"=",
"blast_id",
"end",
"if",
"start_date",
"!=",
"nil",
"data",
"[",
":start_date",
"]",
"=",
"start_date",
"end",
"if",
"end_date",
"!=",
"nil",
"data",
"[",
":end_date",
"]",
"=",
"end_date",
"end",
"data",
"[",
":stat",
"]",
"=",
"'blast'",
"api_get",
"(",
":stats",
",",
"data",
")",
"end"
]
| params
blast_id, String
start_date, String
end_date, String
options, Hash
returns:
hash, response from server
Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range | [
"params",
"blast_id",
"String",
"start_date",
"String",
"end_date",
"String",
"options",
"Hash"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L432-L445 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.stats_send | def stats_send(template = nil, start_date = nil, end_date = nil, options = {})
data = options
if template != nil
data[:template] = template
end
if start_date != nil
data[:start_date] = start_date
end
if end_date != nil
data[:end_date] = end_date
end
data[:stat] = 'send'
api_get(:stats, data)
end | ruby | def stats_send(template = nil, start_date = nil, end_date = nil, options = {})
data = options
if template != nil
data[:template] = template
end
if start_date != nil
data[:start_date] = start_date
end
if end_date != nil
data[:end_date] = end_date
end
data[:stat] = 'send'
api_get(:stats, data)
end | [
"def",
"stats_send",
"(",
"template",
"=",
"nil",
",",
"start_date",
"=",
"nil",
",",
"end_date",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"data",
"=",
"options",
"if",
"template",
"!=",
"nil",
"data",
"[",
":template",
"]",
"=",
"template",
"end",
"if",
"start_date",
"!=",
"nil",
"data",
"[",
":start_date",
"]",
"=",
"start_date",
"end",
"if",
"end_date",
"!=",
"nil",
"data",
"[",
":end_date",
"]",
"=",
"end_date",
"end",
"data",
"[",
":stat",
"]",
"=",
"'send'",
"api_get",
"(",
":stats",
",",
"data",
")",
"end"
]
| params
template, String
start_date, String
end_date, String
options, Hash
returns:
hash, response from server
Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range | [
"params",
"template",
"String",
"start_date",
"String",
"end_date",
"String",
"options",
"Hash"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L456-L469 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.save_alert | def save_alert(email, type, template, _when = nil, options = {})
data = options
data[:email] = email
data[:type] = type
data[:template] = template
if (type == 'weekly' || type == 'daily')
data[:when] = _when
end
api_post(:alert, data)
end | ruby | def save_alert(email, type, template, _when = nil, options = {})
data = options
data[:email] = email
data[:type] = type
data[:template] = template
if (type == 'weekly' || type == 'daily')
data[:when] = _when
end
api_post(:alert, data)
end | [
"def",
"save_alert",
"(",
"email",
",",
"type",
",",
"template",
",",
"_when",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"data",
"=",
"options",
"data",
"[",
":email",
"]",
"=",
"email",
"data",
"[",
":type",
"]",
"=",
"type",
"data",
"[",
":template",
"]",
"=",
"template",
"if",
"(",
"type",
"==",
"'weekly'",
"||",
"type",
"==",
"'daily'",
")",
"data",
"[",
":when",
"]",
"=",
"_when",
"end",
"api_post",
"(",
":alert",
",",
"data",
")",
"end"
]
| params
email, String
type, String
template, String
_when, String
options, hash
Add a new alert to a user. You can add either a realtime or a summary alert (daily/weekly).
_when is only required when alert type is weekly or daily | [
"params",
"email",
"String",
"type",
"String",
"template",
"String",
"_when",
"String",
"options",
"hash"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L566-L575 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.process_job | def process_job(job, options = {}, report_email = nil, postback_url = nil, binary_key = nil)
data = options
data['job'] = job
if !report_email.nil?
data['report_email'] = report_email
end
if !postback_url.nil?
data['postback_url'] = postback_url
end
api_post(:job, data, binary_key)
end | ruby | def process_job(job, options = {}, report_email = nil, postback_url = nil, binary_key = nil)
data = options
data['job'] = job
if !report_email.nil?
data['report_email'] = report_email
end
if !postback_url.nil?
data['postback_url'] = postback_url
end
api_post(:job, data, binary_key)
end | [
"def",
"process_job",
"(",
"job",
",",
"options",
"=",
"{",
"}",
",",
"report_email",
"=",
"nil",
",",
"postback_url",
"=",
"nil",
",",
"binary_key",
"=",
"nil",
")",
"data",
"=",
"options",
"data",
"[",
"'job'",
"]",
"=",
"job",
"if",
"!",
"report_email",
".",
"nil?",
"data",
"[",
"'report_email'",
"]",
"=",
"report_email",
"end",
"if",
"!",
"postback_url",
".",
"nil?",
"data",
"[",
"'postback_url'",
"]",
"=",
"postback_url",
"end",
"api_post",
"(",
":job",
",",
"data",
",",
"binary_key",
")",
"end"
]
| params
job, String
options, hash
report_email, String
postback_url, String
binary_key, String
interface for making request to job call | [
"params",
"job",
"String",
"options",
"hash",
"report_email",
"String",
"postback_url",
"String",
"binary_key",
"String"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L595-L606 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.process_import_job | def process_import_job(list, emails, report_email = nil, postback_url = nil, options = {})
data = options
data['list'] = list
data['emails'] = Array(emails).join(',')
process_job(:import, data, report_email, postback_url)
end | ruby | def process_import_job(list, emails, report_email = nil, postback_url = nil, options = {})
data = options
data['list'] = list
data['emails'] = Array(emails).join(',')
process_job(:import, data, report_email, postback_url)
end | [
"def",
"process_import_job",
"(",
"list",
",",
"emails",
",",
"report_email",
"=",
"nil",
",",
"postback_url",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"data",
"=",
"options",
"data",
"[",
"'list'",
"]",
"=",
"list",
"data",
"[",
"'emails'",
"]",
"=",
"Array",
"(",
"emails",
")",
".",
"join",
"(",
"','",
")",
"process_job",
"(",
":import",
",",
"data",
",",
"report_email",
",",
"postback_url",
")",
"end"
]
| params
emails, String | Array
implementation for import_job | [
"params",
"emails",
"String",
"|",
"Array",
"implementation",
"for",
"import_job"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L611-L616 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.process_import_job_from_file | def process_import_job_from_file(list, file_path, report_email = nil, postback_url = nil, options = {})
data = options
data['list'] = list
data['file'] = file_path
process_job(:import, data, report_email, postback_url, 'file')
end | ruby | def process_import_job_from_file(list, file_path, report_email = nil, postback_url = nil, options = {})
data = options
data['list'] = list
data['file'] = file_path
process_job(:import, data, report_email, postback_url, 'file')
end | [
"def",
"process_import_job_from_file",
"(",
"list",
",",
"file_path",
",",
"report_email",
"=",
"nil",
",",
"postback_url",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"data",
"=",
"options",
"data",
"[",
"'list'",
"]",
"=",
"list",
"data",
"[",
"'file'",
"]",
"=",
"file_path",
"process_job",
"(",
":import",
",",
"data",
",",
"report_email",
",",
"postback_url",
",",
"'file'",
")",
"end"
]
| implementation for import job using file upload | [
"implementation",
"for",
"import",
"job",
"using",
"file",
"upload"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L619-L624 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.process_update_job_from_file | def process_update_job_from_file(file_path, report_email = nil, postback_url = nil, options = {})
data = options
data['file'] = file_path
process_job(:update, data, report_email, postback_url, 'file')
end | ruby | def process_update_job_from_file(file_path, report_email = nil, postback_url = nil, options = {})
data = options
data['file'] = file_path
process_job(:update, data, report_email, postback_url, 'file')
end | [
"def",
"process_update_job_from_file",
"(",
"file_path",
",",
"report_email",
"=",
"nil",
",",
"postback_url",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"data",
"=",
"options",
"data",
"[",
"'file'",
"]",
"=",
"file_path",
"process_job",
"(",
":update",
",",
"data",
",",
"report_email",
",",
"postback_url",
",",
"'file'",
")",
"end"
]
| implementation for update job using file upload | [
"implementation",
"for",
"update",
"job",
"using",
"file",
"upload"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L627-L631 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.process_purchase_import_job_from_file | def process_purchase_import_job_from_file(file_path, report_email = nil, postback_url = nil, options = {})
data = options
data['file'] = file_path
process_job(:purchase_import, data, report_email, postback_url, 'file')
end | ruby | def process_purchase_import_job_from_file(file_path, report_email = nil, postback_url = nil, options = {})
data = options
data['file'] = file_path
process_job(:purchase_import, data, report_email, postback_url, 'file')
end | [
"def",
"process_purchase_import_job_from_file",
"(",
"file_path",
",",
"report_email",
"=",
"nil",
",",
"postback_url",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"data",
"=",
"options",
"data",
"[",
"'file'",
"]",
"=",
"file_path",
"process_job",
"(",
":purchase_import",
",",
"data",
",",
"report_email",
",",
"postback_url",
",",
"'file'",
")",
"end"
]
| implementation for purchase import job using file upload | [
"implementation",
"for",
"purchase",
"import",
"job",
"using",
"file",
"upload"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L634-L638 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.process_snapshot_job | def process_snapshot_job(query = {}, report_email = nil, postback_url = nil, options = {})
data = options
data['query'] = query
process_job(:snapshot, data, report_email, postback_url)
end | ruby | def process_snapshot_job(query = {}, report_email = nil, postback_url = nil, options = {})
data = options
data['query'] = query
process_job(:snapshot, data, report_email, postback_url)
end | [
"def",
"process_snapshot_job",
"(",
"query",
"=",
"{",
"}",
",",
"report_email",
"=",
"nil",
",",
"postback_url",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"data",
"=",
"options",
"data",
"[",
"'query'",
"]",
"=",
"query",
"process_job",
"(",
":snapshot",
",",
"data",
",",
"report_email",
",",
"postback_url",
")",
"end"
]
| implementation for snapshot job | [
"implementation",
"for",
"snapshot",
"job"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L641-L645 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.process_export_list_job | def process_export_list_job(list, report_email = nil, postback_url = nil, options = {})
data = options
data['list'] = list
process_job(:export_list_data, data, report_email, postback_url)
end | ruby | def process_export_list_job(list, report_email = nil, postback_url = nil, options = {})
data = options
data['list'] = list
process_job(:export_list_data, data, report_email, postback_url)
end | [
"def",
"process_export_list_job",
"(",
"list",
",",
"report_email",
"=",
"nil",
",",
"postback_url",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"data",
"=",
"options",
"data",
"[",
"'list'",
"]",
"=",
"list",
"process_job",
"(",
":export_list_data",
",",
"data",
",",
"report_email",
",",
"postback_url",
")",
"end"
]
| implementation for export list job | [
"implementation",
"for",
"export",
"list",
"job"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L648-L652 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.get_user_by_key | def get_user_by_key(id, key, fields = {})
data = {
'id' => id,
'key' => key,
'fields' => fields
}
api_get(:user, data)
end | ruby | def get_user_by_key(id, key, fields = {})
data = {
'id' => id,
'key' => key,
'fields' => fields
}
api_get(:user, data)
end | [
"def",
"get_user_by_key",
"(",
"id",
",",
"key",
",",
"fields",
"=",
"{",
"}",
")",
"data",
"=",
"{",
"'id'",
"=>",
"id",
",",
"'key'",
"=>",
"key",
",",
"'fields'",
"=>",
"fields",
"}",
"api_get",
"(",
":user",
",",
"data",
")",
"end"
]
| Get user by specified key | [
"Get",
"user",
"by",
"specified",
"key"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L665-L672 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.get_trigger_by_template | def get_trigger_by_template(template, trigger_id = nil)
data = {}
data['template'] = template
if trigger_id != nil then data['trigger_id'] = trigger_id end
api_get(:trigger, data)
end | ruby | def get_trigger_by_template(template, trigger_id = nil)
data = {}
data['template'] = template
if trigger_id != nil then data['trigger_id'] = trigger_id end
api_get(:trigger, data)
end | [
"def",
"get_trigger_by_template",
"(",
"template",
",",
"trigger_id",
"=",
"nil",
")",
"data",
"=",
"{",
"}",
"data",
"[",
"'template'",
"]",
"=",
"template",
"if",
"trigger_id",
"!=",
"nil",
"then",
"data",
"[",
"'trigger_id'",
"]",
"=",
"trigger_id",
"end",
"api_get",
"(",
":trigger",
",",
"data",
")",
"end"
]
| params
template, String
trigger_id, String
Get an existing trigger | [
"params",
"template",
"String",
"trigger_id",
"String",
"Get",
"an",
"existing",
"trigger"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L691-L696 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.post_template_trigger | def post_template_trigger(template, time, time_unit, event, zephyr)
data = {}
data['template'] = template
data['time'] = time
data['time_unit'] = time_unit
data['event'] = event
data['zephyr'] = zephyr
api_post(:trigger, data)
end | ruby | def post_template_trigger(template, time, time_unit, event, zephyr)
data = {}
data['template'] = template
data['time'] = time
data['time_unit'] = time_unit
data['event'] = event
data['zephyr'] = zephyr
api_post(:trigger, data)
end | [
"def",
"post_template_trigger",
"(",
"template",
",",
"time",
",",
"time_unit",
",",
"event",
",",
"zephyr",
")",
"data",
"=",
"{",
"}",
"data",
"[",
"'template'",
"]",
"=",
"template",
"data",
"[",
"'time'",
"]",
"=",
"time",
"data",
"[",
"'time_unit'",
"]",
"=",
"time_unit",
"data",
"[",
"'event'",
"]",
"=",
"event",
"data",
"[",
"'zephyr'",
"]",
"=",
"zephyr",
"api_post",
"(",
":trigger",
",",
"data",
")",
"end"
]
| params
template, String
time, String
time_unit, String
event, String
zephyr, String
Create or update a trigger | [
"params",
"template",
"String",
"time",
"String",
"time_unit",
"String",
"event",
"String",
"zephyr",
"String",
"Create",
"or",
"update",
"a",
"trigger"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L714-L722 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.post_event_trigger | def post_event_trigger(event, time, time_unit, zephyr)
data = {}
data['time'] = time
data['time_unit'] = time_unit
data['event'] = event
data['zephyr'] = zephyr
api_post(:trigger, data)
end | ruby | def post_event_trigger(event, time, time_unit, zephyr)
data = {}
data['time'] = time
data['time_unit'] = time_unit
data['event'] = event
data['zephyr'] = zephyr
api_post(:trigger, data)
end | [
"def",
"post_event_trigger",
"(",
"event",
",",
"time",
",",
"time_unit",
",",
"zephyr",
")",
"data",
"=",
"{",
"}",
"data",
"[",
"'time'",
"]",
"=",
"time",
"data",
"[",
"'time_unit'",
"]",
"=",
"time_unit",
"data",
"[",
"'event'",
"]",
"=",
"event",
"data",
"[",
"'zephyr'",
"]",
"=",
"zephyr",
"api_post",
"(",
":trigger",
",",
"data",
")",
"end"
]
| params
template, String
time, String
time_unit, String
zephyr, String
Create or update a trigger | [
"params",
"template",
"String",
"time",
"String",
"time_unit",
"String",
"zephyr",
"String",
"Create",
"or",
"update",
"a",
"trigger"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L730-L737 | train |
sailthru/sailthru-ruby-client | lib/sailthru/client.rb | Sailthru.Client.set_up_post_request | def set_up_post_request(uri, data, headers, binary_key = nil)
if !binary_key.nil?
binary_data = data[binary_key]
if binary_data.is_a?(StringIO)
data[binary_key] = UploadIO.new(
binary_data, "text/plain", "local.path"
)
else
data[binary_key] = UploadIO.new(
File.open(binary_data), "text/plain"
)
end
req = Net::HTTP::Post::Multipart.new(uri.path, data)
else
req = Net::HTTP::Post.new(uri.path, headers)
req.set_form_data(data)
end
req
end | ruby | def set_up_post_request(uri, data, headers, binary_key = nil)
if !binary_key.nil?
binary_data = data[binary_key]
if binary_data.is_a?(StringIO)
data[binary_key] = UploadIO.new(
binary_data, "text/plain", "local.path"
)
else
data[binary_key] = UploadIO.new(
File.open(binary_data), "text/plain"
)
end
req = Net::HTTP::Post::Multipart.new(uri.path, data)
else
req = Net::HTTP::Post.new(uri.path, headers)
req.set_form_data(data)
end
req
end | [
"def",
"set_up_post_request",
"(",
"uri",
",",
"data",
",",
"headers",
",",
"binary_key",
"=",
"nil",
")",
"if",
"!",
"binary_key",
".",
"nil?",
"binary_data",
"=",
"data",
"[",
"binary_key",
"]",
"if",
"binary_data",
".",
"is_a?",
"(",
"StringIO",
")",
"data",
"[",
"binary_key",
"]",
"=",
"UploadIO",
".",
"new",
"(",
"binary_data",
",",
"\"text/plain\"",
",",
"\"local.path\"",
")",
"else",
"data",
"[",
"binary_key",
"]",
"=",
"UploadIO",
".",
"new",
"(",
"File",
".",
"open",
"(",
"binary_data",
")",
",",
"\"text/plain\"",
")",
"end",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
"::",
"Multipart",
".",
"new",
"(",
"uri",
".",
"path",
",",
"data",
")",
"else",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"path",
",",
"headers",
")",
"req",
".",
"set_form_data",
"(",
"data",
")",
"end",
"req",
"end"
]
| set up our post request | [
"set",
"up",
"our",
"post",
"request"
]
| 978deed2b25769a73de14107cb2a0c93143522e4 | https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L824-L844 | train |
basecrm/basecrm-ruby | lib/basecrm/services/tasks_service.rb | BaseCRM.TasksService.create | def create(task)
validate_type!(task)
attributes = sanitize(task)
_, _, root = @client.post("/tasks", attributes)
Task.new(root[:data])
end | ruby | def create(task)
validate_type!(task)
attributes = sanitize(task)
_, _, root = @client.post("/tasks", attributes)
Task.new(root[:data])
end | [
"def",
"create",
"(",
"task",
")",
"validate_type!",
"(",
"task",
")",
"attributes",
"=",
"sanitize",
"(",
"task",
")",
"_",
",",
"_",
",",
"root",
"=",
"@client",
".",
"post",
"(",
"\"/tasks\"",
",",
"attributes",
")",
"Task",
".",
"new",
"(",
"root",
"[",
":data",
"]",
")",
"end"
]
| Create a task
post '/tasks'
Creates a new task
You can create either a **floating** task or create a **related** task and associate it with one of the resource types below:
* [Leads](/docs/rest/reference/leads)
* [Contacts](/docs/rest/reference/contacts)
* [Deals](/docs/rest/reference/deals)
@param task [Task, Hash] Either object of the Task type or Hash. This object's attributes describe the object to be created.
@return [Task] The resulting object represting created resource. | [
"Create",
"a",
"task"
]
| c39ea72477d41c3122805d49587043399ee454ea | https://github.com/basecrm/basecrm-ruby/blob/c39ea72477d41c3122805d49587043399ee454ea/lib/basecrm/services/tasks_service.rb#L63-L70 | train |
basecrm/basecrm-ruby | lib/basecrm/services/tasks_service.rb | BaseCRM.TasksService.update | def update(task)
validate_type!(task)
params = extract_params!(task, :id)
id = params[:id]
attributes = sanitize(task)
_, _, root = @client.put("/tasks/#{id}", attributes)
Task.new(root[:data])
end | ruby | def update(task)
validate_type!(task)
params = extract_params!(task, :id)
id = params[:id]
attributes = sanitize(task)
_, _, root = @client.put("/tasks/#{id}", attributes)
Task.new(root[:data])
end | [
"def",
"update",
"(",
"task",
")",
"validate_type!",
"(",
"task",
")",
"params",
"=",
"extract_params!",
"(",
"task",
",",
":id",
")",
"id",
"=",
"params",
"[",
":id",
"]",
"attributes",
"=",
"sanitize",
"(",
"task",
")",
"_",
",",
"_",
",",
"root",
"=",
"@client",
".",
"put",
"(",
"\"/tasks/#{id}\"",
",",
"attributes",
")",
"Task",
".",
"new",
"(",
"root",
"[",
":data",
"]",
")",
"end"
]
| Update a task
put '/tasks/{id}'
Updates task information
If the specified task does not exist, this query will return an error
@param task [Task, Hash] Either object of the Task type or Hash. This object's attributes describe the object to be updated.
@return [Task] The resulting object represting updated resource. | [
"Update",
"a",
"task"
]
| c39ea72477d41c3122805d49587043399ee454ea | https://github.com/basecrm/basecrm-ruby/blob/c39ea72477d41c3122805d49587043399ee454ea/lib/basecrm/services/tasks_service.rb#L98-L107 | train |
basecrm/basecrm-ruby | lib/basecrm/services/contacts_service.rb | BaseCRM.ContactsService.create | def create(contact)
validate_type!(contact)
attributes = sanitize(contact)
_, _, root = @client.post("/contacts", attributes)
Contact.new(root[:data])
end | ruby | def create(contact)
validate_type!(contact)
attributes = sanitize(contact)
_, _, root = @client.post("/contacts", attributes)
Contact.new(root[:data])
end | [
"def",
"create",
"(",
"contact",
")",
"validate_type!",
"(",
"contact",
")",
"attributes",
"=",
"sanitize",
"(",
"contact",
")",
"_",
",",
"_",
",",
"root",
"=",
"@client",
".",
"post",
"(",
"\"/contacts\"",
",",
"attributes",
")",
"Contact",
".",
"new",
"(",
"root",
"[",
":data",
"]",
")",
"end"
]
| Create a contact
post '/contacts'
Create a new contact
A contact may represent a single individual or an organization
@param contact [Contact, Hash] Either object of the Contact type or Hash. This object's attributes describe the object to be created.
@return [Contact] The resulting object represting created resource. | [
"Create",
"a",
"contact"
]
| c39ea72477d41c3122805d49587043399ee454ea | https://github.com/basecrm/basecrm-ruby/blob/c39ea72477d41c3122805d49587043399ee454ea/lib/basecrm/services/contacts_service.rb#L58-L65 | train |
basecrm/basecrm-ruby | lib/basecrm/services/contacts_service.rb | BaseCRM.ContactsService.update | def update(contact)
validate_type!(contact)
params = extract_params!(contact, :id)
id = params[:id]
attributes = sanitize(contact)
_, _, root = @client.put("/contacts/#{id}", attributes)
Contact.new(root[:data])
end | ruby | def update(contact)
validate_type!(contact)
params = extract_params!(contact, :id)
id = params[:id]
attributes = sanitize(contact)
_, _, root = @client.put("/contacts/#{id}", attributes)
Contact.new(root[:data])
end | [
"def",
"update",
"(",
"contact",
")",
"validate_type!",
"(",
"contact",
")",
"params",
"=",
"extract_params!",
"(",
"contact",
",",
":id",
")",
"id",
"=",
"params",
"[",
":id",
"]",
"attributes",
"=",
"sanitize",
"(",
"contact",
")",
"_",
",",
"_",
",",
"root",
"=",
"@client",
".",
"put",
"(",
"\"/contacts/#{id}\"",
",",
"attributes",
")",
"Contact",
".",
"new",
"(",
"root",
"[",
":data",
"]",
")",
"end"
]
| Update a contact
put '/contacts/{id}'
Updates contact information
If the specified contact does not exist, the request will return an error
**Notice** When updating contact tags, you need to provide all tags
Any missing tag will be removed from a contact's tags
@param contact [Contact, Hash] Either object of the Contact type or Hash. This object's attributes describe the object to be updated.
@return [Contact] The resulting object represting updated resource. | [
"Update",
"a",
"contact"
]
| c39ea72477d41c3122805d49587043399ee454ea | https://github.com/basecrm/basecrm-ruby/blob/c39ea72477d41c3122805d49587043399ee454ea/lib/basecrm/services/contacts_service.rb#L95-L104 | train |
basecrm/basecrm-ruby | lib/basecrm/services/calls_service.rb | BaseCRM.CallsService.create | def create(call)
validate_type!(call)
attributes = sanitize(call)
_, _, root = @client.post("/calls", attributes)
Call.new(root[:data])
end | ruby | def create(call)
validate_type!(call)
attributes = sanitize(call)
_, _, root = @client.post("/calls", attributes)
Call.new(root[:data])
end | [
"def",
"create",
"(",
"call",
")",
"validate_type!",
"(",
"call",
")",
"attributes",
"=",
"sanitize",
"(",
"call",
")",
"_",
",",
"_",
",",
"root",
"=",
"@client",
".",
"post",
"(",
"\"/calls\"",
",",
"attributes",
")",
"Call",
".",
"new",
"(",
"root",
"[",
":data",
"]",
")",
"end"
]
| Create a call
post '/calls'
Create a new call
@param call [Call, Hash] Either object of the Call type or Hash. This object's attributes describe the object to be created.
@return [Call] The resulting object represting created resource. | [
"Create",
"a",
"call"
]
| c39ea72477d41c3122805d49587043399ee454ea | https://github.com/basecrm/basecrm-ruby/blob/c39ea72477d41c3122805d49587043399ee454ea/lib/basecrm/services/calls_service.rb#L50-L57 | train |
basecrm/basecrm-ruby | lib/basecrm/services/calls_service.rb | BaseCRM.CallsService.update | def update(call)
validate_type!(call)
params = extract_params!(call, :id)
id = params[:id]
attributes = sanitize(call)
_, _, root = @client.put("/calls/#{id}", attributes)
Call.new(root[:data])
end | ruby | def update(call)
validate_type!(call)
params = extract_params!(call, :id)
id = params[:id]
attributes = sanitize(call)
_, _, root = @client.put("/calls/#{id}", attributes)
Call.new(root[:data])
end | [
"def",
"update",
"(",
"call",
")",
"validate_type!",
"(",
"call",
")",
"params",
"=",
"extract_params!",
"(",
"call",
",",
":id",
")",
"id",
"=",
"params",
"[",
":id",
"]",
"attributes",
"=",
"sanitize",
"(",
"call",
")",
"_",
",",
"_",
",",
"root",
"=",
"@client",
".",
"put",
"(",
"\"/calls/#{id}\"",
",",
"attributes",
")",
"Call",
".",
"new",
"(",
"root",
"[",
":data",
"]",
")",
"end"
]
| Update a call
put '/calls/{id}'
Allows to attach a Contact or Lead to an existing Call, or change it’s current association
@param call [Call, Hash] Either object of the Call type or Hash. This object's attributes describe the object to be updated.
@return [Call] The resulting object represting updated resource. | [
"Update",
"a",
"call"
]
| c39ea72477d41c3122805d49587043399ee454ea | https://github.com/basecrm/basecrm-ruby/blob/c39ea72477d41c3122805d49587043399ee454ea/lib/basecrm/services/calls_service.rb#L84-L93 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.