repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
mavenlink/brainstem | lib/brainstem/presenter.rb | Brainstem.Presenter.calculate_sort_name_and_direction | def calculate_sort_name_and_direction(user_params = {})
default_column, default_direction = (configuration[:default_sort_order] || "updated_at:desc").split(":")
sort_name, direction = user_params['order'].to_s.split(":")
unless sort_name.present? && configuration[:sort_orders][sort_name]
sort_name = default_column
direction = default_direction
end
[sort_name, direction == 'desc' ? 'desc' : 'asc']
end | ruby | def calculate_sort_name_and_direction(user_params = {})
default_column, default_direction = (configuration[:default_sort_order] || "updated_at:desc").split(":")
sort_name, direction = user_params['order'].to_s.split(":")
unless sort_name.present? && configuration[:sort_orders][sort_name]
sort_name = default_column
direction = default_direction
end
[sort_name, direction == 'desc' ? 'desc' : 'asc']
end | [
"def",
"calculate_sort_name_and_direction",
"(",
"user_params",
"=",
"{",
"}",
")",
"default_column",
",",
"default_direction",
"=",
"(",
"configuration",
"[",
":default_sort_order",
"]",
"||",
"\"updated_at:desc\"",
")",
".",
"split",
"(",
"\":\"",
")",
"sort_name",
",",
"direction",
"=",
"user_params",
"[",
"'order'",
"]",
".",
"to_s",
".",
"split",
"(",
"\":\"",
")",
"unless",
"sort_name",
".",
"present?",
"&&",
"configuration",
"[",
":sort_orders",
"]",
"[",
"sort_name",
"]",
"sort_name",
"=",
"default_column",
"direction",
"=",
"default_direction",
"end",
"[",
"sort_name",
",",
"direction",
"==",
"'desc'",
"?",
"'desc'",
":",
"'asc'",
"]",
"end"
]
| Clean and validate a sort order and direction from user params. | [
"Clean",
"and",
"validate",
"a",
"sort",
"order",
"and",
"direction",
"from",
"user",
"params",
"."
]
| 99558d02e911ff8836f485b0eccdb63f0460e1e2 | https://github.com/mavenlink/brainstem/blob/99558d02e911ff8836f485b0eccdb63f0460e1e2/lib/brainstem/presenter.rb#L248-L257 | train |
mavenlink/brainstem | lib/brainstem/cli.rb | Brainstem.Cli.call | def call
if requested_command && commands.has_key?(requested_command)
self.command_method = commands[requested_command].method(:call)
end
command_method.call(_args.drop(1))
self
end | ruby | def call
if requested_command && commands.has_key?(requested_command)
self.command_method = commands[requested_command].method(:call)
end
command_method.call(_args.drop(1))
self
end | [
"def",
"call",
"if",
"requested_command",
"&&",
"commands",
".",
"has_key?",
"(",
"requested_command",
")",
"self",
".",
"command_method",
"=",
"commands",
"[",
"requested_command",
"]",
".",
"method",
"(",
":call",
")",
"end",
"command_method",
".",
"call",
"(",
"_args",
".",
"drop",
"(",
"1",
")",
")",
"self",
"end"
]
| Creates a new instance of the Cli to respond to user input.
Input is expected to be the name of the subcommand, followed by any
additional arguments.
Routes to an application endpoint depending on given options.
@return [Brainstem::Cli] the instance | [
"Creates",
"a",
"new",
"instance",
"of",
"the",
"Cli",
"to",
"respond",
"to",
"user",
"input",
"."
]
| 99558d02e911ff8836f485b0eccdb63f0460e1e2 | https://github.com/mavenlink/brainstem/blob/99558d02e911ff8836f485b0eccdb63f0460e1e2/lib/brainstem/cli.rb#L41-L49 | train |
Openwsman/openwsman | bindings/ruby/openwsman/openwsman.rb | Openwsman.ClientOptions.properties= | def properties= value
value.each do |k,v|
self.add_property k.to_s, v
end
end | ruby | def properties= value
value.each do |k,v|
self.add_property k.to_s, v
end
end | [
"def",
"properties",
"=",
"value",
"value",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"self",
".",
"add_property",
"k",
".",
"to_s",
",",
"v",
"end",
"end"
]
| assign hash to properties | [
"assign",
"hash",
"to",
"properties"
]
| 5efb1545dbac7e6d1e0a992f3e84ca12cea1c18e | https://github.com/Openwsman/openwsman/blob/5efb1545dbac7e6d1e0a992f3e84ca12cea1c18e/bindings/ruby/openwsman/openwsman.rb#L46-L50 | train |
Openwsman/openwsman | bindings/ruby/openwsman/openwsman.rb | Openwsman.ClientOptions.selectors= | def selectors= value
value.each do |k,v|
self.add_selector k.to_s, v
end
end | ruby | def selectors= value
value.each do |k,v|
self.add_selector k.to_s, v
end
end | [
"def",
"selectors",
"=",
"value",
"value",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"self",
".",
"add_selector",
"k",
".",
"to_s",
",",
"v",
"end",
"end"
]
| assign hash to selectors | [
"assign",
"hash",
"to",
"selectors"
]
| 5efb1545dbac7e6d1e0a992f3e84ca12cea1c18e | https://github.com/Openwsman/openwsman/blob/5efb1545dbac7e6d1e0a992f3e84ca12cea1c18e/bindings/ruby/openwsman/openwsman.rb#L52-L56 | train |
Openwsman/openwsman | bindings/ruby/parse_swig.rb | RDoc.Swig_Parser.handle_class_module | def handle_class_module(class_mod, class_name, options = {})
# puts "handle_class_module(#{class_mod}, #{class_name})"
progress(class_mod[0, 1])
parent = options[:parent]
parent_name = @known_classes[parent] || parent
if @@module_name
enclosure = @top_level.find_module_named(@@module_name)
else
enclosure = @top_level
end
if class_mod == "class"
cm = enclosure.add_class(NormalClass, class_name, parent_name)
@stats.num_classes += 1
else
cm = enclosure.add_module(NormalModule, class_name)
@stats.num_modules += 1
end
cm.record_location(enclosure.toplevel)
cm.body = options[:content]
cm.extend_name = options[:extend_name] || class_name
find_class_comment(class_name, cm)
@classes[class_name] = cm
@known_classes[class_name] = cm.full_name
cm
end | ruby | def handle_class_module(class_mod, class_name, options = {})
# puts "handle_class_module(#{class_mod}, #{class_name})"
progress(class_mod[0, 1])
parent = options[:parent]
parent_name = @known_classes[parent] || parent
if @@module_name
enclosure = @top_level.find_module_named(@@module_name)
else
enclosure = @top_level
end
if class_mod == "class"
cm = enclosure.add_class(NormalClass, class_name, parent_name)
@stats.num_classes += 1
else
cm = enclosure.add_module(NormalModule, class_name)
@stats.num_modules += 1
end
cm.record_location(enclosure.toplevel)
cm.body = options[:content]
cm.extend_name = options[:extend_name] || class_name
find_class_comment(class_name, cm)
@classes[class_name] = cm
@known_classes[class_name] = cm.full_name
cm
end | [
"def",
"handle_class_module",
"(",
"class_mod",
",",
"class_name",
",",
"options",
"=",
"{",
"}",
")",
"progress",
"(",
"class_mod",
"[",
"0",
",",
"1",
"]",
")",
"parent",
"=",
"options",
"[",
":parent",
"]",
"parent_name",
"=",
"@known_classes",
"[",
"parent",
"]",
"||",
"parent",
"if",
"@@module_name",
"enclosure",
"=",
"@top_level",
".",
"find_module_named",
"(",
"@@module_name",
")",
"else",
"enclosure",
"=",
"@top_level",
"end",
"if",
"class_mod",
"==",
"\"class\"",
"cm",
"=",
"enclosure",
".",
"add_class",
"(",
"NormalClass",
",",
"class_name",
",",
"parent_name",
")",
"@stats",
".",
"num_classes",
"+=",
"1",
"else",
"cm",
"=",
"enclosure",
".",
"add_module",
"(",
"NormalModule",
",",
"class_name",
")",
"@stats",
".",
"num_modules",
"+=",
"1",
"end",
"cm",
".",
"record_location",
"(",
"enclosure",
".",
"toplevel",
")",
"cm",
".",
"body",
"=",
"options",
"[",
":content",
"]",
"cm",
".",
"extend_name",
"=",
"options",
"[",
":extend_name",
"]",
"||",
"class_name",
"find_class_comment",
"(",
"class_name",
",",
"cm",
")",
"@classes",
"[",
"class_name",
"]",
"=",
"cm",
"@known_classes",
"[",
"class_name",
"]",
"=",
"cm",
".",
"full_name",
"cm",
"end"
]
| handle class or module
return enclosure | [
"handle",
"class",
"or",
"module"
]
| 5efb1545dbac7e6d1e0a992f3e84ca12cea1c18e | https://github.com/Openwsman/openwsman/blob/5efb1545dbac7e6d1e0a992f3e84ca12cea1c18e/bindings/ruby/parse_swig.rb#L152-L179 | train |
watsonbox/pocketsphinx-ruby | lib/pocketsphinx/speech_recognizer.rb | Pocketsphinx.SpeechRecognizer.recognize | def recognize(max_samples = 2048, &b)
unless ALGORITHMS.include?(algorithm)
raise NotImplementedError, "Unknown speech recognition algorithm: #{algorithm}"
end
start unless recognizing?
FFI::MemoryPointer.new(:int16, max_samples) do |buffer|
loop do
send("recognize_#{algorithm}", max_samples, buffer, &b) or break
end
end
ensure
stop
end | ruby | def recognize(max_samples = 2048, &b)
unless ALGORITHMS.include?(algorithm)
raise NotImplementedError, "Unknown speech recognition algorithm: #{algorithm}"
end
start unless recognizing?
FFI::MemoryPointer.new(:int16, max_samples) do |buffer|
loop do
send("recognize_#{algorithm}", max_samples, buffer, &b) or break
end
end
ensure
stop
end | [
"def",
"recognize",
"(",
"max_samples",
"=",
"2048",
",",
"&",
"b",
")",
"unless",
"ALGORITHMS",
".",
"include?",
"(",
"algorithm",
")",
"raise",
"NotImplementedError",
",",
"\"Unknown speech recognition algorithm: #{algorithm}\"",
"end",
"start",
"unless",
"recognizing?",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":int16",
",",
"max_samples",
")",
"do",
"|",
"buffer",
"|",
"loop",
"do",
"send",
"(",
"\"recognize_#{algorithm}\"",
",",
"max_samples",
",",
"buffer",
",",
"&",
"b",
")",
"or",
"break",
"end",
"end",
"ensure",
"stop",
"end"
]
| Recognize speech and yield hypotheses in infinite loop
@param [Fixnum] max_samples Number of samples to process at a time | [
"Recognize",
"speech",
"and",
"yield",
"hypotheses",
"in",
"infinite",
"loop"
]
| 12c71c35285c38b42bd7779c8246923bd5be150f | https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/speech_recognizer.rb#L46-L60 | train |
watsonbox/pocketsphinx-ruby | lib/pocketsphinx/speech_recognizer.rb | Pocketsphinx.SpeechRecognizer.recognize_continuous | def recognize_continuous(max_samples, buffer)
process_audio(buffer, max_samples).tap do
if hypothesis = decoder.hypothesis
decoder.end_utterance
yield hypothesis
decoder.start_utterance
end
end
end | ruby | def recognize_continuous(max_samples, buffer)
process_audio(buffer, max_samples).tap do
if hypothesis = decoder.hypothesis
decoder.end_utterance
yield hypothesis
decoder.start_utterance
end
end
end | [
"def",
"recognize_continuous",
"(",
"max_samples",
",",
"buffer",
")",
"process_audio",
"(",
"buffer",
",",
"max_samples",
")",
".",
"tap",
"do",
"if",
"hypothesis",
"=",
"decoder",
".",
"hypothesis",
"decoder",
".",
"end_utterance",
"yield",
"hypothesis",
"decoder",
".",
"start_utterance",
"end",
"end",
"end"
]
| Yields as soon as any hypothesis is available | [
"Yields",
"as",
"soon",
"as",
"any",
"hypothesis",
"is",
"available"
]
| 12c71c35285c38b42bd7779c8246923bd5be150f | https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/speech_recognizer.rb#L108-L118 | train |
watsonbox/pocketsphinx-ruby | lib/pocketsphinx/decoder.rb | Pocketsphinx.Decoder.decode | def decode(audio_path_or_file, max_samples = 2048)
case audio_path_or_file
when String
File.open(audio_path_or_file, 'rb') { |f| decode_raw(f, max_samples) }
else
decode_raw(audio_path_or_file, max_samples)
end
end | ruby | def decode(audio_path_or_file, max_samples = 2048)
case audio_path_or_file
when String
File.open(audio_path_or_file, 'rb') { |f| decode_raw(f, max_samples) }
else
decode_raw(audio_path_or_file, max_samples)
end
end | [
"def",
"decode",
"(",
"audio_path_or_file",
",",
"max_samples",
"=",
"2048",
")",
"case",
"audio_path_or_file",
"when",
"String",
"File",
".",
"open",
"(",
"audio_path_or_file",
",",
"'rb'",
")",
"{",
"|",
"f",
"|",
"decode_raw",
"(",
"f",
",",
"max_samples",
")",
"}",
"else",
"decode_raw",
"(",
"audio_path_or_file",
",",
"max_samples",
")",
"end",
"end"
]
| Decode a raw audio stream as a single utterance, opening a file if path given
See #decode_raw
@param [IO] audio_path_or_file The raw audio stream or file path to decode as a single utterance
@param [Fixnum] max_samples The maximum samples to process from the stream on each iteration | [
"Decode",
"a",
"raw",
"audio",
"stream",
"as",
"a",
"single",
"utterance",
"opening",
"a",
"file",
"if",
"path",
"given"
]
| 12c71c35285c38b42bd7779c8246923bd5be150f | https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/decoder.rb#L54-L61 | train |
watsonbox/pocketsphinx-ruby | lib/pocketsphinx/decoder.rb | Pocketsphinx.Decoder.decode_raw | def decode_raw(audio_file, max_samples = 2048)
start_utterance
FFI::MemoryPointer.new(:int16, max_samples) do |buffer|
while data = audio_file.read(max_samples * 2)
buffer.write_string(data)
process_raw(buffer, data.length / 2)
end
end
end_utterance
end | ruby | def decode_raw(audio_file, max_samples = 2048)
start_utterance
FFI::MemoryPointer.new(:int16, max_samples) do |buffer|
while data = audio_file.read(max_samples * 2)
buffer.write_string(data)
process_raw(buffer, data.length / 2)
end
end
end_utterance
end | [
"def",
"decode_raw",
"(",
"audio_file",
",",
"max_samples",
"=",
"2048",
")",
"start_utterance",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":int16",
",",
"max_samples",
")",
"do",
"|",
"buffer",
"|",
"while",
"data",
"=",
"audio_file",
".",
"read",
"(",
"max_samples",
"*",
"2",
")",
"buffer",
".",
"write_string",
"(",
"data",
")",
"process_raw",
"(",
"buffer",
",",
"data",
".",
"length",
"/",
"2",
")",
"end",
"end",
"end_utterance",
"end"
]
| Decode a raw audio stream as a single utterance.
No headers are recognized in this files. The configuration parameters samprate
and input_endian are used to determine the sampling rate and endianness of the stream,
respectively. Audio is always assumed to be 16-bit signed PCM.
@param [IO] audio_file The raw audio stream to decode as a single utterance
@param [Fixnum] max_samples The maximum samples to process from the stream on each iteration | [
"Decode",
"a",
"raw",
"audio",
"stream",
"as",
"a",
"single",
"utterance",
"."
]
| 12c71c35285c38b42bd7779c8246923bd5be150f | https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/decoder.rb#L71-L82 | train |
watsonbox/pocketsphinx-ruby | lib/pocketsphinx/decoder.rb | Pocketsphinx.Decoder.process_raw | def process_raw(buffer, size, no_search = false, full_utt = false)
api_call :ps_process_raw, ps_decoder, buffer, size, no_search ? 1 : 0, full_utt ? 1 : 0
end | ruby | def process_raw(buffer, size, no_search = false, full_utt = false)
api_call :ps_process_raw, ps_decoder, buffer, size, no_search ? 1 : 0, full_utt ? 1 : 0
end | [
"def",
"process_raw",
"(",
"buffer",
",",
"size",
",",
"no_search",
"=",
"false",
",",
"full_utt",
"=",
"false",
")",
"api_call",
":ps_process_raw",
",",
"ps_decoder",
",",
"buffer",
",",
"size",
",",
"no_search",
"?",
"1",
":",
"0",
",",
"full_utt",
"?",
"1",
":",
"0",
"end"
]
| Decode raw audio data.
@param [Boolean] no_search If non-zero, perform feature extraction but don't do any
recognition yet. This may be necessary if your processor has trouble doing recognition in
real-time.
@param [Boolean] full_utt If non-zero, this block of data is a full utterance
worth of data. This may allow the recognizer to produce more accurate results.
@return Number of frames of data searched | [
"Decode",
"raw",
"audio",
"data",
"."
]
| 12c71c35285c38b42bd7779c8246923bd5be150f | https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/decoder.rb#L92-L94 | train |
watsonbox/pocketsphinx-ruby | lib/pocketsphinx/decoder.rb | Pocketsphinx.Decoder.log_prob_to_linear | def log_prob_to_linear(log_prob)
logmath = ps_api.ps_get_logmath(ps_decoder)
ps_api.logmath_exp(logmath, log_prob)
end | ruby | def log_prob_to_linear(log_prob)
logmath = ps_api.ps_get_logmath(ps_decoder)
ps_api.logmath_exp(logmath, log_prob)
end | [
"def",
"log_prob_to_linear",
"(",
"log_prob",
")",
"logmath",
"=",
"ps_api",
".",
"ps_get_logmath",
"(",
"ps_decoder",
")",
"ps_api",
".",
"logmath_exp",
"(",
"logmath",
",",
"log_prob",
")",
"end"
]
| Convert logarithmic probability to linear floating point | [
"Convert",
"logarithmic",
"probability",
"to",
"linear",
"floating",
"point"
]
| 12c71c35285c38b42bd7779c8246923bd5be150f | https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/decoder.rb#L216-L219 | train |
watsonbox/pocketsphinx-ruby | lib/pocketsphinx/microphone.rb | Pocketsphinx.Microphone.read_audio | def read_audio(buffer, max_samples = 2048)
samples = ps_api.ad_read(@ps_audio_device, buffer, max_samples)
samples if samples >= 0
end | ruby | def read_audio(buffer, max_samples = 2048)
samples = ps_api.ad_read(@ps_audio_device, buffer, max_samples)
samples if samples >= 0
end | [
"def",
"read_audio",
"(",
"buffer",
",",
"max_samples",
"=",
"2048",
")",
"samples",
"=",
"ps_api",
".",
"ad_read",
"(",
"@ps_audio_device",
",",
"buffer",
",",
"max_samples",
")",
"samples",
"if",
"samples",
">=",
"0",
"end"
]
| Read next block of audio samples while recording; read upto max samples into buf.
@param [FFI::Pointer] buffer 16bit buffer of at least max_samples in size
@params [Fixnum] max_samples The maximum number of samples to read from the audio device
@return [Fixnum] Samples actually read (could be 0 since non-blocking); nil if not
recording and no more samples remaining to be read from most recent recording. | [
"Read",
"next",
"block",
"of",
"audio",
"samples",
"while",
"recording",
";",
"read",
"upto",
"max",
"samples",
"into",
"buf",
"."
]
| 12c71c35285c38b42bd7779c8246923bd5be150f | https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/microphone.rb#L52-L55 | train |
watsonbox/pocketsphinx-ruby | lib/pocketsphinx/audio_file.rb | Pocketsphinx.AudioFile.read_audio | def read_audio(buffer, max_samples = 2048)
if file.nil?
raise "Can't read audio: use AudioFile#start_recording to open the file first"
end
if data = file.read(max_samples * 2)
buffer.write_string(data)
data.length / 2
end
end | ruby | def read_audio(buffer, max_samples = 2048)
if file.nil?
raise "Can't read audio: use AudioFile#start_recording to open the file first"
end
if data = file.read(max_samples * 2)
buffer.write_string(data)
data.length / 2
end
end | [
"def",
"read_audio",
"(",
"buffer",
",",
"max_samples",
"=",
"2048",
")",
"if",
"file",
".",
"nil?",
"raise",
"\"Can't read audio: use AudioFile#start_recording to open the file first\"",
"end",
"if",
"data",
"=",
"file",
".",
"read",
"(",
"max_samples",
"*",
"2",
")",
"buffer",
".",
"write_string",
"(",
"data",
")",
"data",
".",
"length",
"/",
"2",
"end",
"end"
]
| Read next block of audio samples from file; up to max samples into buffer.
@param [FFI::Pointer] buffer 16bit buffer of at least max_samples in size
@params [Fixnum] max_samples The maximum number of samples to read from the audio file
@return [Fixnum] Samples actually read; nil if EOF | [
"Read",
"next",
"block",
"of",
"audio",
"samples",
"from",
"file",
";",
"up",
"to",
"max",
"samples",
"into",
"buffer",
"."
]
| 12c71c35285c38b42bd7779c8246923bd5be150f | https://github.com/watsonbox/pocketsphinx-ruby/blob/12c71c35285c38b42bd7779c8246923bd5be150f/lib/pocketsphinx/audio_file.rb#L9-L18 | train |
zk-ruby/zk | lib/zk/threadpool.rb | ZK.Threadpool.on_threadpool? | def on_threadpool?
tp = nil
@mutex.synchronize do
return false unless @threadpool # you can't dup nil
tp = @threadpool.dup
end
tp.respond_to?(:include?) and tp.include?(Thread.current)
end | ruby | def on_threadpool?
tp = nil
@mutex.synchronize do
return false unless @threadpool # you can't dup nil
tp = @threadpool.dup
end
tp.respond_to?(:include?) and tp.include?(Thread.current)
end | [
"def",
"on_threadpool?",
"tp",
"=",
"nil",
"@mutex",
".",
"synchronize",
"do",
"return",
"false",
"unless",
"@threadpool",
"tp",
"=",
"@threadpool",
".",
"dup",
"end",
"tp",
".",
"respond_to?",
"(",
":include?",
")",
"and",
"tp",
".",
"include?",
"(",
"Thread",
".",
"current",
")",
"end"
]
| returns true if the current thread is one of the threadpool threads | [
"returns",
"true",
"if",
"the",
"current",
"thread",
"is",
"one",
"of",
"the",
"threadpool",
"threads"
]
| 155db85653c3831cc005140b5fd58adc80a54d8e | https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/threadpool.rb#L76-L85 | train |
zk-ruby/zk | lib/zk/event_handler.rb | ZK.EventHandler.process | def process(event, watch_type = nil)
@zk.raw_event_handler(event)
logger.debug { "EventHandler#process dispatching event for #{watch_type.inspect}: #{event.inspect}" }# unless event.type == -1
event.zk = @zk
cb_keys =
if event.node_event?
[event.path, ALL_NODE_EVENTS_KEY]
elsif event.session_event?
[state_key(event.state), ALL_STATE_EVENTS_KEY]
else
raise ZKError, "don't know how to process event: #{event.inspect}"
end
cb_ary = synchronize do
clear_watch_restrictions(event, watch_type)
@callbacks.values_at(*cb_keys)
end
cb_ary.flatten! # takes care of not modifying original arrays
cb_ary.compact!
# we only filter for node events
if event.node_event?
interest_key = event.interest_key
cb_ary.select! { |sub| sub.interests.include?(interest_key) }
end
safe_call(cb_ary, event)
end | ruby | def process(event, watch_type = nil)
@zk.raw_event_handler(event)
logger.debug { "EventHandler#process dispatching event for #{watch_type.inspect}: #{event.inspect}" }# unless event.type == -1
event.zk = @zk
cb_keys =
if event.node_event?
[event.path, ALL_NODE_EVENTS_KEY]
elsif event.session_event?
[state_key(event.state), ALL_STATE_EVENTS_KEY]
else
raise ZKError, "don't know how to process event: #{event.inspect}"
end
cb_ary = synchronize do
clear_watch_restrictions(event, watch_type)
@callbacks.values_at(*cb_keys)
end
cb_ary.flatten! # takes care of not modifying original arrays
cb_ary.compact!
# we only filter for node events
if event.node_event?
interest_key = event.interest_key
cb_ary.select! { |sub| sub.interests.include?(interest_key) }
end
safe_call(cb_ary, event)
end | [
"def",
"process",
"(",
"event",
",",
"watch_type",
"=",
"nil",
")",
"@zk",
".",
"raw_event_handler",
"(",
"event",
")",
"logger",
".",
"debug",
"{",
"\"EventHandler#process dispatching event for #{watch_type.inspect}: #{event.inspect}\"",
"}",
"event",
".",
"zk",
"=",
"@zk",
"cb_keys",
"=",
"if",
"event",
".",
"node_event?",
"[",
"event",
".",
"path",
",",
"ALL_NODE_EVENTS_KEY",
"]",
"elsif",
"event",
".",
"session_event?",
"[",
"state_key",
"(",
"event",
".",
"state",
")",
",",
"ALL_STATE_EVENTS_KEY",
"]",
"else",
"raise",
"ZKError",
",",
"\"don't know how to process event: #{event.inspect}\"",
"end",
"cb_ary",
"=",
"synchronize",
"do",
"clear_watch_restrictions",
"(",
"event",
",",
"watch_type",
")",
"@callbacks",
".",
"values_at",
"(",
"*",
"cb_keys",
")",
"end",
"cb_ary",
".",
"flatten!",
"cb_ary",
".",
"compact!",
"if",
"event",
".",
"node_event?",
"interest_key",
"=",
"event",
".",
"interest_key",
"cb_ary",
".",
"select!",
"{",
"|",
"sub",
"|",
"sub",
".",
"interests",
".",
"include?",
"(",
"interest_key",
")",
"}",
"end",
"safe_call",
"(",
"cb_ary",
",",
"event",
")",
"end"
]
| called from the Client registered callback when an event fires
@note this is *ONLY* dealing with asynchronous callbacks! watchers
and session events go through here, NOT anything else!!
@private | [
"called",
"from",
"the",
"Client",
"registered",
"callback",
"when",
"an",
"event",
"fires"
]
| 155db85653c3831cc005140b5fd58adc80a54d8e | https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/event_handler.rb#L163-L194 | train |
zk-ruby/zk | lib/zk/event_handler.rb | ZK.EventHandler.restricting_new_watches_for? | def restricting_new_watches_for?(watch_type, path)
synchronize do
if set = @outstanding_watches[watch_type]
return set.include?(path)
end
end
false
end | ruby | def restricting_new_watches_for?(watch_type, path)
synchronize do
if set = @outstanding_watches[watch_type]
return set.include?(path)
end
end
false
end | [
"def",
"restricting_new_watches_for?",
"(",
"watch_type",
",",
"path",
")",
"synchronize",
"do",
"if",
"set",
"=",
"@outstanding_watches",
"[",
"watch_type",
"]",
"return",
"set",
".",
"include?",
"(",
"path",
")",
"end",
"end",
"false",
"end"
]
| returns true if there's a pending watch of type for path
@private | [
"returns",
"true",
"if",
"there",
"s",
"a",
"pending",
"watch",
"of",
"type",
"for",
"path"
]
| 155db85653c3831cc005140b5fd58adc80a54d8e | https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/event_handler.rb#L270-L278 | train |
zk-ruby/zk | lib/zk/message_queue.rb | ZK.MessageQueue.delete_message | def delete_message(message_title)
full_path = "#{full_queue_path}/#{message_title}"
locker = @zk.locker("#{full_queue_path}/#{message_title}")
if locker.lock!
begin
@zk.delete(full_path)
return true
ensure
locker.unlock!
end
else
return false
end
end | ruby | def delete_message(message_title)
full_path = "#{full_queue_path}/#{message_title}"
locker = @zk.locker("#{full_queue_path}/#{message_title}")
if locker.lock!
begin
@zk.delete(full_path)
return true
ensure
locker.unlock!
end
else
return false
end
end | [
"def",
"delete_message",
"(",
"message_title",
")",
"full_path",
"=",
"\"#{full_queue_path}/#{message_title}\"",
"locker",
"=",
"@zk",
".",
"locker",
"(",
"\"#{full_queue_path}/#{message_title}\"",
")",
"if",
"locker",
".",
"lock!",
"begin",
"@zk",
".",
"delete",
"(",
"full_path",
")",
"return",
"true",
"ensure",
"locker",
".",
"unlock!",
"end",
"else",
"return",
"false",
"end",
"end"
]
| you barely ever need to actually use this method but lets you remove a
message from the queue by specifying its title
@param [String] message_title the title of the message to remove | [
"you",
"barely",
"ever",
"need",
"to",
"actually",
"use",
"this",
"method",
"but",
"lets",
"you",
"remove",
"a",
"message",
"from",
"the",
"queue",
"by",
"specifying",
"its",
"title"
]
| 155db85653c3831cc005140b5fd58adc80a54d8e | https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/message_queue.rb#L58-L71 | train |
zk-ruby/zk | lib/zk/message_queue.rb | ZK.MessageQueue.destroy! | def destroy!
unsubscribe # first thing, make sure we don't get any callbacks related to this
children = @zk.children(full_queue_path)
locks = []
children.each do |path|
lock = @zk.locker("#{full_queue_path}/#{path}")
lock.lock! # XXX(slyphon): should this be a blocking lock?
locks << lock
end
children.each do |path|
begin
@zk.delete("#{full_queue_path}/#{path}")
rescue ZK::Exceptions::NoNode
end
end
begin
@zk.delete(full_queue_path)
rescue ZK::Exceptions::NoNode
end
locks.each do |lock|
lock.unlock!
end
end | ruby | def destroy!
unsubscribe # first thing, make sure we don't get any callbacks related to this
children = @zk.children(full_queue_path)
locks = []
children.each do |path|
lock = @zk.locker("#{full_queue_path}/#{path}")
lock.lock! # XXX(slyphon): should this be a blocking lock?
locks << lock
end
children.each do |path|
begin
@zk.delete("#{full_queue_path}/#{path}")
rescue ZK::Exceptions::NoNode
end
end
begin
@zk.delete(full_queue_path)
rescue ZK::Exceptions::NoNode
end
locks.each do |lock|
lock.unlock!
end
end | [
"def",
"destroy!",
"unsubscribe",
"children",
"=",
"@zk",
".",
"children",
"(",
"full_queue_path",
")",
"locks",
"=",
"[",
"]",
"children",
".",
"each",
"do",
"|",
"path",
"|",
"lock",
"=",
"@zk",
".",
"locker",
"(",
"\"#{full_queue_path}/#{path}\"",
")",
"lock",
".",
"lock!",
"locks",
"<<",
"lock",
"end",
"children",
".",
"each",
"do",
"|",
"path",
"|",
"begin",
"@zk",
".",
"delete",
"(",
"\"#{full_queue_path}/#{path}\"",
")",
"rescue",
"ZK",
"::",
"Exceptions",
"::",
"NoNode",
"end",
"end",
"begin",
"@zk",
".",
"delete",
"(",
"full_queue_path",
")",
"rescue",
"ZK",
"::",
"Exceptions",
"::",
"NoNode",
"end",
"locks",
".",
"each",
"do",
"|",
"lock",
"|",
"lock",
".",
"unlock!",
"end",
"end"
]
| highly destructive method!
WARNING! Will delete the queue and all messages in it | [
"highly",
"destructive",
"method!",
"WARNING!",
"Will",
"delete",
"the",
"queue",
"and",
"all",
"messages",
"in",
"it"
]
| 155db85653c3831cc005140b5fd58adc80a54d8e | https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/message_queue.rb#L113-L137 | train |
zk-ruby/zk | lib/zk/threaded_callback.rb | ZK.ThreadedCallback.shutdown | def shutdown(timeout=5)
# logger.debug { "#{self.class}##{__method__}" }
@mutex.lock
begin
return true if @state == :shutdown
@state = :shutdown
@cond.broadcast
ensure
@mutex.unlock rescue nil
end
return true unless @thread
unless @thread.join(timeout) == @thread
logger.error { "#{self.class} timed out waiting for dispatch thread, callback: #{callback.inspect}" }
return false
end
true
end | ruby | def shutdown(timeout=5)
# logger.debug { "#{self.class}##{__method__}" }
@mutex.lock
begin
return true if @state == :shutdown
@state = :shutdown
@cond.broadcast
ensure
@mutex.unlock rescue nil
end
return true unless @thread
unless @thread.join(timeout) == @thread
logger.error { "#{self.class} timed out waiting for dispatch thread, callback: #{callback.inspect}" }
return false
end
true
end | [
"def",
"shutdown",
"(",
"timeout",
"=",
"5",
")",
"@mutex",
".",
"lock",
"begin",
"return",
"true",
"if",
"@state",
"==",
":shutdown",
"@state",
"=",
":shutdown",
"@cond",
".",
"broadcast",
"ensure",
"@mutex",
".",
"unlock",
"rescue",
"nil",
"end",
"return",
"true",
"unless",
"@thread",
"unless",
"@thread",
".",
"join",
"(",
"timeout",
")",
"==",
"@thread",
"logger",
".",
"error",
"{",
"\"#{self.class} timed out waiting for dispatch thread, callback: #{callback.inspect}\"",
"}",
"return",
"false",
"end",
"true",
"end"
]
| how long to wait on thread shutdown before we return | [
"how",
"long",
"to",
"wait",
"on",
"thread",
"shutdown",
"before",
"we",
"return"
]
| 155db85653c3831cc005140b5fd58adc80a54d8e | https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/threaded_callback.rb#L29-L50 | train |
zk-ruby/zk | lib/zk/node_deletion_watcher.rb | ZK.NodeDeletionWatcher.wait_until_blocked | def wait_until_blocked(timeout=nil)
@mutex.synchronize do
return true unless @blocked == NOT_YET
start = Time.now
time_to_stop = timeout ? (start + timeout) : nil
logger.debug { "#{__method__} @blocked: #{@blocked.inspect} about to wait" }
@cond.wait(timeout)
if (time_to_stop and (Time.now > time_to_stop)) and (@blocked == NOT_YET)
return nil
end
(@blocked == NOT_YET) ? nil : true
end
end | ruby | def wait_until_blocked(timeout=nil)
@mutex.synchronize do
return true unless @blocked == NOT_YET
start = Time.now
time_to_stop = timeout ? (start + timeout) : nil
logger.debug { "#{__method__} @blocked: #{@blocked.inspect} about to wait" }
@cond.wait(timeout)
if (time_to_stop and (Time.now > time_to_stop)) and (@blocked == NOT_YET)
return nil
end
(@blocked == NOT_YET) ? nil : true
end
end | [
"def",
"wait_until_blocked",
"(",
"timeout",
"=",
"nil",
")",
"@mutex",
".",
"synchronize",
"do",
"return",
"true",
"unless",
"@blocked",
"==",
"NOT_YET",
"start",
"=",
"Time",
".",
"now",
"time_to_stop",
"=",
"timeout",
"?",
"(",
"start",
"+",
"timeout",
")",
":",
"nil",
"logger",
".",
"debug",
"{",
"\"#{__method__} @blocked: #{@blocked.inspect} about to wait\"",
"}",
"@cond",
".",
"wait",
"(",
"timeout",
")",
"if",
"(",
"time_to_stop",
"and",
"(",
"Time",
".",
"now",
">",
"time_to_stop",
")",
")",
"and",
"(",
"@blocked",
"==",
"NOT_YET",
")",
"return",
"nil",
"end",
"(",
"@blocked",
"==",
"NOT_YET",
")",
"?",
"nil",
":",
"true",
"end",
"end"
]
| this is for testing, allows us to wait until this object has gone into
blocking state.
avoids the race where if we have already been blocked and released
this will not block the caller
pass optional timeout to return after that amount of time or nil to block
forever
@return [true] if we have been blocked previously or are currently blocked,
@return [nil] if we timeout | [
"this",
"is",
"for",
"testing",
"allows",
"us",
"to",
"wait",
"until",
"this",
"object",
"has",
"gone",
"into",
"blocking",
"state",
"."
]
| 155db85653c3831cc005140b5fd58adc80a54d8e | https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/node_deletion_watcher.rb#L84-L100 | train |
zk-ruby/zk | lib/zk/node_deletion_watcher.rb | ZK.NodeDeletionWatcher.wait_for_result | def wait_for_result(timeout)
# do the deadline maths
time_to_stop = timeout ? (Time.now + timeout) : nil # slight time slippage between here
#
until @result #
if timeout # and here
now = Time.now
if @result
return
elsif (now >= time_to_stop)
@result = TIMED_OUT
return
end
@cond.wait(time_to_stop.to_f - now.to_f)
else
@cond.wait_until { @result }
end
end
end | ruby | def wait_for_result(timeout)
# do the deadline maths
time_to_stop = timeout ? (Time.now + timeout) : nil # slight time slippage between here
#
until @result #
if timeout # and here
now = Time.now
if @result
return
elsif (now >= time_to_stop)
@result = TIMED_OUT
return
end
@cond.wait(time_to_stop.to_f - now.to_f)
else
@cond.wait_until { @result }
end
end
end | [
"def",
"wait_for_result",
"(",
"timeout",
")",
"time_to_stop",
"=",
"timeout",
"?",
"(",
"Time",
".",
"now",
"+",
"timeout",
")",
":",
"nil",
"until",
"@result",
"if",
"timeout",
"now",
"=",
"Time",
".",
"now",
"if",
"@result",
"return",
"elsif",
"(",
"now",
">=",
"time_to_stop",
")",
"@result",
"=",
"TIMED_OUT",
"return",
"end",
"@cond",
".",
"wait",
"(",
"time_to_stop",
".",
"to_f",
"-",
"now",
".",
"to_f",
")",
"else",
"@cond",
".",
"wait_until",
"{",
"@result",
"}",
"end",
"end",
"end"
]
| this method must be synchronized on @mutex, obviously | [
"this",
"method",
"must",
"be",
"synchronized",
"on"
]
| 155db85653c3831cc005140b5fd58adc80a54d8e | https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/node_deletion_watcher.rb#L177-L197 | train |
zk-ruby/zk | lib/zk/node_deletion_watcher.rb | ZK.NodeDeletionWatcher.watch_appropriate_nodes | def watch_appropriate_nodes
remaining_paths.last( threshold + 1 ).reverse_each do |path|
next if watched_paths.include? path
watched_paths << path
finish_node(path) unless zk.exists?(path, :watch => true)
end
end | ruby | def watch_appropriate_nodes
remaining_paths.last( threshold + 1 ).reverse_each do |path|
next if watched_paths.include? path
watched_paths << path
finish_node(path) unless zk.exists?(path, :watch => true)
end
end | [
"def",
"watch_appropriate_nodes",
"remaining_paths",
".",
"last",
"(",
"threshold",
"+",
"1",
")",
".",
"reverse_each",
"do",
"|",
"path",
"|",
"next",
"if",
"watched_paths",
".",
"include?",
"path",
"watched_paths",
"<<",
"path",
"finish_node",
"(",
"path",
")",
"unless",
"zk",
".",
"exists?",
"(",
"path",
",",
":watch",
"=>",
"true",
")",
"end",
"end"
]
| ensures that threshold + 1 nodes are being watched | [
"ensures",
"that",
"threshold",
"+",
"1",
"nodes",
"are",
"being",
"watched"
]
| 155db85653c3831cc005140b5fd58adc80a54d8e | https://github.com/zk-ruby/zk/blob/155db85653c3831cc005140b5fd58adc80a54d8e/lib/zk/node_deletion_watcher.rb#L237-L243 | train |
fog/fog-core | lib/fog/core/services_mixin.rb | Fog.ServicesMixin.require_service_provider_library | def require_service_provider_library(service, provider)
require "fog/#{provider}/#{service}"
rescue LoadError # Try to require the service provider in an alternate location
Fog::Logger.deprecation("Unable to require fog/#{provider}/#{service}")
Fog::Logger.deprecation(
format(E_SERVICE_PROVIDER_PATH, service: service, provider: provider)
)
require "fog/#{service}/#{provider}"
end | ruby | def require_service_provider_library(service, provider)
require "fog/#{provider}/#{service}"
rescue LoadError # Try to require the service provider in an alternate location
Fog::Logger.deprecation("Unable to require fog/#{provider}/#{service}")
Fog::Logger.deprecation(
format(E_SERVICE_PROVIDER_PATH, service: service, provider: provider)
)
require "fog/#{service}/#{provider}"
end | [
"def",
"require_service_provider_library",
"(",
"service",
",",
"provider",
")",
"require",
"\"fog/#{provider}/#{service}\"",
"rescue",
"LoadError",
"Fog",
"::",
"Logger",
".",
"deprecation",
"(",
"\"Unable to require fog/#{provider}/#{service}\"",
")",
"Fog",
"::",
"Logger",
".",
"deprecation",
"(",
"format",
"(",
"E_SERVICE_PROVIDER_PATH",
",",
"service",
":",
"service",
",",
"provider",
":",
"provider",
")",
")",
"require",
"\"fog/#{service}/#{provider}\"",
"end"
]
| This method should be removed once all providers are extracted.
Bundler will correctly require all dependencies automatically and thus
fog-core wont need to know any specifics providers. Each provider will
have to load its dependencies. | [
"This",
"method",
"should",
"be",
"removed",
"once",
"all",
"providers",
"are",
"extracted",
".",
"Bundler",
"will",
"correctly",
"require",
"all",
"dependencies",
"automatically",
"and",
"thus",
"fog",
"-",
"core",
"wont",
"need",
"to",
"know",
"any",
"specifics",
"providers",
".",
"Each",
"provider",
"will",
"have",
"to",
"load",
"its",
"dependencies",
"."
]
| a60d4001981b8d4ca9a803ae9cac07f3a99fad23 | https://github.com/fog/fog-core/blob/a60d4001981b8d4ca9a803ae9cac07f3a99fad23/lib/fog/core/services_mixin.rb#L46-L54 | train |
boxen/boxen | lib/boxen/flags.rb | Boxen.Flags.apply | def apply(config)
config.debug = debug?
config.fde = fde? if config.fde?
config.homedir = homedir if homedir
config.logfile = logfile if logfile
config.login = login if login
config.token = token if token
config.pretend = pretend?
config.profile = profile?
config.future_parser = future_parser?
config.report = report?
config.graph = graph?
config.srcdir = srcdir if srcdir
config.stealth = stealth?
config.user = user if user
config.color = color?
config
end | ruby | def apply(config)
config.debug = debug?
config.fde = fde? if config.fde?
config.homedir = homedir if homedir
config.logfile = logfile if logfile
config.login = login if login
config.token = token if token
config.pretend = pretend?
config.profile = profile?
config.future_parser = future_parser?
config.report = report?
config.graph = graph?
config.srcdir = srcdir if srcdir
config.stealth = stealth?
config.user = user if user
config.color = color?
config
end | [
"def",
"apply",
"(",
"config",
")",
"config",
".",
"debug",
"=",
"debug?",
"config",
".",
"fde",
"=",
"fde?",
"if",
"config",
".",
"fde?",
"config",
".",
"homedir",
"=",
"homedir",
"if",
"homedir",
"config",
".",
"logfile",
"=",
"logfile",
"if",
"logfile",
"config",
".",
"login",
"=",
"login",
"if",
"login",
"config",
".",
"token",
"=",
"token",
"if",
"token",
"config",
".",
"pretend",
"=",
"pretend?",
"config",
".",
"profile",
"=",
"profile?",
"config",
".",
"future_parser",
"=",
"future_parser?",
"config",
".",
"report",
"=",
"report?",
"config",
".",
"graph",
"=",
"graph?",
"config",
".",
"srcdir",
"=",
"srcdir",
"if",
"srcdir",
"config",
".",
"stealth",
"=",
"stealth?",
"config",
".",
"user",
"=",
"user",
"if",
"user",
"config",
".",
"color",
"=",
"color?",
"config",
"end"
]
| Create a new instance, optionally providing CLI `args` to
parse immediately.
Apply these flags to `config`. Returns `config`. | [
"Create",
"a",
"new",
"instance",
"optionally",
"providing",
"CLI",
"args",
"to",
"parse",
"immediately",
".",
"Apply",
"these",
"flags",
"to",
"config",
".",
"Returns",
"config",
"."
]
| a11fcba2ee9fe9ad60109e36e4ec481c476c98e9 | https://github.com/boxen/boxen/blob/a11fcba2ee9fe9ad60109e36e4ec481c476c98e9/lib/boxen/flags.rb#L160-L178 | train |
AnkurGel/Instamojo-rb | lib/common_object.rb | Instamojo.CommonObject.construct_hash | def construct_hash
vars = instance_variables.reject { |x| [:@client, :@original].include? x }
Hash[vars.map { |key| [key.to_s[1..key.length], instance_variable_get(key)] }]
end | ruby | def construct_hash
vars = instance_variables.reject { |x| [:@client, :@original].include? x }
Hash[vars.map { |key| [key.to_s[1..key.length], instance_variable_get(key)] }]
end | [
"def",
"construct_hash",
"vars",
"=",
"instance_variables",
".",
"reject",
"{",
"|",
"x",
"|",
"[",
":@client",
",",
":@original",
"]",
".",
"include?",
"x",
"}",
"Hash",
"[",
"vars",
".",
"map",
"{",
"|",
"key",
"|",
"[",
"key",
".",
"to_s",
"[",
"1",
"..",
"key",
".",
"length",
"]",
",",
"instance_variable_get",
"(",
"key",
")",
"]",
"}",
"]",
"end"
]
| Construct hash from mutated parameters | [
"Construct",
"hash",
"from",
"mutated",
"parameters"
]
| 39972c695bcb460673bf29de01cb6b47b57baa58 | https://github.com/AnkurGel/Instamojo-rb/blob/39972c695bcb460673bf29de01cb6b47b57baa58/lib/common_object.rb#L35-L38 | train |
whazzmaster/fitgem | lib/fitgem/notifications.rb | Fitgem.Client.create_subscription | def create_subscription(opts)
resp = raw_post make_subscription_url(opts.merge({:use_subscription_id => true})), EMPTY_BODY, make_headers(opts)
[resp.status, extract_response_body(resp)]
end | ruby | def create_subscription(opts)
resp = raw_post make_subscription_url(opts.merge({:use_subscription_id => true})), EMPTY_BODY, make_headers(opts)
[resp.status, extract_response_body(resp)]
end | [
"def",
"create_subscription",
"(",
"opts",
")",
"resp",
"=",
"raw_post",
"make_subscription_url",
"(",
"opts",
".",
"merge",
"(",
"{",
":use_subscription_id",
"=>",
"true",
"}",
")",
")",
",",
"EMPTY_BODY",
",",
"make_headers",
"(",
"opts",
")",
"[",
"resp",
".",
"status",
",",
"extract_response_body",
"(",
"resp",
")",
"]",
"end"
]
| Creates a notification subscription
@note You must check the HTTP response code to check the status of the request to add 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 (valid
values are :activities, :foods, :sleep, :body, and :all). REQUIRED
@option opts [Integer, String] :subscriptionId The subscription id
@return [Integer, Hash] An array containing the HTTP response code and
a hash containing confirmation information for the subscription.
@since v0.4.0 | [
"Creates",
"a",
"notification",
"subscription"
]
| c8c4fc908feee91bb138e518f6882507b3067ae1 | https://github.com/whazzmaster/fitgem/blob/c8c4fc908feee91bb138e518f6882507b3067ae1/lib/fitgem/notifications.rb#L29-L32 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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",
"@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",
"selected_unit_system",
"=",
"Fitgem",
"::",
"ApiUnitSystem",
".",
"METRIC",
"if",
"selected_unit_system",
"==",
"\"METRIC\"",
"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 | train |
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",
")",
"model",
"=",
"to_class",
"(",
"table_name",
".",
"singularize",
".",
"camelcase",
")",
"return",
"model",
"if",
"model",
"!=",
"nil",
"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",
"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 | train |
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",
")",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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",
")",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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",
")",
"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 | train |
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}\"",
"if",
"abs_digest_path",
".",
"match",
"(",
"/",
"\\.",
"/",
")",
"mtime",
"=",
"File",
".",
"mtime",
"(",
"abs_digest_path",
")",
"asset_body",
"=",
"File",
".",
"read",
"(",
"abs_digest_path",
")",
"asset_body",
".",
"gsub!",
"(",
"DIGEST_REGEX",
")",
"do",
"|",
"match",
"|",
"$1",
".",
"in?",
"(",
"@asset_digests",
".",
"values",
")",
"?",
"''",
":",
"match",
"end",
"File",
".",
"open",
"abs_logical_path",
",",
"'w'",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"asset_body",
"end",
"File",
".",
"utime",
"(",
"File",
".",
"atime",
"(",
"abs_digest_path",
")",
",",
"mtime",
",",
"abs_logical_path",
")",
"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",
"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}\"",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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",
")",
"num_cal_rows",
"=",
"options",
"[",
":event_strips",
"]",
".",
"first",
".",
"size",
"/",
"7",
"min_height",
"=",
"(",
"options",
"[",
":height",
"]",
"-",
"options",
"[",
":day_names_height",
"]",
")",
"/",
"num_cal_rows",
"row_heights",
"=",
"[",
"]",
"num_event_rows",
"=",
"0",
"1",
".",
"upto",
"(",
"options",
"[",
":event_strips",
"]",
".",
"first",
".",
"size",
"+",
"1",
")",
"do",
"|",
"index",
"|",
"num_events",
"=",
"0",
"options",
"[",
":event_strips",
"]",
".",
"each_with_index",
"do",
"|",
"strip",
",",
"strip_num",
"|",
"num_events",
"=",
"strip_num",
"+",
"1",
"unless",
"strip",
"[",
"index",
"-",
"1",
"]",
".",
"blank?",
"end",
"num_event_rows",
"=",
"[",
"num_event_rows",
",",
"num_events",
"]",
".",
"max",
"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 | train |
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 | train |
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_of_month",
"=",
"Date",
".",
"civil",
"(",
"shown_date",
".",
"year",
",",
"shown_date",
".",
"month",
",",
"1",
")",
"strip_start",
"=",
"beginning_of_week",
"(",
"start_of_month",
",",
"first_day_of_week",
")",
"if",
"start_of_month",
".",
"next_month",
"==",
"beginning_of_week",
"(",
"start_of_month",
".",
"next_month",
",",
"first_day_of_week",
")",
"strip_end",
"=",
"start_of_month",
".",
"next_month",
"else",
"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 | train |
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 | train |
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",
")",
"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",
"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?",
"new_strip",
"=",
"[",
"nil",
"]",
"*",
"(",
"strip_end",
"-",
"strip_start",
"+",
"1",
")",
"range",
".",
"each",
"{",
"|",
"r",
"|",
"new_strip",
"[",
"r",
"]",
"=",
"event",
"}",
"event_strips",
"<<",
"new_strip",
"else",
"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 | train |
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",
")",
"start_at_d",
"=",
"start_at",
".",
"to_date",
"end_at_d",
"=",
"end_at",
".",
"to_date",
"if",
"(",
"start_at_d",
"<",
"start_d",
"and",
"end_at_d",
">=",
"start_d",
")",
"clipped_start",
"=",
"start_d",
"else",
"clipped_start",
"=",
"start_at_d",
"end",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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:[email protected]), in email-address format ([email protected]) 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 '[email protected]', '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 | train |
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",
"@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 | train |
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",
",",
"rtd",
":",
"true",
"}",
"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",
"@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 | train |
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 | train |
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 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.