id
int32 0
24.9k
| 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
20,000
|
whazzmaster/fitgem
|
lib/fitgem/notifications.rb
|
Fitgem.Client.remove_subscription
|
def remove_subscription(opts)
resp = raw_delete make_subscription_url(opts.merge({:use_subscription_id => true})), make_headers(opts)
[resp.status, extract_response_body(resp)]
end
|
ruby
|
def remove_subscription(opts)
resp = raw_delete make_subscription_url(opts.merge({:use_subscription_id => true})), make_headers(opts)
[resp.status, extract_response_body(resp)]
end
|
[
"def",
"remove_subscription",
"(",
"opts",
")",
"resp",
"=",
"raw_delete",
"make_subscription_url",
"(",
"opts",
".",
"merge",
"(",
"{",
":use_subscription_id",
"=>",
"true",
"}",
")",
")",
",",
"make_headers",
"(",
"opts",
")",
"[",
"resp",
".",
"status",
",",
"extract_response_body",
"(",
"resp",
")",
"]",
"end"
] |
Removes a notification subscription
@note You must check the HTTP response code to check the status of the request to remove a subscription. See {https://wiki.fitbit.com/display/API/Fitbit+Subscriptions+API} for information about what the codes mean.
@param [Hash] opts The notification subscription data
@option opts [Symbol] :type The type of subscription to remove;
valid values are :activities, :foods, :sleep, :body, and :all).
REQUIRED
@option opts [Integer, String] :subscription_id The id of the
subscription to remove.
@option opts [Inteter, Stri)g] :subscriber_id The subscriber id of the client
application, created via {http://dev.fitbit.com}
@return [Integer, Hash] An array containing the HTTP response code and
a hash containing confirmation information for the subscription.
@since v0.4.0
|
[
"Removes",
"a",
"notification",
"subscription"
] |
c8c4fc908feee91bb138e518f6882507b3067ae1
|
https://github.com/whazzmaster/fitgem/blob/c8c4fc908feee91bb138e518f6882507b3067ae1/lib/fitgem/notifications.rb#L50-L53
|
20,001
|
whazzmaster/fitgem
|
lib/fitgem/notifications.rb
|
Fitgem.Client.validate_subscription_type
|
def validate_subscription_type(subscription_type)
unless subscription_type && SUBSCRIBABLE_TYPES.include?(subscription_type)
raise Fitgem::InvalidArgumentError, "Invalid subscription type (valid values are #{SUBSCRIBABLE_TYPES.join(', ')})"
end
true
end
|
ruby
|
def validate_subscription_type(subscription_type)
unless subscription_type && SUBSCRIBABLE_TYPES.include?(subscription_type)
raise Fitgem::InvalidArgumentError, "Invalid subscription type (valid values are #{SUBSCRIBABLE_TYPES.join(', ')})"
end
true
end
|
[
"def",
"validate_subscription_type",
"(",
"subscription_type",
")",
"unless",
"subscription_type",
"&&",
"SUBSCRIBABLE_TYPES",
".",
"include?",
"(",
"subscription_type",
")",
"raise",
"Fitgem",
"::",
"InvalidArgumentError",
",",
"\"Invalid subscription type (valid values are #{SUBSCRIBABLE_TYPES.join(', ')})\"",
"end",
"true",
"end"
] |
Ensures that the type supplied is valid
@param [Symbol] subscription_type The type of subscription;
valid values are (:sleep, :body, :activities, :foods, and
:all)
@raise [Fitgem::InvalidArgumentError] Raised if the supplied type
is not valid
@return [Boolean]
|
[
"Ensures",
"that",
"the",
"type",
"supplied",
"is",
"valid"
] |
c8c4fc908feee91bb138e518f6882507b3067ae1
|
https://github.com/whazzmaster/fitgem/blob/c8c4fc908feee91bb138e518f6882507b3067ae1/lib/fitgem/notifications.rb#L65-L70
|
20,002
|
whazzmaster/fitgem
|
lib/fitgem/notifications.rb
|
Fitgem.Client.make_subscription_url
|
def make_subscription_url(opts)
validate_subscription_type opts[:type]
path = if opts[:type] == :all
""
else
"/"+opts[:type].to_s
end
url = "/user/#{@user_id}#{path}/apiSubscriptions"
if opts[:use_subscription_id]
unless opts[:subscription_id]
raise Fitgem::InvalidArgumentError, "Must include options[:subscription_id]"
end
url += "/#{opts[:subscription_id]}"
end
url += ".json"
end
|
ruby
|
def make_subscription_url(opts)
validate_subscription_type opts[:type]
path = if opts[:type] == :all
""
else
"/"+opts[:type].to_s
end
url = "/user/#{@user_id}#{path}/apiSubscriptions"
if opts[:use_subscription_id]
unless opts[:subscription_id]
raise Fitgem::InvalidArgumentError, "Must include options[:subscription_id]"
end
url += "/#{opts[:subscription_id]}"
end
url += ".json"
end
|
[
"def",
"make_subscription_url",
"(",
"opts",
")",
"validate_subscription_type",
"opts",
"[",
":type",
"]",
"path",
"=",
"if",
"opts",
"[",
":type",
"]",
"==",
":all",
"\"\"",
"else",
"\"/\"",
"+",
"opts",
"[",
":type",
"]",
".",
"to_s",
"end",
"url",
"=",
"\"/user/#{@user_id}#{path}/apiSubscriptions\"",
"if",
"opts",
"[",
":use_subscription_id",
"]",
"unless",
"opts",
"[",
":subscription_id",
"]",
"raise",
"Fitgem",
"::",
"InvalidArgumentError",
",",
"\"Must include options[:subscription_id]\"",
"end",
"url",
"+=",
"\"/#{opts[:subscription_id]}\"",
"end",
"url",
"+=",
"\".json\"",
"end"
] |
Create the subscription management API url
@param [Hash] opts The options on how to construct the
subscription API url
@option opts [Symbol] :type The type of subscription;
valid values are (:sleep, :body, :activities, :foods, and
:all)
@option opts [Symbol] :use_subscription_id If true, then
opts[:subscription_id] will be used in url construction
@option opts [String] :subscription_id The id of the subscription
that the URL is for
@return [String] The url to use for subscription management
|
[
"Create",
"the",
"subscription",
"management",
"API",
"url"
] |
c8c4fc908feee91bb138e518f6882507b3067ae1
|
https://github.com/whazzmaster/fitgem/blob/c8c4fc908feee91bb138e518f6882507b3067ae1/lib/fitgem/notifications.rb#L103-L118
|
20,003
|
whazzmaster/fitgem
|
lib/fitgem/body_measurements.rb
|
Fitgem.Client.log_weight
|
def log_weight(weight, date, opts={})
opts[:time] = format_time(opts[:time]) if opts[:time]
post("/user/#{@user_id}/body/log/weight.json", opts.merge(:weight => weight, :date => format_date(date)))
end
|
ruby
|
def log_weight(weight, date, opts={})
opts[:time] = format_time(opts[:time]) if opts[:time]
post("/user/#{@user_id}/body/log/weight.json", opts.merge(:weight => weight, :date => format_date(date)))
end
|
[
"def",
"log_weight",
"(",
"weight",
",",
"date",
",",
"opts",
"=",
"{",
"}",
")",
"opts",
"[",
":time",
"]",
"=",
"format_time",
"(",
"opts",
"[",
":time",
"]",
")",
"if",
"opts",
"[",
":time",
"]",
"post",
"(",
"\"/user/#{@user_id}/body/log/weight.json\"",
",",
"opts",
".",
"merge",
"(",
":weight",
"=>",
"weight",
",",
":date",
"=>",
"format_date",
"(",
"date",
")",
")",
")",
"end"
] |
Log weight to fitbit for the current user
@param [Integer, String] weight The weight to log, as either
an integer or a string in "X.XX'" format
@param [DateTime, String] date The date the weight should be
logged, as either a DateTime or a String in 'yyyy-MM-dd' format
@options opts [DateTime, String] :time The time the weight should be logged
as either a DateTime or a String in 'HH:mm:ss' format
@return [Hash]
@since v0.9.0
|
[
"Log",
"weight",
"to",
"fitbit",
"for",
"the",
"current",
"user"
] |
c8c4fc908feee91bb138e518f6882507b3067ae1
|
https://github.com/whazzmaster/fitgem/blob/c8c4fc908feee91bb138e518f6882507b3067ae1/lib/fitgem/body_measurements.rb#L121-L124
|
20,004
|
whazzmaster/fitgem
|
lib/fitgem/body_measurements.rb
|
Fitgem.Client.log_body_fat
|
def log_body_fat(fatPercentage, date, opts={})
opts[:fat] = fatPercentage
opts[:date] = format_date(date)
opts[:time] = format_time(opts[:time]) if opts[:time]
post("/user/#{@user_id}/body/fat.json", opts)
end
|
ruby
|
def log_body_fat(fatPercentage, date, opts={})
opts[:fat] = fatPercentage
opts[:date] = format_date(date)
opts[:time] = format_time(opts[:time]) if opts[:time]
post("/user/#{@user_id}/body/fat.json", opts)
end
|
[
"def",
"log_body_fat",
"(",
"fatPercentage",
",",
"date",
",",
"opts",
"=",
"{",
"}",
")",
"opts",
"[",
":fat",
"]",
"=",
"fatPercentage",
"opts",
"[",
":date",
"]",
"=",
"format_date",
"(",
"date",
")",
"opts",
"[",
":time",
"]",
"=",
"format_time",
"(",
"opts",
"[",
":time",
"]",
")",
"if",
"opts",
"[",
":time",
"]",
"post",
"(",
"\"/user/#{@user_id}/body/fat.json\"",
",",
"opts",
")",
"end"
] |
Log body fat percentage
@param [Decimal, Integer, String] fatPercentage Body fat percentage to log,
in format "X.XX" if a string
@param [DateTime, Date, String] date The date to log body fat percentage on,
in format "yyyy-MM-dd" if a string
@param [Hash] opts
@option opts [DateTime, Time, String] :time The time to log body fat percentage
at, in " HH:mm:ss" format if a String
@since v0.9.0
|
[
"Log",
"body",
"fat",
"percentage"
] |
c8c4fc908feee91bb138e518f6882507b3067ae1
|
https://github.com/whazzmaster/fitgem/blob/c8c4fc908feee91bb138e518f6882507b3067ae1/lib/fitgem/body_measurements.rb#L137-L142
|
20,005
|
whazzmaster/fitgem
|
lib/fitgem/body_measurements.rb
|
Fitgem.Client.create_or_update_body_weight_goal
|
def create_or_update_body_weight_goal(startDate, startWeight, goalWeight)
opts = {startDate: format_date(startDate), startWeight: startWeight, weight: goalWeight}
post("/user/#{@user_id}/body/log/weight/goal.json", opts)
end
|
ruby
|
def create_or_update_body_weight_goal(startDate, startWeight, goalWeight)
opts = {startDate: format_date(startDate), startWeight: startWeight, weight: goalWeight}
post("/user/#{@user_id}/body/log/weight/goal.json", opts)
end
|
[
"def",
"create_or_update_body_weight_goal",
"(",
"startDate",
",",
"startWeight",
",",
"goalWeight",
")",
"opts",
"=",
"{",
"startDate",
":",
"format_date",
"(",
"startDate",
")",
",",
"startWeight",
":",
"startWeight",
",",
"weight",
":",
"goalWeight",
"}",
"post",
"(",
"\"/user/#{@user_id}/body/log/weight/goal.json\"",
",",
"opts",
")",
"end"
] |
Create or update a user's weight goal
@param [DateTime, Date, String] startDate Weight goal start date;
in the format "yyyy-MM-dd" if a string
@param [Decimal, Integer, String] startWeight Weight goal start weight;
in the format "X.XX" if a string
@param [Decimal, Integer, String] goalWeight Weight goal target weight;
in the format "X.XX" if a string
@since v0.9.0
|
[
"Create",
"or",
"update",
"a",
"user",
"s",
"weight",
"goal"
] |
c8c4fc908feee91bb138e518f6882507b3067ae1
|
https://github.com/whazzmaster/fitgem/blob/c8c4fc908feee91bb138e518f6882507b3067ae1/lib/fitgem/body_measurements.rb#L154-L157
|
20,006
|
whazzmaster/fitgem
|
lib/fitgem/body_measurements.rb
|
Fitgem.Client.determine_body_uri
|
def determine_body_uri(base_uri, opts = {})
if opts[:date]
date = format_date opts[:date]
"#{base_uri}/date/#{date}.json"
elsif opts[:base_date] && (opts[:period] || opts[:end_date])
date_range = construct_date_range_fragment opts
"#{base_uri}/#{date_range}.json"
else
raise Fitgem::InvalidArgumentError, "You didn't supply one of the required options."
end
end
|
ruby
|
def determine_body_uri(base_uri, opts = {})
if opts[:date]
date = format_date opts[:date]
"#{base_uri}/date/#{date}.json"
elsif opts[:base_date] && (opts[:period] || opts[:end_date])
date_range = construct_date_range_fragment opts
"#{base_uri}/#{date_range}.json"
else
raise Fitgem::InvalidArgumentError, "You didn't supply one of the required options."
end
end
|
[
"def",
"determine_body_uri",
"(",
"base_uri",
",",
"opts",
"=",
"{",
"}",
")",
"if",
"opts",
"[",
":date",
"]",
"date",
"=",
"format_date",
"opts",
"[",
":date",
"]",
"\"#{base_uri}/date/#{date}.json\"",
"elsif",
"opts",
"[",
":base_date",
"]",
"&&",
"(",
"opts",
"[",
":period",
"]",
"||",
"opts",
"[",
":end_date",
"]",
")",
"date_range",
"=",
"construct_date_range_fragment",
"opts",
"\"#{base_uri}/#{date_range}.json\"",
"else",
"raise",
"Fitgem",
"::",
"InvalidArgumentError",
",",
"\"You didn't supply one of the required options.\"",
"end",
"end"
] |
Determine the URI for the body_weight or body_fat method
@params [String] base_uri the base URI for the body weight or body fat method
@params [Hash] opts body weight/fat options
@option opts [Date] date The date in the format YYYY-mm-dd.
@option opts [Date] base-date The end date when period is provided, in the
format yyyy-MM-dd or today; range start date when a date range is provided.
@option opts [String] period The date range period. One of 1d, 7d, 30d, 1w, 1m
@option opts [Date] end-date Range end date when date range is provided.
Note that period should not be longer than 31 day
@return [String] an URI based on the base URI and provided options
|
[
"Determine",
"the",
"URI",
"for",
"the",
"body_weight",
"or",
"body_fat",
"method"
] |
c8c4fc908feee91bb138e518f6882507b3067ae1
|
https://github.com/whazzmaster/fitgem/blob/c8c4fc908feee91bb138e518f6882507b3067ae1/lib/fitgem/body_measurements.rb#L206-L216
|
20,007
|
whazzmaster/fitgem
|
lib/fitgem/activities.rb
|
Fitgem.Client.create_or_update_weekly_goal
|
def create_or_update_weekly_goal(opts)
unless opts[:type] && [:steps, :distance, :floors].include?(opts[:type])
raise InvalidArgumentError, 'Must specify type in order to create or update a weekly goal. One of (:steps, :distance, or :floors) is required.'
end
unless opts[:value]
raise InvalidArgumentError, 'Must specify value of the weekly goal to be created or updated.'
end
post("/user/#{@user_id}/activities/goals/weekly.json", opts)
end
|
ruby
|
def create_or_update_weekly_goal(opts)
unless opts[:type] && [:steps, :distance, :floors].include?(opts[:type])
raise InvalidArgumentError, 'Must specify type in order to create or update a weekly goal. One of (:steps, :distance, or :floors) is required.'
end
unless opts[:value]
raise InvalidArgumentError, 'Must specify value of the weekly goal to be created or updated.'
end
post("/user/#{@user_id}/activities/goals/weekly.json", opts)
end
|
[
"def",
"create_or_update_weekly_goal",
"(",
"opts",
")",
"unless",
"opts",
"[",
":type",
"]",
"&&",
"[",
":steps",
",",
":distance",
",",
":floors",
"]",
".",
"include?",
"(",
"opts",
"[",
":type",
"]",
")",
"raise",
"InvalidArgumentError",
",",
"'Must specify type in order to create or update a weekly goal. One of (:steps, :distance, or :floors) is required.'",
"end",
"unless",
"opts",
"[",
":value",
"]",
"raise",
"InvalidArgumentError",
",",
"'Must specify value of the weekly goal to be created or updated.'",
"end",
"post",
"(",
"\"/user/#{@user_id}/activities/goals/weekly.json\"",
",",
"opts",
")",
"end"
] |
Create or update a user's weekly goal
@param [Hash] :opts
@option opts [Symbol] :type The type of goal to create or update; must be one of
:steps, :distance, or :floors. REQUIRED
@option opts [Decimal, Integer, String] :value The goal value; in the format 'X.XX'
if a string. REQUIRED
@since v0.9.0
|
[
"Create",
"or",
"update",
"a",
"user",
"s",
"weekly",
"goal"
] |
c8c4fc908feee91bb138e518f6882507b3067ae1
|
https://github.com/whazzmaster/fitgem/blob/c8c4fc908feee91bb138e518f6882507b3067ae1/lib/fitgem/activities.rb#L192-L202
|
20,008
|
whazzmaster/fitgem
|
lib/fitgem/alarms.rb
|
Fitgem.Client.update_alarm
|
def update_alarm(alarm_id, device_id, opts)
opts[:time] = format_time opts[:time], include_timezone: true
post("/user/#{@user_id}/devices/tracker/#{device_id}/alarms/#{alarm_id}.json", opts)
end
|
ruby
|
def update_alarm(alarm_id, device_id, opts)
opts[:time] = format_time opts[:time], include_timezone: true
post("/user/#{@user_id}/devices/tracker/#{device_id}/alarms/#{alarm_id}.json", opts)
end
|
[
"def",
"update_alarm",
"(",
"alarm_id",
",",
"device_id",
",",
"opts",
")",
"opts",
"[",
":time",
"]",
"=",
"format_time",
"opts",
"[",
":time",
"]",
",",
"include_timezone",
":",
"true",
"post",
"(",
"\"/user/#{@user_id}/devices/tracker/#{device_id}/alarms/#{alarm_id}.json\"",
",",
"opts",
")",
"end"
] |
Update an existing alarm
@param [Integer, String] alarm_id The id of the alarm
@param [Integer, String] device_id The id of the device you would like to
manage the alarm on
@param [Hash] opts Alarm settings
@option opts [DateTime, Time, String] :time Time of the alarm
@option opts [TrueClass, FalseClass] :enabled
@option opts [TrueClass, FalseClass] :recurring One time or recurring alarm
@option opts [String] :weekDays The days the alarm is active on as a list of
comma separated values: MONDAY, WEDNESDAY, SATURDAY. For recurring only
@option opts [Integer] :snoozeLength Minutes between the alarms
@option opts [Integer] :snoozeCount Maximum snooze count
@option opts [String] :label Label for the alarm
@return [Hash] Hash containing updated alarm settings
|
[
"Update",
"an",
"existing",
"alarm"
] |
c8c4fc908feee91bb138e518f6882507b3067ae1
|
https://github.com/whazzmaster/fitgem/blob/c8c4fc908feee91bb138e518f6882507b3067ae1/lib/fitgem/alarms.rb#L61-L64
|
20,009
|
whazzmaster/fitgem
|
lib/fitgem/helpers.rb
|
Fitgem.Client.format_time
|
def format_time(time, opts = {})
format = opts[:include_timezone] ? "%H:%M%:z" : "%H:%M"
if time.is_a? String
case time
when 'now'
return DateTime.now.strftime format
else
unless time =~ /^\d{2}\:\d{2}$/
raise Fitgem::InvalidTimeArgument, "Invalid time (#{time}), must be in HH:mm format"
end
timezone = DateTime.now.strftime("%:z")
return opts[:include_timezone] ? [ time, timezone ].join : time
end
elsif DateTime === time || Time === time
return time.strftime format
else
raise Fitgem::InvalidTimeArgument, "Date used must be a valid time object or a string in the format HH:mm; supplied argument is a #{time.class}"
end
end
|
ruby
|
def format_time(time, opts = {})
format = opts[:include_timezone] ? "%H:%M%:z" : "%H:%M"
if time.is_a? String
case time
when 'now'
return DateTime.now.strftime format
else
unless time =~ /^\d{2}\:\d{2}$/
raise Fitgem::InvalidTimeArgument, "Invalid time (#{time}), must be in HH:mm format"
end
timezone = DateTime.now.strftime("%:z")
return opts[:include_timezone] ? [ time, timezone ].join : time
end
elsif DateTime === time || Time === time
return time.strftime format
else
raise Fitgem::InvalidTimeArgument, "Date used must be a valid time object or a string in the format HH:mm; supplied argument is a #{time.class}"
end
end
|
[
"def",
"format_time",
"(",
"time",
",",
"opts",
"=",
"{",
"}",
")",
"format",
"=",
"opts",
"[",
":include_timezone",
"]",
"?",
"\"%H:%M%:z\"",
":",
"\"%H:%M\"",
"if",
"time",
".",
"is_a?",
"String",
"case",
"time",
"when",
"'now'",
"return",
"DateTime",
".",
"now",
".",
"strftime",
"format",
"else",
"unless",
"time",
"=~",
"/",
"\\d",
"\\:",
"\\d",
"/",
"raise",
"Fitgem",
"::",
"InvalidTimeArgument",
",",
"\"Invalid time (#{time}), must be in HH:mm format\"",
"end",
"timezone",
"=",
"DateTime",
".",
"now",
".",
"strftime",
"(",
"\"%:z\"",
")",
"return",
"opts",
"[",
":include_timezone",
"]",
"?",
"[",
"time",
",",
"timezone",
"]",
".",
"join",
":",
"time",
"end",
"elsif",
"DateTime",
"===",
"time",
"||",
"Time",
"===",
"time",
"return",
"time",
".",
"strftime",
"format",
"else",
"raise",
"Fitgem",
"::",
"InvalidTimeArgument",
",",
"\"Date used must be a valid time object or a string in the format HH:mm; supplied argument is a #{time.class}\"",
"end",
"end"
] |
Format any of a variety of time-related types into the formatted string
required when using the fitbit API.
The time parameter can take several different kind of objects: a DateTime object,
a Time object, or a String Object. Furthermore, the string object may be either
the date in a preformatted string ("HH:mm"), or it may be the string value "now" to
indicate that the time value used is the current localtime.
@param [DateTime, Time, String] time The object to format into a time string
@param [Hash] opts format time options
@option opts [TrueClass, FalseClass] :include_timezone Include timezone in the output or not
@raise [Fitgem::InvalidTimeArgument] Raised when the parameter object is not a
DateTime, Time, or a valid ("HH:mm" or "now") string object
@return [String] Date in "HH:mm" string format
|
[
"Format",
"any",
"of",
"a",
"variety",
"of",
"time",
"-",
"related",
"types",
"into",
"the",
"formatted",
"string",
"required",
"when",
"using",
"the",
"fitbit",
"API",
"."
] |
c8c4fc908feee91bb138e518f6882507b3067ae1
|
https://github.com/whazzmaster/fitgem/blob/c8c4fc908feee91bb138e518f6882507b3067ae1/lib/fitgem/helpers.rb#L51-L69
|
20,010
|
whazzmaster/fitgem
|
lib/fitgem/helpers.rb
|
Fitgem.Client.label_for_measurement
|
def label_for_measurement(measurement_type, respect_user_unit_preferences=true)
unless [:duration, :distance, :elevation, :height, :weight, :measurements, :liquids, :blood_glucose].include?(measurement_type)
raise InvalidMeasurementType, "Supplied measurement_type parameter must be one of [:duration, :distance, :elevation, :height, :weight, :measurements, :liquids, :blood_glucose], current value is :#{measurement_type}"
end
selected_unit_system = api_unit_system
if respect_user_unit_preferences
unless connected?
raise ConnectionRequiredError, "No connection to Fitbit API; one is required when passing respect_user_unit_preferences=true"
end
# Cache the unit systems for the current user
@unit_systems ||= self.user_info['user'].select {|key, value| key =~ /Unit$/ }
case measurement_type
when :distance
selected_unit_system = @unit_systems["distanceUnit"]
when :height
selected_unit_system = @unit_systems["heightUnit"]
when :liquids
selected_unit_system = @unit_systems["waterUnit"]
when :weight
selected_unit_system = @unit_systems["weightUnit"]
when :blood_glucose
selected_unit_system = @unit_systems["glucoseUnit"]
else
selected_unit_system = api_unit_system
end
end
# Fix the METRIC system difference
selected_unit_system = Fitgem::ApiUnitSystem.METRIC if selected_unit_system == "METRIC"
# Ensure the target unit system is one that we know about
unless [ApiUnitSystem.US, ApiUnitSystem.UK, ApiUnitSystem.METRIC].include?(selected_unit_system)
raise InvalidUnitSystem, "The select unit system must be one of [ApiUnitSystem.US, ApiUnitSystem.UK, ApiUnitSystem.METRIC], current value is #{selected_unit_system}"
end
unit_mappings[selected_unit_system][measurement_type]
end
|
ruby
|
def label_for_measurement(measurement_type, respect_user_unit_preferences=true)
unless [:duration, :distance, :elevation, :height, :weight, :measurements, :liquids, :blood_glucose].include?(measurement_type)
raise InvalidMeasurementType, "Supplied measurement_type parameter must be one of [:duration, :distance, :elevation, :height, :weight, :measurements, :liquids, :blood_glucose], current value is :#{measurement_type}"
end
selected_unit_system = api_unit_system
if respect_user_unit_preferences
unless connected?
raise ConnectionRequiredError, "No connection to Fitbit API; one is required when passing respect_user_unit_preferences=true"
end
# Cache the unit systems for the current user
@unit_systems ||= self.user_info['user'].select {|key, value| key =~ /Unit$/ }
case measurement_type
when :distance
selected_unit_system = @unit_systems["distanceUnit"]
when :height
selected_unit_system = @unit_systems["heightUnit"]
when :liquids
selected_unit_system = @unit_systems["waterUnit"]
when :weight
selected_unit_system = @unit_systems["weightUnit"]
when :blood_glucose
selected_unit_system = @unit_systems["glucoseUnit"]
else
selected_unit_system = api_unit_system
end
end
# Fix the METRIC system difference
selected_unit_system = Fitgem::ApiUnitSystem.METRIC if selected_unit_system == "METRIC"
# Ensure the target unit system is one that we know about
unless [ApiUnitSystem.US, ApiUnitSystem.UK, ApiUnitSystem.METRIC].include?(selected_unit_system)
raise InvalidUnitSystem, "The select unit system must be one of [ApiUnitSystem.US, ApiUnitSystem.UK, ApiUnitSystem.METRIC], current value is #{selected_unit_system}"
end
unit_mappings[selected_unit_system][measurement_type]
end
|
[
"def",
"label_for_measurement",
"(",
"measurement_type",
",",
"respect_user_unit_preferences",
"=",
"true",
")",
"unless",
"[",
":duration",
",",
":distance",
",",
":elevation",
",",
":height",
",",
":weight",
",",
":measurements",
",",
":liquids",
",",
":blood_glucose",
"]",
".",
"include?",
"(",
"measurement_type",
")",
"raise",
"InvalidMeasurementType",
",",
"\"Supplied measurement_type parameter must be one of [:duration, :distance, :elevation, :height, :weight, :measurements, :liquids, :blood_glucose], current value is :#{measurement_type}\"",
"end",
"selected_unit_system",
"=",
"api_unit_system",
"if",
"respect_user_unit_preferences",
"unless",
"connected?",
"raise",
"ConnectionRequiredError",
",",
"\"No connection to Fitbit API; one is required when passing respect_user_unit_preferences=true\"",
"end",
"# Cache the unit systems for the current user",
"@unit_systems",
"||=",
"self",
".",
"user_info",
"[",
"'user'",
"]",
".",
"select",
"{",
"|",
"key",
",",
"value",
"|",
"key",
"=~",
"/",
"/",
"}",
"case",
"measurement_type",
"when",
":distance",
"selected_unit_system",
"=",
"@unit_systems",
"[",
"\"distanceUnit\"",
"]",
"when",
":height",
"selected_unit_system",
"=",
"@unit_systems",
"[",
"\"heightUnit\"",
"]",
"when",
":liquids",
"selected_unit_system",
"=",
"@unit_systems",
"[",
"\"waterUnit\"",
"]",
"when",
":weight",
"selected_unit_system",
"=",
"@unit_systems",
"[",
"\"weightUnit\"",
"]",
"when",
":blood_glucose",
"selected_unit_system",
"=",
"@unit_systems",
"[",
"\"glucoseUnit\"",
"]",
"else",
"selected_unit_system",
"=",
"api_unit_system",
"end",
"end",
"# Fix the METRIC system difference",
"selected_unit_system",
"=",
"Fitgem",
"::",
"ApiUnitSystem",
".",
"METRIC",
"if",
"selected_unit_system",
"==",
"\"METRIC\"",
"# Ensure the target unit system is one that we know about",
"unless",
"[",
"ApiUnitSystem",
".",
"US",
",",
"ApiUnitSystem",
".",
"UK",
",",
"ApiUnitSystem",
".",
"METRIC",
"]",
".",
"include?",
"(",
"selected_unit_system",
")",
"raise",
"InvalidUnitSystem",
",",
"\"The select unit system must be one of [ApiUnitSystem.US, ApiUnitSystem.UK, ApiUnitSystem.METRIC], current value is #{selected_unit_system}\"",
"end",
"unit_mappings",
"[",
"selected_unit_system",
"]",
"[",
"measurement_type",
"]",
"end"
] |
Fetch the correct label for the desired measurement unit.
The general use case for this method is that you are using the client for
a specific user, and wish to get the correct labels for the unit measurements
returned for that user.
A secondary use case is that you wish to get the label for a measurement given a unit
system that you supply (by setting the Fitgem::Client.api_unit_system attribute).
In order for this method to get the correct value for the current user's preferences,
the client must have the ability to make API calls. If you respect_user_unit_preferences
is passed as 'true' (or left as the default value) and the client cannot make API calls
then an error will be raised by the method.
@param [Symbol] measurement_type The measurement type to fetch the label for
@param [Boolean] respect_user_unit_preferences Should the method fetch the current user's
specific measurement preferences and use those (true), or use the value set on Fitgem::Client.api_unit_system (false)
@raise [Fitgem::ConnectionRequiredError] Raised when respect_user_unit_preferences is true but the
client is not capable of making API calls.
@raise [Fitgem::InvalidUnitSystem] Raised when the current value of Fitgem::Client.api_unit_system
is not one of [ApiUnitSystem.US, ApiUnitSystem.UK, ApiUnitSystem.METRIC]
@raise [Fitgem::InvalidMeasurementType] Raised when the supplied measurement_type is not one of
[:duration, :distance, :elevation, :height, :weight, :measurements, :liquids, :blood_glucose]
@return [String] The string label corresponding to the measurement type and
current api_unit_system.
|
[
"Fetch",
"the",
"correct",
"label",
"for",
"the",
"desired",
"measurement",
"unit",
"."
] |
c8c4fc908feee91bb138e518f6882507b3067ae1
|
https://github.com/whazzmaster/fitgem/blob/c8c4fc908feee91bb138e518f6882507b3067ae1/lib/fitgem/helpers.rb#L96-L135
|
20,011
|
grosser/gettext_i18n_rails
|
lib/gettext_i18n_rails/model_attributes_finder.rb
|
GettextI18nRails.ModelAttributesFinder.table_name_to_namespaced_model
|
def table_name_to_namespaced_model(table_name)
# First assume that there are no namespaces
model = to_class(table_name.singularize.camelcase)
return model if model != nil
# If you were wrong, assume that the model is in a namespace.
# Iterate over the underscores and try to substitute each of them
# for a slash that camelcase() replaces with the scope operator (::).
underscore_position = table_name.index('_')
while underscore_position != nil
namespaced_table_name = table_name.dup
namespaced_table_name[underscore_position] = '/'
model = to_class(namespaced_table_name.singularize.camelcase)
return model if model != nil
underscore_position = table_name.index('_', underscore_position + 1)
end
# The model either is not defined or is buried more than one level
# deep in a module hierarchy
return nil
end
|
ruby
|
def table_name_to_namespaced_model(table_name)
# First assume that there are no namespaces
model = to_class(table_name.singularize.camelcase)
return model if model != nil
# If you were wrong, assume that the model is in a namespace.
# Iterate over the underscores and try to substitute each of them
# for a slash that camelcase() replaces with the scope operator (::).
underscore_position = table_name.index('_')
while underscore_position != nil
namespaced_table_name = table_name.dup
namespaced_table_name[underscore_position] = '/'
model = to_class(namespaced_table_name.singularize.camelcase)
return model if model != nil
underscore_position = table_name.index('_', underscore_position + 1)
end
# The model either is not defined or is buried more than one level
# deep in a module hierarchy
return nil
end
|
[
"def",
"table_name_to_namespaced_model",
"(",
"table_name",
")",
"# First assume that there are no namespaces",
"model",
"=",
"to_class",
"(",
"table_name",
".",
"singularize",
".",
"camelcase",
")",
"return",
"model",
"if",
"model",
"!=",
"nil",
"# If you were wrong, assume that the model is in a namespace.",
"# Iterate over the underscores and try to substitute each of them",
"# for a slash that camelcase() replaces with the scope operator (::).",
"underscore_position",
"=",
"table_name",
".",
"index",
"(",
"'_'",
")",
"while",
"underscore_position",
"!=",
"nil",
"namespaced_table_name",
"=",
"table_name",
".",
"dup",
"namespaced_table_name",
"[",
"underscore_position",
"]",
"=",
"'/'",
"model",
"=",
"to_class",
"(",
"namespaced_table_name",
".",
"singularize",
".",
"camelcase",
")",
"return",
"model",
"if",
"model",
"!=",
"nil",
"underscore_position",
"=",
"table_name",
".",
"index",
"(",
"'_'",
",",
"underscore_position",
"+",
"1",
")",
"end",
"# The model either is not defined or is buried more than one level",
"# deep in a module hierarchy",
"return",
"nil",
"end"
] |
Tries to find the model class corresponding to specified table name.
Takes into account that the model can be defined in a namespace.
Searches only up to one level deep - won't find models nested in two
or more modules.
Note that if we allow namespaces, the conversion can be ambiguous, i.e.
if the table is named "aa_bb_cc" and AaBbCc, Aa::BbCc and AaBb::Cc are
all defined there's no absolute rule that tells us which one to use.
This method prefers the less nested one and, if there are two at
the same level, the one with shorter module name.
|
[
"Tries",
"to",
"find",
"the",
"model",
"class",
"corresponding",
"to",
"specified",
"table",
"name",
".",
"Takes",
"into",
"account",
"that",
"the",
"model",
"can",
"be",
"defined",
"in",
"a",
"namespace",
".",
"Searches",
"only",
"up",
"to",
"one",
"level",
"deep",
"-",
"won",
"t",
"find",
"models",
"nested",
"in",
"two",
"or",
"more",
"modules",
"."
] |
decc53ed0f2084b77b82969e2275b37cd854eddb
|
https://github.com/grosser/gettext_i18n_rails/blob/decc53ed0f2084b77b82969e2275b37cd854eddb/lib/gettext_i18n_rails/model_attributes_finder.rb#L102-L123
|
20,012
|
grosser/gettext_i18n_rails
|
lib/gettext_i18n_rails/model_attributes_finder.rb
|
GettextI18nRails.ModelAttributesFinder.to_class
|
def to_class(name)
# I wanted to use Module.const_defined?() here to avoid relying
# on exceptions for normal program flow but it's of no use.
# If class autoloading is enabled, the constant may be undefined
# but turn out to be present when we actually try to use it.
begin
constant = name.constantize
rescue NameError
return nil
rescue LoadError => e
$stderr.puts "failed to load '#{name}', ignoring (#{e.class}: #{e.message})"
return nil
end
return constant.is_a?(Class) ? constant : nil
end
|
ruby
|
def to_class(name)
# I wanted to use Module.const_defined?() here to avoid relying
# on exceptions for normal program flow but it's of no use.
# If class autoloading is enabled, the constant may be undefined
# but turn out to be present when we actually try to use it.
begin
constant = name.constantize
rescue NameError
return nil
rescue LoadError => e
$stderr.puts "failed to load '#{name}', ignoring (#{e.class}: #{e.message})"
return nil
end
return constant.is_a?(Class) ? constant : nil
end
|
[
"def",
"to_class",
"(",
"name",
")",
"# I wanted to use Module.const_defined?() here to avoid relying",
"# on exceptions for normal program flow but it's of no use.",
"# If class autoloading is enabled, the constant may be undefined",
"# but turn out to be present when we actually try to use it.",
"begin",
"constant",
"=",
"name",
".",
"constantize",
"rescue",
"NameError",
"return",
"nil",
"rescue",
"LoadError",
"=>",
"e",
"$stderr",
".",
"puts",
"\"failed to load '#{name}', ignoring (#{e.class}: #{e.message})\"",
"return",
"nil",
"end",
"return",
"constant",
".",
"is_a?",
"(",
"Class",
")",
"?",
"constant",
":",
"nil",
"end"
] |
Checks if there is a class of specified name and if so, returns
the class object. Otherwise returns nil.
|
[
"Checks",
"if",
"there",
"is",
"a",
"class",
"of",
"specified",
"name",
"and",
"if",
"so",
"returns",
"the",
"class",
"object",
".",
"Otherwise",
"returns",
"nil",
"."
] |
decc53ed0f2084b77b82969e2275b37cd854eddb
|
https://github.com/grosser/gettext_i18n_rails/blob/decc53ed0f2084b77b82969e2275b37cd854eddb/lib/gettext_i18n_rails/model_attributes_finder.rb#L127-L142
|
20,013
|
YorickPeterse/ruby-ll
|
lib/ll/compiled_grammar.rb
|
LL.CompiledGrammar.display_messages
|
def display_messages
[:errors, :warnings].each do |type|
send(type).each do |msg|
output.puts(msg.to_s)
end
end
end
|
ruby
|
def display_messages
[:errors, :warnings].each do |type|
send(type).each do |msg|
output.puts(msg.to_s)
end
end
end
|
[
"def",
"display_messages",
"[",
":errors",
",",
":warnings",
"]",
".",
"each",
"do",
"|",
"type",
"|",
"send",
"(",
"type",
")",
".",
"each",
"do",
"|",
"msg",
"|",
"output",
".",
"puts",
"(",
"msg",
".",
"to_s",
")",
"end",
"end",
"end"
] |
Displays all warnings and errors.
|
[
"Displays",
"all",
"warnings",
"and",
"errors",
"."
] |
23f98a807c0bad24c10630818e955750b4cb2a63
|
https://github.com/YorickPeterse/ruby-ll/blob/23f98a807c0bad24c10630818e955750b4cb2a63/lib/ll/compiled_grammar.rb#L152-L158
|
20,014
|
YorickPeterse/ruby-ll
|
lib/ll/configuration_compiler.rb
|
LL.ConfigurationCompiler.generate_rules
|
def generate_rules(grammar)
rules = []
action_index = 0
rule_indices = grammar.rule_indices
term_indices = grammar.terminal_indices
grammar.rules.each_with_index do |rule, rule_index|
rule.branches.each do |branch|
row = [TYPES[:action], action_index]
action_index += 1
branch.steps.reverse_each do |step|
if step.is_a?(Terminal)
row << TYPES[:terminal]
row << term_indices[step] + 1
elsif step.is_a?(Rule)
row << TYPES[:rule]
row << rule_indices[step]
elsif step.is_a?(Epsilon)
row << TYPES[:epsilon]
row << 0
elsif step.is_a?(Operator)
row << TYPES[step.type]
row << rule_indices[step.receiver]
unless SKIP_VALUE_STACK.include?(step.type)
row << TYPES[:add_value_stack]
row << 0
end
end
end
rules << row
end
end
return rules
end
|
ruby
|
def generate_rules(grammar)
rules = []
action_index = 0
rule_indices = grammar.rule_indices
term_indices = grammar.terminal_indices
grammar.rules.each_with_index do |rule, rule_index|
rule.branches.each do |branch|
row = [TYPES[:action], action_index]
action_index += 1
branch.steps.reverse_each do |step|
if step.is_a?(Terminal)
row << TYPES[:terminal]
row << term_indices[step] + 1
elsif step.is_a?(Rule)
row << TYPES[:rule]
row << rule_indices[step]
elsif step.is_a?(Epsilon)
row << TYPES[:epsilon]
row << 0
elsif step.is_a?(Operator)
row << TYPES[step.type]
row << rule_indices[step.receiver]
unless SKIP_VALUE_STACK.include?(step.type)
row << TYPES[:add_value_stack]
row << 0
end
end
end
rules << row
end
end
return rules
end
|
[
"def",
"generate_rules",
"(",
"grammar",
")",
"rules",
"=",
"[",
"]",
"action_index",
"=",
"0",
"rule_indices",
"=",
"grammar",
".",
"rule_indices",
"term_indices",
"=",
"grammar",
".",
"terminal_indices",
"grammar",
".",
"rules",
".",
"each_with_index",
"do",
"|",
"rule",
",",
"rule_index",
"|",
"rule",
".",
"branches",
".",
"each",
"do",
"|",
"branch",
"|",
"row",
"=",
"[",
"TYPES",
"[",
":action",
"]",
",",
"action_index",
"]",
"action_index",
"+=",
"1",
"branch",
".",
"steps",
".",
"reverse_each",
"do",
"|",
"step",
"|",
"if",
"step",
".",
"is_a?",
"(",
"Terminal",
")",
"row",
"<<",
"TYPES",
"[",
":terminal",
"]",
"row",
"<<",
"term_indices",
"[",
"step",
"]",
"+",
"1",
"elsif",
"step",
".",
"is_a?",
"(",
"Rule",
")",
"row",
"<<",
"TYPES",
"[",
":rule",
"]",
"row",
"<<",
"rule_indices",
"[",
"step",
"]",
"elsif",
"step",
".",
"is_a?",
"(",
"Epsilon",
")",
"row",
"<<",
"TYPES",
"[",
":epsilon",
"]",
"row",
"<<",
"0",
"elsif",
"step",
".",
"is_a?",
"(",
"Operator",
")",
"row",
"<<",
"TYPES",
"[",
"step",
".",
"type",
"]",
"row",
"<<",
"rule_indices",
"[",
"step",
".",
"receiver",
"]",
"unless",
"SKIP_VALUE_STACK",
".",
"include?",
"(",
"step",
".",
"type",
")",
"row",
"<<",
"TYPES",
"[",
":add_value_stack",
"]",
"row",
"<<",
"0",
"end",
"end",
"end",
"rules",
"<<",
"row",
"end",
"end",
"return",
"rules",
"end"
] |
Builds the rules table of the parser. Each row is built in reverse order.
@param [LL::CompiledGrammar] grammar
@return [Array]
|
[
"Builds",
"the",
"rules",
"table",
"of",
"the",
"parser",
".",
"Each",
"row",
"is",
"built",
"in",
"reverse",
"order",
"."
] |
23f98a807c0bad24c10630818e955750b4cb2a63
|
https://github.com/YorickPeterse/ruby-ll/blob/23f98a807c0bad24c10630818e955750b4cb2a63/lib/ll/configuration_compiler.rb#L149-L190
|
20,015
|
YorickPeterse/ruby-ll
|
lib/ll/grammar_compiler.rb
|
LL.GrammarCompiler.warn_for_unused_rules
|
def warn_for_unused_rules(compiled_grammar)
compiled_grammar.rules.each_with_index do |rule, index|
next if index == 0 || rule.references > 0
compiled_grammar.add_warning(
"Unused rule #{rule.name.inspect}",
rule.source_line
)
end
end
|
ruby
|
def warn_for_unused_rules(compiled_grammar)
compiled_grammar.rules.each_with_index do |rule, index|
next if index == 0 || rule.references > 0
compiled_grammar.add_warning(
"Unused rule #{rule.name.inspect}",
rule.source_line
)
end
end
|
[
"def",
"warn_for_unused_rules",
"(",
"compiled_grammar",
")",
"compiled_grammar",
".",
"rules",
".",
"each_with_index",
"do",
"|",
"rule",
",",
"index",
"|",
"next",
"if",
"index",
"==",
"0",
"||",
"rule",
".",
"references",
">",
"0",
"compiled_grammar",
".",
"add_warning",
"(",
"\"Unused rule #{rule.name.inspect}\"",
",",
"rule",
".",
"source_line",
")",
"end",
"end"
] |
Adds warnings for any unused rules. The first defined rule is skipped
since it's the root rule.
@param [LL::CompiledGrammar] compiled_grammar
|
[
"Adds",
"warnings",
"for",
"any",
"unused",
"rules",
".",
"The",
"first",
"defined",
"rule",
"is",
"skipped",
"since",
"it",
"s",
"the",
"root",
"rule",
"."
] |
23f98a807c0bad24c10630818e955750b4cb2a63
|
https://github.com/YorickPeterse/ruby-ll/blob/23f98a807c0bad24c10630818e955750b4cb2a63/lib/ll/grammar_compiler.rb#L42-L51
|
20,016
|
YorickPeterse/ruby-ll
|
lib/ll/grammar_compiler.rb
|
LL.GrammarCompiler.warn_for_unused_terminals
|
def warn_for_unused_terminals(compiled_grammar)
compiled_grammar.terminals.each do |terminal|
next if terminal.references > 0
compiled_grammar.add_warning(
"Unused terminal #{terminal.name.inspect}",
terminal.source_line
)
end
end
|
ruby
|
def warn_for_unused_terminals(compiled_grammar)
compiled_grammar.terminals.each do |terminal|
next if terminal.references > 0
compiled_grammar.add_warning(
"Unused terminal #{terminal.name.inspect}",
terminal.source_line
)
end
end
|
[
"def",
"warn_for_unused_terminals",
"(",
"compiled_grammar",
")",
"compiled_grammar",
".",
"terminals",
".",
"each",
"do",
"|",
"terminal",
"|",
"next",
"if",
"terminal",
".",
"references",
">",
"0",
"compiled_grammar",
".",
"add_warning",
"(",
"\"Unused terminal #{terminal.name.inspect}\"",
",",
"terminal",
".",
"source_line",
")",
"end",
"end"
] |
Adds warnings for any unused terminals.
@param [LL::CompiledGrammar] compiled_grammar
|
[
"Adds",
"warnings",
"for",
"any",
"unused",
"terminals",
"."
] |
23f98a807c0bad24c10630818e955750b4cb2a63
|
https://github.com/YorickPeterse/ruby-ll/blob/23f98a807c0bad24c10630818e955750b4cb2a63/lib/ll/grammar_compiler.rb#L58-L67
|
20,017
|
YorickPeterse/ruby-ll
|
lib/ll/grammar_compiler.rb
|
LL.GrammarCompiler.on_grammar
|
def on_grammar(node, compiled_grammar)
# Create the prototypes for all rules since rules can be referenced before
# they are defined.
node.children.each do |child|
if child.type == :rule
on_rule_prototype(child, compiled_grammar)
end
end
node.children.each do |child|
process(child, compiled_grammar)
end
end
|
ruby
|
def on_grammar(node, compiled_grammar)
# Create the prototypes for all rules since rules can be referenced before
# they are defined.
node.children.each do |child|
if child.type == :rule
on_rule_prototype(child, compiled_grammar)
end
end
node.children.each do |child|
process(child, compiled_grammar)
end
end
|
[
"def",
"on_grammar",
"(",
"node",
",",
"compiled_grammar",
")",
"# Create the prototypes for all rules since rules can be referenced before",
"# they are defined.",
"node",
".",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"if",
"child",
".",
"type",
"==",
":rule",
"on_rule_prototype",
"(",
"child",
",",
"compiled_grammar",
")",
"end",
"end",
"node",
".",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"process",
"(",
"child",
",",
"compiled_grammar",
")",
"end",
"end"
] |
Processes the root node of a grammar.
@param [LL::AST::Node] node
@param [LL::CompiledGrammar] compiled_grammar
|
[
"Processes",
"the",
"root",
"node",
"of",
"a",
"grammar",
"."
] |
23f98a807c0bad24c10630818e955750b4cb2a63
|
https://github.com/YorickPeterse/ruby-ll/blob/23f98a807c0bad24c10630818e955750b4cb2a63/lib/ll/grammar_compiler.rb#L146-L158
|
20,018
|
YorickPeterse/ruby-ll
|
lib/ll/grammar_compiler.rb
|
LL.GrammarCompiler.on_name
|
def on_name(node, compiled_grammar)
if compiled_grammar.name
compiled_grammar.add_warning(
"Overwriting existing parser name #{compiled_grammar.name.inspect}",
node.source_line
)
end
parts = node.children.map { |child| process(child, compiled_grammar) }
compiled_grammar.name = parts.join('::')
end
|
ruby
|
def on_name(node, compiled_grammar)
if compiled_grammar.name
compiled_grammar.add_warning(
"Overwriting existing parser name #{compiled_grammar.name.inspect}",
node.source_line
)
end
parts = node.children.map { |child| process(child, compiled_grammar) }
compiled_grammar.name = parts.join('::')
end
|
[
"def",
"on_name",
"(",
"node",
",",
"compiled_grammar",
")",
"if",
"compiled_grammar",
".",
"name",
"compiled_grammar",
".",
"add_warning",
"(",
"\"Overwriting existing parser name #{compiled_grammar.name.inspect}\"",
",",
"node",
".",
"source_line",
")",
"end",
"parts",
"=",
"node",
".",
"children",
".",
"map",
"{",
"|",
"child",
"|",
"process",
"(",
"child",
",",
"compiled_grammar",
")",
"}",
"compiled_grammar",
".",
"name",
"=",
"parts",
".",
"join",
"(",
"'::'",
")",
"end"
] |
Sets the name of the parser.
@param [LL::AST::Node] node
@param [LL::CompiledGrammar] compiled_grammar
|
[
"Sets",
"the",
"name",
"of",
"the",
"parser",
"."
] |
23f98a807c0bad24c10630818e955750b4cb2a63
|
https://github.com/YorickPeterse/ruby-ll/blob/23f98a807c0bad24c10630818e955750b4cb2a63/lib/ll/grammar_compiler.rb#L166-L177
|
20,019
|
YorickPeterse/ruby-ll
|
lib/ll/grammar_compiler.rb
|
LL.GrammarCompiler.on_terminals
|
def on_terminals(node, compiled_grammar)
node.children.each do |child|
name = process(child, compiled_grammar)
if compiled_grammar.has_terminal?(name)
compiled_grammar.add_error(
"The terminal #{name.inspect} has already been defined",
child.source_line
)
else
compiled_grammar.add_terminal(name, child.source_line)
end
end
end
|
ruby
|
def on_terminals(node, compiled_grammar)
node.children.each do |child|
name = process(child, compiled_grammar)
if compiled_grammar.has_terminal?(name)
compiled_grammar.add_error(
"The terminal #{name.inspect} has already been defined",
child.source_line
)
else
compiled_grammar.add_terminal(name, child.source_line)
end
end
end
|
[
"def",
"on_terminals",
"(",
"node",
",",
"compiled_grammar",
")",
"node",
".",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"name",
"=",
"process",
"(",
"child",
",",
"compiled_grammar",
")",
"if",
"compiled_grammar",
".",
"has_terminal?",
"(",
"name",
")",
"compiled_grammar",
".",
"add_error",
"(",
"\"The terminal #{name.inspect} has already been defined\"",
",",
"child",
".",
"source_line",
")",
"else",
"compiled_grammar",
".",
"add_terminal",
"(",
"name",
",",
"child",
".",
"source_line",
")",
"end",
"end",
"end"
] |
Processes the assignment of terminals.
@see [#process]
|
[
"Processes",
"the",
"assignment",
"of",
"terminals",
"."
] |
23f98a807c0bad24c10630818e955750b4cb2a63
|
https://github.com/YorickPeterse/ruby-ll/blob/23f98a807c0bad24c10630818e955750b4cb2a63/lib/ll/grammar_compiler.rb#L184-L197
|
20,020
|
YorickPeterse/ruby-ll
|
lib/ll/grammar_compiler.rb
|
LL.GrammarCompiler.on_rule
|
def on_rule(node, compiled_grammar)
name = process(node.children[0], compiled_grammar)
if compiled_grammar.has_terminal?(name)
compiled_grammar.add_error(
"the rule name #{name.inspect} is already used as a terminal name",
node.source_line
)
end
if compiled_grammar.has_rule_with_branches?(name)
compiled_grammar.add_error(
"the rule #{name.inspect} has already been defined",
node.source_line
)
return
end
branches = node.children[1..-1].map do |child|
process(child, compiled_grammar)
end
rule = compiled_grammar.lookup_rule(name)
rule.branches.concat(branches)
end
|
ruby
|
def on_rule(node, compiled_grammar)
name = process(node.children[0], compiled_grammar)
if compiled_grammar.has_terminal?(name)
compiled_grammar.add_error(
"the rule name #{name.inspect} is already used as a terminal name",
node.source_line
)
end
if compiled_grammar.has_rule_with_branches?(name)
compiled_grammar.add_error(
"the rule #{name.inspect} has already been defined",
node.source_line
)
return
end
branches = node.children[1..-1].map do |child|
process(child, compiled_grammar)
end
rule = compiled_grammar.lookup_rule(name)
rule.branches.concat(branches)
end
|
[
"def",
"on_rule",
"(",
"node",
",",
"compiled_grammar",
")",
"name",
"=",
"process",
"(",
"node",
".",
"children",
"[",
"0",
"]",
",",
"compiled_grammar",
")",
"if",
"compiled_grammar",
".",
"has_terminal?",
"(",
"name",
")",
"compiled_grammar",
".",
"add_error",
"(",
"\"the rule name #{name.inspect} is already used as a terminal name\"",
",",
"node",
".",
"source_line",
")",
"end",
"if",
"compiled_grammar",
".",
"has_rule_with_branches?",
"(",
"name",
")",
"compiled_grammar",
".",
"add_error",
"(",
"\"the rule #{name.inspect} has already been defined\"",
",",
"node",
".",
"source_line",
")",
"return",
"end",
"branches",
"=",
"node",
".",
"children",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"map",
"do",
"|",
"child",
"|",
"process",
"(",
"child",
",",
"compiled_grammar",
")",
"end",
"rule",
"=",
"compiled_grammar",
".",
"lookup_rule",
"(",
"name",
")",
"rule",
".",
"branches",
".",
"concat",
"(",
"branches",
")",
"end"
] |
Processes the assignment of a rule.
@see [#process]
|
[
"Processes",
"the",
"assignment",
"of",
"a",
"rule",
"."
] |
23f98a807c0bad24c10630818e955750b4cb2a63
|
https://github.com/YorickPeterse/ruby-ll/blob/23f98a807c0bad24c10630818e955750b4cb2a63/lib/ll/grammar_compiler.rb#L252-L278
|
20,021
|
YorickPeterse/ruby-ll
|
lib/ll/grammar_compiler.rb
|
LL.GrammarCompiler.on_rule_prototype
|
def on_rule_prototype(node, compiled_grammar)
name = process(node.children[0], compiled_grammar)
return if compiled_grammar.has_rule?(name)
rule = Rule.new(name, node.source_line)
compiled_grammar.add_rule(rule)
end
|
ruby
|
def on_rule_prototype(node, compiled_grammar)
name = process(node.children[0], compiled_grammar)
return if compiled_grammar.has_rule?(name)
rule = Rule.new(name, node.source_line)
compiled_grammar.add_rule(rule)
end
|
[
"def",
"on_rule_prototype",
"(",
"node",
",",
"compiled_grammar",
")",
"name",
"=",
"process",
"(",
"node",
".",
"children",
"[",
"0",
"]",
",",
"compiled_grammar",
")",
"return",
"if",
"compiled_grammar",
".",
"has_rule?",
"(",
"name",
")",
"rule",
"=",
"Rule",
".",
"new",
"(",
"name",
",",
"node",
".",
"source_line",
")",
"compiled_grammar",
".",
"add_rule",
"(",
"rule",
")",
"end"
] |
Creates a basic prototype for a rule.
@see [#process]
|
[
"Creates",
"a",
"basic",
"prototype",
"for",
"a",
"rule",
"."
] |
23f98a807c0bad24c10630818e955750b4cb2a63
|
https://github.com/YorickPeterse/ruby-ll/blob/23f98a807c0bad24c10630818e955750b4cb2a63/lib/ll/grammar_compiler.rb#L285-L293
|
20,022
|
YorickPeterse/ruby-ll
|
lib/ll/grammar_compiler.rb
|
LL.GrammarCompiler.on_branch
|
def on_branch(node, compiled_grammar)
steps = process(node.children[0], compiled_grammar)
if node.children[1]
code = process(node.children[1], compiled_grammar)
else
code = nil
end
return Branch.new(steps, node.source_line, code)
end
|
ruby
|
def on_branch(node, compiled_grammar)
steps = process(node.children[0], compiled_grammar)
if node.children[1]
code = process(node.children[1], compiled_grammar)
else
code = nil
end
return Branch.new(steps, node.source_line, code)
end
|
[
"def",
"on_branch",
"(",
"node",
",",
"compiled_grammar",
")",
"steps",
"=",
"process",
"(",
"node",
".",
"children",
"[",
"0",
"]",
",",
"compiled_grammar",
")",
"if",
"node",
".",
"children",
"[",
"1",
"]",
"code",
"=",
"process",
"(",
"node",
".",
"children",
"[",
"1",
"]",
",",
"compiled_grammar",
")",
"else",
"code",
"=",
"nil",
"end",
"return",
"Branch",
".",
"new",
"(",
"steps",
",",
"node",
".",
"source_line",
",",
"code",
")",
"end"
] |
Processes a single rule branch.
@see [#process]
@return [LL::Branch]
|
[
"Processes",
"a",
"single",
"rule",
"branch",
"."
] |
23f98a807c0bad24c10630818e955750b4cb2a63
|
https://github.com/YorickPeterse/ruby-ll/blob/23f98a807c0bad24c10630818e955750b4cb2a63/lib/ll/grammar_compiler.rb#L301-L311
|
20,023
|
hallidave/ruby-snmp
|
lib/snmp/pdu.rb
|
SNMP.SNMPv2_Trap.sys_up_time
|
def sys_up_time
varbind = @varbind_list[0]
if varbind && (varbind.name == SYS_UP_TIME_OID)
return varbind.value
else
raise InvalidTrapVarbind, "Expected sysUpTime.0, found " + varbind.to_s
end
end
|
ruby
|
def sys_up_time
varbind = @varbind_list[0]
if varbind && (varbind.name == SYS_UP_TIME_OID)
return varbind.value
else
raise InvalidTrapVarbind, "Expected sysUpTime.0, found " + varbind.to_s
end
end
|
[
"def",
"sys_up_time",
"varbind",
"=",
"@varbind_list",
"[",
"0",
"]",
"if",
"varbind",
"&&",
"(",
"varbind",
".",
"name",
"==",
"SYS_UP_TIME_OID",
")",
"return",
"varbind",
".",
"value",
"else",
"raise",
"InvalidTrapVarbind",
",",
"\"Expected sysUpTime.0, found \"",
"+",
"varbind",
".",
"to_s",
"end",
"end"
] |
Returns the value of the mandatory sysUpTime varbind for this trap.
Throws InvalidTrapVarbind if the sysUpTime varbind is not present.
|
[
"Returns",
"the",
"value",
"of",
"the",
"mandatory",
"sysUpTime",
"varbind",
"for",
"this",
"trap",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/pdu.rb#L286-L293
|
20,024
|
hallidave/ruby-snmp
|
lib/snmp/pdu.rb
|
SNMP.SNMPv2_Trap.trap_oid
|
def trap_oid
varbind = @varbind_list[1]
if varbind && (varbind.name == SNMP_TRAP_OID_OID)
return varbind.value
else
raise InvalidTrapVarbind, "Expected snmpTrapOID.0, found " + varbind.to_s
end
end
|
ruby
|
def trap_oid
varbind = @varbind_list[1]
if varbind && (varbind.name == SNMP_TRAP_OID_OID)
return varbind.value
else
raise InvalidTrapVarbind, "Expected snmpTrapOID.0, found " + varbind.to_s
end
end
|
[
"def",
"trap_oid",
"varbind",
"=",
"@varbind_list",
"[",
"1",
"]",
"if",
"varbind",
"&&",
"(",
"varbind",
".",
"name",
"==",
"SNMP_TRAP_OID_OID",
")",
"return",
"varbind",
".",
"value",
"else",
"raise",
"InvalidTrapVarbind",
",",
"\"Expected snmpTrapOID.0, found \"",
"+",
"varbind",
".",
"to_s",
"end",
"end"
] |
Returns the value of the mandatory snmpTrapOID varbind for this trap.
Throws InvalidTrapVarbind if the snmpTrapOID varbind is not present.
|
[
"Returns",
"the",
"value",
"of",
"the",
"mandatory",
"snmpTrapOID",
"varbind",
"for",
"this",
"trap",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/pdu.rb#L300-L307
|
20,025
|
hallidave/ruby-snmp
|
lib/snmp/varbind.rb
|
SNMP.ObjectId.subtree_of?
|
def subtree_of?(parent_tree)
parent_tree = make_object_id(parent_tree)
if parent_tree.length > self.length
false
else
parent_tree.each_index do |i|
return false if parent_tree[i] != self[i]
end
true
end
end
|
ruby
|
def subtree_of?(parent_tree)
parent_tree = make_object_id(parent_tree)
if parent_tree.length > self.length
false
else
parent_tree.each_index do |i|
return false if parent_tree[i] != self[i]
end
true
end
end
|
[
"def",
"subtree_of?",
"(",
"parent_tree",
")",
"parent_tree",
"=",
"make_object_id",
"(",
"parent_tree",
")",
"if",
"parent_tree",
".",
"length",
">",
"self",
".",
"length",
"false",
"else",
"parent_tree",
".",
"each_index",
"do",
"|",
"i",
"|",
"return",
"false",
"if",
"parent_tree",
"[",
"i",
"]",
"!=",
"self",
"[",
"i",
"]",
"end",
"true",
"end",
"end"
] |
Returns true if this ObjectId is a subtree of the provided parent tree
ObjectId. For example, "1.3.6.1.5" is a subtree of "1.3.6.1".
|
[
"Returns",
"true",
"if",
"this",
"ObjectId",
"is",
"a",
"subtree",
"of",
"the",
"provided",
"parent",
"tree",
"ObjectId",
".",
"For",
"example",
"1",
".",
"3",
".",
"6",
".",
"1",
".",
"5",
"is",
"a",
"subtree",
"of",
"1",
".",
"3",
".",
"6",
".",
"1",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/varbind.rb#L226-L236
|
20,026
|
hallidave/ruby-snmp
|
lib/snmp/varbind.rb
|
SNMP.ObjectId.index
|
def index(parent_tree)
parent_tree = make_object_id(parent_tree)
if not subtree_of?(parent_tree)
raise ArgumentError, "#{self.to_s} not a subtree of #{parent_tree.to_s}"
elsif self.length == parent_tree.length
raise ArgumentError, "OIDs are the same"
else
ObjectId.new(self[parent_tree.length..-1])
end
end
|
ruby
|
def index(parent_tree)
parent_tree = make_object_id(parent_tree)
if not subtree_of?(parent_tree)
raise ArgumentError, "#{self.to_s} not a subtree of #{parent_tree.to_s}"
elsif self.length == parent_tree.length
raise ArgumentError, "OIDs are the same"
else
ObjectId.new(self[parent_tree.length..-1])
end
end
|
[
"def",
"index",
"(",
"parent_tree",
")",
"parent_tree",
"=",
"make_object_id",
"(",
"parent_tree",
")",
"if",
"not",
"subtree_of?",
"(",
"parent_tree",
")",
"raise",
"ArgumentError",
",",
"\"#{self.to_s} not a subtree of #{parent_tree.to_s}\"",
"elsif",
"self",
".",
"length",
"==",
"parent_tree",
".",
"length",
"raise",
"ArgumentError",
",",
"\"OIDs are the same\"",
"else",
"ObjectId",
".",
"new",
"(",
"self",
"[",
"parent_tree",
".",
"length",
"..",
"-",
"1",
"]",
")",
"end",
"end"
] |
Returns an index based on the difference between this ObjectId
and the provided parent ObjectId.
For example, ObjectId.new("1.3.6.1.5").index("1.3.6.1") returns an
ObjectId of "5".
|
[
"Returns",
"an",
"index",
"based",
"on",
"the",
"difference",
"between",
"this",
"ObjectId",
"and",
"the",
"provided",
"parent",
"ObjectId",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/varbind.rb#L245-L254
|
20,027
|
hallidave/ruby-snmp
|
lib/snmp/mib.rb
|
SNMP.MIB.varbind_list
|
def varbind_list(object_list, option=:KeepValue)
raise ArgumentError, "A list of ObjectId or VarBind objects is NilClass" if object_list.nil?
vb_list = VarBindList.new
if object_list.respond_to? :to_str
vb_list << oid(object_list).to_varbind
elsif object_list.respond_to? :to_varbind
vb_list << apply_option(object_list.to_varbind, option)
else
object_list.each do |item|
if item.respond_to? :to_str
varbind = oid(item).to_varbind
else
varbind = item.to_varbind
end
vb_list << apply_option(varbind, option)
end
end
vb_list
end
|
ruby
|
def varbind_list(object_list, option=:KeepValue)
raise ArgumentError, "A list of ObjectId or VarBind objects is NilClass" if object_list.nil?
vb_list = VarBindList.new
if object_list.respond_to? :to_str
vb_list << oid(object_list).to_varbind
elsif object_list.respond_to? :to_varbind
vb_list << apply_option(object_list.to_varbind, option)
else
object_list.each do |item|
if item.respond_to? :to_str
varbind = oid(item).to_varbind
else
varbind = item.to_varbind
end
vb_list << apply_option(varbind, option)
end
end
vb_list
end
|
[
"def",
"varbind_list",
"(",
"object_list",
",",
"option",
"=",
":KeepValue",
")",
"raise",
"ArgumentError",
",",
"\"A list of ObjectId or VarBind objects is NilClass\"",
"if",
"object_list",
".",
"nil?",
"vb_list",
"=",
"VarBindList",
".",
"new",
"if",
"object_list",
".",
"respond_to?",
":to_str",
"vb_list",
"<<",
"oid",
"(",
"object_list",
")",
".",
"to_varbind",
"elsif",
"object_list",
".",
"respond_to?",
":to_varbind",
"vb_list",
"<<",
"apply_option",
"(",
"object_list",
".",
"to_varbind",
",",
"option",
")",
"else",
"object_list",
".",
"each",
"do",
"|",
"item",
"|",
"if",
"item",
".",
"respond_to?",
":to_str",
"varbind",
"=",
"oid",
"(",
"item",
")",
".",
"to_varbind",
"else",
"varbind",
"=",
"item",
".",
"to_varbind",
"end",
"vb_list",
"<<",
"apply_option",
"(",
"varbind",
",",
"option",
")",
"end",
"end",
"vb_list",
"end"
] |
Returns a VarBindList for the provided list of objects. If a
string is provided it is interpretted as a symbolic OID.
This method accepts many different kinds of objects:
- single string object IDs e.g. "1.3.6.1" or "IF-MIB::ifTable.1.1"
- single ObjectId
- list of string object IDs
- list of ObjectIds
- list of VarBinds
|
[
"Returns",
"a",
"VarBindList",
"for",
"the",
"provided",
"list",
"of",
"objects",
".",
"If",
"a",
"string",
"is",
"provided",
"it",
"is",
"interpretted",
"as",
"a",
"symbolic",
"OID",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/mib.rb#L186-L204
|
20,028
|
hallidave/ruby-snmp
|
lib/snmp/mib.rb
|
SNMP.MIB.name
|
def name(oid)
current_oid = ObjectId.new(oid)
index = []
while current_oid.size > 1
name = @by_oid[current_oid.to_s]
if name
return index.empty? ? name : "#{name}.#{index.join('.')}"
end
index.unshift current_oid.slice!(-1)
end
ObjectId.new(oid).to_s
end
|
ruby
|
def name(oid)
current_oid = ObjectId.new(oid)
index = []
while current_oid.size > 1
name = @by_oid[current_oid.to_s]
if name
return index.empty? ? name : "#{name}.#{index.join('.')}"
end
index.unshift current_oid.slice!(-1)
end
ObjectId.new(oid).to_s
end
|
[
"def",
"name",
"(",
"oid",
")",
"current_oid",
"=",
"ObjectId",
".",
"new",
"(",
"oid",
")",
"index",
"=",
"[",
"]",
"while",
"current_oid",
".",
"size",
">",
"1",
"name",
"=",
"@by_oid",
"[",
"current_oid",
".",
"to_s",
"]",
"if",
"name",
"return",
"index",
".",
"empty?",
"?",
"name",
":",
"\"#{name}.#{index.join('.')}\"",
"end",
"index",
".",
"unshift",
"current_oid",
".",
"slice!",
"(",
"-",
"1",
")",
"end",
"ObjectId",
".",
"new",
"(",
"oid",
")",
".",
"to_s",
"end"
] |
Returns the symbolic name of the given OID.
e.g. OID "1.3.6.1.2.1.1.0" returns symbol "SNMPv2-MIB::system.0"
|
[
"Returns",
"the",
"symbolic",
"name",
"of",
"the",
"given",
"OID",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/mib.rb#L261-L272
|
20,029
|
hallidave/ruby-snmp
|
lib/snmp/manager.rb
|
SNMP.Manager.get_next
|
def get_next(object_list)
varbind_list = @mib.varbind_list(object_list, :NullValue)
request = GetNextRequest.new(@@request_id.next, varbind_list)
try_request(request)
end
|
ruby
|
def get_next(object_list)
varbind_list = @mib.varbind_list(object_list, :NullValue)
request = GetNextRequest.new(@@request_id.next, varbind_list)
try_request(request)
end
|
[
"def",
"get_next",
"(",
"object_list",
")",
"varbind_list",
"=",
"@mib",
".",
"varbind_list",
"(",
"object_list",
",",
":NullValue",
")",
"request",
"=",
"GetNextRequest",
".",
"new",
"(",
"@@request_id",
".",
"next",
",",
"varbind_list",
")",
"try_request",
"(",
"request",
")",
"end"
] |
Sends a get-next request for the supplied list of ObjectId or VarBind
objects.
Returns a Response PDU with the results of the request.
|
[
"Sends",
"a",
"get",
"-",
"next",
"request",
"for",
"the",
"supplied",
"list",
"of",
"ObjectId",
"or",
"VarBind",
"objects",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/manager.rb#L280-L284
|
20,030
|
hallidave/ruby-snmp
|
lib/snmp/manager.rb
|
SNMP.Manager.get_bulk
|
def get_bulk(non_repeaters, max_repetitions, object_list)
varbind_list = @mib.varbind_list(object_list, :NullValue)
request = GetBulkRequest.new(
@@request_id.next,
varbind_list,
non_repeaters,
max_repetitions)
try_request(request)
end
|
ruby
|
def get_bulk(non_repeaters, max_repetitions, object_list)
varbind_list = @mib.varbind_list(object_list, :NullValue)
request = GetBulkRequest.new(
@@request_id.next,
varbind_list,
non_repeaters,
max_repetitions)
try_request(request)
end
|
[
"def",
"get_bulk",
"(",
"non_repeaters",
",",
"max_repetitions",
",",
"object_list",
")",
"varbind_list",
"=",
"@mib",
".",
"varbind_list",
"(",
"object_list",
",",
":NullValue",
")",
"request",
"=",
"GetBulkRequest",
".",
"new",
"(",
"@@request_id",
".",
"next",
",",
"varbind_list",
",",
"non_repeaters",
",",
"max_repetitions",
")",
"try_request",
"(",
"request",
")",
"end"
] |
Sends a get-bulk request. The non_repeaters parameter specifies
the number of objects in the object_list to be retrieved once. The
remaining objects in the list will be retrieved up to the number of
times specified by max_repetitions.
|
[
"Sends",
"a",
"get",
"-",
"bulk",
"request",
".",
"The",
"non_repeaters",
"parameter",
"specifies",
"the",
"number",
"of",
"objects",
"in",
"the",
"object_list",
"to",
"be",
"retrieved",
"once",
".",
"The",
"remaining",
"objects",
"in",
"the",
"list",
"will",
"be",
"retrieved",
"up",
"to",
"the",
"number",
"of",
"times",
"specified",
"by",
"max_repetitions",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/manager.rb#L292-L300
|
20,031
|
hallidave/ruby-snmp
|
lib/snmp/manager.rb
|
SNMP.Manager.set
|
def set(object_list)
varbind_list = @mib.varbind_list(object_list, :KeepValue)
request = SetRequest.new(@@request_id.next, varbind_list)
try_request(request, @write_community)
end
|
ruby
|
def set(object_list)
varbind_list = @mib.varbind_list(object_list, :KeepValue)
request = SetRequest.new(@@request_id.next, varbind_list)
try_request(request, @write_community)
end
|
[
"def",
"set",
"(",
"object_list",
")",
"varbind_list",
"=",
"@mib",
".",
"varbind_list",
"(",
"object_list",
",",
":KeepValue",
")",
"request",
"=",
"SetRequest",
".",
"new",
"(",
"@@request_id",
".",
"next",
",",
"varbind_list",
")",
"try_request",
"(",
"request",
",",
"@write_community",
")",
"end"
] |
Sends a set request using the supplied list of VarBind objects.
Returns a Response PDU with the results of the request.
|
[
"Sends",
"a",
"set",
"request",
"using",
"the",
"supplied",
"list",
"of",
"VarBind",
"objects",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/manager.rb#L307-L311
|
20,032
|
hallidave/ruby-snmp
|
lib/snmp/manager.rb
|
SNMP.Manager.trap_v1
|
def trap_v1(enterprise, agent_addr, generic_trap, specific_trap, timestamp, object_list=[])
vb_list = @mib.varbind_list(object_list, :KeepValue)
ent_oid = @mib.oid(enterprise)
agent_ip = IpAddress.new(agent_addr)
specific_int = Integer(specific_trap)
ticks = TimeTicks.new(timestamp)
trap = SNMPv1_Trap.new(ent_oid, agent_ip, generic_trap, specific_int, ticks, vb_list)
send_request(trap, @community, @host, @trap_port)
end
|
ruby
|
def trap_v1(enterprise, agent_addr, generic_trap, specific_trap, timestamp, object_list=[])
vb_list = @mib.varbind_list(object_list, :KeepValue)
ent_oid = @mib.oid(enterprise)
agent_ip = IpAddress.new(agent_addr)
specific_int = Integer(specific_trap)
ticks = TimeTicks.new(timestamp)
trap = SNMPv1_Trap.new(ent_oid, agent_ip, generic_trap, specific_int, ticks, vb_list)
send_request(trap, @community, @host, @trap_port)
end
|
[
"def",
"trap_v1",
"(",
"enterprise",
",",
"agent_addr",
",",
"generic_trap",
",",
"specific_trap",
",",
"timestamp",
",",
"object_list",
"=",
"[",
"]",
")",
"vb_list",
"=",
"@mib",
".",
"varbind_list",
"(",
"object_list",
",",
":KeepValue",
")",
"ent_oid",
"=",
"@mib",
".",
"oid",
"(",
"enterprise",
")",
"agent_ip",
"=",
"IpAddress",
".",
"new",
"(",
"agent_addr",
")",
"specific_int",
"=",
"Integer",
"(",
"specific_trap",
")",
"ticks",
"=",
"TimeTicks",
".",
"new",
"(",
"timestamp",
")",
"trap",
"=",
"SNMPv1_Trap",
".",
"new",
"(",
"ent_oid",
",",
"agent_ip",
",",
"generic_trap",
",",
"specific_int",
",",
"ticks",
",",
"vb_list",
")",
"send_request",
"(",
"trap",
",",
"@community",
",",
"@host",
",",
"@trap_port",
")",
"end"
] |
Sends an SNMPv1 style trap.
enterprise: The enterprise OID from the IANA assigned numbers
(http://www.iana.org/assignments/enterprise-numbers) as a String or
an ObjectId.
agent_addr: The IP address of the SNMP agent as a String or IpAddress.
generic_trap: The generic trap identifier. One of :coldStart,
:warmStart, :linkDown, :linkUp, :authenticationFailure,
:egpNeighborLoss, or :enterpriseSpecific
specific_trap: An integer representing the specific trap type for
an enterprise-specific trap.
timestamp: An integer respresenting the number of hundredths of
a second that this system has been up.
object_list: A list of additional varbinds to send with the trap.
For example:
Manager.open(:Version => :SNMPv1) do |snmp|
snmp.trap_v1(
"enterprises.9",
"10.1.2.3",
:enterpriseSpecific,
42,
12345,
[VarBind.new("1.3.6.1.2.3.4", Integer.new(1))])
end
|
[
"Sends",
"an",
"SNMPv1",
"style",
"trap",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/manager.rb#L346-L354
|
20,033
|
hallidave/ruby-snmp
|
lib/snmp/manager.rb
|
SNMP.Manager.trap_v2
|
def trap_v2(sys_up_time, trap_oid, object_list=[])
vb_list = create_trap_vb_list(sys_up_time, trap_oid, object_list)
trap = SNMPv2_Trap.new(@@request_id.next, vb_list)
send_request(trap, @community, @host, @trap_port)
end
|
ruby
|
def trap_v2(sys_up_time, trap_oid, object_list=[])
vb_list = create_trap_vb_list(sys_up_time, trap_oid, object_list)
trap = SNMPv2_Trap.new(@@request_id.next, vb_list)
send_request(trap, @community, @host, @trap_port)
end
|
[
"def",
"trap_v2",
"(",
"sys_up_time",
",",
"trap_oid",
",",
"object_list",
"=",
"[",
"]",
")",
"vb_list",
"=",
"create_trap_vb_list",
"(",
"sys_up_time",
",",
"trap_oid",
",",
"object_list",
")",
"trap",
"=",
"SNMPv2_Trap",
".",
"new",
"(",
"@@request_id",
".",
"next",
",",
"vb_list",
")",
"send_request",
"(",
"trap",
",",
"@community",
",",
"@host",
",",
"@trap_port",
")",
"end"
] |
Sends an SNMPv2c style trap.
sys_up_time: An integer respresenting the number of hundredths of
a second that this system has been up.
trap_oid: An ObjectId or String with the OID identifier for this
trap.
object_list: A list of additional varbinds to send with the trap.
|
[
"Sends",
"an",
"SNMPv2c",
"style",
"trap",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/manager.rb#L367-L371
|
20,034
|
hallidave/ruby-snmp
|
lib/snmp/manager.rb
|
SNMP.Manager.inform
|
def inform(sys_up_time, trap_oid, object_list=[])
vb_list = create_trap_vb_list(sys_up_time, trap_oid, object_list)
request = InformRequest.new(@@request_id.next, vb_list)
try_request(request, @community, @host, @trap_port)
end
|
ruby
|
def inform(sys_up_time, trap_oid, object_list=[])
vb_list = create_trap_vb_list(sys_up_time, trap_oid, object_list)
request = InformRequest.new(@@request_id.next, vb_list)
try_request(request, @community, @host, @trap_port)
end
|
[
"def",
"inform",
"(",
"sys_up_time",
",",
"trap_oid",
",",
"object_list",
"=",
"[",
"]",
")",
"vb_list",
"=",
"create_trap_vb_list",
"(",
"sys_up_time",
",",
"trap_oid",
",",
"object_list",
")",
"request",
"=",
"InformRequest",
".",
"new",
"(",
"@@request_id",
".",
"next",
",",
"vb_list",
")",
"try_request",
"(",
"request",
",",
"@community",
",",
"@host",
",",
"@trap_port",
")",
"end"
] |
Sends an inform request using the supplied varbind list.
sys_up_time: An integer respresenting the number of hundredths of
a second that this system has been up.
trap_oid: An ObjectId or String with the OID identifier for this
inform request.
object_list: A list of additional varbinds to send with the inform.
|
[
"Sends",
"an",
"inform",
"request",
"using",
"the",
"supplied",
"varbind",
"list",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/manager.rb#L384-L388
|
20,035
|
hallidave/ruby-snmp
|
lib/snmp/manager.rb
|
SNMP.Manager.create_trap_vb_list
|
def create_trap_vb_list(sys_up_time, trap_oid, object_list)
vb_args = @mib.varbind_list(object_list, :KeepValue)
uptime_vb = VarBind.new(SNMP::SYS_UP_TIME_OID, TimeTicks.new(sys_up_time.to_int))
trap_vb = VarBind.new(SNMP::SNMP_TRAP_OID_OID, @mib.oid(trap_oid))
VarBindList.new([uptime_vb, trap_vb, *vb_args])
end
|
ruby
|
def create_trap_vb_list(sys_up_time, trap_oid, object_list)
vb_args = @mib.varbind_list(object_list, :KeepValue)
uptime_vb = VarBind.new(SNMP::SYS_UP_TIME_OID, TimeTicks.new(sys_up_time.to_int))
trap_vb = VarBind.new(SNMP::SNMP_TRAP_OID_OID, @mib.oid(trap_oid))
VarBindList.new([uptime_vb, trap_vb, *vb_args])
end
|
[
"def",
"create_trap_vb_list",
"(",
"sys_up_time",
",",
"trap_oid",
",",
"object_list",
")",
"vb_args",
"=",
"@mib",
".",
"varbind_list",
"(",
"object_list",
",",
":KeepValue",
")",
"uptime_vb",
"=",
"VarBind",
".",
"new",
"(",
"SNMP",
"::",
"SYS_UP_TIME_OID",
",",
"TimeTicks",
".",
"new",
"(",
"sys_up_time",
".",
"to_int",
")",
")",
"trap_vb",
"=",
"VarBind",
".",
"new",
"(",
"SNMP",
"::",
"SNMP_TRAP_OID_OID",
",",
"@mib",
".",
"oid",
"(",
"trap_oid",
")",
")",
"VarBindList",
".",
"new",
"(",
"[",
"uptime_vb",
",",
"trap_vb",
",",
"vb_args",
"]",
")",
"end"
] |
Helper method for building VarBindList for trap and inform requests.
|
[
"Helper",
"method",
"for",
"building",
"VarBindList",
"for",
"trap",
"and",
"inform",
"requests",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/manager.rb#L393-L398
|
20,036
|
hallidave/ruby-snmp
|
lib/snmp/manager.rb
|
SNMP.Manager.walk
|
def walk(object_list, index_column=0)
raise ArgumentError, "expected a block to be given" unless block_given?
vb_list = @mib.varbind_list(object_list, :NullValue)
raise ArgumentError, "index_column is past end of varbind list" if index_column >= vb_list.length
is_single_vb = object_list.respond_to?(:to_str) ||
object_list.respond_to?(:to_varbind)
start_list = vb_list
start_oid = vb_list[index_column].name
last_oid = start_oid
loop do
vb_list = get_next(vb_list).vb_list
index_vb = vb_list[index_column]
break if EndOfMibView == index_vb.value
stop_oid = index_vb.name
if !@ignore_oid_order && stop_oid <= last_oid
warn "OIDs are not increasing, #{last_oid} followed by #{stop_oid}"
break
end
break unless stop_oid.subtree_of?(start_oid)
last_oid = stop_oid
if is_single_vb
yield index_vb
else
vb_list = validate_row(vb_list, start_list, index_column)
yield vb_list
end
end
end
|
ruby
|
def walk(object_list, index_column=0)
raise ArgumentError, "expected a block to be given" unless block_given?
vb_list = @mib.varbind_list(object_list, :NullValue)
raise ArgumentError, "index_column is past end of varbind list" if index_column >= vb_list.length
is_single_vb = object_list.respond_to?(:to_str) ||
object_list.respond_to?(:to_varbind)
start_list = vb_list
start_oid = vb_list[index_column].name
last_oid = start_oid
loop do
vb_list = get_next(vb_list).vb_list
index_vb = vb_list[index_column]
break if EndOfMibView == index_vb.value
stop_oid = index_vb.name
if !@ignore_oid_order && stop_oid <= last_oid
warn "OIDs are not increasing, #{last_oid} followed by #{stop_oid}"
break
end
break unless stop_oid.subtree_of?(start_oid)
last_oid = stop_oid
if is_single_vb
yield index_vb
else
vb_list = validate_row(vb_list, start_list, index_column)
yield vb_list
end
end
end
|
[
"def",
"walk",
"(",
"object_list",
",",
"index_column",
"=",
"0",
")",
"raise",
"ArgumentError",
",",
"\"expected a block to be given\"",
"unless",
"block_given?",
"vb_list",
"=",
"@mib",
".",
"varbind_list",
"(",
"object_list",
",",
":NullValue",
")",
"raise",
"ArgumentError",
",",
"\"index_column is past end of varbind list\"",
"if",
"index_column",
">=",
"vb_list",
".",
"length",
"is_single_vb",
"=",
"object_list",
".",
"respond_to?",
"(",
":to_str",
")",
"||",
"object_list",
".",
"respond_to?",
"(",
":to_varbind",
")",
"start_list",
"=",
"vb_list",
"start_oid",
"=",
"vb_list",
"[",
"index_column",
"]",
".",
"name",
"last_oid",
"=",
"start_oid",
"loop",
"do",
"vb_list",
"=",
"get_next",
"(",
"vb_list",
")",
".",
"vb_list",
"index_vb",
"=",
"vb_list",
"[",
"index_column",
"]",
"break",
"if",
"EndOfMibView",
"==",
"index_vb",
".",
"value",
"stop_oid",
"=",
"index_vb",
".",
"name",
"if",
"!",
"@ignore_oid_order",
"&&",
"stop_oid",
"<=",
"last_oid",
"warn",
"\"OIDs are not increasing, #{last_oid} followed by #{stop_oid}\"",
"break",
"end",
"break",
"unless",
"stop_oid",
".",
"subtree_of?",
"(",
"start_oid",
")",
"last_oid",
"=",
"stop_oid",
"if",
"is_single_vb",
"yield",
"index_vb",
"else",
"vb_list",
"=",
"validate_row",
"(",
"vb_list",
",",
"start_list",
",",
"index_column",
")",
"yield",
"vb_list",
"end",
"end",
"end"
] |
Walks a list of ObjectId or VarBind objects using get_next until
the response to the first OID in the list reaches the end of its
MIB subtree.
The varbinds from each get_next are yielded to the given block as
they are retrieved. The result is yielded as a VarBind when walking
a single object or as a VarBindList when walking a list of objects.
Normally this method is used for walking tables by providing an
ObjectId for each column of the table.
For example:
SNMP::Manager.open(:host => "localhost") do |manager|
manager.walk("ifTable") { |vb| puts vb }
end
SNMP::Manager.open(:host => "localhost") do |manager|
manager.walk(["ifIndex", "ifDescr"]) do |index, descr|
puts "#{index.value} #{descr.value}"
end
end
The index_column identifies the column that will provide the index
for each row. This information is used to deal with "holes" in a
table (when a row is missing a varbind for one column). A missing
varbind is replaced with a varbind with the value NoSuchInstance.
Note: If you are getting back rows where all columns have a value of
NoSuchInstance then your index column is probably missing one of the
rows. Choose an index column that includes all indexes for the table.
|
[
"Walks",
"a",
"list",
"of",
"ObjectId",
"or",
"VarBind",
"objects",
"using",
"get_next",
"until",
"the",
"response",
"to",
"the",
"first",
"OID",
"in",
"the",
"list",
"reaches",
"the",
"end",
"of",
"its",
"MIB",
"subtree",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/manager.rb#L433-L460
|
20,037
|
hallidave/ruby-snmp
|
lib/snmp/manager.rb
|
SNMP.Manager.validate_row
|
def validate_row(vb_list, start_list, index_column)
start_vb = start_list[index_column]
index_vb = vb_list[index_column]
row_index = index_vb.name.index(start_vb.name)
vb_list.each_index do |i|
if i != index_column
expected_oid = start_list[i].name + row_index
if vb_list[i].name != expected_oid
vb_list[i] = VarBind.new(expected_oid, NoSuchInstance).with_mib(@mib)
end
end
end
vb_list
end
|
ruby
|
def validate_row(vb_list, start_list, index_column)
start_vb = start_list[index_column]
index_vb = vb_list[index_column]
row_index = index_vb.name.index(start_vb.name)
vb_list.each_index do |i|
if i != index_column
expected_oid = start_list[i].name + row_index
if vb_list[i].name != expected_oid
vb_list[i] = VarBind.new(expected_oid, NoSuchInstance).with_mib(@mib)
end
end
end
vb_list
end
|
[
"def",
"validate_row",
"(",
"vb_list",
",",
"start_list",
",",
"index_column",
")",
"start_vb",
"=",
"start_list",
"[",
"index_column",
"]",
"index_vb",
"=",
"vb_list",
"[",
"index_column",
"]",
"row_index",
"=",
"index_vb",
".",
"name",
".",
"index",
"(",
"start_vb",
".",
"name",
")",
"vb_list",
".",
"each_index",
"do",
"|",
"i",
"|",
"if",
"i",
"!=",
"index_column",
"expected_oid",
"=",
"start_list",
"[",
"i",
"]",
".",
"name",
"+",
"row_index",
"if",
"vb_list",
"[",
"i",
"]",
".",
"name",
"!=",
"expected_oid",
"vb_list",
"[",
"i",
"]",
"=",
"VarBind",
".",
"new",
"(",
"expected_oid",
",",
"NoSuchInstance",
")",
".",
"with_mib",
"(",
"@mib",
")",
"end",
"end",
"end",
"vb_list",
"end"
] |
Helper method for walk. Checks all of the VarBinds in vb_list to
make sure that the row indices match. If the row index does not
match the index column, then that varbind is replaced with a varbind
with a value of NoSuchInstance.
|
[
"Helper",
"method",
"for",
"walk",
".",
"Checks",
"all",
"of",
"the",
"VarBinds",
"in",
"vb_list",
"to",
"make",
"sure",
"that",
"the",
"row",
"indices",
"match",
".",
"If",
"the",
"row",
"index",
"does",
"not",
"match",
"the",
"index",
"column",
"then",
"that",
"varbind",
"is",
"replaced",
"with",
"a",
"varbind",
"with",
"a",
"value",
"of",
"NoSuchInstance",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/manager.rb#L468-L481
|
20,038
|
hallidave/ruby-snmp
|
lib/snmp/manager.rb
|
SNMP.Manager.get_response
|
def get_response(request)
begin
data = @transport.recv(@max_bytes)
message = Message.decode(data, @mib)
response = message.pdu
end until request.request_id == response.request_id
response
end
|
ruby
|
def get_response(request)
begin
data = @transport.recv(@max_bytes)
message = Message.decode(data, @mib)
response = message.pdu
end until request.request_id == response.request_id
response
end
|
[
"def",
"get_response",
"(",
"request",
")",
"begin",
"data",
"=",
"@transport",
".",
"recv",
"(",
"@max_bytes",
")",
"message",
"=",
"Message",
".",
"decode",
"(",
"data",
",",
"@mib",
")",
"response",
"=",
"message",
".",
"pdu",
"end",
"until",
"request",
".",
"request_id",
"==",
"response",
".",
"request_id",
"response",
"end"
] |
Wait until response arrives. Ignore responses with mismatched IDs;
these responses are typically from previous requests that timed out
or almost timed out.
|
[
"Wait",
"until",
"response",
"arrives",
".",
"Ignore",
"responses",
"with",
"mismatched",
"IDs",
";",
"these",
"responses",
"are",
"typically",
"from",
"previous",
"requests",
"that",
"timed",
"out",
"or",
"almost",
"timed",
"out",
"."
] |
4b9deda96f14f5a216e9743313cf100f9ed1da45
|
https://github.com/hallidave/ruby-snmp/blob/4b9deda96f14f5a216e9743313cf100f9ed1da45/lib/snmp/manager.rb#L531-L538
|
20,039
|
saucelabs/sauce_ruby
|
lib/sauce/config.rb
|
Sauce.Config.is_defined?
|
def is_defined? (top_mod, sub_mod = nil)
return_value = Object.const_defined? top_mod
unless !return_value || sub_mod.nil?
return_value = Object.const_get(top_mod).const_defined? sub_mod
end
return_value
end
|
ruby
|
def is_defined? (top_mod, sub_mod = nil)
return_value = Object.const_defined? top_mod
unless !return_value || sub_mod.nil?
return_value = Object.const_get(top_mod).const_defined? sub_mod
end
return_value
end
|
[
"def",
"is_defined?",
"(",
"top_mod",
",",
"sub_mod",
"=",
"nil",
")",
"return_value",
"=",
"Object",
".",
"const_defined?",
"top_mod",
"unless",
"!",
"return_value",
"||",
"sub_mod",
".",
"nil?",
"return_value",
"=",
"Object",
".",
"const_get",
"(",
"top_mod",
")",
".",
"const_defined?",
"sub_mod",
"end",
"return_value",
"end"
] |
Only here to be stubbed for testing. Gross.
|
[
"Only",
"here",
"to",
"be",
"stubbed",
"for",
"testing",
".",
"Gross",
"."
] |
b1c4dab8516fb5e9c75ef16fb72b59b72c0ff0b0
|
https://github.com/saucelabs/sauce_ruby/blob/b1c4dab8516fb5e9c75ef16fb72b59b72c0ff0b0/lib/sauce/config.rb#L325-L332
|
20,040
|
saucelabs/sauce_ruby
|
lib/sauce/job.rb
|
Sauce.Job.build!
|
def build!(options)
# Massage JSON
options.each { |key,value| options[key] = false if options[key] == "false" }
@id = options["id"]
@owner = options["owner"]
@status = options["status"]
@error = options["error"]
@name = options["name"]
@browser = options["browser"]
@browser_version = options["browser_version"]
@os = options["os"]
@creation_time = options["creation_time"].to_i
@start_time = options["start_time"].to_i
@end_time = options["end_time"].to_i
@video_url = options["video_url"]
@log_url = options["log_url"]
@public = options["public"]
@tags = options["tags"]
@passed = options["passed"]
@custom_data = options['custom-data']
raise NoIDError if @id.nil? or @id.empty?
end
|
ruby
|
def build!(options)
# Massage JSON
options.each { |key,value| options[key] = false if options[key] == "false" }
@id = options["id"]
@owner = options["owner"]
@status = options["status"]
@error = options["error"]
@name = options["name"]
@browser = options["browser"]
@browser_version = options["browser_version"]
@os = options["os"]
@creation_time = options["creation_time"].to_i
@start_time = options["start_time"].to_i
@end_time = options["end_time"].to_i
@video_url = options["video_url"]
@log_url = options["log_url"]
@public = options["public"]
@tags = options["tags"]
@passed = options["passed"]
@custom_data = options['custom-data']
raise NoIDError if @id.nil? or @id.empty?
end
|
[
"def",
"build!",
"(",
"options",
")",
"# Massage JSON",
"options",
".",
"each",
"{",
"|",
"key",
",",
"value",
"|",
"options",
"[",
"key",
"]",
"=",
"false",
"if",
"options",
"[",
"key",
"]",
"==",
"\"false\"",
"}",
"@id",
"=",
"options",
"[",
"\"id\"",
"]",
"@owner",
"=",
"options",
"[",
"\"owner\"",
"]",
"@status",
"=",
"options",
"[",
"\"status\"",
"]",
"@error",
"=",
"options",
"[",
"\"error\"",
"]",
"@name",
"=",
"options",
"[",
"\"name\"",
"]",
"@browser",
"=",
"options",
"[",
"\"browser\"",
"]",
"@browser_version",
"=",
"options",
"[",
"\"browser_version\"",
"]",
"@os",
"=",
"options",
"[",
"\"os\"",
"]",
"@creation_time",
"=",
"options",
"[",
"\"creation_time\"",
"]",
".",
"to_i",
"@start_time",
"=",
"options",
"[",
"\"start_time\"",
"]",
".",
"to_i",
"@end_time",
"=",
"options",
"[",
"\"end_time\"",
"]",
".",
"to_i",
"@video_url",
"=",
"options",
"[",
"\"video_url\"",
"]",
"@log_url",
"=",
"options",
"[",
"\"log_url\"",
"]",
"@public",
"=",
"options",
"[",
"\"public\"",
"]",
"@tags",
"=",
"options",
"[",
"\"tags\"",
"]",
"@passed",
"=",
"options",
"[",
"\"passed\"",
"]",
"@custom_data",
"=",
"options",
"[",
"'custom-data'",
"]",
"raise",
"NoIDError",
"if",
"@id",
".",
"nil?",
"or",
"@id",
".",
"empty?",
"end"
] |
Sets all internal variables from a hash
|
[
"Sets",
"all",
"internal",
"variables",
"from",
"a",
"hash"
] |
b1c4dab8516fb5e9c75ef16fb72b59b72c0ff0b0
|
https://github.com/saucelabs/sauce_ruby/blob/b1c4dab8516fb5e9c75ef16fb72b59b72c0ff0b0/lib/sauce/job.rb#L134-L157
|
20,041
|
ndbroadbent/turbo-sprockets-rails3
|
lib/sprockets/static_non_digest_generator.rb
|
Sprockets.StaticNonDigestGenerator.generate
|
def generate
start_time = Time.now.to_f
env.each_logical_path do |logical_path|
if File.basename(logical_path)[/[^\.]+/, 0] == 'index'
logical_path.sub!(/\/index\./, '.')
end
next unless compile_path?(logical_path)
if digest_path = @digests[logical_path]
abs_digest_path = "#{@target}/#{digest_path}"
abs_logical_path = "#{@target}/#{logical_path}"
# Remove known digests from css & js
if abs_digest_path.match(/\.(?:js|css)$/)
mtime = File.mtime(abs_digest_path)
asset_body = File.read(abs_digest_path)
# Find all hashes in the asset body with a leading '-'
asset_body.gsub!(DIGEST_REGEX) do |match|
# Only remove if known digest
$1.in?(@asset_digests.values) ? '' : match
end
# Write non-digest file
File.open abs_logical_path, 'w' do |f|
f.write asset_body
end
# Set modification and access times
File.utime(File.atime(abs_digest_path), mtime, abs_logical_path)
# Also write gzipped asset
File.open("#{abs_logical_path}.gz", 'wb') do |f|
gz = Zlib::GzipWriter.new(f, Zlib::BEST_COMPRESSION)
gz.mtime = mtime.to_i
gz.write asset_body
gz.close
end
env.logger.debug "Stripped digests, copied to #{logical_path}, and created gzipped asset"
else
# Otherwise, treat file as binary and copy it.
# Ignore paths that have no digests, such as READMEs
unless !File.exist?(abs_digest_path) || abs_digest_path == abs_logical_path
FileUtils.cp_r abs_digest_path, abs_logical_path, :remove_destination => true
env.logger.debug "Copied binary asset to #{logical_path}"
# Copy gzipped asset if exists
if File.exist? "#{abs_digest_path}.gz"
FileUtils.cp_r "#{abs_digest_path}.gz", "#{abs_logical_path}.gz", :remove_destination => true
env.logger.debug "Copied gzipped asset to #{logical_path}.gz"
end
end
end
end
end
elapsed_time = ((Time.now.to_f - start_time) * 1000).to_i
env.logger.debug "Generated non-digest assets in #{elapsed_time}ms"
end
|
ruby
|
def generate
start_time = Time.now.to_f
env.each_logical_path do |logical_path|
if File.basename(logical_path)[/[^\.]+/, 0] == 'index'
logical_path.sub!(/\/index\./, '.')
end
next unless compile_path?(logical_path)
if digest_path = @digests[logical_path]
abs_digest_path = "#{@target}/#{digest_path}"
abs_logical_path = "#{@target}/#{logical_path}"
# Remove known digests from css & js
if abs_digest_path.match(/\.(?:js|css)$/)
mtime = File.mtime(abs_digest_path)
asset_body = File.read(abs_digest_path)
# Find all hashes in the asset body with a leading '-'
asset_body.gsub!(DIGEST_REGEX) do |match|
# Only remove if known digest
$1.in?(@asset_digests.values) ? '' : match
end
# Write non-digest file
File.open abs_logical_path, 'w' do |f|
f.write asset_body
end
# Set modification and access times
File.utime(File.atime(abs_digest_path), mtime, abs_logical_path)
# Also write gzipped asset
File.open("#{abs_logical_path}.gz", 'wb') do |f|
gz = Zlib::GzipWriter.new(f, Zlib::BEST_COMPRESSION)
gz.mtime = mtime.to_i
gz.write asset_body
gz.close
end
env.logger.debug "Stripped digests, copied to #{logical_path}, and created gzipped asset"
else
# Otherwise, treat file as binary and copy it.
# Ignore paths that have no digests, such as READMEs
unless !File.exist?(abs_digest_path) || abs_digest_path == abs_logical_path
FileUtils.cp_r abs_digest_path, abs_logical_path, :remove_destination => true
env.logger.debug "Copied binary asset to #{logical_path}"
# Copy gzipped asset if exists
if File.exist? "#{abs_digest_path}.gz"
FileUtils.cp_r "#{abs_digest_path}.gz", "#{abs_logical_path}.gz", :remove_destination => true
env.logger.debug "Copied gzipped asset to #{logical_path}.gz"
end
end
end
end
end
elapsed_time = ((Time.now.to_f - start_time) * 1000).to_i
env.logger.debug "Generated non-digest assets in #{elapsed_time}ms"
end
|
[
"def",
"generate",
"start_time",
"=",
"Time",
".",
"now",
".",
"to_f",
"env",
".",
"each_logical_path",
"do",
"|",
"logical_path",
"|",
"if",
"File",
".",
"basename",
"(",
"logical_path",
")",
"[",
"/",
"\\.",
"/",
",",
"0",
"]",
"==",
"'index'",
"logical_path",
".",
"sub!",
"(",
"/",
"\\/",
"\\.",
"/",
",",
"'.'",
")",
"end",
"next",
"unless",
"compile_path?",
"(",
"logical_path",
")",
"if",
"digest_path",
"=",
"@digests",
"[",
"logical_path",
"]",
"abs_digest_path",
"=",
"\"#{@target}/#{digest_path}\"",
"abs_logical_path",
"=",
"\"#{@target}/#{logical_path}\"",
"# Remove known digests from css & js",
"if",
"abs_digest_path",
".",
"match",
"(",
"/",
"\\.",
"/",
")",
"mtime",
"=",
"File",
".",
"mtime",
"(",
"abs_digest_path",
")",
"asset_body",
"=",
"File",
".",
"read",
"(",
"abs_digest_path",
")",
"# Find all hashes in the asset body with a leading '-'",
"asset_body",
".",
"gsub!",
"(",
"DIGEST_REGEX",
")",
"do",
"|",
"match",
"|",
"# Only remove if known digest",
"$1",
".",
"in?",
"(",
"@asset_digests",
".",
"values",
")",
"?",
"''",
":",
"match",
"end",
"# Write non-digest file",
"File",
".",
"open",
"abs_logical_path",
",",
"'w'",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"asset_body",
"end",
"# Set modification and access times",
"File",
".",
"utime",
"(",
"File",
".",
"atime",
"(",
"abs_digest_path",
")",
",",
"mtime",
",",
"abs_logical_path",
")",
"# Also write gzipped asset",
"File",
".",
"open",
"(",
"\"#{abs_logical_path}.gz\"",
",",
"'wb'",
")",
"do",
"|",
"f",
"|",
"gz",
"=",
"Zlib",
"::",
"GzipWriter",
".",
"new",
"(",
"f",
",",
"Zlib",
"::",
"BEST_COMPRESSION",
")",
"gz",
".",
"mtime",
"=",
"mtime",
".",
"to_i",
"gz",
".",
"write",
"asset_body",
"gz",
".",
"close",
"end",
"env",
".",
"logger",
".",
"debug",
"\"Stripped digests, copied to #{logical_path}, and created gzipped asset\"",
"else",
"# Otherwise, treat file as binary and copy it.",
"# Ignore paths that have no digests, such as READMEs",
"unless",
"!",
"File",
".",
"exist?",
"(",
"abs_digest_path",
")",
"||",
"abs_digest_path",
"==",
"abs_logical_path",
"FileUtils",
".",
"cp_r",
"abs_digest_path",
",",
"abs_logical_path",
",",
":remove_destination",
"=>",
"true",
"env",
".",
"logger",
".",
"debug",
"\"Copied binary asset to #{logical_path}\"",
"# Copy gzipped asset if exists",
"if",
"File",
".",
"exist?",
"\"#{abs_digest_path}.gz\"",
"FileUtils",
".",
"cp_r",
"\"#{abs_digest_path}.gz\"",
",",
"\"#{abs_logical_path}.gz\"",
",",
":remove_destination",
"=>",
"true",
"env",
".",
"logger",
".",
"debug",
"\"Copied gzipped asset to #{logical_path}.gz\"",
"end",
"end",
"end",
"end",
"end",
"elapsed_time",
"=",
"(",
"(",
"Time",
".",
"now",
".",
"to_f",
"-",
"start_time",
")",
"*",
"1000",
")",
".",
"to_i",
"env",
".",
"logger",
".",
"debug",
"\"Generated non-digest assets in #{elapsed_time}ms\"",
"end"
] |
Generate non-digest assets by making a copy of the digest asset,
with digests stripped from js and css. The new files are also gzipped.
Other assets are copied verbatim.
|
[
"Generate",
"non",
"-",
"digest",
"assets",
"by",
"making",
"a",
"copy",
"of",
"the",
"digest",
"asset",
"with",
"digests",
"stripped",
"from",
"js",
"and",
"css",
".",
"The",
"new",
"files",
"are",
"also",
"gzipped",
".",
"Other",
"assets",
"are",
"copied",
"verbatim",
"."
] |
17fc5c88c4616746811d0e82f9394db1011f27fe
|
https://github.com/ndbroadbent/turbo-sprockets-rails3/blob/17fc5c88c4616746811d0e82f9394db1011f27fe/lib/sprockets/static_non_digest_generator.rb#L26-L88
|
20,042
|
ndbroadbent/turbo-sprockets-rails3
|
lib/sprockets/asset_with_dependencies.rb
|
Sprockets.AssetWithDependencies.init_with
|
def init_with(environment, coder, asset_options = {})
asset_options[:bundle] = false
super(environment, coder)
@source = coder['source']
@dependency_digest = coder['dependency_digest']
@required_assets = coder['required_paths'].map { |p|
p = expand_root_path(p)
unless environment.paths.detect { |path| p[path] }
raise UnserializeError, "#{p} isn't in paths"
end
p == pathname.to_s ? self : environment.find_asset(p, asset_options)
}
@dependency_paths = coder['dependency_paths'].map { |h|
DependencyFile.new(expand_root_path(h['path']), h['mtime'], h['digest'])
}
end
|
ruby
|
def init_with(environment, coder, asset_options = {})
asset_options[:bundle] = false
super(environment, coder)
@source = coder['source']
@dependency_digest = coder['dependency_digest']
@required_assets = coder['required_paths'].map { |p|
p = expand_root_path(p)
unless environment.paths.detect { |path| p[path] }
raise UnserializeError, "#{p} isn't in paths"
end
p == pathname.to_s ? self : environment.find_asset(p, asset_options)
}
@dependency_paths = coder['dependency_paths'].map { |h|
DependencyFile.new(expand_root_path(h['path']), h['mtime'], h['digest'])
}
end
|
[
"def",
"init_with",
"(",
"environment",
",",
"coder",
",",
"asset_options",
"=",
"{",
"}",
")",
"asset_options",
"[",
":bundle",
"]",
"=",
"false",
"super",
"(",
"environment",
",",
"coder",
")",
"@source",
"=",
"coder",
"[",
"'source'",
"]",
"@dependency_digest",
"=",
"coder",
"[",
"'dependency_digest'",
"]",
"@required_assets",
"=",
"coder",
"[",
"'required_paths'",
"]",
".",
"map",
"{",
"|",
"p",
"|",
"p",
"=",
"expand_root_path",
"(",
"p",
")",
"unless",
"environment",
".",
"paths",
".",
"detect",
"{",
"|",
"path",
"|",
"p",
"[",
"path",
"]",
"}",
"raise",
"UnserializeError",
",",
"\"#{p} isn't in paths\"",
"end",
"p",
"==",
"pathname",
".",
"to_s",
"?",
"self",
":",
"environment",
".",
"find_asset",
"(",
"p",
",",
"asset_options",
")",
"}",
"@dependency_paths",
"=",
"coder",
"[",
"'dependency_paths'",
"]",
".",
"map",
"{",
"|",
"h",
"|",
"DependencyFile",
".",
"new",
"(",
"expand_root_path",
"(",
"h",
"[",
"'path'",
"]",
")",
",",
"h",
"[",
"'mtime'",
"]",
",",
"h",
"[",
"'digest'",
"]",
")",
"}",
"end"
] |
Initialize asset from serialized hash
|
[
"Initialize",
"asset",
"from",
"serialized",
"hash"
] |
17fc5c88c4616746811d0e82f9394db1011f27fe
|
https://github.com/ndbroadbent/turbo-sprockets-rails3/blob/17fc5c88c4616746811d0e82f9394db1011f27fe/lib/sprockets/asset_with_dependencies.rb#L13-L33
|
20,043
|
ndbroadbent/turbo-sprockets-rails3
|
lib/sprockets/asset_with_dependencies.rb
|
Sprockets.AssetWithDependencies.encode_with
|
def encode_with(coder)
super
coder['source'] = source
coder['dependency_digest'] = dependency_digest
coder['required_paths'] = required_assets.map { |a|
relativize_root_path(a.pathname).to_s
}
coder['dependency_paths'] = dependency_paths.map { |d|
{ 'path' => relativize_root_path(d.pathname).to_s,
'mtime' => d.mtime.iso8601,
'digest' => d.digest }
}
end
|
ruby
|
def encode_with(coder)
super
coder['source'] = source
coder['dependency_digest'] = dependency_digest
coder['required_paths'] = required_assets.map { |a|
relativize_root_path(a.pathname).to_s
}
coder['dependency_paths'] = dependency_paths.map { |d|
{ 'path' => relativize_root_path(d.pathname).to_s,
'mtime' => d.mtime.iso8601,
'digest' => d.digest }
}
end
|
[
"def",
"encode_with",
"(",
"coder",
")",
"super",
"coder",
"[",
"'source'",
"]",
"=",
"source",
"coder",
"[",
"'dependency_digest'",
"]",
"=",
"dependency_digest",
"coder",
"[",
"'required_paths'",
"]",
"=",
"required_assets",
".",
"map",
"{",
"|",
"a",
"|",
"relativize_root_path",
"(",
"a",
".",
"pathname",
")",
".",
"to_s",
"}",
"coder",
"[",
"'dependency_paths'",
"]",
"=",
"dependency_paths",
".",
"map",
"{",
"|",
"d",
"|",
"{",
"'path'",
"=>",
"relativize_root_path",
"(",
"d",
".",
"pathname",
")",
".",
"to_s",
",",
"'mtime'",
"=>",
"d",
".",
"mtime",
".",
"iso8601",
",",
"'digest'",
"=>",
"d",
".",
"digest",
"}",
"}",
"end"
] |
Serialize custom attributes.
|
[
"Serialize",
"custom",
"attributes",
"."
] |
17fc5c88c4616746811d0e82f9394db1011f27fe
|
https://github.com/ndbroadbent/turbo-sprockets-rails3/blob/17fc5c88c4616746811d0e82f9394db1011f27fe/lib/sprockets/asset_with_dependencies.rb#L36-L50
|
20,044
|
saucelabs/sauce_ruby
|
gems/sauce-connect/lib/sauce/connect.rb
|
Sauce.Connect.extract_config
|
def extract_config options
@username = options[:username]
@access_key = options[:access_key]
@cli_options = options[:connect_options]
@sc4_executable = options[:sauce_connect_4_executable]
@skip_connection_test = options[:skip_connection_test]
@quiet = options[:quiet]
@timeout = options.fetch(:timeout) { TIMEOUT }
unless options.fetch(:skip_sauce_config, false)
require 'sauce/config'
@config = Sauce::Config.new(options)
@username ||= @config.username
@access_key ||= @config.access_key
@cli_options ||= @config[:connect_options]
@sc4_executable ||= @config[:sauce_connect_4_executable]
@skip_connection_test = @config[:skip_connection_test]
end
end
|
ruby
|
def extract_config options
@username = options[:username]
@access_key = options[:access_key]
@cli_options = options[:connect_options]
@sc4_executable = options[:sauce_connect_4_executable]
@skip_connection_test = options[:skip_connection_test]
@quiet = options[:quiet]
@timeout = options.fetch(:timeout) { TIMEOUT }
unless options.fetch(:skip_sauce_config, false)
require 'sauce/config'
@config = Sauce::Config.new(options)
@username ||= @config.username
@access_key ||= @config.access_key
@cli_options ||= @config[:connect_options]
@sc4_executable ||= @config[:sauce_connect_4_executable]
@skip_connection_test = @config[:skip_connection_test]
end
end
|
[
"def",
"extract_config",
"options",
"@username",
"=",
"options",
"[",
":username",
"]",
"@access_key",
"=",
"options",
"[",
":access_key",
"]",
"@cli_options",
"=",
"options",
"[",
":connect_options",
"]",
"@sc4_executable",
"=",
"options",
"[",
":sauce_connect_4_executable",
"]",
"@skip_connection_test",
"=",
"options",
"[",
":skip_connection_test",
"]",
"@quiet",
"=",
"options",
"[",
":quiet",
"]",
"@timeout",
"=",
"options",
".",
"fetch",
"(",
":timeout",
")",
"{",
"TIMEOUT",
"}",
"unless",
"options",
".",
"fetch",
"(",
":skip_sauce_config",
",",
"false",
")",
"require",
"'sauce/config'",
"@config",
"=",
"Sauce",
"::",
"Config",
".",
"new",
"(",
"options",
")",
"@username",
"||=",
"@config",
".",
"username",
"@access_key",
"||=",
"@config",
".",
"access_key",
"@cli_options",
"||=",
"@config",
"[",
":connect_options",
"]",
"@sc4_executable",
"||=",
"@config",
"[",
":sauce_connect_4_executable",
"]",
"@skip_connection_test",
"=",
"@config",
"[",
":skip_connection_test",
"]",
"end",
"end"
] |
extract options from the options hash with highest priority over Sauce.config
but fall back on Sauce.config otherwise
|
[
"extract",
"options",
"from",
"the",
"options",
"hash",
"with",
"highest",
"priority",
"over",
"Sauce",
".",
"config",
"but",
"fall",
"back",
"on",
"Sauce",
".",
"config",
"otherwise"
] |
b1c4dab8516fb5e9c75ef16fb72b59b72c0ff0b0
|
https://github.com/saucelabs/sauce_ruby/blob/b1c4dab8516fb5e9c75ef16fb72b59b72c0ff0b0/gems/sauce-connect/lib/sauce/connect.rb#L27-L45
|
20,045
|
ulfurinn/wongi-engine
|
lib/wongi-engine/token.rb
|
Wongi::Engine.Token.generated?
|
def generated? wme
return true if generated_wmes.any? { |w| w == wme }
return children.any? { |t| t.generated? wme }
end
|
ruby
|
def generated? wme
return true if generated_wmes.any? { |w| w == wme }
return children.any? { |t| t.generated? wme }
end
|
[
"def",
"generated?",
"wme",
"return",
"true",
"if",
"generated_wmes",
".",
"any?",
"{",
"|",
"w",
"|",
"w",
"==",
"wme",
"}",
"return",
"children",
".",
"any?",
"{",
"|",
"t",
"|",
"t",
".",
"generated?",
"wme",
"}",
"end"
] |
for neg feedback loop protection
|
[
"for",
"neg",
"feedback",
"loop",
"protection"
] |
5251e6f41208568906cfd261a3513f883ac129e6
|
https://github.com/ulfurinn/wongi-engine/blob/5251e6f41208568906cfd261a3513f883ac129e6/lib/wongi-engine/token.rb#L92-L95
|
20,046
|
zenaton/zenaton-ruby
|
lib/zenaton/client.rb
|
Zenaton.Client.website_url
|
def website_url(resource = '', params = {})
api_url = ENV['ZENATON_API_URL'] || ZENATON_API_URL
url = "#{api_url}/#{resource}"
if params.is_a?(Hash)
params[API_TOKEN] = @api_token
append_params_to_url(url, params)
else
add_app_env("#{url}?#{API_TOKEN}=#{@api_token}&", params)
end
end
|
ruby
|
def website_url(resource = '', params = {})
api_url = ENV['ZENATON_API_URL'] || ZENATON_API_URL
url = "#{api_url}/#{resource}"
if params.is_a?(Hash)
params[API_TOKEN] = @api_token
append_params_to_url(url, params)
else
add_app_env("#{url}?#{API_TOKEN}=#{@api_token}&", params)
end
end
|
[
"def",
"website_url",
"(",
"resource",
"=",
"''",
",",
"params",
"=",
"{",
"}",
")",
"api_url",
"=",
"ENV",
"[",
"'ZENATON_API_URL'",
"]",
"||",
"ZENATON_API_URL",
"url",
"=",
"\"#{api_url}/#{resource}\"",
"if",
"params",
".",
"is_a?",
"(",
"Hash",
")",
"params",
"[",
"API_TOKEN",
"]",
"=",
"@api_token",
"append_params_to_url",
"(",
"url",
",",
"params",
")",
"else",
"add_app_env",
"(",
"\"#{url}?#{API_TOKEN}=#{@api_token}&\"",
",",
"params",
")",
"end",
"end"
] |
Gets the url for zenaton api
@param resource [String] the endpoint for the api
@param params [Hash|String] query params to be url encoded
@return [String] the api url with parameters
|
[
"Gets",
"the",
"url",
"for",
"zenaton",
"api"
] |
b80badb6919482e7cf78722c5c3cc94f2bb18fc6
|
https://github.com/zenaton/zenaton-ruby/blob/b80badb6919482e7cf78722c5c3cc94f2bb18fc6/lib/zenaton/client.rb#L85-L95
|
20,047
|
zenaton/zenaton-ruby
|
lib/zenaton/client.rb
|
Zenaton.Client.start_task
|
def start_task(task)
max_processing_time = if task.respond_to?(:max_processing_time)
task.max_processing_time
end
@http.post(
worker_url('tasks'),
ATTR_PROG => PROG,
ATTR_NAME => class_name(task),
ATTR_DATA => @serializer.encode(@properties.from(task)),
ATTR_MAX_PROCESSING_TIME => max_processing_time
)
end
|
ruby
|
def start_task(task)
max_processing_time = if task.respond_to?(:max_processing_time)
task.max_processing_time
end
@http.post(
worker_url('tasks'),
ATTR_PROG => PROG,
ATTR_NAME => class_name(task),
ATTR_DATA => @serializer.encode(@properties.from(task)),
ATTR_MAX_PROCESSING_TIME => max_processing_time
)
end
|
[
"def",
"start_task",
"(",
"task",
")",
"max_processing_time",
"=",
"if",
"task",
".",
"respond_to?",
"(",
":max_processing_time",
")",
"task",
".",
"max_processing_time",
"end",
"@http",
".",
"post",
"(",
"worker_url",
"(",
"'tasks'",
")",
",",
"ATTR_PROG",
"=>",
"PROG",
",",
"ATTR_NAME",
"=>",
"class_name",
"(",
"task",
")",
",",
"ATTR_DATA",
"=>",
"@serializer",
".",
"encode",
"(",
"@properties",
".",
"from",
"(",
"task",
")",
")",
",",
"ATTR_MAX_PROCESSING_TIME",
"=>",
"max_processing_time",
")",
"end"
] |
Start a single task
@param task [Zenaton::Interfaces::Task]
|
[
"Start",
"a",
"single",
"task"
] |
b80badb6919482e7cf78722c5c3cc94f2bb18fc6
|
https://github.com/zenaton/zenaton-ruby/blob/b80badb6919482e7cf78722c5c3cc94f2bb18fc6/lib/zenaton/client.rb#L99-L110
|
20,048
|
zenaton/zenaton-ruby
|
lib/zenaton/client.rb
|
Zenaton.Client.start_workflow
|
def start_workflow(flow)
@http.post(
instance_worker_url,
ATTR_PROG => PROG,
ATTR_CANONICAL => canonical_name(flow),
ATTR_NAME => class_name(flow),
ATTR_DATA => @serializer.encode(@properties.from(flow)),
ATTR_ID => parse_custom_id_from(flow)
)
end
|
ruby
|
def start_workflow(flow)
@http.post(
instance_worker_url,
ATTR_PROG => PROG,
ATTR_CANONICAL => canonical_name(flow),
ATTR_NAME => class_name(flow),
ATTR_DATA => @serializer.encode(@properties.from(flow)),
ATTR_ID => parse_custom_id_from(flow)
)
end
|
[
"def",
"start_workflow",
"(",
"flow",
")",
"@http",
".",
"post",
"(",
"instance_worker_url",
",",
"ATTR_PROG",
"=>",
"PROG",
",",
"ATTR_CANONICAL",
"=>",
"canonical_name",
"(",
"flow",
")",
",",
"ATTR_NAME",
"=>",
"class_name",
"(",
"flow",
")",
",",
"ATTR_DATA",
"=>",
"@serializer",
".",
"encode",
"(",
"@properties",
".",
"from",
"(",
"flow",
")",
")",
",",
"ATTR_ID",
"=>",
"parse_custom_id_from",
"(",
"flow",
")",
")",
"end"
] |
Start the specified workflow
@param flow [Zenaton::Interfaces::Workflow]
|
[
"Start",
"the",
"specified",
"workflow"
] |
b80badb6919482e7cf78722c5c3cc94f2bb18fc6
|
https://github.com/zenaton/zenaton-ruby/blob/b80badb6919482e7cf78722c5c3cc94f2bb18fc6/lib/zenaton/client.rb#L114-L123
|
20,049
|
zenaton/zenaton-ruby
|
lib/zenaton/client.rb
|
Zenaton.Client.find_workflow
|
def find_workflow(workflow_name, custom_id)
params = { ATTR_ID => custom_id, ATTR_NAME => workflow_name }
params[ATTR_PROG] = PROG
data = @http.get(instance_website_url(params))['data']
data && @properties.object_from(
data['name'],
@serializer.decode(data['properties'])
)
rescue Zenaton::InternalError => exception
return nil if exception.message =~ /No workflow instance found/
raise exception
end
|
ruby
|
def find_workflow(workflow_name, custom_id)
params = { ATTR_ID => custom_id, ATTR_NAME => workflow_name }
params[ATTR_PROG] = PROG
data = @http.get(instance_website_url(params))['data']
data && @properties.object_from(
data['name'],
@serializer.decode(data['properties'])
)
rescue Zenaton::InternalError => exception
return nil if exception.message =~ /No workflow instance found/
raise exception
end
|
[
"def",
"find_workflow",
"(",
"workflow_name",
",",
"custom_id",
")",
"params",
"=",
"{",
"ATTR_ID",
"=>",
"custom_id",
",",
"ATTR_NAME",
"=>",
"workflow_name",
"}",
"params",
"[",
"ATTR_PROG",
"]",
"=",
"PROG",
"data",
"=",
"@http",
".",
"get",
"(",
"instance_website_url",
"(",
"params",
")",
")",
"[",
"'data'",
"]",
"data",
"&&",
"@properties",
".",
"object_from",
"(",
"data",
"[",
"'name'",
"]",
",",
"@serializer",
".",
"decode",
"(",
"data",
"[",
"'properties'",
"]",
")",
")",
"rescue",
"Zenaton",
"::",
"InternalError",
"=>",
"exception",
"return",
"nil",
"if",
"exception",
".",
"message",
"=~",
"/",
"/",
"raise",
"exception",
"end"
] |
Finds a workflow
@param workflow_name [String] the class name of the workflow
@param custom_id [String] the custom ID of the workflow
@return [Zenaton::Interfaces::Workflow, nil]
|
[
"Finds",
"a",
"workflow"
] |
b80badb6919482e7cf78722c5c3cc94f2bb18fc6
|
https://github.com/zenaton/zenaton-ruby/blob/b80badb6919482e7cf78722c5c3cc94f2bb18fc6/lib/zenaton/client.rb#L153-L164
|
20,050
|
zenaton/zenaton-ruby
|
lib/zenaton/client.rb
|
Zenaton.Client.send_event
|
def send_event(workflow_name, custom_id, event)
body = {
ATTR_PROG => PROG,
ATTR_NAME => workflow_name,
ATTR_ID => custom_id,
EVENT_NAME => event.class.name,
EVENT_INPUT => @serializer.encode(@properties.from(event))
}
@http.post(send_event_url, body)
end
|
ruby
|
def send_event(workflow_name, custom_id, event)
body = {
ATTR_PROG => PROG,
ATTR_NAME => workflow_name,
ATTR_ID => custom_id,
EVENT_NAME => event.class.name,
EVENT_INPUT => @serializer.encode(@properties.from(event))
}
@http.post(send_event_url, body)
end
|
[
"def",
"send_event",
"(",
"workflow_name",
",",
"custom_id",
",",
"event",
")",
"body",
"=",
"{",
"ATTR_PROG",
"=>",
"PROG",
",",
"ATTR_NAME",
"=>",
"workflow_name",
",",
"ATTR_ID",
"=>",
"custom_id",
",",
"EVENT_NAME",
"=>",
"event",
".",
"class",
".",
"name",
",",
"EVENT_INPUT",
"=>",
"@serializer",
".",
"encode",
"(",
"@properties",
".",
"from",
"(",
"event",
")",
")",
"}",
"@http",
".",
"post",
"(",
"send_event_url",
",",
"body",
")",
"end"
] |
Sends an event to a workflow
@param workflow_name [String] the class name of the workflow
@param custom_id [String] the custom ID of the workflow (if any)
@param event [Zenaton::Interfaces::Event] the event to send
@return [NilClass]
|
[
"Sends",
"an",
"event",
"to",
"a",
"workflow"
] |
b80badb6919482e7cf78722c5c3cc94f2bb18fc6
|
https://github.com/zenaton/zenaton-ruby/blob/b80badb6919482e7cf78722c5c3cc94f2bb18fc6/lib/zenaton/client.rb#L171-L180
|
20,051
|
zenaton/zenaton-ruby
|
lib/zenaton/engine.rb
|
Zenaton.Engine.dispatch
|
def dispatch(jobs)
jobs.map(&method(:check_argument))
jobs.map(&method(:local_dispatch)) if process_locally?(jobs)
@processor&.process(jobs, false) unless jobs.length.zero?
nil
end
|
ruby
|
def dispatch(jobs)
jobs.map(&method(:check_argument))
jobs.map(&method(:local_dispatch)) if process_locally?(jobs)
@processor&.process(jobs, false) unless jobs.length.zero?
nil
end
|
[
"def",
"dispatch",
"(",
"jobs",
")",
"jobs",
".",
"map",
"(",
"method",
"(",
":check_argument",
")",
")",
"jobs",
".",
"map",
"(",
"method",
"(",
":local_dispatch",
")",
")",
"if",
"process_locally?",
"(",
"jobs",
")",
"@processor",
"&.",
"process",
"(",
"jobs",
",",
"false",
")",
"unless",
"jobs",
".",
"length",
".",
"zero?",
"nil",
"end"
] |
Executes jobs asynchronously
@param jobs [Array<Zenaton::Interfaces::Job>]
@return nil
|
[
"Executes",
"jobs",
"asynchronously"
] |
b80badb6919482e7cf78722c5c3cc94f2bb18fc6
|
https://github.com/zenaton/zenaton-ruby/blob/b80badb6919482e7cf78722c5c3cc94f2bb18fc6/lib/zenaton/engine.rb#L39-L44
|
20,052
|
PhilipCastiglione/clubhouse_ruby
|
lib/clubhouse_ruby/path_builder.rb
|
ClubhouseRuby.PathBuilder.method_missing
|
def method_missing(name, *args)
if known_action?(name)
execute_request(ACTIONS[name], args.first)
elsif known_resource?(name)
build_path(name, args.first)
elsif known_exception?(name)
build_path(EXCEPTIONS[name][:path], nil)
execute_request(EXCEPTIONS[name][:action], args.first)
else
super
end
end
|
ruby
|
def method_missing(name, *args)
if known_action?(name)
execute_request(ACTIONS[name], args.first)
elsif known_resource?(name)
build_path(name, args.first)
elsif known_exception?(name)
build_path(EXCEPTIONS[name][:path], nil)
execute_request(EXCEPTIONS[name][:action], args.first)
else
super
end
end
|
[
"def",
"method_missing",
"(",
"name",
",",
"*",
"args",
")",
"if",
"known_action?",
"(",
"name",
")",
"execute_request",
"(",
"ACTIONS",
"[",
"name",
"]",
",",
"args",
".",
"first",
")",
"elsif",
"known_resource?",
"(",
"name",
")",
"build_path",
"(",
"name",
",",
"args",
".",
"first",
")",
"elsif",
"known_exception?",
"(",
"name",
")",
"build_path",
"(",
"EXCEPTIONS",
"[",
"name",
"]",
"[",
":path",
"]",
",",
"nil",
")",
"execute_request",
"(",
"EXCEPTIONS",
"[",
"name",
"]",
"[",
":action",
"]",
",",
"args",
".",
"first",
")",
"else",
"super",
"end",
"end"
] |
Uh oh! This will allow the class including this module to "build a path"
by chaining calls to resources, terminated with a method linked to an
action that will execute the api call.
For example:
`foo.stories(story_id).comments.update(id: comment_id, text: "comment text")`
This example will execute a call to:
`https://api.clubhouse.io/api/v2/stories/{story-id}/comments/{comment-id}`
with arguments:
`{ text: "comment text" }`
|
[
"Uh",
"oh!",
"This",
"will",
"allow",
"the",
"class",
"including",
"this",
"module",
"to",
"build",
"a",
"path",
"by",
"chaining",
"calls",
"to",
"resources",
"terminated",
"with",
"a",
"method",
"linked",
"to",
"an",
"action",
"that",
"will",
"execute",
"the",
"api",
"call",
"."
] |
dd51319a436bb5486e746df1dff854a5ef15e7af
|
https://github.com/PhilipCastiglione/clubhouse_ruby/blob/dd51319a436bb5486e746df1dff854a5ef15e7af/lib/clubhouse_ruby/path_builder.rb#L25-L36
|
20,053
|
PhilipCastiglione/clubhouse_ruby
|
lib/clubhouse_ruby/path_builder.rb
|
ClubhouseRuby.PathBuilder.respond_to_missing?
|
def respond_to_missing?(name, include_private = false)
known_action?(name) ||
known_resource?(name) ||
known_exception?(name) ||
super
end
|
ruby
|
def respond_to_missing?(name, include_private = false)
known_action?(name) ||
known_resource?(name) ||
known_exception?(name) ||
super
end
|
[
"def",
"respond_to_missing?",
"(",
"name",
",",
"include_private",
"=",
"false",
")",
"known_action?",
"(",
"name",
")",
"||",
"known_resource?",
"(",
"name",
")",
"||",
"known_exception?",
"(",
"name",
")",
"||",
"super",
"end"
] |
We'd better not lie when asked.
|
[
"We",
"d",
"better",
"not",
"lie",
"when",
"asked",
"."
] |
dd51319a436bb5486e746df1dff854a5ef15e7af
|
https://github.com/PhilipCastiglione/clubhouse_ruby/blob/dd51319a436bb5486e746df1dff854a5ef15e7af/lib/clubhouse_ruby/path_builder.rb#L52-L57
|
20,054
|
PhilipCastiglione/clubhouse_ruby
|
lib/clubhouse_ruby/request.rb
|
ClubhouseRuby.Request.fetch
|
def fetch
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |https|
req = Net::HTTP.const_get(action).new(uri)
set_body(req)
set_format_header(req)
wrap_response(https.request(req))
end
end
|
ruby
|
def fetch
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |https|
req = Net::HTTP.const_get(action).new(uri)
set_body(req)
set_format_header(req)
wrap_response(https.request(req))
end
end
|
[
"def",
"fetch",
"Net",
"::",
"HTTP",
".",
"start",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
",",
"use_ssl",
":",
"true",
")",
"do",
"|",
"https",
"|",
"req",
"=",
"Net",
"::",
"HTTP",
".",
"const_get",
"(",
"action",
")",
".",
"new",
"(",
"uri",
")",
"set_body",
"(",
"req",
")",
"set_format_header",
"(",
"req",
")",
"wrap_response",
"(",
"https",
".",
"request",
"(",
"req",
")",
")",
"end",
"end"
] |
Prepares a fancy request object and ensures the inputs make as much sense
as possible. It's still totally possible to just provide a path that
doesn't match a real url though.
Executes the http(s) request and provides the response with some
additional decoration in a Hash.
|
[
"Prepares",
"a",
"fancy",
"request",
"object",
"and",
"ensures",
"the",
"inputs",
"make",
"as",
"much",
"sense",
"as",
"possible",
".",
"It",
"s",
"still",
"totally",
"possible",
"to",
"just",
"provide",
"a",
"path",
"that",
"doesn",
"t",
"match",
"a",
"real",
"url",
"though",
"."
] |
dd51319a436bb5486e746df1dff854a5ef15e7af
|
https://github.com/PhilipCastiglione/clubhouse_ruby/blob/dd51319a436bb5486e746df1dff854a5ef15e7af/lib/clubhouse_ruby/request.rb#L23-L32
|
20,055
|
elevation/event_calendar
|
lib/event_calendar/calendar_helper.rb
|
EventCalendar.CalendarHelper.day_link
|
def day_link(text, date, day_action)
link_to(text, params.merge(:action => day_action, :year => date.year, :month => date.month, :day => date.day), :class => 'ec-day-link')
end
|
ruby
|
def day_link(text, date, day_action)
link_to(text, params.merge(:action => day_action, :year => date.year, :month => date.month, :day => date.day), :class => 'ec-day-link')
end
|
[
"def",
"day_link",
"(",
"text",
",",
"date",
",",
"day_action",
")",
"link_to",
"(",
"text",
",",
"params",
".",
"merge",
"(",
":action",
"=>",
"day_action",
",",
":year",
"=>",
"date",
".",
"year",
",",
":month",
"=>",
"date",
".",
"month",
",",
":day",
"=>",
"date",
".",
"day",
")",
",",
":class",
"=>",
"'ec-day-link'",
")",
"end"
] |
override this in your own helper for greater control
|
[
"override",
"this",
"in",
"your",
"own",
"helper",
"for",
"greater",
"control"
] |
131d6dee147f4d515daa77d4acc7fa77f369bfcc
|
https://github.com/elevation/event_calendar/blob/131d6dee147f4d515daa77d4acc7fa77f369bfcc/lib/event_calendar/calendar_helper.rb#L292-L294
|
20,056
|
elevation/event_calendar
|
lib/event_calendar/calendar_helper.rb
|
EventCalendar.CalendarHelper.cal_row_heights
|
def cal_row_heights(options)
# number of rows is the number of days in the event strips divided by 7
num_cal_rows = options[:event_strips].first.size / 7
# the row will be at least this big
min_height = (options[:height] - options[:day_names_height]) / num_cal_rows
row_heights = []
num_event_rows = 0
# for every day in the event strip...
1.upto(options[:event_strips].first.size+1) do |index|
num_events = 0
# get the largest event strip that has an event on this day
options[:event_strips].each_with_index do |strip, strip_num|
num_events = strip_num + 1 unless strip[index-1].blank?
end
# get the most event rows for this week
num_event_rows = [num_event_rows, num_events].max
# if we reached the end of the week, calculate this row's height
if index % 7 == 0
total_event_height = options[:event_height] + options[:event_margin]
calc_row_height = (num_event_rows * total_event_height) + options[:day_nums_height] + options[:event_margin]
row_height = [min_height, calc_row_height].max
row_heights << row_height
num_event_rows = 0
end
end
row_heights
end
|
ruby
|
def cal_row_heights(options)
# number of rows is the number of days in the event strips divided by 7
num_cal_rows = options[:event_strips].first.size / 7
# the row will be at least this big
min_height = (options[:height] - options[:day_names_height]) / num_cal_rows
row_heights = []
num_event_rows = 0
# for every day in the event strip...
1.upto(options[:event_strips].first.size+1) do |index|
num_events = 0
# get the largest event strip that has an event on this day
options[:event_strips].each_with_index do |strip, strip_num|
num_events = strip_num + 1 unless strip[index-1].blank?
end
# get the most event rows for this week
num_event_rows = [num_event_rows, num_events].max
# if we reached the end of the week, calculate this row's height
if index % 7 == 0
total_event_height = options[:event_height] + options[:event_margin]
calc_row_height = (num_event_rows * total_event_height) + options[:day_nums_height] + options[:event_margin]
row_height = [min_height, calc_row_height].max
row_heights << row_height
num_event_rows = 0
end
end
row_heights
end
|
[
"def",
"cal_row_heights",
"(",
"options",
")",
"# number of rows is the number of days in the event strips divided by 7",
"num_cal_rows",
"=",
"options",
"[",
":event_strips",
"]",
".",
"first",
".",
"size",
"/",
"7",
"# the row will be at least this big",
"min_height",
"=",
"(",
"options",
"[",
":height",
"]",
"-",
"options",
"[",
":day_names_height",
"]",
")",
"/",
"num_cal_rows",
"row_heights",
"=",
"[",
"]",
"num_event_rows",
"=",
"0",
"# for every day in the event strip...",
"1",
".",
"upto",
"(",
"options",
"[",
":event_strips",
"]",
".",
"first",
".",
"size",
"+",
"1",
")",
"do",
"|",
"index",
"|",
"num_events",
"=",
"0",
"# get the largest event strip that has an event on this day",
"options",
"[",
":event_strips",
"]",
".",
"each_with_index",
"do",
"|",
"strip",
",",
"strip_num",
"|",
"num_events",
"=",
"strip_num",
"+",
"1",
"unless",
"strip",
"[",
"index",
"-",
"1",
"]",
".",
"blank?",
"end",
"# get the most event rows for this week",
"num_event_rows",
"=",
"[",
"num_event_rows",
",",
"num_events",
"]",
".",
"max",
"# if we reached the end of the week, calculate this row's height",
"if",
"index",
"%",
"7",
"==",
"0",
"total_event_height",
"=",
"options",
"[",
":event_height",
"]",
"+",
"options",
"[",
":event_margin",
"]",
"calc_row_height",
"=",
"(",
"num_event_rows",
"*",
"total_event_height",
")",
"+",
"options",
"[",
":day_nums_height",
"]",
"+",
"options",
"[",
":event_margin",
"]",
"row_height",
"=",
"[",
"min_height",
",",
"calc_row_height",
"]",
".",
"max",
"row_heights",
"<<",
"row_height",
"num_event_rows",
"=",
"0",
"end",
"end",
"row_heights",
"end"
] |
calculate the height of each row
by default, it will be the height option minus the day names height,
divided by the total number of calendar rows
this gets tricky, however, if there are too many event rows to fit into the row's height
then we need to add additional height
|
[
"calculate",
"the",
"height",
"of",
"each",
"row",
"by",
"default",
"it",
"will",
"be",
"the",
"height",
"option",
"minus",
"the",
"day",
"names",
"height",
"divided",
"by",
"the",
"total",
"number",
"of",
"calendar",
"rows",
"this",
"gets",
"tricky",
"however",
"if",
"there",
"are",
"too",
"many",
"event",
"rows",
"to",
"fit",
"into",
"the",
"row",
"s",
"height",
"then",
"we",
"need",
"to",
"add",
"additional",
"height"
] |
131d6dee147f4d515daa77d4acc7fa77f369bfcc
|
https://github.com/elevation/event_calendar/blob/131d6dee147f4d515daa77d4acc7fa77f369bfcc/lib/event_calendar/calendar_helper.rb#L325-L351
|
20,057
|
elevation/event_calendar
|
lib/event_calendar.rb
|
EventCalendar.ClassMethods.event_strips_for_month
|
def event_strips_for_month(shown_date, first_day_of_week=0, find_options = {})
if first_day_of_week.is_a?(Hash)
find_options.merge!(first_day_of_week)
first_day_of_week = 0
end
strip_start, strip_end = get_start_and_end_dates(shown_date, first_day_of_week)
events = events_for_date_range(strip_start, strip_end, find_options)
event_strips = create_event_strips(strip_start, strip_end, events)
event_strips
end
|
ruby
|
def event_strips_for_month(shown_date, first_day_of_week=0, find_options = {})
if first_day_of_week.is_a?(Hash)
find_options.merge!(first_day_of_week)
first_day_of_week = 0
end
strip_start, strip_end = get_start_and_end_dates(shown_date, first_day_of_week)
events = events_for_date_range(strip_start, strip_end, find_options)
event_strips = create_event_strips(strip_start, strip_end, events)
event_strips
end
|
[
"def",
"event_strips_for_month",
"(",
"shown_date",
",",
"first_day_of_week",
"=",
"0",
",",
"find_options",
"=",
"{",
"}",
")",
"if",
"first_day_of_week",
".",
"is_a?",
"(",
"Hash",
")",
"find_options",
".",
"merge!",
"(",
"first_day_of_week",
")",
"first_day_of_week",
"=",
"0",
"end",
"strip_start",
",",
"strip_end",
"=",
"get_start_and_end_dates",
"(",
"shown_date",
",",
"first_day_of_week",
")",
"events",
"=",
"events_for_date_range",
"(",
"strip_start",
",",
"strip_end",
",",
"find_options",
")",
"event_strips",
"=",
"create_event_strips",
"(",
"strip_start",
",",
"strip_end",
",",
"events",
")",
"event_strips",
"end"
] |
For the given month, find the start and end dates
Find all the events within this range, and create event strips for them
|
[
"For",
"the",
"given",
"month",
"find",
"the",
"start",
"and",
"end",
"dates",
"Find",
"all",
"the",
"events",
"within",
"this",
"range",
"and",
"create",
"event",
"strips",
"for",
"them"
] |
131d6dee147f4d515daa77d4acc7fa77f369bfcc
|
https://github.com/elevation/event_calendar/blob/131d6dee147f4d515daa77d4acc7fa77f369bfcc/lib/event_calendar.rb#L21-L30
|
20,058
|
elevation/event_calendar
|
lib/event_calendar.rb
|
EventCalendar.ClassMethods.get_start_and_end_dates
|
def get_start_and_end_dates(shown_date, first_day_of_week=0)
# start with the first day of the given month
start_of_month = Date.civil(shown_date.year, shown_date.month, 1)
# the end of last month
strip_start = beginning_of_week(start_of_month, first_day_of_week)
# the beginning of next month, unless this month ended evenly on the last day of the week
if start_of_month.next_month == beginning_of_week(start_of_month.next_month, first_day_of_week)
# last day of the month is also the last day of the week
strip_end = start_of_month.next_month
else
# add the extra days from next month
strip_end = beginning_of_week(start_of_month.next_month + 7, first_day_of_week)
end
[strip_start, strip_end]
end
|
ruby
|
def get_start_and_end_dates(shown_date, first_day_of_week=0)
# start with the first day of the given month
start_of_month = Date.civil(shown_date.year, shown_date.month, 1)
# the end of last month
strip_start = beginning_of_week(start_of_month, first_day_of_week)
# the beginning of next month, unless this month ended evenly on the last day of the week
if start_of_month.next_month == beginning_of_week(start_of_month.next_month, first_day_of_week)
# last day of the month is also the last day of the week
strip_end = start_of_month.next_month
else
# add the extra days from next month
strip_end = beginning_of_week(start_of_month.next_month + 7, first_day_of_week)
end
[strip_start, strip_end]
end
|
[
"def",
"get_start_and_end_dates",
"(",
"shown_date",
",",
"first_day_of_week",
"=",
"0",
")",
"# start with the first day of the given month",
"start_of_month",
"=",
"Date",
".",
"civil",
"(",
"shown_date",
".",
"year",
",",
"shown_date",
".",
"month",
",",
"1",
")",
"# the end of last month",
"strip_start",
"=",
"beginning_of_week",
"(",
"start_of_month",
",",
"first_day_of_week",
")",
"# the beginning of next month, unless this month ended evenly on the last day of the week",
"if",
"start_of_month",
".",
"next_month",
"==",
"beginning_of_week",
"(",
"start_of_month",
".",
"next_month",
",",
"first_day_of_week",
")",
"# last day of the month is also the last day of the week",
"strip_end",
"=",
"start_of_month",
".",
"next_month",
"else",
"# add the extra days from next month",
"strip_end",
"=",
"beginning_of_week",
"(",
"start_of_month",
".",
"next_month",
"+",
"7",
",",
"first_day_of_week",
")",
"end",
"[",
"strip_start",
",",
"strip_end",
"]",
"end"
] |
Expand start and end dates to show the previous month and next month's days,
that overlap with the shown months display
|
[
"Expand",
"start",
"and",
"end",
"dates",
"to",
"show",
"the",
"previous",
"month",
"and",
"next",
"month",
"s",
"days",
"that",
"overlap",
"with",
"the",
"shown",
"months",
"display"
] |
131d6dee147f4d515daa77d4acc7fa77f369bfcc
|
https://github.com/elevation/event_calendar/blob/131d6dee147f4d515daa77d4acc7fa77f369bfcc/lib/event_calendar.rb#L34-L48
|
20,059
|
elevation/event_calendar
|
lib/event_calendar.rb
|
EventCalendar.ClassMethods.events_for_date_range
|
def events_for_date_range(start_d, end_d, find_options = {})
self.scoped(find_options).find(
:all,
:conditions => [ "(? <= #{self.quoted_table_name}.#{self.end_at_field}) AND (#{self.quoted_table_name}.#{self.start_at_field}< ?)", start_d.to_time.utc, end_d.to_time.utc ],
:order => "#{self.quoted_table_name}.#{self.start_at_field} ASC"
)
end
|
ruby
|
def events_for_date_range(start_d, end_d, find_options = {})
self.scoped(find_options).find(
:all,
:conditions => [ "(? <= #{self.quoted_table_name}.#{self.end_at_field}) AND (#{self.quoted_table_name}.#{self.start_at_field}< ?)", start_d.to_time.utc, end_d.to_time.utc ],
:order => "#{self.quoted_table_name}.#{self.start_at_field} ASC"
)
end
|
[
"def",
"events_for_date_range",
"(",
"start_d",
",",
"end_d",
",",
"find_options",
"=",
"{",
"}",
")",
"self",
".",
"scoped",
"(",
"find_options",
")",
".",
"find",
"(",
":all",
",",
":conditions",
"=>",
"[",
"\"(? <= #{self.quoted_table_name}.#{self.end_at_field}) AND (#{self.quoted_table_name}.#{self.start_at_field}< ?)\"",
",",
"start_d",
".",
"to_time",
".",
"utc",
",",
"end_d",
".",
"to_time",
".",
"utc",
"]",
",",
":order",
"=>",
"\"#{self.quoted_table_name}.#{self.start_at_field} ASC\"",
")",
"end"
] |
Get the events overlapping the given start and end dates
|
[
"Get",
"the",
"events",
"overlapping",
"the",
"given",
"start",
"and",
"end",
"dates"
] |
131d6dee147f4d515daa77d4acc7fa77f369bfcc
|
https://github.com/elevation/event_calendar/blob/131d6dee147f4d515daa77d4acc7fa77f369bfcc/lib/event_calendar.rb#L51-L57
|
20,060
|
elevation/event_calendar
|
lib/event_calendar.rb
|
EventCalendar.ClassMethods.create_event_strips
|
def create_event_strips(strip_start, strip_end, events)
# create an inital event strip, with a nil entry for every day of the displayed days
event_strips = [[nil] * (strip_end - strip_start + 1)]
events.each do |event|
cur_date = event.start_at.to_date
end_date = event.end_at.to_date
cur_date, end_date = event.clip_range(strip_start, strip_end)
start_range = (cur_date - strip_start).to_i
end_range = (end_date - strip_start).to_i
# make sure the event is within our viewing range
if (start_range <= end_range) and (end_range >= 0)
range = start_range..end_range
open_strip = space_in_current_strips?(event_strips, range)
if open_strip.nil?
# no strips open, make a new one
new_strip = [nil] * (strip_end - strip_start + 1)
range.each {|r| new_strip[r] = event}
event_strips << new_strip
else
# found an open strip, add this event to it
range.each {|r| open_strip[r] = event}
end
end
end
event_strips
end
|
ruby
|
def create_event_strips(strip_start, strip_end, events)
# create an inital event strip, with a nil entry for every day of the displayed days
event_strips = [[nil] * (strip_end - strip_start + 1)]
events.each do |event|
cur_date = event.start_at.to_date
end_date = event.end_at.to_date
cur_date, end_date = event.clip_range(strip_start, strip_end)
start_range = (cur_date - strip_start).to_i
end_range = (end_date - strip_start).to_i
# make sure the event is within our viewing range
if (start_range <= end_range) and (end_range >= 0)
range = start_range..end_range
open_strip = space_in_current_strips?(event_strips, range)
if open_strip.nil?
# no strips open, make a new one
new_strip = [nil] * (strip_end - strip_start + 1)
range.each {|r| new_strip[r] = event}
event_strips << new_strip
else
# found an open strip, add this event to it
range.each {|r| open_strip[r] = event}
end
end
end
event_strips
end
|
[
"def",
"create_event_strips",
"(",
"strip_start",
",",
"strip_end",
",",
"events",
")",
"# create an inital event strip, with a nil entry for every day of the displayed days",
"event_strips",
"=",
"[",
"[",
"nil",
"]",
"*",
"(",
"strip_end",
"-",
"strip_start",
"+",
"1",
")",
"]",
"events",
".",
"each",
"do",
"|",
"event",
"|",
"cur_date",
"=",
"event",
".",
"start_at",
".",
"to_date",
"end_date",
"=",
"event",
".",
"end_at",
".",
"to_date",
"cur_date",
",",
"end_date",
"=",
"event",
".",
"clip_range",
"(",
"strip_start",
",",
"strip_end",
")",
"start_range",
"=",
"(",
"cur_date",
"-",
"strip_start",
")",
".",
"to_i",
"end_range",
"=",
"(",
"end_date",
"-",
"strip_start",
")",
".",
"to_i",
"# make sure the event is within our viewing range",
"if",
"(",
"start_range",
"<=",
"end_range",
")",
"and",
"(",
"end_range",
">=",
"0",
")",
"range",
"=",
"start_range",
"..",
"end_range",
"open_strip",
"=",
"space_in_current_strips?",
"(",
"event_strips",
",",
"range",
")",
"if",
"open_strip",
".",
"nil?",
"# no strips open, make a new one",
"new_strip",
"=",
"[",
"nil",
"]",
"*",
"(",
"strip_end",
"-",
"strip_start",
"+",
"1",
")",
"range",
".",
"each",
"{",
"|",
"r",
"|",
"new_strip",
"[",
"r",
"]",
"=",
"event",
"}",
"event_strips",
"<<",
"new_strip",
"else",
"# found an open strip, add this event to it",
"range",
".",
"each",
"{",
"|",
"r",
"|",
"open_strip",
"[",
"r",
"]",
"=",
"event",
"}",
"end",
"end",
"end",
"event_strips",
"end"
] |
Create the various strips that show events.
|
[
"Create",
"the",
"various",
"strips",
"that",
"show",
"events",
"."
] |
131d6dee147f4d515daa77d4acc7fa77f369bfcc
|
https://github.com/elevation/event_calendar/blob/131d6dee147f4d515daa77d4acc7fa77f369bfcc/lib/event_calendar.rb#L60-L89
|
20,061
|
elevation/event_calendar
|
lib/event_calendar.rb
|
EventCalendar.InstanceMethods.clip_range
|
def clip_range(start_d, end_d)
# make sure we are comparing date objects to date objects,
# otherwise timezones can cause problems
start_at_d = start_at.to_date
end_at_d = end_at.to_date
# Clip start date, make sure it also ends on or after the start range
if (start_at_d < start_d and end_at_d >= start_d)
clipped_start = start_d
else
clipped_start = start_at_d
end
# Clip end date
if (end_at_d > end_d)
clipped_end = end_d
else
clipped_end = end_at_d
end
[clipped_start, clipped_end]
end
|
ruby
|
def clip_range(start_d, end_d)
# make sure we are comparing date objects to date objects,
# otherwise timezones can cause problems
start_at_d = start_at.to_date
end_at_d = end_at.to_date
# Clip start date, make sure it also ends on or after the start range
if (start_at_d < start_d and end_at_d >= start_d)
clipped_start = start_d
else
clipped_start = start_at_d
end
# Clip end date
if (end_at_d > end_d)
clipped_end = end_d
else
clipped_end = end_at_d
end
[clipped_start, clipped_end]
end
|
[
"def",
"clip_range",
"(",
"start_d",
",",
"end_d",
")",
"# make sure we are comparing date objects to date objects,",
"# otherwise timezones can cause problems",
"start_at_d",
"=",
"start_at",
".",
"to_date",
"end_at_d",
"=",
"end_at",
".",
"to_date",
"# Clip start date, make sure it also ends on or after the start range",
"if",
"(",
"start_at_d",
"<",
"start_d",
"and",
"end_at_d",
">=",
"start_d",
")",
"clipped_start",
"=",
"start_d",
"else",
"clipped_start",
"=",
"start_at_d",
"end",
"# Clip end date",
"if",
"(",
"end_at_d",
">",
"end_d",
")",
"clipped_end",
"=",
"end_d",
"else",
"clipped_end",
"=",
"end_at_d",
"end",
"[",
"clipped_start",
",",
"clipped_end",
"]",
"end"
] |
start_d - start of the month, or start of the week
end_d - end of the month, or end of the week
|
[
"start_d",
"-",
"start",
"of",
"the",
"month",
"or",
"start",
"of",
"the",
"week",
"end_d",
"-",
"end",
"of",
"the",
"month",
"or",
"end",
"of",
"the",
"week"
] |
131d6dee147f4d515daa77d4acc7fa77f369bfcc
|
https://github.com/elevation/event_calendar/blob/131d6dee147f4d515daa77d4acc7fa77f369bfcc/lib/event_calendar.rb#L155-L174
|
20,062
|
langalex/couch_potato
|
lib/couch_potato/database.rb
|
CouchPotato.Database.view
|
def view(spec)
results = CouchPotato::View::ViewQuery.new(
couchrest_database,
spec.design_document,
{spec.view_name => {
:map => spec.map_function,
:reduce => spec.reduce_function
}
},
({spec.list_name => spec.list_function} unless spec.list_name.nil?),
spec.lib,
spec.language
).query_view!(spec.view_parameters)
processed_results = spec.process_results results
processed_results.each do |document|
document.database = self if document.respond_to?(:database=)
end if processed_results.respond_to?(:each)
processed_results
end
|
ruby
|
def view(spec)
results = CouchPotato::View::ViewQuery.new(
couchrest_database,
spec.design_document,
{spec.view_name => {
:map => spec.map_function,
:reduce => spec.reduce_function
}
},
({spec.list_name => spec.list_function} unless spec.list_name.nil?),
spec.lib,
spec.language
).query_view!(spec.view_parameters)
processed_results = spec.process_results results
processed_results.each do |document|
document.database = self if document.respond_to?(:database=)
end if processed_results.respond_to?(:each)
processed_results
end
|
[
"def",
"view",
"(",
"spec",
")",
"results",
"=",
"CouchPotato",
"::",
"View",
"::",
"ViewQuery",
".",
"new",
"(",
"couchrest_database",
",",
"spec",
".",
"design_document",
",",
"{",
"spec",
".",
"view_name",
"=>",
"{",
":map",
"=>",
"spec",
".",
"map_function",
",",
":reduce",
"=>",
"spec",
".",
"reduce_function",
"}",
"}",
",",
"(",
"{",
"spec",
".",
"list_name",
"=>",
"spec",
".",
"list_function",
"}",
"unless",
"spec",
".",
"list_name",
".",
"nil?",
")",
",",
"spec",
".",
"lib",
",",
"spec",
".",
"language",
")",
".",
"query_view!",
"(",
"spec",
".",
"view_parameters",
")",
"processed_results",
"=",
"spec",
".",
"process_results",
"results",
"processed_results",
".",
"each",
"do",
"|",
"document",
"|",
"document",
".",
"database",
"=",
"self",
"if",
"document",
".",
"respond_to?",
"(",
":database=",
")",
"end",
"if",
"processed_results",
".",
"respond_to?",
"(",
":each",
")",
"processed_results",
"end"
] |
executes a view and return the results. you pass in a view spec
which is usually a result of a SomePersistentClass.some_view call.
Example:
class User
include CouchPotato::Persistence
property :age
view :all, key: :age
end
db = CouchPotato.database
db.view(User.all) # => [user1, user2]
You can pass the usual parameters you can pass to a couchdb view to the view:
db.view(User.all(limit: 5, startkey: 2, reduce: false))
For your convenience when passing a hash with only a key parameter you can just pass in the value
db.view(User.all(key: 1)) == db.view(User.all(1))
Instead of passing a startkey and endkey you can pass in a key with a range:
db.view(User.all(key: 1..20)) == db.view(startkey: 1, endkey: 20) == db.view(User.all(1..20))
You can also pass in multiple keys:
db.view(User.all(keys: [1, 2, 3]))
|
[
"executes",
"a",
"view",
"and",
"return",
"the",
"results",
".",
"you",
"pass",
"in",
"a",
"view",
"spec",
"which",
"is",
"usually",
"a",
"result",
"of",
"a",
"SomePersistentClass",
".",
"some_view",
"call",
"."
] |
cd1de222029ac88be7fd9263625d489cb7f715a7
|
https://github.com/langalex/couch_potato/blob/cd1de222029ac88be7fd9263625d489cb7f715a7/lib/couch_potato/database.rb#L39-L57
|
20,063
|
viseztrance/rails-sitemap
|
lib/sitemap/generator.rb
|
Sitemap.Generator.load
|
def load(options = {}, &block)
options.each do |k, v|
self.send("#{k}=", v)
end
self.routes = block
end
|
ruby
|
def load(options = {}, &block)
options.each do |k, v|
self.send("#{k}=", v)
end
self.routes = block
end
|
[
"def",
"load",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"options",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"self",
".",
"send",
"(",
"\"#{k}=\"",
",",
"v",
")",
"end",
"self",
".",
"routes",
"=",
"block",
"end"
] |
Instantiates a new object.
Should never be called directly.
Sets the urls to be indexed.
The +host+, or any other global option can be set here:
Sitemap::Generator.instance.load :host => "mywebsite.com" do
...
end
Literal paths can be added as follows:
Sitemap::Generator.instance.load :host => "mywebsite.com" do
literal "/some_fancy_url"
end
Simple paths can be added as follows:
Sitemap::Generator.instance.load :host => "mywebsite.com" do
path :faq
end
Object collections are supported too:
Sitemap::Generator.instance.load :host => "mywebsite.com" do
resources :activities
end
Search options such as frequency and priority can be declared as an options hash:
Sitemap::Generator.instance.load :host => "mywebsite.com" do
path :root, :priority => 1
path :faq, :priority => 0.8, :change_frequency => "daily"
resources :activities, :change_frequency => "weekly"
end
|
[
"Instantiates",
"a",
"new",
"object",
".",
"Should",
"never",
"be",
"called",
"directly",
".",
"Sets",
"the",
"urls",
"to",
"be",
"indexed",
"."
] |
3c99256d131a753079a78fb9deac1f7703ebe4d9
|
https://github.com/viseztrance/rails-sitemap/blob/3c99256d131a753079a78fb9deac1f7703ebe4d9/lib/sitemap/generator.rb#L61-L66
|
20,064
|
viseztrance/rails-sitemap
|
lib/sitemap/generator.rb
|
Sitemap.Generator.resources
|
def resources(type, options = {})
path(type) unless options[:skip_index]
link_params = options.reject { |k, v| k == :objects }
get_objects = lambda {
options[:objects] ? options[:objects].call : type.to_s.classify.constantize
}
get_objects.call.find_each(:batch_size => Sitemap.configuration.query_batch_size) do |object|
path(object, link_params)
end
end
|
ruby
|
def resources(type, options = {})
path(type) unless options[:skip_index]
link_params = options.reject { |k, v| k == :objects }
get_objects = lambda {
options[:objects] ? options[:objects].call : type.to_s.classify.constantize
}
get_objects.call.find_each(:batch_size => Sitemap.configuration.query_batch_size) do |object|
path(object, link_params)
end
end
|
[
"def",
"resources",
"(",
"type",
",",
"options",
"=",
"{",
"}",
")",
"path",
"(",
"type",
")",
"unless",
"options",
"[",
":skip_index",
"]",
"link_params",
"=",
"options",
".",
"reject",
"{",
"|",
"k",
",",
"v",
"|",
"k",
"==",
":objects",
"}",
"get_objects",
"=",
"lambda",
"{",
"options",
"[",
":objects",
"]",
"?",
"options",
"[",
":objects",
"]",
".",
"call",
":",
"type",
".",
"to_s",
".",
"classify",
".",
"constantize",
"}",
"get_objects",
".",
"call",
".",
"find_each",
"(",
":batch_size",
"=>",
"Sitemap",
".",
"configuration",
".",
"query_batch_size",
")",
"do",
"|",
"object",
"|",
"path",
"(",
"object",
",",
"link_params",
")",
"end",
"end"
] |
Adds the associated object types.
The following will map all Activity entries, as well as the index (<tt>/activities</tt>) page:
resources :activities
You can also specify which entries are being mapped:
resources :articles, :objects => proc { Article.published }
To skip the index action and map only the records:
resources :articles, :skip_index => true
As with the path, you can specify params through the +params+ options hash.
The params can also be build conditionally by using a +proc+:
resources :activities, :params => { :host => proc { |activity| [activity.location, host].join(".") } }, :skip_index => true
In this case the host will change based the each of the objects associated +location+ attribute.
Because the index page doesn't have this attribute it's best to skip it.
|
[
"Adds",
"the",
"associated",
"object",
"types",
"."
] |
3c99256d131a753079a78fb9deac1f7703ebe4d9
|
https://github.com/viseztrance/rails-sitemap/blob/3c99256d131a753079a78fb9deac1f7703ebe4d9/lib/sitemap/generator.rb#L137-L146
|
20,065
|
viseztrance/rails-sitemap
|
lib/sitemap/generator.rb
|
Sitemap.Generator.render
|
def render(object = "fragment")
xml = Builder::XmlMarkup.new(:indent => 2)
file = File.read(File.expand_path("../../views/#{object}.xml.builder", __FILE__))
instance_eval file
end
|
ruby
|
def render(object = "fragment")
xml = Builder::XmlMarkup.new(:indent => 2)
file = File.read(File.expand_path("../../views/#{object}.xml.builder", __FILE__))
instance_eval file
end
|
[
"def",
"render",
"(",
"object",
"=",
"\"fragment\"",
")",
"xml",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"(",
":indent",
"=>",
"2",
")",
"file",
"=",
"File",
".",
"read",
"(",
"File",
".",
"expand_path",
"(",
"\"../../views/#{object}.xml.builder\"",
",",
"__FILE__",
")",
")",
"instance_eval",
"file",
"end"
] |
Parses the loaded data and returns the xml entries.
|
[
"Parses",
"the",
"loaded",
"data",
"and",
"returns",
"the",
"xml",
"entries",
"."
] |
3c99256d131a753079a78fb9deac1f7703ebe4d9
|
https://github.com/viseztrance/rails-sitemap/blob/3c99256d131a753079a78fb9deac1f7703ebe4d9/lib/sitemap/generator.rb#L149-L153
|
20,066
|
viseztrance/rails-sitemap
|
lib/sitemap/generator.rb
|
Sitemap.Generator.process_fragment!
|
def process_fragment!
file = Tempfile.new("sitemap.xml")
file.write(render)
file.close
self.fragments << file
end
|
ruby
|
def process_fragment!
file = Tempfile.new("sitemap.xml")
file.write(render)
file.close
self.fragments << file
end
|
[
"def",
"process_fragment!",
"file",
"=",
"Tempfile",
".",
"new",
"(",
"\"sitemap.xml\"",
")",
"file",
".",
"write",
"(",
"render",
")",
"file",
".",
"close",
"self",
".",
"fragments",
"<<",
"file",
"end"
] |
Creates a temporary file from the existing entries.
|
[
"Creates",
"a",
"temporary",
"file",
"from",
"the",
"existing",
"entries",
"."
] |
3c99256d131a753079a78fb9deac1f7703ebe4d9
|
https://github.com/viseztrance/rails-sitemap/blob/3c99256d131a753079a78fb9deac1f7703ebe4d9/lib/sitemap/generator.rb#L156-L161
|
20,067
|
viseztrance/rails-sitemap
|
lib/sitemap/generator.rb
|
Sitemap.Generator.file_url
|
def file_url(path = "sitemap.xml")
if context
file_path = File.join("/", context, path)
else
file_path = File.join("/", path)
end
URI::HTTP.build(:host => host, :path => file_path).to_s
end
|
ruby
|
def file_url(path = "sitemap.xml")
if context
file_path = File.join("/", context, path)
else
file_path = File.join("/", path)
end
URI::HTTP.build(:host => host, :path => file_path).to_s
end
|
[
"def",
"file_url",
"(",
"path",
"=",
"\"sitemap.xml\"",
")",
"if",
"context",
"file_path",
"=",
"File",
".",
"join",
"(",
"\"/\"",
",",
"context",
",",
"path",
")",
"else",
"file_path",
"=",
"File",
".",
"join",
"(",
"\"/\"",
",",
"path",
")",
"end",
"URI",
"::",
"HTTP",
".",
"build",
"(",
":host",
"=>",
"host",
",",
":path",
"=>",
"file_path",
")",
".",
"to_s",
"end"
] |
URL to the sitemap file.
Defaults to <tt>sitemap.xml</tt>.
|
[
"URL",
"to",
"the",
"sitemap",
"file",
"."
] |
3c99256d131a753079a78fb9deac1f7703ebe4d9
|
https://github.com/viseztrance/rails-sitemap/blob/3c99256d131a753079a78fb9deac1f7703ebe4d9/lib/sitemap/generator.rb#L192-L200
|
20,068
|
mojolingo/sippy_cup
|
lib/sippy_cup/scenario.rb
|
SippyCup.Scenario.build
|
def build(steps)
raise ArgumentError, "Must provide scenario steps" unless steps
steps.each_with_index do |step, index|
begin
instruction, args = step.split ' ', 2
args = split_quoted_string args
if args && !args.empty?
self.__send__ instruction, *args
else
self.__send__ instruction
end
rescue => e
@errors << {step: index + 1, message: "#{step}: #{e.message}"}
end
end
end
|
ruby
|
def build(steps)
raise ArgumentError, "Must provide scenario steps" unless steps
steps.each_with_index do |step, index|
begin
instruction, args = step.split ' ', 2
args = split_quoted_string args
if args && !args.empty?
self.__send__ instruction, *args
else
self.__send__ instruction
end
rescue => e
@errors << {step: index + 1, message: "#{step}: #{e.message}"}
end
end
end
|
[
"def",
"build",
"(",
"steps",
")",
"raise",
"ArgumentError",
",",
"\"Must provide scenario steps\"",
"unless",
"steps",
"steps",
".",
"each_with_index",
"do",
"|",
"step",
",",
"index",
"|",
"begin",
"instruction",
",",
"args",
"=",
"step",
".",
"split",
"' '",
",",
"2",
"args",
"=",
"split_quoted_string",
"args",
"if",
"args",
"&&",
"!",
"args",
".",
"empty?",
"self",
".",
"__send__",
"instruction",
",",
"args",
"else",
"self",
".",
"__send__",
"instruction",
"end",
"rescue",
"=>",
"e",
"@errors",
"<<",
"{",
"step",
":",
"index",
"+",
"1",
",",
"message",
":",
"\"#{step}: #{e.message}\"",
"}",
"end",
"end",
"end"
] |
Build the scenario steps provided
@param [Array<String>] steps A collection of steps to build the scenario
|
[
"Build",
"the",
"scenario",
"steps",
"provided"
] |
f778cdf429dc9a95884d05669dd1ed04b07134e4
|
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/scenario.rb#L131-L146
|
20,069
|
mojolingo/sippy_cup
|
lib/sippy_cup/scenario.rb
|
SippyCup.Scenario.register
|
def register(user, password = nil, opts = {})
send_opts = opts.dup
send_opts[:retrans] ||= DEFAULT_RETRANS
user, domain = parse_user user
if password
send register_message(domain, user), send_opts
recv opts.merge(response: 401, auth: true, optional: false)
send register_auth(domain, user, password), send_opts
receive_ok opts.merge(optional: false)
else
send register_message(domain, user), send_opts
end
end
|
ruby
|
def register(user, password = nil, opts = {})
send_opts = opts.dup
send_opts[:retrans] ||= DEFAULT_RETRANS
user, domain = parse_user user
if password
send register_message(domain, user), send_opts
recv opts.merge(response: 401, auth: true, optional: false)
send register_auth(domain, user, password), send_opts
receive_ok opts.merge(optional: false)
else
send register_message(domain, user), send_opts
end
end
|
[
"def",
"register",
"(",
"user",
",",
"password",
"=",
"nil",
",",
"opts",
"=",
"{",
"}",
")",
"send_opts",
"=",
"opts",
".",
"dup",
"send_opts",
"[",
":retrans",
"]",
"||=",
"DEFAULT_RETRANS",
"user",
",",
"domain",
"=",
"parse_user",
"user",
"if",
"password",
"send",
"register_message",
"(",
"domain",
",",
"user",
")",
",",
"send_opts",
"recv",
"opts",
".",
"merge",
"(",
"response",
":",
"401",
",",
"auth",
":",
"true",
",",
"optional",
":",
"false",
")",
"send",
"register_auth",
"(",
"domain",
",",
"user",
",",
"password",
")",
",",
"send_opts",
"receive_ok",
"opts",
".",
"merge",
"(",
"optional",
":",
"false",
")",
"else",
"send",
"register_message",
"(",
"domain",
",",
"user",
")",
",",
"send_opts",
"end",
"end"
] |
Send a REGISTER message with the specified credentials
@param [String] user the user to register as. May be given as a full SIP URI (sip:user@domain.com), in email-address format (user@domain.com) or as a simple username ('user'). If no domain is supplied, the source IP from SIPp will be used.
@param [optional, String, nil] password the password to authenticate with.
@param [Hash] opts A set of options to modify the message
@example Register with authentication
s.register 'frank@there.com', 'abc123'
@example Register without authentication or a domain
s.register 'frank'
|
[
"Send",
"a",
"REGISTER",
"message",
"with",
"the",
"specified",
"credentials"
] |
f778cdf429dc9a95884d05669dd1ed04b07134e4
|
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/scenario.rb#L217-L229
|
20,070
|
mojolingo/sippy_cup
|
lib/sippy_cup/scenario.rb
|
SippyCup.Scenario.receive_invite
|
def receive_invite(opts = {})
recv(opts.merge(request: 'INVITE', rrs: true)) do |recv|
action = doc.create_element('action') do |action|
action << doc.create_element('ereg') do |ereg|
ereg['regexp'] = '<sip:(.*)>.*;tag=([^;]*)'
ereg['search_in'] = 'hdr'
ereg['header'] = 'From:'
ereg['assign_to'] = 'dummy,remote_addr,remote_tag'
end
action << doc.create_element('ereg') do |ereg|
ereg['regexp'] = '<sip:(.*)>'
ereg['search_in'] = 'hdr'
ereg['header'] = 'To:'
ereg['assign_to'] = 'dummy,local_addr'
end
action << doc.create_element('assignstr') do |assignstr|
assignstr['assign_to'] = "call_addr"
assignstr['value'] = "[$local_addr]"
end
end
recv << action
end
# These variables (except dummy) will only be used if we initiate a hangup
@reference_variables += %w(dummy remote_addr remote_tag local_addr call_addr)
end
|
ruby
|
def receive_invite(opts = {})
recv(opts.merge(request: 'INVITE', rrs: true)) do |recv|
action = doc.create_element('action') do |action|
action << doc.create_element('ereg') do |ereg|
ereg['regexp'] = '<sip:(.*)>.*;tag=([^;]*)'
ereg['search_in'] = 'hdr'
ereg['header'] = 'From:'
ereg['assign_to'] = 'dummy,remote_addr,remote_tag'
end
action << doc.create_element('ereg') do |ereg|
ereg['regexp'] = '<sip:(.*)>'
ereg['search_in'] = 'hdr'
ereg['header'] = 'To:'
ereg['assign_to'] = 'dummy,local_addr'
end
action << doc.create_element('assignstr') do |assignstr|
assignstr['assign_to'] = "call_addr"
assignstr['value'] = "[$local_addr]"
end
end
recv << action
end
# These variables (except dummy) will only be used if we initiate a hangup
@reference_variables += %w(dummy remote_addr remote_tag local_addr call_addr)
end
|
[
"def",
"receive_invite",
"(",
"opts",
"=",
"{",
"}",
")",
"recv",
"(",
"opts",
".",
"merge",
"(",
"request",
":",
"'INVITE'",
",",
"rrs",
":",
"true",
")",
")",
"do",
"|",
"recv",
"|",
"action",
"=",
"doc",
".",
"create_element",
"(",
"'action'",
")",
"do",
"|",
"action",
"|",
"action",
"<<",
"doc",
".",
"create_element",
"(",
"'ereg'",
")",
"do",
"|",
"ereg",
"|",
"ereg",
"[",
"'regexp'",
"]",
"=",
"'<sip:(.*)>.*;tag=([^;]*)'",
"ereg",
"[",
"'search_in'",
"]",
"=",
"'hdr'",
"ereg",
"[",
"'header'",
"]",
"=",
"'From:'",
"ereg",
"[",
"'assign_to'",
"]",
"=",
"'dummy,remote_addr,remote_tag'",
"end",
"action",
"<<",
"doc",
".",
"create_element",
"(",
"'ereg'",
")",
"do",
"|",
"ereg",
"|",
"ereg",
"[",
"'regexp'",
"]",
"=",
"'<sip:(.*)>'",
"ereg",
"[",
"'search_in'",
"]",
"=",
"'hdr'",
"ereg",
"[",
"'header'",
"]",
"=",
"'To:'",
"ereg",
"[",
"'assign_to'",
"]",
"=",
"'dummy,local_addr'",
"end",
"action",
"<<",
"doc",
".",
"create_element",
"(",
"'assignstr'",
")",
"do",
"|",
"assignstr",
"|",
"assignstr",
"[",
"'assign_to'",
"]",
"=",
"\"call_addr\"",
"assignstr",
"[",
"'value'",
"]",
"=",
"\"[$local_addr]\"",
"end",
"end",
"recv",
"<<",
"action",
"end",
"# These variables (except dummy) will only be used if we initiate a hangup",
"@reference_variables",
"+=",
"%w(",
"dummy",
"remote_addr",
"remote_tag",
"local_addr",
"call_addr",
")",
"end"
] |
Expect to receive a SIP INVITE
@param [Hash] opts A set of options containing SIPp <recv> element attributes
|
[
"Expect",
"to",
"receive",
"a",
"SIP",
"INVITE"
] |
f778cdf429dc9a95884d05669dd1ed04b07134e4
|
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/scenario.rb#L236-L260
|
20,071
|
mojolingo/sippy_cup
|
lib/sippy_cup/scenario.rb
|
SippyCup.Scenario.receive_answer
|
def receive_answer(opts = {})
options = {
rrs: true, # Record Record Set: Make the Route headers available via [routes] later
rtd: true # Response Time Duration: Record the response time
}
receive_200(options.merge(opts)) do |recv|
recv << doc.create_element('action') do |action|
action << doc.create_element('ereg') do |ereg|
ereg['regexp'] = '<sip:(.*)>.*;tag=([^;]*)'
ereg['search_in'] = 'hdr'
ereg['header'] = 'To:'
ereg['assign_to'] = 'dummy,remote_addr,remote_tag'
end
end
end
# These variables will only be used if we initiate a hangup
@reference_variables += %w(dummy remote_addr remote_tag)
end
|
ruby
|
def receive_answer(opts = {})
options = {
rrs: true, # Record Record Set: Make the Route headers available via [routes] later
rtd: true # Response Time Duration: Record the response time
}
receive_200(options.merge(opts)) do |recv|
recv << doc.create_element('action') do |action|
action << doc.create_element('ereg') do |ereg|
ereg['regexp'] = '<sip:(.*)>.*;tag=([^;]*)'
ereg['search_in'] = 'hdr'
ereg['header'] = 'To:'
ereg['assign_to'] = 'dummy,remote_addr,remote_tag'
end
end
end
# These variables will only be used if we initiate a hangup
@reference_variables += %w(dummy remote_addr remote_tag)
end
|
[
"def",
"receive_answer",
"(",
"opts",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"rrs",
":",
"true",
",",
"# Record Record Set: Make the Route headers available via [routes] later",
"rtd",
":",
"true",
"# Response Time Duration: Record the response time",
"}",
"receive_200",
"(",
"options",
".",
"merge",
"(",
"opts",
")",
")",
"do",
"|",
"recv",
"|",
"recv",
"<<",
"doc",
".",
"create_element",
"(",
"'action'",
")",
"do",
"|",
"action",
"|",
"action",
"<<",
"doc",
".",
"create_element",
"(",
"'ereg'",
")",
"do",
"|",
"ereg",
"|",
"ereg",
"[",
"'regexp'",
"]",
"=",
"'<sip:(.*)>.*;tag=([^;]*)'",
"ereg",
"[",
"'search_in'",
"]",
"=",
"'hdr'",
"ereg",
"[",
"'header'",
"]",
"=",
"'To:'",
"ereg",
"[",
"'assign_to'",
"]",
"=",
"'dummy,remote_addr,remote_tag'",
"end",
"end",
"end",
"# These variables will only be used if we initiate a hangup",
"@reference_variables",
"+=",
"%w(",
"dummy",
"remote_addr",
"remote_tag",
")",
"end"
] |
Sets an expectation for a SIP 200 message from the remote party
as well as storing the record set and the response time duration
@param [Hash] opts A set of options to modify the expectation
@option opts [true, false] :optional Whether or not receipt of the message is optional. Defaults to false.
|
[
"Sets",
"an",
"expectation",
"for",
"a",
"SIP",
"200",
"message",
"from",
"the",
"remote",
"party",
"as",
"well",
"as",
"storing",
"the",
"record",
"set",
"and",
"the",
"response",
"time",
"duration"
] |
f778cdf429dc9a95884d05669dd1ed04b07134e4
|
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/scenario.rb#L394-L412
|
20,072
|
mojolingo/sippy_cup
|
lib/sippy_cup/scenario.rb
|
SippyCup.Scenario.wait_for_answer
|
def wait_for_answer(opts = {})
receive_trying opts
receive_ringing opts
receive_progress opts
receive_answer opts
ack_answer opts
end
|
ruby
|
def wait_for_answer(opts = {})
receive_trying opts
receive_ringing opts
receive_progress opts
receive_answer opts
ack_answer opts
end
|
[
"def",
"wait_for_answer",
"(",
"opts",
"=",
"{",
"}",
")",
"receive_trying",
"opts",
"receive_ringing",
"opts",
"receive_progress",
"opts",
"receive_answer",
"opts",
"ack_answer",
"opts",
"end"
] |
Convenience method to wait for an answer from the called party
This sets expectations for optional SIP 100, 180 and 183,
followed by a required 200 and sending the acknowledgement.
@param [Hash] opts A set of options to modify the expectations
|
[
"Convenience",
"method",
"to",
"wait",
"for",
"an",
"answer",
"from",
"the",
"called",
"party"
] |
f778cdf429dc9a95884d05669dd1ed04b07134e4
|
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/scenario.rb#L433-L439
|
20,073
|
mojolingo/sippy_cup
|
lib/sippy_cup/scenario.rb
|
SippyCup.Scenario.receive_message
|
def receive_message(regexp = nil)
recv = Nokogiri::XML::Node.new 'recv', doc
recv['request'] = 'MESSAGE'
scenario_node << recv
if regexp
action = Nokogiri::XML::Node.new 'action', doc
ereg = Nokogiri::XML::Node.new 'ereg', doc
ereg['regexp'] = regexp
ereg['search_in'] = 'body'
ereg['check_it'] = true
var = "message_#{@message_variables += 1}"
ereg['assign_to'] = var
@reference_variables << var
action << ereg
recv << action
end
okay
end
|
ruby
|
def receive_message(regexp = nil)
recv = Nokogiri::XML::Node.new 'recv', doc
recv['request'] = 'MESSAGE'
scenario_node << recv
if regexp
action = Nokogiri::XML::Node.new 'action', doc
ereg = Nokogiri::XML::Node.new 'ereg', doc
ereg['regexp'] = regexp
ereg['search_in'] = 'body'
ereg['check_it'] = true
var = "message_#{@message_variables += 1}"
ereg['assign_to'] = var
@reference_variables << var
action << ereg
recv << action
end
okay
end
|
[
"def",
"receive_message",
"(",
"regexp",
"=",
"nil",
")",
"recv",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Node",
".",
"new",
"'recv'",
",",
"doc",
"recv",
"[",
"'request'",
"]",
"=",
"'MESSAGE'",
"scenario_node",
"<<",
"recv",
"if",
"regexp",
"action",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Node",
".",
"new",
"'action'",
",",
"doc",
"ereg",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Node",
".",
"new",
"'ereg'",
",",
"doc",
"ereg",
"[",
"'regexp'",
"]",
"=",
"regexp",
"ereg",
"[",
"'search_in'",
"]",
"=",
"'body'",
"ereg",
"[",
"'check_it'",
"]",
"=",
"true",
"var",
"=",
"\"message_#{@message_variables += 1}\"",
"ereg",
"[",
"'assign_to'",
"]",
"=",
"var",
"@reference_variables",
"<<",
"var",
"action",
"<<",
"ereg",
"recv",
"<<",
"action",
"end",
"okay",
"end"
] |
Expect to receive a MESSAGE message
@param [String] regexp A regular expression (as a String) to match the message body against
|
[
"Expect",
"to",
"receive",
"a",
"MESSAGE",
"message"
] |
f778cdf429dc9a95884d05669dd1ed04b07134e4
|
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/scenario.rb#L532-L554
|
20,074
|
mojolingo/sippy_cup
|
lib/sippy_cup/scenario.rb
|
SippyCup.Scenario.call_length_repartition
|
def call_length_repartition(min, max, interval)
partition_table 'CallLengthRepartition', min.to_i, max.to_i, interval.to_i
end
|
ruby
|
def call_length_repartition(min, max, interval)
partition_table 'CallLengthRepartition', min.to_i, max.to_i, interval.to_i
end
|
[
"def",
"call_length_repartition",
"(",
"min",
",",
"max",
",",
"interval",
")",
"partition_table",
"'CallLengthRepartition'",
",",
"min",
".",
"to_i",
",",
"max",
".",
"to_i",
",",
"interval",
".",
"to_i",
"end"
] |
Create partition table for Call Length
@param [Integer] min An value specifying the minimum time in milliseconds for the table
@param [Integer] max An value specifying the maximum time in milliseconds for the table
@param [Integer] interval An value specifying the interval in milliseconds for the table
|
[
"Create",
"partition",
"table",
"for",
"Call",
"Length"
] |
f778cdf429dc9a95884d05669dd1ed04b07134e4
|
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/scenario.rb#L637-L639
|
20,075
|
mojolingo/sippy_cup
|
lib/sippy_cup/scenario.rb
|
SippyCup.Scenario.response_time_repartition
|
def response_time_repartition(min, max, interval)
partition_table 'ResponseTimeRepartition', min.to_i, max.to_i, interval.to_i
end
|
ruby
|
def response_time_repartition(min, max, interval)
partition_table 'ResponseTimeRepartition', min.to_i, max.to_i, interval.to_i
end
|
[
"def",
"response_time_repartition",
"(",
"min",
",",
"max",
",",
"interval",
")",
"partition_table",
"'ResponseTimeRepartition'",
",",
"min",
".",
"to_i",
",",
"max",
".",
"to_i",
",",
"interval",
".",
"to_i",
"end"
] |
Create partition table for Response Time
@param [Integer] min An value specifying the minimum time in milliseconds for the table
@param [Integer] max An value specifying the maximum time in milliseconds for the table
@param [Integer] interval An value specifying the interval in milliseconds for the table
|
[
"Create",
"partition",
"table",
"for",
"Response",
"Time"
] |
f778cdf429dc9a95884d05669dd1ed04b07134e4
|
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/scenario.rb#L646-L648
|
20,076
|
mojolingo/sippy_cup
|
lib/sippy_cup/scenario.rb
|
SippyCup.Scenario.to_xml
|
def to_xml(options = {})
pcap_path = options[:pcap_path]
docdup = doc.dup
# Not removing in reverse would most likely remove the wrong
# nodes because of changing indices.
@media_nodes.reverse.each do |nop|
nopdup = docdup.xpath(nop.path)
if pcap_path.nil? or @media.blank?
nopdup.remove
else
exec = nopdup.xpath("./action/exec").first
exec['play_pcap_audio'] = pcap_path
end
end
unless @reference_variables.empty?
scenario_node = docdup.xpath('scenario').first
scenario_node << docdup.create_element('Reference') do |ref|
ref[:variables] = @reference_variables.to_a.join ','
end
end
docdup.to_xml
end
|
ruby
|
def to_xml(options = {})
pcap_path = options[:pcap_path]
docdup = doc.dup
# Not removing in reverse would most likely remove the wrong
# nodes because of changing indices.
@media_nodes.reverse.each do |nop|
nopdup = docdup.xpath(nop.path)
if pcap_path.nil? or @media.blank?
nopdup.remove
else
exec = nopdup.xpath("./action/exec").first
exec['play_pcap_audio'] = pcap_path
end
end
unless @reference_variables.empty?
scenario_node = docdup.xpath('scenario').first
scenario_node << docdup.create_element('Reference') do |ref|
ref[:variables] = @reference_variables.to_a.join ','
end
end
docdup.to_xml
end
|
[
"def",
"to_xml",
"(",
"options",
"=",
"{",
"}",
")",
"pcap_path",
"=",
"options",
"[",
":pcap_path",
"]",
"docdup",
"=",
"doc",
".",
"dup",
"# Not removing in reverse would most likely remove the wrong",
"# nodes because of changing indices.",
"@media_nodes",
".",
"reverse",
".",
"each",
"do",
"|",
"nop",
"|",
"nopdup",
"=",
"docdup",
".",
"xpath",
"(",
"nop",
".",
"path",
")",
"if",
"pcap_path",
".",
"nil?",
"or",
"@media",
".",
"blank?",
"nopdup",
".",
"remove",
"else",
"exec",
"=",
"nopdup",
".",
"xpath",
"(",
"\"./action/exec\"",
")",
".",
"first",
"exec",
"[",
"'play_pcap_audio'",
"]",
"=",
"pcap_path",
"end",
"end",
"unless",
"@reference_variables",
".",
"empty?",
"scenario_node",
"=",
"docdup",
".",
"xpath",
"(",
"'scenario'",
")",
".",
"first",
"scenario_node",
"<<",
"docdup",
".",
"create_element",
"(",
"'Reference'",
")",
"do",
"|",
"ref",
"|",
"ref",
"[",
":variables",
"]",
"=",
"@reference_variables",
".",
"to_a",
".",
"join",
"','",
"end",
"end",
"docdup",
".",
"to_xml",
"end"
] |
Dump the scenario to a SIPp XML string
@return [String] the SIPp XML scenario
|
[
"Dump",
"the",
"scenario",
"to",
"a",
"SIPp",
"XML",
"string"
] |
f778cdf429dc9a95884d05669dd1ed04b07134e4
|
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/scenario.rb#L654-L679
|
20,077
|
mojolingo/sippy_cup
|
lib/sippy_cup/scenario.rb
|
SippyCup.Scenario.compile!
|
def compile!
unless @media.blank?
print "Compiling media to #{@filename}.pcap..."
compile_media.to_file filename: "#{@filename}.pcap"
puts "done."
end
scenario_filename = "#{@filename}.xml"
print "Compiling scenario to #{scenario_filename}..."
File.open scenario_filename, 'w' do |file|
file.write to_xml(:pcap_path => "#{@filename}.pcap")
end
puts "done."
scenario_filename
end
|
ruby
|
def compile!
unless @media.blank?
print "Compiling media to #{@filename}.pcap..."
compile_media.to_file filename: "#{@filename}.pcap"
puts "done."
end
scenario_filename = "#{@filename}.xml"
print "Compiling scenario to #{scenario_filename}..."
File.open scenario_filename, 'w' do |file|
file.write to_xml(:pcap_path => "#{@filename}.pcap")
end
puts "done."
scenario_filename
end
|
[
"def",
"compile!",
"unless",
"@media",
".",
"blank?",
"print",
"\"Compiling media to #{@filename}.pcap...\"",
"compile_media",
".",
"to_file",
"filename",
":",
"\"#{@filename}.pcap\"",
"puts",
"\"done.\"",
"end",
"scenario_filename",
"=",
"\"#{@filename}.xml\"",
"print",
"\"Compiling scenario to #{scenario_filename}...\"",
"File",
".",
"open",
"scenario_filename",
",",
"'w'",
"do",
"|",
"file",
"|",
"file",
".",
"write",
"to_xml",
"(",
":pcap_path",
"=>",
"\"#{@filename}.pcap\"",
")",
"end",
"puts",
"\"done.\"",
"scenario_filename",
"end"
] |
Compile the scenario and its media to disk
Writes the SIPp scenario file to disk at {filename}.xml, and the PCAP media to {filename}.pcap if applicable.
{filename} is taken from the :filename option when creating the scenario, or falls back to a down-snake-cased version of the scenario name.
@return [String] the path to the resulting scenario file
@example Export a scenario to a specified filename
scenario = Scenario.new 'Test Scenario', filename: 'my_scenario'
scenario.compile! # Leaves files at my_scenario.xml and my_scenario.pcap
@example Export a scenario to a calculated filename
scenario = Scenario.new 'Test Scenario'
scenario.compile! # Leaves files at test_scenario.xml and test_scenario.pcap
|
[
"Compile",
"the",
"scenario",
"and",
"its",
"media",
"to",
"disk"
] |
f778cdf429dc9a95884d05669dd1ed04b07134e4
|
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/scenario.rb#L697-L712
|
20,078
|
mojolingo/sippy_cup
|
lib/sippy_cup/xml_scenario.rb
|
SippyCup.XMLScenario.to_tmpfiles
|
def to_tmpfiles
scenario_file = Tempfile.new 'scenario'
scenario_file.write @xml
scenario_file.rewind
if @media
media_file = Tempfile.new 'media'
media_file.write @media
media_file.rewind
else
media_file = nil
end
{scenario: scenario_file, media: media_file}
end
|
ruby
|
def to_tmpfiles
scenario_file = Tempfile.new 'scenario'
scenario_file.write @xml
scenario_file.rewind
if @media
media_file = Tempfile.new 'media'
media_file.write @media
media_file.rewind
else
media_file = nil
end
{scenario: scenario_file, media: media_file}
end
|
[
"def",
"to_tmpfiles",
"scenario_file",
"=",
"Tempfile",
".",
"new",
"'scenario'",
"scenario_file",
".",
"write",
"@xml",
"scenario_file",
".",
"rewind",
"if",
"@media",
"media_file",
"=",
"Tempfile",
".",
"new",
"'media'",
"media_file",
".",
"write",
"@media",
"media_file",
".",
"rewind",
"else",
"media_file",
"=",
"nil",
"end",
"{",
"scenario",
":",
"scenario_file",
",",
"media",
":",
"media_file",
"}",
"end"
] |
Create a scenario instance
@param [String] name The scenario's name
@param [String] xml The XML document representing the scenario
@param [String] media The media to be invoked by the scenario in PCAP format
@param [Hash] args options to customise the scenario. @see Scenario#initialize.
Write compiled Scenario XML and PCAP media to tempfiles.
These will automatically be closed and deleted once they have gone out of scope, and can be used to execute the scenario without leaving stuff behind.
@return [Hash<Symbol => Tempfile>] handles to created Tempfiles at :scenario and :media
@see http://www.ruby-doc.org/stdlib-1.9.3/libdoc/tempfile/rdoc/Tempfile.html
|
[
"Create",
"a",
"scenario",
"instance"
] |
f778cdf429dc9a95884d05669dd1ed04b07134e4
|
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/xml_scenario.rb#L34-L48
|
20,079
|
mojolingo/sippy_cup
|
lib/sippy_cup/runner.rb
|
SippyCup.Runner.wait
|
def wait
exit_status = Process.wait2 @sipp_pid.to_i
@err_rd.close if @err_rd
@stdout_rd.close if @stdout_rd
final_result = process_exit_status exit_status, @stderr_buffer
if final_result
@logger.info "Test completed successfully!"
else
@logger.info "Test completed successfully but some calls failed."
end
@logger.info "Statistics logged at #{File.expand_path @scenario_options[:stats_file]}" if @scenario_options[:stats_file]
final_result
ensure
cleanup_input_files
end
|
ruby
|
def wait
exit_status = Process.wait2 @sipp_pid.to_i
@err_rd.close if @err_rd
@stdout_rd.close if @stdout_rd
final_result = process_exit_status exit_status, @stderr_buffer
if final_result
@logger.info "Test completed successfully!"
else
@logger.info "Test completed successfully but some calls failed."
end
@logger.info "Statistics logged at #{File.expand_path @scenario_options[:stats_file]}" if @scenario_options[:stats_file]
final_result
ensure
cleanup_input_files
end
|
[
"def",
"wait",
"exit_status",
"=",
"Process",
".",
"wait2",
"@sipp_pid",
".",
"to_i",
"@err_rd",
".",
"close",
"if",
"@err_rd",
"@stdout_rd",
".",
"close",
"if",
"@stdout_rd",
"final_result",
"=",
"process_exit_status",
"exit_status",
",",
"@stderr_buffer",
"if",
"final_result",
"@logger",
".",
"info",
"\"Test completed successfully!\"",
"else",
"@logger",
".",
"info",
"\"Test completed successfully but some calls failed.\"",
"end",
"@logger",
".",
"info",
"\"Statistics logged at #{File.expand_path @scenario_options[:stats_file]}\"",
"if",
"@scenario_options",
"[",
":stats_file",
"]",
"final_result",
"ensure",
"cleanup_input_files",
"end"
] |
Waits for the runner to finish execution
@raises Errno::ENOENT when the SIPp executable cannot be found
@raises SippyCup::ExitOnInternalCommand when SIPp exits on an internal command. Calls may have been processed
@raises SippyCup::NoCallsProcessed when SIPp exit normally, but has processed no calls
@raises SippyCup::FatalError when SIPp encounters a fatal failure
@raises SippyCup::FatalSocketBindingError when SIPp fails to bind to the specified socket
@raises SippyCup::SippGenericError when SIPp encounters another type of error
@return Boolean true if execution succeeded without any failed calls, false otherwise
|
[
"Waits",
"for",
"the",
"runner",
"to",
"finish",
"execution"
] |
f778cdf429dc9a95884d05669dd1ed04b07134e4
|
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/runner.rb#L70-L85
|
20,080
|
notahat/machinist
|
lib/machinist/machinable.rb
|
Machinist.Machinable.blueprint
|
def blueprint(name = :master, &block)
@blueprints ||= {}
if block_given?
parent = (name == :master ? superclass : self) # Where should we look for the parent blueprint?
@blueprints[name] = blueprint_class.new(self, :parent => parent, &block)
end
@blueprints[name]
end
|
ruby
|
def blueprint(name = :master, &block)
@blueprints ||= {}
if block_given?
parent = (name == :master ? superclass : self) # Where should we look for the parent blueprint?
@blueprints[name] = blueprint_class.new(self, :parent => parent, &block)
end
@blueprints[name]
end
|
[
"def",
"blueprint",
"(",
"name",
"=",
":master",
",",
"&",
"block",
")",
"@blueprints",
"||=",
"{",
"}",
"if",
"block_given?",
"parent",
"=",
"(",
"name",
"==",
":master",
"?",
"superclass",
":",
"self",
")",
"# Where should we look for the parent blueprint?",
"@blueprints",
"[",
"name",
"]",
"=",
"blueprint_class",
".",
"new",
"(",
"self",
",",
":parent",
"=>",
"parent",
",",
"block",
")",
"end",
"@blueprints",
"[",
"name",
"]",
"end"
] |
Define a blueprint with the given name for this class.
e.g.
Post.blueprint do
title { "A Post" }
body { "Lorem ipsum..." }
end
If you provide the +name+ argument, a named blueprint will be created.
See the +blueprint_name+ argument to the make method.
|
[
"Define",
"a",
"blueprint",
"with",
"the",
"given",
"name",
"for",
"this",
"class",
"."
] |
dba78a430cd67646a270393c4adfa19a5516f569
|
https://github.com/notahat/machinist/blob/dba78a430cd67646a270393c4adfa19a5516f569/lib/machinist/machinable.rb#L15-L22
|
20,081
|
notahat/machinist
|
lib/machinist/machinable.rb
|
Machinist.Machinable.make!
|
def make!(*args)
decode_args_to_make(*args) do |blueprint, attributes|
raise BlueprintCantSaveError.new(blueprint) unless blueprint.respond_to?(:make!)
blueprint.make!(attributes)
end
end
|
ruby
|
def make!(*args)
decode_args_to_make(*args) do |blueprint, attributes|
raise BlueprintCantSaveError.new(blueprint) unless blueprint.respond_to?(:make!)
blueprint.make!(attributes)
end
end
|
[
"def",
"make!",
"(",
"*",
"args",
")",
"decode_args_to_make",
"(",
"args",
")",
"do",
"|",
"blueprint",
",",
"attributes",
"|",
"raise",
"BlueprintCantSaveError",
".",
"new",
"(",
"blueprint",
")",
"unless",
"blueprint",
".",
"respond_to?",
"(",
":make!",
")",
"blueprint",
".",
"make!",
"(",
"attributes",
")",
"end",
"end"
] |
Construct and save an object from a blueprint, if the class allows saving.
:call-seq:
make!([count], [blueprint_name], [attributes = {}])
Arguments are the same as for make.
|
[
"Construct",
"and",
"save",
"an",
"object",
"from",
"a",
"blueprint",
"if",
"the",
"class",
"allows",
"saving",
"."
] |
dba78a430cd67646a270393c4adfa19a5516f569
|
https://github.com/notahat/machinist/blob/dba78a430cd67646a270393c4adfa19a5516f569/lib/machinist/machinable.rb#L49-L54
|
20,082
|
notahat/machinist
|
lib/machinist/machinable.rb
|
Machinist.Machinable.decode_args_to_make
|
def decode_args_to_make(*args) #:nodoc:
shift_arg = lambda {|klass| args.shift if args.first.is_a?(klass) }
count = shift_arg[Fixnum]
name = shift_arg[Symbol] || :master
attributes = shift_arg[Hash] || {}
raise ArgumentError.new("Couldn't understand arguments") unless args.empty?
@blueprints ||= {}
blueprint = @blueprints[name]
raise NoBlueprintError.new(self, name) unless blueprint
if count.nil?
yield(blueprint, attributes)
else
Array.new(count) { yield(blueprint, attributes) }
end
end
|
ruby
|
def decode_args_to_make(*args) #:nodoc:
shift_arg = lambda {|klass| args.shift if args.first.is_a?(klass) }
count = shift_arg[Fixnum]
name = shift_arg[Symbol] || :master
attributes = shift_arg[Hash] || {}
raise ArgumentError.new("Couldn't understand arguments") unless args.empty?
@blueprints ||= {}
blueprint = @blueprints[name]
raise NoBlueprintError.new(self, name) unless blueprint
if count.nil?
yield(blueprint, attributes)
else
Array.new(count) { yield(blueprint, attributes) }
end
end
|
[
"def",
"decode_args_to_make",
"(",
"*",
"args",
")",
"#:nodoc:",
"shift_arg",
"=",
"lambda",
"{",
"|",
"klass",
"|",
"args",
".",
"shift",
"if",
"args",
".",
"first",
".",
"is_a?",
"(",
"klass",
")",
"}",
"count",
"=",
"shift_arg",
"[",
"Fixnum",
"]",
"name",
"=",
"shift_arg",
"[",
"Symbol",
"]",
"||",
":master",
"attributes",
"=",
"shift_arg",
"[",
"Hash",
"]",
"||",
"{",
"}",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Couldn't understand arguments\"",
")",
"unless",
"args",
".",
"empty?",
"@blueprints",
"||=",
"{",
"}",
"blueprint",
"=",
"@blueprints",
"[",
"name",
"]",
"raise",
"NoBlueprintError",
".",
"new",
"(",
"self",
",",
"name",
")",
"unless",
"blueprint",
"if",
"count",
".",
"nil?",
"yield",
"(",
"blueprint",
",",
"attributes",
")",
"else",
"Array",
".",
"new",
"(",
"count",
")",
"{",
"yield",
"(",
"blueprint",
",",
"attributes",
")",
"}",
"end",
"end"
] |
Parses the arguments to make.
Yields a blueprint and an attributes hash to the block, which should
construct an object from them. The block may be called multiple times to
construct multiple objects.
|
[
"Parses",
"the",
"arguments",
"to",
"make",
"."
] |
dba78a430cd67646a270393c4adfa19a5516f569
|
https://github.com/notahat/machinist/blob/dba78a430cd67646a270393c4adfa19a5516f569/lib/machinist/machinable.rb#L76-L92
|
20,083
|
notahat/machinist
|
lib/machinist/blueprint.rb
|
Machinist.Blueprint.make
|
def make(attributes = {})
lathe = lathe_class.new(@klass, new_serial_number, attributes)
lathe.instance_eval(&@block)
each_ancestor {|blueprint| lathe.instance_eval(&blueprint.block) }
lathe.object
end
|
ruby
|
def make(attributes = {})
lathe = lathe_class.new(@klass, new_serial_number, attributes)
lathe.instance_eval(&@block)
each_ancestor {|blueprint| lathe.instance_eval(&blueprint.block) }
lathe.object
end
|
[
"def",
"make",
"(",
"attributes",
"=",
"{",
"}",
")",
"lathe",
"=",
"lathe_class",
".",
"new",
"(",
"@klass",
",",
"new_serial_number",
",",
"attributes",
")",
"lathe",
".",
"instance_eval",
"(",
"@block",
")",
"each_ancestor",
"{",
"|",
"blueprint",
"|",
"lathe",
".",
"instance_eval",
"(",
"blueprint",
".",
"block",
")",
"}",
"lathe",
".",
"object",
"end"
] |
Generate an object from this blueprint.
Pass in attributes to override values defined in the blueprint.
|
[
"Generate",
"an",
"object",
"from",
"this",
"blueprint",
"."
] |
dba78a430cd67646a270393c4adfa19a5516f569
|
https://github.com/notahat/machinist/blob/dba78a430cd67646a270393c4adfa19a5516f569/lib/machinist/blueprint.rb#L23-L30
|
20,084
|
zk-ruby/zookeeper
|
lib/zookeeper/request_registry.rb
|
Zookeeper.RequestRegistry.get_watcher
|
def get_watcher(req_id, opts={})
@mutex.synchronize do
if Constants::ZKRB_GLOBAL_CB_REQ == req_id
{ :watcher => @default_watcher, :watcher_context => nil }
elsif opts[:keep]
@watcher_reqs[req_id]
else
@watcher_reqs.delete(req_id)
end
end
end
|
ruby
|
def get_watcher(req_id, opts={})
@mutex.synchronize do
if Constants::ZKRB_GLOBAL_CB_REQ == req_id
{ :watcher => @default_watcher, :watcher_context => nil }
elsif opts[:keep]
@watcher_reqs[req_id]
else
@watcher_reqs.delete(req_id)
end
end
end
|
[
"def",
"get_watcher",
"(",
"req_id",
",",
"opts",
"=",
"{",
"}",
")",
"@mutex",
".",
"synchronize",
"do",
"if",
"Constants",
"::",
"ZKRB_GLOBAL_CB_REQ",
"==",
"req_id",
"{",
":watcher",
"=>",
"@default_watcher",
",",
":watcher_context",
"=>",
"nil",
"}",
"elsif",
"opts",
"[",
":keep",
"]",
"@watcher_reqs",
"[",
"req_id",
"]",
"else",
"@watcher_reqs",
".",
"delete",
"(",
"req_id",
")",
"end",
"end",
"end"
] |
Return the watcher hash associated with the req_id. If the req_id
is the ZKRB_GLOBAL_CB_REQ, then does not clear the req from the internal
store, otherwise the req_id is removed.
|
[
"Return",
"the",
"watcher",
"hash",
"associated",
"with",
"the",
"req_id",
".",
"If",
"the",
"req_id",
"is",
"the",
"ZKRB_GLOBAL_CB_REQ",
"then",
"does",
"not",
"clear",
"the",
"req",
"from",
"the",
"internal",
"store",
"otherwise",
"the",
"req_id",
"is",
"removed",
"."
] |
b99cb25195b8c947be0eb82141cc261eec9c8724
|
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/lib/zookeeper/request_registry.rb#L82-L92
|
20,085
|
zk-ruby/zookeeper
|
ext/c_zookeeper.rb
|
Zookeeper.CZookeeper.wait_until_connected
|
def wait_until_connected(timeout=10)
time_to_stop = timeout ? Time.now + timeout : nil
return false unless wait_until_running(timeout)
@state_mutex.synchronize do
while true
if timeout
now = Time.now
break if (@state == ZOO_CONNECTED_STATE) || unhealthy? || (now > time_to_stop)
delay = time_to_stop.to_f - now.to_f
@state_cond.wait(delay)
else
break if (@state == ZOO_CONNECTED_STATE) || unhealthy?
@state_cond.wait
end
end
end
connected?
end
|
ruby
|
def wait_until_connected(timeout=10)
time_to_stop = timeout ? Time.now + timeout : nil
return false unless wait_until_running(timeout)
@state_mutex.synchronize do
while true
if timeout
now = Time.now
break if (@state == ZOO_CONNECTED_STATE) || unhealthy? || (now > time_to_stop)
delay = time_to_stop.to_f - now.to_f
@state_cond.wait(delay)
else
break if (@state == ZOO_CONNECTED_STATE) || unhealthy?
@state_cond.wait
end
end
end
connected?
end
|
[
"def",
"wait_until_connected",
"(",
"timeout",
"=",
"10",
")",
"time_to_stop",
"=",
"timeout",
"?",
"Time",
".",
"now",
"+",
"timeout",
":",
"nil",
"return",
"false",
"unless",
"wait_until_running",
"(",
"timeout",
")",
"@state_mutex",
".",
"synchronize",
"do",
"while",
"true",
"if",
"timeout",
"now",
"=",
"Time",
".",
"now",
"break",
"if",
"(",
"@state",
"==",
"ZOO_CONNECTED_STATE",
")",
"||",
"unhealthy?",
"||",
"(",
"now",
">",
"time_to_stop",
")",
"delay",
"=",
"time_to_stop",
".",
"to_f",
"-",
"now",
".",
"to_f",
"@state_cond",
".",
"wait",
"(",
"delay",
")",
"else",
"break",
"if",
"(",
"@state",
"==",
"ZOO_CONNECTED_STATE",
")",
"||",
"unhealthy?",
"@state_cond",
".",
"wait",
"end",
"end",
"end",
"connected?",
"end"
] |
this implementation is gross, but i don't really see another way of doing it
without more grossness
returns true if we're connected, false if we're not
if timeout is nil, we never time out, and wait forever for CONNECTED state
|
[
"this",
"implementation",
"is",
"gross",
"but",
"i",
"don",
"t",
"really",
"see",
"another",
"way",
"of",
"doing",
"it",
"without",
"more",
"grossness"
] |
b99cb25195b8c947be0eb82141cc261eec9c8724
|
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/ext/c_zookeeper.rb#L178-L198
|
20,086
|
zk-ruby/zookeeper
|
ext/c_zookeeper.rb
|
Zookeeper.CZookeeper.submit_and_block
|
def submit_and_block(meth, *args)
@mutex.synchronize do
raise Exceptions::NotConnected if unhealthy?
end
cnt = Continuation.new(meth, *args)
@reg.synchronize do |r|
if meth == :state
r.state_check << cnt
else
r.pending << cnt
end
end
wake_event_loop!
cnt.value
end
|
ruby
|
def submit_and_block(meth, *args)
@mutex.synchronize do
raise Exceptions::NotConnected if unhealthy?
end
cnt = Continuation.new(meth, *args)
@reg.synchronize do |r|
if meth == :state
r.state_check << cnt
else
r.pending << cnt
end
end
wake_event_loop!
cnt.value
end
|
[
"def",
"submit_and_block",
"(",
"meth",
",",
"*",
"args",
")",
"@mutex",
".",
"synchronize",
"do",
"raise",
"Exceptions",
"::",
"NotConnected",
"if",
"unhealthy?",
"end",
"cnt",
"=",
"Continuation",
".",
"new",
"(",
"meth",
",",
"args",
")",
"@reg",
".",
"synchronize",
"do",
"|",
"r",
"|",
"if",
"meth",
"==",
":state",
"r",
".",
"state_check",
"<<",
"cnt",
"else",
"r",
".",
"pending",
"<<",
"cnt",
"end",
"end",
"wake_event_loop!",
"cnt",
".",
"value",
"end"
] |
submits a job for processing
blocks the caller until result has returned
|
[
"submits",
"a",
"job",
"for",
"processing",
"blocks",
"the",
"caller",
"until",
"result",
"has",
"returned"
] |
b99cb25195b8c947be0eb82141cc261eec9c8724
|
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/ext/c_zookeeper.rb#L217-L232
|
20,087
|
zk-ruby/zookeeper
|
lib/zookeeper/continuation.rb
|
Zookeeper.Continuation.call
|
def call(hash)
logger.debug { "continuation req_id #{req_id}, got hash: #{hash.inspect}" }
@rval = hash.values_at(*METH_TO_ASYNC_RESULT_KEYS.fetch(meth))
logger.debug { "delivering result #{@rval.inspect}" }
deliver!
end
|
ruby
|
def call(hash)
logger.debug { "continuation req_id #{req_id}, got hash: #{hash.inspect}" }
@rval = hash.values_at(*METH_TO_ASYNC_RESULT_KEYS.fetch(meth))
logger.debug { "delivering result #{@rval.inspect}" }
deliver!
end
|
[
"def",
"call",
"(",
"hash",
")",
"logger",
".",
"debug",
"{",
"\"continuation req_id #{req_id}, got hash: #{hash.inspect}\"",
"}",
"@rval",
"=",
"hash",
".",
"values_at",
"(",
"METH_TO_ASYNC_RESULT_KEYS",
".",
"fetch",
"(",
"meth",
")",
")",
"logger",
".",
"debug",
"{",
"\"delivering result #{@rval.inspect}\"",
"}",
"deliver!",
"end"
] |
receive the response from the server, set @rval, notify caller
|
[
"receive",
"the",
"response",
"from",
"the",
"server",
"set"
] |
b99cb25195b8c947be0eb82141cc261eec9c8724
|
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/lib/zookeeper/continuation.rb#L141-L146
|
20,088
|
zk-ruby/zookeeper
|
ext/zookeeper_base.rb
|
Zookeeper.ZookeeperBase.close
|
def close
sd_thread = nil
@mutex.synchronize do
return unless @czk
inst, @czk = @czk, nil
sd_thread = Thread.new(inst) do |_inst|
stop_dispatch_thread!
_inst.close
end
end
# if we're on the event dispatch thread for some stupid reason, then don't join
unless event_dispatch_thread?
# hard-coded 30 second delay, don't hang forever
if sd_thread.join(30) != sd_thread
logger.error { "timed out waiting for shutdown thread to exit" }
end
end
nil
end
|
ruby
|
def close
sd_thread = nil
@mutex.synchronize do
return unless @czk
inst, @czk = @czk, nil
sd_thread = Thread.new(inst) do |_inst|
stop_dispatch_thread!
_inst.close
end
end
# if we're on the event dispatch thread for some stupid reason, then don't join
unless event_dispatch_thread?
# hard-coded 30 second delay, don't hang forever
if sd_thread.join(30) != sd_thread
logger.error { "timed out waiting for shutdown thread to exit" }
end
end
nil
end
|
[
"def",
"close",
"sd_thread",
"=",
"nil",
"@mutex",
".",
"synchronize",
"do",
"return",
"unless",
"@czk",
"inst",
",",
"@czk",
"=",
"@czk",
",",
"nil",
"sd_thread",
"=",
"Thread",
".",
"new",
"(",
"inst",
")",
"do",
"|",
"_inst",
"|",
"stop_dispatch_thread!",
"_inst",
".",
"close",
"end",
"end",
"# if we're on the event dispatch thread for some stupid reason, then don't join",
"unless",
"event_dispatch_thread?",
"# hard-coded 30 second delay, don't hang forever",
"if",
"sd_thread",
".",
"join",
"(",
"30",
")",
"!=",
"sd_thread",
"logger",
".",
"error",
"{",
"\"timed out waiting for shutdown thread to exit\"",
"}",
"end",
"end",
"nil",
"end"
] |
close the connection normally, stops the dispatch thread and closes the
underlying connection cleanly
|
[
"close",
"the",
"connection",
"normally",
"stops",
"the",
"dispatch",
"thread",
"and",
"closes",
"the",
"underlying",
"connection",
"cleanly"
] |
b99cb25195b8c947be0eb82141cc261eec9c8724
|
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/ext/zookeeper_base.rb#L129-L151
|
20,089
|
zk-ruby/zookeeper
|
ext/zookeeper_base.rb
|
Zookeeper.ZookeeperBase.create
|
def create(*args)
# since we don't care about the inputs, just glob args
rc, new_path = czk.create(*args)
[rc, @req_registry.strip_chroot_from(new_path)]
end
|
ruby
|
def create(*args)
# since we don't care about the inputs, just glob args
rc, new_path = czk.create(*args)
[rc, @req_registry.strip_chroot_from(new_path)]
end
|
[
"def",
"create",
"(",
"*",
"args",
")",
"# since we don't care about the inputs, just glob args",
"rc",
",",
"new_path",
"=",
"czk",
".",
"create",
"(",
"args",
")",
"[",
"rc",
",",
"@req_registry",
".",
"strip_chroot_from",
"(",
"new_path",
")",
"]",
"end"
] |
the C lib doesn't strip the chroot path off of returned path values, which
is pretty damn annoying. this is used to clean things up.
|
[
"the",
"C",
"lib",
"doesn",
"t",
"strip",
"the",
"chroot",
"path",
"off",
"of",
"returned",
"path",
"values",
"which",
"is",
"pretty",
"damn",
"annoying",
".",
"this",
"is",
"used",
"to",
"clean",
"things",
"up",
"."
] |
b99cb25195b8c947be0eb82141cc261eec9c8724
|
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/ext/zookeeper_base.rb#L155-L159
|
20,090
|
zk-ruby/zookeeper
|
ext/zookeeper_base.rb
|
Zookeeper.ZookeeperBase.strip_chroot_from
|
def strip_chroot_from(path)
return path unless (chrooted? and path and path.start_with?(chroot_path))
path[chroot_path.length..-1]
end
|
ruby
|
def strip_chroot_from(path)
return path unless (chrooted? and path and path.start_with?(chroot_path))
path[chroot_path.length..-1]
end
|
[
"def",
"strip_chroot_from",
"(",
"path",
")",
"return",
"path",
"unless",
"(",
"chrooted?",
"and",
"path",
"and",
"path",
".",
"start_with?",
"(",
"chroot_path",
")",
")",
"path",
"[",
"chroot_path",
".",
"length",
"..",
"-",
"1",
"]",
"end"
] |
if we're chrooted, this method will strip the chroot prefix from +path+
|
[
"if",
"we",
"re",
"chrooted",
"this",
"method",
"will",
"strip",
"the",
"chroot",
"prefix",
"from",
"+",
"path",
"+"
] |
b99cb25195b8c947be0eb82141cc261eec9c8724
|
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/ext/zookeeper_base.rb#L227-L230
|
20,091
|
zk-ruby/zookeeper
|
spec/support/zookeeper_spec_helpers.rb
|
Zookeeper.SpecHelpers.rm_rf
|
def rm_rf(z, path)
z.get_children(:path => path).tap do |h|
if h[:rc].zero?
h[:children].each do |child|
rm_rf(z, File.join(path, child))
end
elsif h[:rc] == ZNONODE
# no-op
else
raise "Oh noes! unexpected return value! #{h.inspect}"
end
end
rv = z.delete(:path => path)
unless (rv[:rc].zero? or rv[:rc] == ZNONODE)
raise "oh noes! failed to delete #{path}"
end
path
end
|
ruby
|
def rm_rf(z, path)
z.get_children(:path => path).tap do |h|
if h[:rc].zero?
h[:children].each do |child|
rm_rf(z, File.join(path, child))
end
elsif h[:rc] == ZNONODE
# no-op
else
raise "Oh noes! unexpected return value! #{h.inspect}"
end
end
rv = z.delete(:path => path)
unless (rv[:rc].zero? or rv[:rc] == ZNONODE)
raise "oh noes! failed to delete #{path}"
end
path
end
|
[
"def",
"rm_rf",
"(",
"z",
",",
"path",
")",
"z",
".",
"get_children",
"(",
":path",
"=>",
"path",
")",
".",
"tap",
"do",
"|",
"h",
"|",
"if",
"h",
"[",
":rc",
"]",
".",
"zero?",
"h",
"[",
":children",
"]",
".",
"each",
"do",
"|",
"child",
"|",
"rm_rf",
"(",
"z",
",",
"File",
".",
"join",
"(",
"path",
",",
"child",
")",
")",
"end",
"elsif",
"h",
"[",
":rc",
"]",
"==",
"ZNONODE",
"# no-op",
"else",
"raise",
"\"Oh noes! unexpected return value! #{h.inspect}\"",
"end",
"end",
"rv",
"=",
"z",
".",
"delete",
"(",
":path",
"=>",
"path",
")",
"unless",
"(",
"rv",
"[",
":rc",
"]",
".",
"zero?",
"or",
"rv",
"[",
":rc",
"]",
"==",
"ZNONODE",
")",
"raise",
"\"oh noes! failed to delete #{path}\"",
"end",
"path",
"end"
] |
this is not as safe as the one in ZK, just to be used to clean up
when we're the only one adjusting a particular path
|
[
"this",
"is",
"not",
"as",
"safe",
"as",
"the",
"one",
"in",
"ZK",
"just",
"to",
"be",
"used",
"to",
"clean",
"up",
"when",
"we",
"re",
"the",
"only",
"one",
"adjusting",
"a",
"particular",
"path"
] |
b99cb25195b8c947be0eb82141cc261eec9c8724
|
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/spec/support/zookeeper_spec_helpers.rb#L37-L57
|
20,092
|
cubesystems/releaf
|
releaf-content/lib/releaf/content/route.rb
|
Releaf::Content.Route.params
|
def params(method_or_path, options = {})
method_or_path = method_or_path.to_s
[
path_for(method_or_path, options),
options_for(method_or_path, options)
]
end
|
ruby
|
def params(method_or_path, options = {})
method_or_path = method_or_path.to_s
[
path_for(method_or_path, options),
options_for(method_or_path, options)
]
end
|
[
"def",
"params",
"(",
"method_or_path",
",",
"options",
"=",
"{",
"}",
")",
"method_or_path",
"=",
"method_or_path",
".",
"to_s",
"[",
"path_for",
"(",
"method_or_path",
",",
"options",
")",
",",
"options_for",
"(",
"method_or_path",
",",
"options",
")",
"]",
"end"
] |
Return node route params which can be used in Rails route options
@param method_or_path [String] string with action and controller for route (Ex. home#index)
@param options [Hash] options to merge with internally built params. Passed params overrides route params.
@return [Hash] route options. Will return at least node "node_id" and "locale" keys.
|
[
"Return",
"node",
"route",
"params",
"which",
"can",
"be",
"used",
"in",
"Rails",
"route",
"options"
] |
5ea615abcf6e62afbbf82259d0aa533221d6de08
|
https://github.com/cubesystems/releaf/blob/5ea615abcf6e62afbbf82259d0aa533221d6de08/releaf-content/lib/releaf/content/route.rb#L18-L24
|
20,093
|
cubesystems/releaf
|
releaf-content/lib/releaf/content/node.rb
|
Releaf::Content.Node.maintain_name
|
def maintain_name
postfix = nil
total_count = 0
while self.class.where(parent_id: parent_id, name: "#{name}#{postfix}").where("id != ?", id.to_i).exists? do
total_count += 1
postfix = "(#{total_count})"
end
if postfix
self.name = "#{name}#{postfix}"
end
end
|
ruby
|
def maintain_name
postfix = nil
total_count = 0
while self.class.where(parent_id: parent_id, name: "#{name}#{postfix}").where("id != ?", id.to_i).exists? do
total_count += 1
postfix = "(#{total_count})"
end
if postfix
self.name = "#{name}#{postfix}"
end
end
|
[
"def",
"maintain_name",
"postfix",
"=",
"nil",
"total_count",
"=",
"0",
"while",
"self",
".",
"class",
".",
"where",
"(",
"parent_id",
":",
"parent_id",
",",
"name",
":",
"\"#{name}#{postfix}\"",
")",
".",
"where",
"(",
"\"id != ?\"",
",",
"id",
".",
"to_i",
")",
".",
"exists?",
"do",
"total_count",
"+=",
"1",
"postfix",
"=",
"\"(#{total_count})\"",
"end",
"if",
"postfix",
"self",
".",
"name",
"=",
"\"#{name}#{postfix}\"",
"end",
"end"
] |
Maintain unique name within parent_id scope.
If name is not unique add numeric postfix.
|
[
"Maintain",
"unique",
"name",
"within",
"parent_id",
"scope",
".",
"If",
"name",
"is",
"not",
"unique",
"add",
"numeric",
"postfix",
"."
] |
5ea615abcf6e62afbbf82259d0aa533221d6de08
|
https://github.com/cubesystems/releaf/blob/5ea615abcf6e62afbbf82259d0aa533221d6de08/releaf-content/lib/releaf/content/node.rb#L73-L85
|
20,094
|
cubesystems/releaf
|
releaf-content/lib/releaf/content/node.rb
|
Releaf::Content.Node.maintain_slug
|
def maintain_slug
postfix = nil
total_count = 0
while self.class.where(parent_id: parent_id, slug: "#{slug}#{postfix}").where("id != ?", id.to_i).exists? do
total_count += 1
postfix = "-#{total_count}"
end
if postfix
self.slug = "#{slug}#{postfix}"
end
end
|
ruby
|
def maintain_slug
postfix = nil
total_count = 0
while self.class.where(parent_id: parent_id, slug: "#{slug}#{postfix}").where("id != ?", id.to_i).exists? do
total_count += 1
postfix = "-#{total_count}"
end
if postfix
self.slug = "#{slug}#{postfix}"
end
end
|
[
"def",
"maintain_slug",
"postfix",
"=",
"nil",
"total_count",
"=",
"0",
"while",
"self",
".",
"class",
".",
"where",
"(",
"parent_id",
":",
"parent_id",
",",
"slug",
":",
"\"#{slug}#{postfix}\"",
")",
".",
"where",
"(",
"\"id != ?\"",
",",
"id",
".",
"to_i",
")",
".",
"exists?",
"do",
"total_count",
"+=",
"1",
"postfix",
"=",
"\"-#{total_count}\"",
"end",
"if",
"postfix",
"self",
".",
"slug",
"=",
"\"#{slug}#{postfix}\"",
"end",
"end"
] |
Maintain unique slug within parent_id scope.
If slug is not unique add numeric postfix.
|
[
"Maintain",
"unique",
"slug",
"within",
"parent_id",
"scope",
".",
"If",
"slug",
"is",
"not",
"unique",
"add",
"numeric",
"postfix",
"."
] |
5ea615abcf6e62afbbf82259d0aa533221d6de08
|
https://github.com/cubesystems/releaf/blob/5ea615abcf6e62afbbf82259d0aa533221d6de08/releaf-content/lib/releaf/content/node.rb#L89-L101
|
20,095
|
cubesystems/releaf
|
releaf-content/lib/releaf/content/acts_as_node.rb
|
ActsAsNode.ClassMethods.acts_as_node
|
def acts_as_node(params: nil, fields: nil)
configuration = {params: params, fields: fields}
ActsAsNode.register_class(self.name)
# Store acts_as_node configuration
cattr_accessor :acts_as_node_configuration
self.acts_as_node_configuration = configuration
end
|
ruby
|
def acts_as_node(params: nil, fields: nil)
configuration = {params: params, fields: fields}
ActsAsNode.register_class(self.name)
# Store acts_as_node configuration
cattr_accessor :acts_as_node_configuration
self.acts_as_node_configuration = configuration
end
|
[
"def",
"acts_as_node",
"(",
"params",
":",
"nil",
",",
"fields",
":",
"nil",
")",
"configuration",
"=",
"{",
"params",
":",
"params",
",",
"fields",
":",
"fields",
"}",
"ActsAsNode",
".",
"register_class",
"(",
"self",
".",
"name",
")",
"# Store acts_as_node configuration",
"cattr_accessor",
":acts_as_node_configuration",
"self",
".",
"acts_as_node_configuration",
"=",
"configuration",
"end"
] |
There are no configuration options yet.
|
[
"There",
"are",
"no",
"configuration",
"options",
"yet",
"."
] |
5ea615abcf6e62afbbf82259d0aa533221d6de08
|
https://github.com/cubesystems/releaf/blob/5ea615abcf6e62afbbf82259d0aa533221d6de08/releaf-content/lib/releaf/content/acts_as_node.rb#L15-L23
|
20,096
|
rr/rr
|
lib/rr/space.rb
|
RR.Space.verify_ordered_double
|
def verify_ordered_double(double)
unless double.terminal?
raise RR::Errors.build_error(:DoubleOrderError,
"Ordered Doubles cannot have a NonTerminal TimesCalledExpectation")
end
unless @ordered_doubles.first == double
message = Double.formatted_name(double.method_name, double.expected_arguments)
message << " called out of order in list\n"
message << Double.list_message_part(@ordered_doubles)
raise RR::Errors.build_error(:DoubleOrderError, message)
end
@ordered_doubles.shift unless double.attempt?
double
end
|
ruby
|
def verify_ordered_double(double)
unless double.terminal?
raise RR::Errors.build_error(:DoubleOrderError,
"Ordered Doubles cannot have a NonTerminal TimesCalledExpectation")
end
unless @ordered_doubles.first == double
message = Double.formatted_name(double.method_name, double.expected_arguments)
message << " called out of order in list\n"
message << Double.list_message_part(@ordered_doubles)
raise RR::Errors.build_error(:DoubleOrderError, message)
end
@ordered_doubles.shift unless double.attempt?
double
end
|
[
"def",
"verify_ordered_double",
"(",
"double",
")",
"unless",
"double",
".",
"terminal?",
"raise",
"RR",
"::",
"Errors",
".",
"build_error",
"(",
":DoubleOrderError",
",",
"\"Ordered Doubles cannot have a NonTerminal TimesCalledExpectation\"",
")",
"end",
"unless",
"@ordered_doubles",
".",
"first",
"==",
"double",
"message",
"=",
"Double",
".",
"formatted_name",
"(",
"double",
".",
"method_name",
",",
"double",
".",
"expected_arguments",
")",
"message",
"<<",
"\" called out of order in list\\n\"",
"message",
"<<",
"Double",
".",
"list_message_part",
"(",
"@ordered_doubles",
")",
"raise",
"RR",
"::",
"Errors",
".",
"build_error",
"(",
":DoubleOrderError",
",",
"message",
")",
"end",
"@ordered_doubles",
".",
"shift",
"unless",
"double",
".",
"attempt?",
"double",
"end"
] |
Verifies that the passed in ordered Double is being called
in the correct position.
|
[
"Verifies",
"that",
"the",
"passed",
"in",
"ordered",
"Double",
"is",
"being",
"called",
"in",
"the",
"correct",
"position",
"."
] |
d110480098473531aebff319493dbb95a4d8e706
|
https://github.com/rr/rr/blob/d110480098473531aebff319493dbb95a4d8e706/lib/rr/space.rb#L38-L51
|
20,097
|
rr/rr
|
lib/rr/space.rb
|
RR.Space.reset
|
def reset
RR.trim_backtrace = false
RR.overridden_error_class = nil
reset_ordered_doubles
Injections::DoubleInjection.reset
reset_method_missing_injections
reset_singleton_method_added_injections
reset_recorded_calls
reset_bound_objects
end
|
ruby
|
def reset
RR.trim_backtrace = false
RR.overridden_error_class = nil
reset_ordered_doubles
Injections::DoubleInjection.reset
reset_method_missing_injections
reset_singleton_method_added_injections
reset_recorded_calls
reset_bound_objects
end
|
[
"def",
"reset",
"RR",
".",
"trim_backtrace",
"=",
"false",
"RR",
".",
"overridden_error_class",
"=",
"nil",
"reset_ordered_doubles",
"Injections",
"::",
"DoubleInjection",
".",
"reset",
"reset_method_missing_injections",
"reset_singleton_method_added_injections",
"reset_recorded_calls",
"reset_bound_objects",
"end"
] |
Resets the registered Doubles and ordered Doubles
|
[
"Resets",
"the",
"registered",
"Doubles",
"and",
"ordered",
"Doubles"
] |
d110480098473531aebff319493dbb95a4d8e706
|
https://github.com/rr/rr/blob/d110480098473531aebff319493dbb95a4d8e706/lib/rr/space.rb#L61-L70
|
20,098
|
rr/rr
|
spec/fixtures/rubygems_patch_for_187.rb
|
Gem.SourceIndex.load_gems_in
|
def load_gems_in(*spec_dirs)
@gems.clear
spec_dirs.reverse_each do |spec_dir|
spec_files = Dir.glob File.join(spec_dir, '*.gemspec')
spec_files.each do |spec_file|
gemspec = self.class.load_specification spec_file.untaint
add_spec gemspec if gemspec
end
end
self
end
|
ruby
|
def load_gems_in(*spec_dirs)
@gems.clear
spec_dirs.reverse_each do |spec_dir|
spec_files = Dir.glob File.join(spec_dir, '*.gemspec')
spec_files.each do |spec_file|
gemspec = self.class.load_specification spec_file.untaint
add_spec gemspec if gemspec
end
end
self
end
|
[
"def",
"load_gems_in",
"(",
"*",
"spec_dirs",
")",
"@gems",
".",
"clear",
"spec_dirs",
".",
"reverse_each",
"do",
"|",
"spec_dir",
"|",
"spec_files",
"=",
"Dir",
".",
"glob",
"File",
".",
"join",
"(",
"spec_dir",
",",
"'*.gemspec'",
")",
"spec_files",
".",
"each",
"do",
"|",
"spec_file",
"|",
"gemspec",
"=",
"self",
".",
"class",
".",
"load_specification",
"spec_file",
".",
"untaint",
"add_spec",
"gemspec",
"if",
"gemspec",
"end",
"end",
"self",
"end"
] |
Reconstruct the source index from the specifications in +spec_dirs+.
|
[
"Reconstruct",
"the",
"source",
"index",
"from",
"the",
"specifications",
"in",
"+",
"spec_dirs",
"+",
"."
] |
d110480098473531aebff319493dbb95a4d8e706
|
https://github.com/rr/rr/blob/d110480098473531aebff319493dbb95a4d8e706/spec/fixtures/rubygems_patch_for_187.rb#L119-L132
|
20,099
|
rr/rr
|
spec/fixtures/rubygems_patch_for_187.rb
|
Gem.SourceIndex.index_signature
|
def index_signature
require 'digest'
Digest::SHA256.new.hexdigest(@gems.keys.sort.join(',')).to_s
end
|
ruby
|
def index_signature
require 'digest'
Digest::SHA256.new.hexdigest(@gems.keys.sort.join(',')).to_s
end
|
[
"def",
"index_signature",
"require",
"'digest'",
"Digest",
"::",
"SHA256",
".",
"new",
".",
"hexdigest",
"(",
"@gems",
".",
"keys",
".",
"sort",
".",
"join",
"(",
"','",
")",
")",
".",
"to_s",
"end"
] |
The signature for the source index. Changes in the signature indicate a
change in the index.
|
[
"The",
"signature",
"for",
"the",
"source",
"index",
".",
"Changes",
"in",
"the",
"signature",
"indicate",
"a",
"change",
"in",
"the",
"index",
"."
] |
d110480098473531aebff319493dbb95a4d8e706
|
https://github.com/rr/rr/blob/d110480098473531aebff319493dbb95a4d8e706/spec/fixtures/rubygems_patch_for_187.rb#L228-L232
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.