id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
21,700
kreynolds/phidgets-ffi
lib/phidgets-ffi/motor_control.rb
Phidgets.MotorControl.on_back_emf_update
def on_back_emf_update(obj=nil, &block) @on_back_emf_update_obj = obj @on_back_emf_update = Proc.new { |device, obj_ptr, motor, voltage| yield self, @motors[motor], voltage, object_for(obj_ptr) } Klass.set_OnBackEMFUpdate_Handler(@handle, @on_back_emf_update, pointer_for(obj)) end
ruby
def on_back_emf_update(obj=nil, &block) @on_back_emf_update_obj = obj @on_back_emf_update = Proc.new { |device, obj_ptr, motor, voltage| yield self, @motors[motor], voltage, object_for(obj_ptr) } Klass.set_OnBackEMFUpdate_Handler(@handle, @on_back_emf_update, pointer_for(obj)) end
[ "def", "on_back_emf_update", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_back_emf_update_obj", "=", "obj", "@on_back_emf_update", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "motor", ",", "voltage", "|", "yield", "self", ",", "@motors", "[", "motor", "]", ",", "voltage", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnBackEMFUpdate_Handler", "(", "@handle", ",", "@on_back_emf_update", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets a Back EMF update handler callback function. This is called at a steady rate of 16ms, when BackEMF sensing is enabled. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example mc.on_back_emf_update do |device, motor, voltage| puts "Motor #{motor.index}'s back EMF is #{voltage}" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "a", "Back", "EMF", "update", "handler", "callback", "function", ".", "This", "is", "called", "at", "a", "steady", "rate", "of", "16ms", "when", "BackEMF", "sensing", "is", "enabled", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/motor_control.rb#L126-L132
21,701
kreynolds/phidgets-ffi
lib/phidgets-ffi/motor_control.rb
Phidgets.MotorControl.on_position_update
def on_position_update(obj=nil, &block) @on_position_update_obj = obj @on_position_update = Proc.new { |device, obj_ptr, encoder, position| yield self, @encoders[encoder], position, object_for(obj_ptr) } Klass.set_OnEncoderPositionUpdate_Handler(@handle, @on_position_update, pointer_for(obj)) end
ruby
def on_position_update(obj=nil, &block) @on_position_update_obj = obj @on_position_update = Proc.new { |device, obj_ptr, encoder, position| yield self, @encoders[encoder], position, object_for(obj_ptr) } Klass.set_OnEncoderPositionUpdate_Handler(@handle, @on_position_update, pointer_for(obj)) end
[ "def", "on_position_update", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_position_update_obj", "=", "obj", "@on_position_update", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "encoder", ",", "position", "|", "yield", "self", ",", "@encoders", "[", "encoder", "]", ",", "position", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnEncoderPositionUpdate_Handler", "(", "@handle", ",", "@on_position_update", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets a position update handler callback function. This event provides data about how many ticks have occured since the last update event. It is called at a steady rate of 8ms. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example mc.on_position_update do |device, encoder, position| puts "Encoder #{encoder.index}'s position is #{position}" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "a", "position", "update", "handler", "callback", "function", ".", "This", "event", "provides", "data", "about", "how", "many", "ticks", "have", "occured", "since", "the", "last", "update", "event", ".", "It", "is", "called", "at", "a", "steady", "rate", "of", "8ms", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/motor_control.rb#L164-L172
21,702
kreynolds/phidgets-ffi
lib/phidgets-ffi/motor_control.rb
Phidgets.MotorControl.on_sensor_update
def on_sensor_update(obj=nil, &block) @on_sensor_update_obj = obj @on_sensor_update = Proc.new { |device, obj_ptr, index, value| yield self, @sensors[index], value, object_for(obj_ptr) } Klass.set_OnSensorUpdate_Handler(@handle, @on_sensor_update, pointer_for(obj)) end
ruby
def on_sensor_update(obj=nil, &block) @on_sensor_update_obj = obj @on_sensor_update = Proc.new { |device, obj_ptr, index, value| yield self, @sensors[index], value, object_for(obj_ptr) } Klass.set_OnSensorUpdate_Handler(@handle, @on_sensor_update, pointer_for(obj)) end
[ "def", "on_sensor_update", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_sensor_update_obj", "=", "obj", "@on_sensor_update", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "index", ",", "value", "|", "yield", "self", ",", "@sensors", "[", "index", "]", ",", "value", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnSensorUpdate_Handler", "(", "@handle", ",", "@on_sensor_update", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets a sensor update handler callback function. This is called at a steady rate of 8ms. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example mc.on_sensor_update do |device, sensor, value| puts "Analog Sensor #{sensor.index}'s value is #{value}" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "a", "sensor", "update", "handler", "callback", "function", ".", "This", "is", "called", "at", "a", "steady", "rate", "of", "8ms", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/motor_control.rb#L184-L190
21,703
kreynolds/phidgets-ffi
lib/phidgets-ffi/motor_control.rb
Phidgets.MotorControl.ratiometric
def ratiometric ptr = ::FFI::MemoryPointer.new(:int) Klass.getRatiometric(@handle, ptr) (ptr.get_int(0) == 0) ? false : true end
ruby
def ratiometric ptr = ::FFI::MemoryPointer.new(:int) Klass.getRatiometric(@handle, ptr) (ptr.get_int(0) == 0) ? false : true end
[ "def", "ratiometric", "ptr", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int", ")", "Klass", ".", "getRatiometric", "(", "@handle", ",", "ptr", ")", "(", "ptr", ".", "get_int", "(", "0", ")", "==", "0", ")", "?", "false", ":", "true", "end" ]
Returns the ratiometric state of the board @return [Boolean] returns the ratiometric state or raises an error
[ "Returns", "the", "ratiometric", "state", "of", "the", "board" ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/motor_control.rb#L195-L199
21,704
notEthan/jsi
lib/jsi/base.rb
JSI.Base.pretty_print
def pretty_print(q) q.instance_exec(self) do |obj| text "\#<#{obj.class.to_s}" group_sub { nest(2) { breakable ' ' pp obj.instance } } breakable '' text '>' end end
ruby
def pretty_print(q) q.instance_exec(self) do |obj| text "\#<#{obj.class.to_s}" group_sub { nest(2) { breakable ' ' pp obj.instance } } breakable '' text '>' end end
[ "def", "pretty_print", "(", "q", ")", "q", ".", "instance_exec", "(", "self", ")", "do", "|", "obj", "|", "text", "\"\\#<#{obj.class.to_s}\"", "group_sub", "{", "nest", "(", "2", ")", "{", "breakable", "' '", "pp", "obj", ".", "instance", "}", "}", "breakable", "''", "text", "'>'", "end", "end" ]
pretty-prints a representation this JSI to the given printer @return [void]
[ "pretty", "-", "prints", "a", "representation", "this", "JSI", "to", "the", "given", "printer" ]
57483606e9d1996ce589e1797bd9948fa0684b88
https://github.com/notEthan/jsi/blob/57483606e9d1996ce589e1797bd9948fa0684b88/lib/jsi/base.rb#L175-L187
21,705
notEthan/jsi
lib/jsi/base.rb
JSI.Base.subscript_assign
def subscript_assign(subscript, value) clear_memo(:[], subscript) if value.is_a?(Base) instance[subscript] = value.instance else instance[subscript] = value end end
ruby
def subscript_assign(subscript, value) clear_memo(:[], subscript) if value.is_a?(Base) instance[subscript] = value.instance else instance[subscript] = value end end
[ "def", "subscript_assign", "(", "subscript", ",", "value", ")", "clear_memo", "(", ":[]", ",", "subscript", ")", "if", "value", ".", "is_a?", "(", "Base", ")", "instance", "[", "subscript", "]", "=", "value", ".", "instance", "else", "instance", "[", "subscript", "]", "=", "value", "end", "end" ]
assigns a subscript, taking care of memoization and unwrapping a JSI if given. @param subscript [Object] the bit between the [ and ] @param value [JSI::Base, Object] the value to be assigned
[ "assigns", "a", "subscript", "taking", "care", "of", "memoization", "and", "unwrapping", "a", "JSI", "if", "given", "." ]
57483606e9d1996ce589e1797bd9948fa0684b88
https://github.com/notEthan/jsi/blob/57483606e9d1996ce589e1797bd9948fa0684b88/lib/jsi/base.rb#L226-L233
21,706
kreynolds/phidgets-ffi
lib/phidgets-ffi/rfid.rb
Phidgets.RFID.on_output_change
def on_output_change(obj=nil, &block) @on_output_change_obj = obj @on_output_change = Proc.new { |device, obj_ptr, index, state| yield self, @outputs[index], (state == 0 ? false : true), object_for(obj_ptr) } Klass.set_OnOutputChange_Handler(@handle, @on_output_change, pointer_for(obj)) end
ruby
def on_output_change(obj=nil, &block) @on_output_change_obj = obj @on_output_change = Proc.new { |device, obj_ptr, index, state| yield self, @outputs[index], (state == 0 ? false : true), object_for(obj_ptr) } Klass.set_OnOutputChange_Handler(@handle, @on_output_change, pointer_for(obj)) end
[ "def", "on_output_change", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_output_change_obj", "=", "obj", "@on_output_change", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "index", ",", "state", "|", "yield", "self", ",", "@outputs", "[", "index", "]", ",", "(", "state", "==", "0", "?", "false", ":", "true", ")", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnOutputChange_Handler", "(", "@handle", ",", "@on_output_change", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets an output change handler callback function. This is called when a digital output on the PhidgetRFID board has changed. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example rfid.on_output_change do |device, output, state, obj| print "Digital Output #{output.index}, changed to #{state}\n" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "an", "output", "change", "handler", "callback", "function", ".", "This", "is", "called", "when", "a", "digital", "output", "on", "the", "PhidgetRFID", "board", "has", "changed", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/rfid.rb#L34-L40
21,707
kreynolds/phidgets-ffi
lib/phidgets-ffi/rfid.rb
Phidgets.RFID.on_tag
def on_tag(obj=nil, &block) @on_tag_obj = obj @on_tag = Proc.new { |device, obj_ptr, tag, proto| yield self, tag.read_string, object_for(obj_ptr) } Klass.set_OnTag2_Handler(@handle, @on_tag, pointer_for(obj)) end
ruby
def on_tag(obj=nil, &block) @on_tag_obj = obj @on_tag = Proc.new { |device, obj_ptr, tag, proto| yield self, tag.read_string, object_for(obj_ptr) } Klass.set_OnTag2_Handler(@handle, @on_tag, pointer_for(obj)) end
[ "def", "on_tag", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_tag_obj", "=", "obj", "@on_tag", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "tag", ",", "proto", "|", "yield", "self", ",", "tag", ".", "read_string", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnTag2_Handler", "(", "@handle", ",", "@on_tag", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets a tag handler callback function. This is called when a new tag is seen by the reader. The event is only fired one time for a new tag, so the tag has to be removed and then replaced before another tag gained event will fire. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example rfid.on_tag do |device, tag, obj| puts "Tag #{tag} detected" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "a", "tag", "handler", "callback", "function", ".", "This", "is", "called", "when", "a", "new", "tag", "is", "seen", "by", "the", "reader", ".", "The", "event", "is", "only", "fired", "one", "time", "for", "a", "new", "tag", "so", "the", "tag", "has", "to", "be", "removed", "and", "then", "replaced", "before", "another", "tag", "gained", "event", "will", "fire", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/rfid.rb#L52-L58
21,708
kreynolds/phidgets-ffi
lib/phidgets-ffi/rfid.rb
Phidgets.RFID.on_tag_lost
def on_tag_lost(obj=nil, &block) @on_tag_lost_obj = obj @on_tag_lost = Proc.new { |device, obj_ptr, tag, proto| yield self, tag.read_string, object_for(obj_ptr) } Klass.set_OnTagLost2_Handler(@handle, @on_tag_lost, pointer_for(obj)) end
ruby
def on_tag_lost(obj=nil, &block) @on_tag_lost_obj = obj @on_tag_lost = Proc.new { |device, obj_ptr, tag, proto| yield self, tag.read_string, object_for(obj_ptr) } Klass.set_OnTagLost2_Handler(@handle, @on_tag_lost, pointer_for(obj)) end
[ "def", "on_tag_lost", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_tag_lost_obj", "=", "obj", "@on_tag_lost", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "tag", ",", "proto", "|", "yield", "self", ",", "tag", ".", "read_string", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnTagLost2_Handler", "(", "@handle", ",", "@on_tag_lost", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets a tag lost handler callback function. This is called when a tag is removed from the reader @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example rfid.on_tag_lost do |device, tag, obj| puts "Tag #{tag} removed" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "a", "tag", "lost", "handler", "callback", "function", ".", "This", "is", "called", "when", "a", "tag", "is", "removed", "from", "the", "reader" ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/rfid.rb#L70-L76
21,709
kreynolds/phidgets-ffi
lib/phidgets-ffi/rfid.rb
Phidgets.RFID.antenna
def antenna ptr = ::FFI::MemoryPointer.new(:int) Klass.getAntennaOn(@handle, ptr) (ptr.get_int(0) == 0) ? false : true end
ruby
def antenna ptr = ::FFI::MemoryPointer.new(:int) Klass.getAntennaOn(@handle, ptr) (ptr.get_int(0) == 0) ? false : true end
[ "def", "antenna", "ptr", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int", ")", "Klass", ".", "getAntennaOn", "(", "@handle", ",", "ptr", ")", "(", "ptr", ".", "get_int", "(", "0", ")", "==", "0", ")", "?", "false", ":", "true", "end" ]
Returns the antenna state of the Phidget. @return [Boolean] returns the ratiometric state or raises an error
[ "Returns", "the", "antenna", "state", "of", "the", "Phidget", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/rfid.rb#L81-L85
21,710
kreynolds/phidgets-ffi
lib/phidgets-ffi/rfid.rb
Phidgets.RFID.led
def led ptr = ::FFI::MemoryPointer.new(:int) Klass.getLEDOn(@handle, ptr) (ptr.get_int(0) == 0) ? false : true end
ruby
def led ptr = ::FFI::MemoryPointer.new(:int) Klass.getLEDOn(@handle, ptr) (ptr.get_int(0) == 0) ? false : true end
[ "def", "led", "ptr", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int", ")", "Klass", ".", "getLEDOn", "(", "@handle", ",", "ptr", ")", "(", "ptr", ".", "get_int", "(", "0", ")", "==", "0", ")", "?", "false", ":", "true", "end" ]
Returns the LED state. @return [Boolean] returns the LED state or raises an error
[ "Returns", "the", "LED", "state", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/rfid.rb#L99-L103
21,711
kreynolds/phidgets-ffi
lib/phidgets-ffi/rfid.rb
Phidgets.RFID.tag_present
def tag_present ptr = ::FFI::MemoryPointer.new(:int) Klass.getTagStatus(@handle, ptr) (ptr.get_int(0) == 0) ? false : true end
ruby
def tag_present ptr = ::FFI::MemoryPointer.new(:int) Klass.getTagStatus(@handle, ptr) (ptr.get_int(0) == 0) ? false : true end
[ "def", "tag_present", "ptr", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int", ")", "Klass", ".", "getTagStatus", "(", "@handle", ",", "ptr", ")", "(", "ptr", ".", "get_int", "(", "0", ")", "==", "0", ")", "?", "false", ":", "true", "end" ]
Returns the value indicating whether or not a tag is on the reader. @return [Boolean] returns a value indicating whether or not a tag is on the reader, or raises an error
[ "Returns", "the", "value", "indicating", "whether", "or", "not", "a", "tag", "is", "on", "the", "reader", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/rfid.rb#L138-L142
21,712
kreynolds/phidgets-ffi
lib/phidgets-ffi/rfid.rb
Phidgets.RFID.write
def write(tag, protocol, lock=false) tmp = lock ? 1 : 0 Klass.write(@handle, tag, Phidgets::FFI::RFIDTagProtocol[protocol], tmp) true end
ruby
def write(tag, protocol, lock=false) tmp = lock ? 1 : 0 Klass.write(@handle, tag, Phidgets::FFI::RFIDTagProtocol[protocol], tmp) true end
[ "def", "write", "(", "tag", ",", "protocol", ",", "lock", "=", "false", ")", "tmp", "=", "lock", "?", "1", ":", "0", "Klass", ".", "write", "(", "@handle", ",", "tag", ",", "Phidgets", "::", "FFI", "::", "RFIDTagProtocol", "[", "protocol", "]", ",", "tmp", ")", "true", "end" ]
Writes to a tag. @param [String] tag Tag data to write. See product manual for formatting. @param [Phidgets::FFI::RFIDTagProtocol] protocol Tag Protocol to use. @param [Boolean] lock Lock the tag from further writes @return [Boolean] returns true or raises an error
[ "Writes", "to", "a", "tag", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/rfid.rb#L150-L154
21,713
kreynolds/phidgets-ffi
lib/phidgets-ffi/spatial.rb
Phidgets.Spatial.set_compass_correction_parameters
def set_compass_correction_parameters(new_mag_field, new_offset0, new_offset1, new_offset2, new_gain0, new_gain1, new_gain2, new_t0, new_t1, new_t2, new_t3, new_t4, new_t5) Klass.setCompassCorrectionParameters(@handle, new_mag_field, new_offset0, new_offset1, new_offset2, new_gain0, new_gain1, new_gain2, new_t0, new_t1, new_t2, new_t3, new_t4, new_t5) true end
ruby
def set_compass_correction_parameters(new_mag_field, new_offset0, new_offset1, new_offset2, new_gain0, new_gain1, new_gain2, new_t0, new_t1, new_t2, new_t3, new_t4, new_t5) Klass.setCompassCorrectionParameters(@handle, new_mag_field, new_offset0, new_offset1, new_offset2, new_gain0, new_gain1, new_gain2, new_t0, new_t1, new_t2, new_t3, new_t4, new_t5) true end
[ "def", "set_compass_correction_parameters", "(", "new_mag_field", ",", "new_offset0", ",", "new_offset1", ",", "new_offset2", ",", "new_gain0", ",", "new_gain1", ",", "new_gain2", ",", "new_t0", ",", "new_t1", ",", "new_t2", ",", "new_t3", ",", "new_t4", ",", "new_t5", ")", "Klass", ".", "setCompassCorrectionParameters", "(", "@handle", ",", "new_mag_field", ",", "new_offset0", ",", "new_offset1", ",", "new_offset2", ",", "new_gain0", ",", "new_gain1", ",", "new_gain2", ",", "new_t0", ",", "new_t1", ",", "new_t2", ",", "new_t3", ",", "new_t4", ",", "new_t5", ")", "true", "end" ]
Sets correction paramaters for the magnetometer triad. This is for filtering out hard and soft iron offsets, and scaling the output to match the local field strength. These parameters can be obtained from the compass calibration program provided by Phidgets Inc. @param [Integer] new_mag_field local magnetic field strength @param [Integer] new_offset0 axis 0 offset correction @param [Integer] new_offset1 axis 1 offset correction @param [Integer] new_offset2 axis 2 offset correction @param [Integer] new_gain0 axis 0 gain correction. @param [Integer] new_gain1 axis 1 gain correction. @param [Integer] new_gain2 axis 2 gain correction. @param [Integer] new_t0 non-orthogonality correction factor 0 @param [Integer] new_t1 non-orthogonality correction factor 1 @param [Integer] new_t2 non-orthogonality correction factor 2 @param [Integer] new_t3 non-orthogonality correction factor 3 @param [Integer] new_t4 non-orthogonality correction factor 4 @param [Integer] new_t5 non-orthogonality correction factor 5 @return [Boolean] returns true if successful, or raises an error.
[ "Sets", "correction", "paramaters", "for", "the", "magnetometer", "triad", ".", "This", "is", "for", "filtering", "out", "hard", "and", "soft", "iron", "offsets", "and", "scaling", "the", "output", "to", "match", "the", "local", "field", "strength", ".", "These", "parameters", "can", "be", "obtained", "from", "the", "compass", "calibration", "program", "provided", "by", "Phidgets", "Inc", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/spatial.rb#L99-L102
21,714
kreynolds/phidgets-ffi
lib/phidgets-ffi/dictionary.rb
Phidgets.Dictionary.open
def open(options) password = (options[:password].nil? ? nil : options[:password].to_s) if !options[:server_id].nil? Klass.openRemote(@handle, options[:server_id].to_s, password) else Klass.openRemoteIP(@handle, options[:address].to_s, options[:port].to_i, password) end sleep 1 true end
ruby
def open(options) password = (options[:password].nil? ? nil : options[:password].to_s) if !options[:server_id].nil? Klass.openRemote(@handle, options[:server_id].to_s, password) else Klass.openRemoteIP(@handle, options[:address].to_s, options[:port].to_i, password) end sleep 1 true end
[ "def", "open", "(", "options", ")", "password", "=", "(", "options", "[", ":password", "]", ".", "nil?", "?", "nil", ":", "options", "[", ":password", "]", ".", "to_s", ")", "if", "!", "options", "[", ":server_id", "]", ".", "nil?", "Klass", ".", "openRemote", "(", "@handle", ",", "options", "[", ":server_id", "]", ".", "to_s", ",", "password", ")", "else", "Klass", ".", "openRemoteIP", "(", "@handle", ",", "options", "[", ":address", "]", ".", "to_s", ",", "options", "[", ":port", "]", ".", "to_i", ",", "password", ")", "end", "sleep", "1", "true", "end" ]
Opens a PhidgetDictionary over the WebService. If you are not programming with the block method, you will have to call this explicitly. This is called automatically if you are programming with the block method. <b>Usage:</b> Open a PhidgetDictionary using an address, port, and an optional password. options = {:address => 'localhost', :port => 5001, :password => nil} dict.open(options) Open a PhidgetDictionary using a server id, and an optional password. options = {:server_id => 'localhost', :password => nil} dict.open(options) @return [Boolean] returns true or raises an error
[ "Opens", "a", "PhidgetDictionary", "over", "the", "WebService", ".", "If", "you", "are", "not", "programming", "with", "the", "block", "method", "you", "will", "have", "to", "call", "this", "explicitly", ".", "This", "is", "called", "automatically", "if", "you", "are", "programming", "with", "the", "block", "method", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/dictionary.rb#L68-L77
21,715
kreynolds/phidgets-ffi
lib/phidgets-ffi/dictionary.rb
Phidgets.Dictionary.delete
def delete(pattern) Klass.removeKey(@handle, (pattern.kind_of?(Regexp) ? pattern.source : pattern.to_s)) true end
ruby
def delete(pattern) Klass.removeKey(@handle, (pattern.kind_of?(Regexp) ? pattern.source : pattern.to_s)) true end
[ "def", "delete", "(", "pattern", ")", "Klass", ".", "removeKey", "(", "@handle", ",", "(", "pattern", ".", "kind_of?", "(", "Regexp", ")", "?", "pattern", ".", "source", ":", "pattern", ".", "to_s", ")", ")", "true", "end" ]
Removes a set of keys from the dictionary @return [Boolean] returns true or raises an error
[ "Removes", "a", "set", "of", "keys", "from", "the", "dictionary" ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/dictionary.rb#L130-L133
21,716
kreynolds/phidgets-ffi
lib/phidgets-ffi/dictionary.rb
Phidgets.Dictionary.on_connect
def on_connect(obj=nil, &block) @on_connect_obj = obj @on_connect = Proc.new { |handle, obj_ptr| # On connect, we'll need to re-add all of our change handlers @listeners.each_pair do |pattern, (listener, proc)| begin next if status != :connected Klass.set_OnKeyChange_Handler(@handle, listener, pattern, proc, pointer_for(obj)) sleep @handler_sleep rescue Phidgets::Log.error("#{self.class}::on_connect", $!.to_s) end end yield self, object_for(obj_ptr) } Klass.set_OnServerConnect_Handler(@handle, @on_connect, pointer_for(obj)) sleep @handler_sleep end
ruby
def on_connect(obj=nil, &block) @on_connect_obj = obj @on_connect = Proc.new { |handle, obj_ptr| # On connect, we'll need to re-add all of our change handlers @listeners.each_pair do |pattern, (listener, proc)| begin next if status != :connected Klass.set_OnKeyChange_Handler(@handle, listener, pattern, proc, pointer_for(obj)) sleep @handler_sleep rescue Phidgets::Log.error("#{self.class}::on_connect", $!.to_s) end end yield self, object_for(obj_ptr) } Klass.set_OnServerConnect_Handler(@handle, @on_connect, pointer_for(obj)) sleep @handler_sleep end
[ "def", "on_connect", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_connect_obj", "=", "obj", "@on_connect", "=", "Proc", ".", "new", "{", "|", "handle", ",", "obj_ptr", "|", "# On connect, we'll need to re-add all of our change handlers", "@listeners", ".", "each_pair", "do", "|", "pattern", ",", "(", "listener", ",", "proc", ")", "|", "begin", "next", "if", "status", "!=", ":connected", "Klass", ".", "set_OnKeyChange_Handler", "(", "@handle", ",", "listener", ",", "pattern", ",", "proc", ",", "pointer_for", "(", "obj", ")", ")", "sleep", "@handler_sleep", "rescue", "Phidgets", "::", "Log", ".", "error", "(", "\"#{self.class}::on_connect\"", ",", "$!", ".", "to_s", ")", "end", "end", "yield", "self", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnServerConnect_Handler", "(", "@handle", ",", "@on_connect", ",", "pointer_for", "(", "obj", ")", ")", "sleep", "@handler_sleep", "end" ]
Sets a server connect handler callback function. This is called when a connection to the server has been made. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example dict.on_connect do |obj| puts 'Connected' end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "a", "server", "connect", "handler", "callback", "function", ".", "This", "is", "called", "when", "a", "connection", "to", "the", "server", "has", "been", "made", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/dictionary.rb#L145-L162
21,717
kreynolds/phidgets-ffi
lib/phidgets-ffi/dictionary.rb
Phidgets.Dictionary.on_disconnect
def on_disconnect(obj=nil, &block) @on_disconnect_obj = obj @on_disconnect = Proc.new { |handle, obj_ptr| # On disconnect, we'll need to remove all of our change handlers @listeners.each_pair do |pattern, (listener, proc)| Klass.remove_OnKeyChange_Handler(listener.get_pointer(0)) sleep @handler_sleep end yield self, object_for(obj_ptr) } Klass.set_OnServerDisconnect_Handler(@handle, @on_disconnect, pointer_for(obj)) sleep @handler_sleep end
ruby
def on_disconnect(obj=nil, &block) @on_disconnect_obj = obj @on_disconnect = Proc.new { |handle, obj_ptr| # On disconnect, we'll need to remove all of our change handlers @listeners.each_pair do |pattern, (listener, proc)| Klass.remove_OnKeyChange_Handler(listener.get_pointer(0)) sleep @handler_sleep end yield self, object_for(obj_ptr) } Klass.set_OnServerDisconnect_Handler(@handle, @on_disconnect, pointer_for(obj)) sleep @handler_sleep end
[ "def", "on_disconnect", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_disconnect_obj", "=", "obj", "@on_disconnect", "=", "Proc", ".", "new", "{", "|", "handle", ",", "obj_ptr", "|", "# On disconnect, we'll need to remove all of our change handlers", "@listeners", ".", "each_pair", "do", "|", "pattern", ",", "(", "listener", ",", "proc", ")", "|", "Klass", ".", "remove_OnKeyChange_Handler", "(", "listener", ".", "get_pointer", "(", "0", ")", ")", "sleep", "@handler_sleep", "end", "yield", "self", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnServerDisconnect_Handler", "(", "@handle", ",", "@on_disconnect", ",", "pointer_for", "(", "obj", ")", ")", "sleep", "@handler_sleep", "end" ]
Sets a server disconnect handler callback function. This is called when a connection to the server has been lost. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example dict.on_disconnect do |obj| puts 'Disconnected' end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "a", "server", "disconnect", "handler", "callback", "function", ".", "This", "is", "called", "when", "a", "connection", "to", "the", "server", "has", "been", "lost", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/dictionary.rb#L174-L186
21,718
kreynolds/phidgets-ffi
lib/phidgets-ffi/dictionary.rb
Phidgets.Dictionary.on_change
def on_change(pattern=".*", obj=nil, &block) pattern = (pattern.kind_of?(Regexp) ? pattern.source : pattern.to_s) @listeners[pattern] = [ ::FFI::MemoryPointer.new(:pointer), Proc.new { |handle, obj_ptr, key, value, reason| yield object_for(obj_ptr), key, value, reason } ] Klass.set_OnKeyChange_Handler(@handle, @listeners[pattern][0], pattern, @listeners[pattern][1], pointer_for(obj)) sleep @handler_sleep end
ruby
def on_change(pattern=".*", obj=nil, &block) pattern = (pattern.kind_of?(Regexp) ? pattern.source : pattern.to_s) @listeners[pattern] = [ ::FFI::MemoryPointer.new(:pointer), Proc.new { |handle, obj_ptr, key, value, reason| yield object_for(obj_ptr), key, value, reason } ] Klass.set_OnKeyChange_Handler(@handle, @listeners[pattern][0], pattern, @listeners[pattern][1], pointer_for(obj)) sleep @handler_sleep end
[ "def", "on_change", "(", "pattern", "=", "\".*\"", ",", "obj", "=", "nil", ",", "&", "block", ")", "pattern", "=", "(", "pattern", ".", "kind_of?", "(", "Regexp", ")", "?", "pattern", ".", "source", ":", "pattern", ".", "to_s", ")", "@listeners", "[", "pattern", "]", "=", "[", "::", "FFI", "::", "MemoryPointer", ".", "new", "(", ":pointer", ")", ",", "Proc", ".", "new", "{", "|", "handle", ",", "obj_ptr", ",", "key", ",", "value", ",", "reason", "|", "yield", "object_for", "(", "obj_ptr", ")", ",", "key", ",", "value", ",", "reason", "}", "]", "Klass", ".", "set_OnKeyChange_Handler", "(", "@handle", ",", "@listeners", "[", "pattern", "]", "[", "0", "]", ",", "pattern", ",", "@listeners", "[", "pattern", "]", "[", "1", "]", ",", "pointer_for", "(", "obj", ")", ")", "sleep", "@handler_sleep", "end" ]
Adds a key listener to an opened dictionary. Note that this should only be called after the connection has been made - unlike all other events. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example dict.on_change do |obj, key, val, reason| puts "Every key: #{key} => #{val}-- #{reason}" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Adds", "a", "key", "listener", "to", "an", "opened", "dictionary", ".", "Note", "that", "this", "should", "only", "be", "called", "after", "the", "connection", "has", "been", "made", "-", "unlike", "all", "other", "events", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/dictionary.rb#L217-L228
21,719
kreynolds/phidgets-ffi
lib/phidgets-ffi/dictionary.rb
Phidgets.Dictionary.remove_on_change
def remove_on_change(pattern=".*") pattern = (pattern.kind_of?(Regexp) ? pattern.source : pattern.to_s) if @listeners.has_key?(pattern) listener, proc = @listeners.delete(pattern) Klass.remove_OnKeyChange_Handler(listener.get_pointer(0)) sleep @handler_sleep true else nil end end
ruby
def remove_on_change(pattern=".*") pattern = (pattern.kind_of?(Regexp) ? pattern.source : pattern.to_s) if @listeners.has_key?(pattern) listener, proc = @listeners.delete(pattern) Klass.remove_OnKeyChange_Handler(listener.get_pointer(0)) sleep @handler_sleep true else nil end end
[ "def", "remove_on_change", "(", "pattern", "=", "\".*\"", ")", "pattern", "=", "(", "pattern", ".", "kind_of?", "(", "Regexp", ")", "?", "pattern", ".", "source", ":", "pattern", ".", "to_s", ")", "if", "@listeners", ".", "has_key?", "(", "pattern", ")", "listener", ",", "proc", "=", "@listeners", ".", "delete", "(", "pattern", ")", "Klass", ".", "remove_OnKeyChange_Handler", "(", "listener", ".", "get_pointer", "(", "0", ")", ")", "sleep", "@handler_sleep", "true", "else", "nil", "end", "end" ]
Removes a key listener @param [String] pattern pattern @return [Boolean] returns true or raises an error
[ "Removes", "a", "key", "listener" ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/dictionary.rb#L233-L243
21,720
metanorma/iev
lib/iev/db_cache.rb
Iev.DbCache.fetched
def fetched(key) value = self[key] return unless value # if value =~ /^not_found/ # value.match(/\d{4}-\d{2}-\d{2}/).to_s # else doc = Nokogiri::XML value doc.at("/bibitem/fetched")&.text # end end
ruby
def fetched(key) value = self[key] return unless value # if value =~ /^not_found/ # value.match(/\d{4}-\d{2}-\d{2}/).to_s # else doc = Nokogiri::XML value doc.at("/bibitem/fetched")&.text # end end
[ "def", "fetched", "(", "key", ")", "value", "=", "self", "[", "key", "]", "return", "unless", "value", "# if value =~ /^not_found/", "# value.match(/\\d{4}-\\d{2}-\\d{2}/).to_s", "# else", "doc", "=", "Nokogiri", "::", "XML", "value", "doc", ".", "at", "(", "\"/bibitem/fetched\"", ")", "&.", "text", "# end", "end" ]
Return fetched date @param key [String] @return [String]
[ "Return", "fetched", "date" ]
bdda9f125421752d305986334fae3a7daa422854
https://github.com/metanorma/iev/blob/bdda9f125421752d305986334fae3a7daa422854/lib/iev/db_cache.rb#L40-L50
21,721
nwjsmith/thumbtack
lib/thumbtack/client.rb
Thumbtack.Client.action
def action(path, params) response = @adapter.get(path, params) unless response['result_code'] == 'done' raise ResultError, response['result_code'] end self end
ruby
def action(path, params) response = @adapter.get(path, params) unless response['result_code'] == 'done' raise ResultError, response['result_code'] end self end
[ "def", "action", "(", "path", ",", "params", ")", "response", "=", "@adapter", ".", "get", "(", "path", ",", "params", ")", "unless", "response", "[", "'result_code'", "]", "==", "'done'", "raise", "ResultError", ",", "response", "[", "'result_code'", "]", "end", "self", "end" ]
Perform an action request against the Pinboard API @param [String] path the path to fetch from, relative to from the base Pinboard API URL @param [Hash] params query parameters to append to the URL @return [Hash] the response parsed from the JSON @raise [RateLimitError] if the response is rate-limited @raise [ResultError] if the result code isn't "done" @api private @see https://pinboard.in/api/#errors
[ "Perform", "an", "action", "request", "against", "the", "Pinboard", "API" ]
f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb
https://github.com/nwjsmith/thumbtack/blob/f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb/lib/thumbtack/client.rb#L91-L98
21,722
activenetwork-automation/vcoworkflows
lib/vcoworkflows/vcosession.rb
VcoWorkflows.VcoSession.post
def post(endpoint, body, headers = {}) headers = { accept: :json, content_type: :json }.merge(headers) @rest_resource[endpoint].post body, headers end
ruby
def post(endpoint, body, headers = {}) headers = { accept: :json, content_type: :json }.merge(headers) @rest_resource[endpoint].post body, headers end
[ "def", "post", "(", "endpoint", ",", "body", ",", "headers", "=", "{", "}", ")", "headers", "=", "{", "accept", ":", ":json", ",", "content_type", ":", ":json", "}", ".", "merge", "(", "headers", ")", "@rest_resource", "[", "endpoint", "]", ".", "post", "body", ",", "headers", "end" ]
Perform a REST POST operation against the specified endpoint with the given data body @param [String] endpoint REST endpoint to use @param [String] body JSON data body to post @param [Hash] headers Optional headers to use in request @return [String] JSON response body
[ "Perform", "a", "REST", "POST", "operation", "against", "the", "specified", "endpoint", "with", "the", "given", "data", "body" ]
01db57318c14e572dc47261f55c8d08341306642
https://github.com/activenetwork-automation/vcoworkflows/blob/01db57318c14e572dc47261f55c8d08341306642/lib/vcoworkflows/vcosession.rb#L66-L69
21,723
kreynolds/phidgets-ffi
lib/phidgets-ffi/ir.rb
Phidgets.IR.on_raw_data
def on_raw_data(obj=nil, &block) @on_raw_data_obj = obj @on_raw_data = Proc.new { |device, obj_ptr, raw_data, data_length| data = [] data_length.times { |i| data << raw_data[i].get_int(0) } yield self, data, data_length, object_for(obj_ptr) } Klass.set_OnRawData_Handler(@handle, @on_raw_data, pointer_for(obj)) end
ruby
def on_raw_data(obj=nil, &block) @on_raw_data_obj = obj @on_raw_data = Proc.new { |device, obj_ptr, raw_data, data_length| data = [] data_length.times { |i| data << raw_data[i].get_int(0) } yield self, data, data_length, object_for(obj_ptr) } Klass.set_OnRawData_Handler(@handle, @on_raw_data, pointer_for(obj)) end
[ "def", "on_raw_data", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_raw_data_obj", "=", "obj", "@on_raw_data", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "raw_data", ",", "data_length", "|", "data", "=", "[", "]", "data_length", ".", "times", "{", "|", "i", "|", "data", "<<", "raw_data", "[", "i", "]", ".", "get_int", "(", "0", ")", "}", "yield", "self", ",", "data", ",", "data_length", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnRawData_Handler", "(", "@handle", ",", "@on_raw_data", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets a raw data handler callback function. This is called whenever a new IR data is available. Data is in the form of an array of microsecond pulse values. This can be used if the user wishes to do their own data decoding, or for codes that the PhidgetIR cannot automatically recognize. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example ir.on_raw_data do |device, raw_data, data_length, obj| puts "Raw data: #{raw_data}, length: #{data_length}" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "a", "raw", "data", "handler", "callback", "function", ".", "This", "is", "called", "whenever", "a", "new", "IR", "data", "is", "available", ".", "Data", "is", "in", "the", "form", "of", "an", "array", "of", "microsecond", "pulse", "values", ".", "This", "can", "be", "used", "if", "the", "user", "wishes", "to", "do", "their", "own", "data", "decoding", "or", "for", "codes", "that", "the", "PhidgetIR", "cannot", "automatically", "recognize", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/ir.rb#L106-L117
21,724
kreynolds/phidgets-ffi
lib/phidgets-ffi/ir.rb
Phidgets.IR.on_code
def on_code(obj=nil, &block) @on_code_obj = obj @on_code = Proc.new { |device, obj_ptr, data, data_length, bit_count, repeat| data_string = [] data_length.times { |i| data_string[i] = data[i].get_uchar(0).to_s(16) } yield self, data_string, data_length, bit_count, repeat, object_for(obj_ptr) } Klass.set_OnCode_Handler(@handle, @on_code, pointer_for(obj)) end
ruby
def on_code(obj=nil, &block) @on_code_obj = obj @on_code = Proc.new { |device, obj_ptr, data, data_length, bit_count, repeat| data_string = [] data_length.times { |i| data_string[i] = data[i].get_uchar(0).to_s(16) } yield self, data_string, data_length, bit_count, repeat, object_for(obj_ptr) } Klass.set_OnCode_Handler(@handle, @on_code, pointer_for(obj)) end
[ "def", "on_code", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_code_obj", "=", "obj", "@on_code", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "data", ",", "data_length", ",", "bit_count", ",", "repeat", "|", "data_string", "=", "[", "]", "data_length", ".", "times", "{", "|", "i", "|", "data_string", "[", "i", "]", "=", "data", "[", "i", "]", ".", "get_uchar", "(", "0", ")", ".", "to_s", "(", "16", ")", "}", "yield", "self", ",", "data_string", ",", "data_length", ",", "bit_count", ",", "repeat", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnCode_Handler", "(", "@handle", ",", "@on_code", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets a code handler callback function. This is called whenever a new code is recognized. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example ir.on_code do |device, data, data_length, bit_count, repeat, obj| puts "Code #{data} received, length: #{data_length}, bit count: #{bit_count}, repeat: #{repeat}" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "a", "code", "handler", "callback", "function", ".", "This", "is", "called", "whenever", "a", "new", "code", "is", "recognized", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/ir.rb#L129-L140
21,725
kreynolds/phidgets-ffi
lib/phidgets-ffi/ir.rb
Phidgets.IR.on_learn
def on_learn(obj=nil, &block) @on_learn_obj = obj @on_learn = Proc.new { |device, obj_ptr, int_data, data_length, code_info| data = [] data_length.times { |i| data[i] = int_data[i].get_uchar(0).to_s(16) } code_info_struct = IR_code_info.new(code_info) yield self, data, data_length, code_info_struct, object_for(obj_ptr) } Klass.set_OnLearn_Handler(@handle, @on_learn, pointer_for(obj)) end
ruby
def on_learn(obj=nil, &block) @on_learn_obj = obj @on_learn = Proc.new { |device, obj_ptr, int_data, data_length, code_info| data = [] data_length.times { |i| data[i] = int_data[i].get_uchar(0).to_s(16) } code_info_struct = IR_code_info.new(code_info) yield self, data, data_length, code_info_struct, object_for(obj_ptr) } Klass.set_OnLearn_Handler(@handle, @on_learn, pointer_for(obj)) end
[ "def", "on_learn", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_learn_obj", "=", "obj", "@on_learn", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "int_data", ",", "data_length", ",", "code_info", "|", "data", "=", "[", "]", "data_length", ".", "times", "{", "|", "i", "|", "data", "[", "i", "]", "=", "int_data", "[", "i", "]", ".", "get_uchar", "(", "0", ")", ".", "to_s", "(", "16", ")", "}", "code_info_struct", "=", "IR_code_info", ".", "new", "(", "code_info", ")", "yield", "self", ",", "data", ",", "data_length", ",", "code_info_struct", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnLearn_Handler", "(", "@handle", ",", "@on_learn", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets a learn handler callback function. This is called when a new code has been learned. This generally requires the button to be held down for a second or two. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example ir.on_learn do |device, data, data_length, code_info, obj| puts "Code #{data} learnt" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "a", "learn", "handler", "callback", "function", ".", "This", "is", "called", "when", "a", "new", "code", "has", "been", "learned", ".", "This", "generally", "requires", "the", "button", "to", "be", "held", "down", "for", "a", "second", "or", "two", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/ir.rb#L152-L165
21,726
kreynolds/phidgets-ffi
lib/phidgets-ffi/ir.rb
Phidgets.IR.transmit
def transmit(data, code_info) pdata = ::FFI::MemoryPointer.new(:uchar, 16) data_ffi = [] data.size.times { |i| data_ffi[i] = data[i].to_i(16) } data_ffi = ::FFI::MemoryPointer.new(:uchar, 16).write_array_of_uchar(data_ffi) Klass.Transmit(@handle, data_ffi, code_info) true end
ruby
def transmit(data, code_info) pdata = ::FFI::MemoryPointer.new(:uchar, 16) data_ffi = [] data.size.times { |i| data_ffi[i] = data[i].to_i(16) } data_ffi = ::FFI::MemoryPointer.new(:uchar, 16).write_array_of_uchar(data_ffi) Klass.Transmit(@handle, data_ffi, code_info) true end
[ "def", "transmit", "(", "data", ",", "code_info", ")", "pdata", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", "(", ":uchar", ",", "16", ")", "data_ffi", "=", "[", "]", "data", ".", "size", ".", "times", "{", "|", "i", "|", "data_ffi", "[", "i", "]", "=", "data", "[", "i", "]", ".", "to_i", "(", "16", ")", "}", "data_ffi", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", "(", ":uchar", ",", "16", ")", ".", "write_array_of_uchar", "(", "data_ffi", ")", "Klass", ".", "Transmit", "(", "@handle", ",", "data_ffi", ",", "code_info", ")", "true", "end" ]
Transmits a code @param [Array<String>] data data to send @param [IR_code_info] code_info code info structure specifying the attributes of the code to send. Anything that is not set is set to default. @return [Boolean] returns true if the code was successfully transmitted, or raises an error.
[ "Transmits", "a", "code" ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/ir.rb#L171-L184
21,727
kreynolds/phidgets-ffi
lib/phidgets-ffi/ir.rb
Phidgets.IR.transmit_raw
def transmit_raw(data, length, carrier_frequency, duty_cycle, gap) c_data = ::FFI::MemoryPointer.new(:int, data.size).write_array_of_int(data) Klass.TransmitRaw(@handle, c_data, length.to_i, carrier_frequency.to_i, duty_cycle.to_i, gap.to_i) true end
ruby
def transmit_raw(data, length, carrier_frequency, duty_cycle, gap) c_data = ::FFI::MemoryPointer.new(:int, data.size).write_array_of_int(data) Klass.TransmitRaw(@handle, c_data, length.to_i, carrier_frequency.to_i, duty_cycle.to_i, gap.to_i) true end
[ "def", "transmit_raw", "(", "data", ",", "length", ",", "carrier_frequency", ",", "duty_cycle", ",", "gap", ")", "c_data", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int", ",", "data", ".", "size", ")", ".", "write_array_of_int", "(", "data", ")", "Klass", ".", "TransmitRaw", "(", "@handle", ",", "c_data", ",", "length", ".", "to_i", ",", "carrier_frequency", ".", "to_i", ",", "duty_cycle", ".", "to_i", ",", "gap", ".", "to_i", ")", "true", "end" ]
Transmits raw data as a series of pulses and spaces. @param [Array] data data to send @param [Integer] length length of the data array @param [Integer] carrier_frequency carrier frequency in Hz. Leave as 0 for default @param [Integer] duty_cycle duty cycle(10-50). Leave as 0 for default @param [Integer] gap_time gap time in us. This guarantees a gap time(no transmitting) after the data is sent, but can be set to 0 @return [Boolean] returns true if the raw data was successfully transmitted, or raises an error.
[ "Transmits", "raw", "data", "as", "a", "series", "of", "pulses", "and", "spaces", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/ir.rb#L200-L204
21,728
kreynolds/phidgets-ffi
lib/phidgets-ffi/ir.rb
Phidgets.IR.last_code
def last_code data_ffi = ::FFI::MemoryPointer.new(:uchar, 16) data_length = ::FFI::MemoryPointer.new(:int) data_length.write_int(16) bit_count = ::FFI::MemoryPointer.new(:int) Klass.getLastCode(@handle, data_ffi, data_length, bit_count) data = [] data_length.get_int(0).times { |i| data << data_ffi[i].get_uchar(0).to_s(16) } [data, data_length.get_int(0), bit_count.get_int(0)] end
ruby
def last_code data_ffi = ::FFI::MemoryPointer.new(:uchar, 16) data_length = ::FFI::MemoryPointer.new(:int) data_length.write_int(16) bit_count = ::FFI::MemoryPointer.new(:int) Klass.getLastCode(@handle, data_ffi, data_length, bit_count) data = [] data_length.get_int(0).times { |i| data << data_ffi[i].get_uchar(0).to_s(16) } [data, data_length.get_int(0), bit_count.get_int(0)] end
[ "def", "last_code", "data_ffi", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", "(", ":uchar", ",", "16", ")", "data_length", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int", ")", "data_length", ".", "write_int", "(", "16", ")", "bit_count", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int", ")", "Klass", ".", "getLastCode", "(", "@handle", ",", "data_ffi", ",", "data_length", ",", "bit_count", ")", "data", "=", "[", "]", "data_length", ".", "get_int", "(", "0", ")", ".", "times", "{", "|", "i", "|", "data", "<<", "data_ffi", "[", "i", "]", ".", "get_uchar", "(", "0", ")", ".", "to_s", "(", "16", ")", "}", "[", "data", ",", "data_length", ".", "get_int", "(", "0", ")", ",", "bit_count", ".", "get_int", "(", "0", ")", "]", "end" ]
Gets the last code that was received. @return [Array<String>] returns the last code, or raises an error. @return [Integer] returns the data length, or raises an error. @return [Object] returns the bit count, or raises an error.
[ "Gets", "the", "last", "code", "that", "was", "received", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/ir.rb#L230-L248
21,729
kreynolds/phidgets-ffi
lib/phidgets-ffi/ir.rb
Phidgets.IR.last_learned_code
def last_learned_code data_ffi = ::FFI::MemoryPointer.new(:uchar, 16) data_length = ::FFI::MemoryPointer.new(:int) data_length.write_int(16) code_info = ::FFI::MemoryPointer.new(IR_code_info) Klass.getLastLearnedCode(@handle, data_ffi, data_length, code_info) data = [] data_length.get_int(0).times { |i| data << data_ffi[i].get_uchar(0).to_s(16) } code_info_struct = IR_code_info.new(code_info) [data, data_length.get_int(0), code_info_struct] end
ruby
def last_learned_code data_ffi = ::FFI::MemoryPointer.new(:uchar, 16) data_length = ::FFI::MemoryPointer.new(:int) data_length.write_int(16) code_info = ::FFI::MemoryPointer.new(IR_code_info) Klass.getLastLearnedCode(@handle, data_ffi, data_length, code_info) data = [] data_length.get_int(0).times { |i| data << data_ffi[i].get_uchar(0).to_s(16) } code_info_struct = IR_code_info.new(code_info) [data, data_length.get_int(0), code_info_struct] end
[ "def", "last_learned_code", "data_ffi", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", "(", ":uchar", ",", "16", ")", "data_length", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int", ")", "data_length", ".", "write_int", "(", "16", ")", "code_info", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", "(", "IR_code_info", ")", "Klass", ".", "getLastLearnedCode", "(", "@handle", ",", "data_ffi", ",", "data_length", ",", "code_info", ")", "data", "=", "[", "]", "data_length", ".", "get_int", "(", "0", ")", ".", "times", "{", "|", "i", "|", "data", "<<", "data_ffi", "[", "i", "]", ".", "get_uchar", "(", "0", ")", ".", "to_s", "(", "16", ")", "}", "code_info_struct", "=", "IR_code_info", ".", "new", "(", "code_info", ")", "[", "data", ",", "data_length", ".", "get_int", "(", "0", ")", ",", "code_info_struct", "]", "end" ]
Gets the last code that was learned. @return [Array<String>] returns the last learned code, or raises an error. @return [Integer] returns the data length, or raises an error. @return [IR_code_info] returns the code info structure for the learned code, or raises an error.
[ "Gets", "the", "last", "code", "that", "was", "learned", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/ir.rb#L254-L275
21,730
axsh/isono
lib/isono/amqp_client.rb
Isono.AmqpClient.publish_to
def publish_to(exname, message, opts={}) EventMachine.schedule { ex = amq.exchanges[exname] || raise("Undefined exchange name : #{exname}") case ex.type when :topic unless opts.has_key? :key opts[:key] = '*' end end ex.publish(Serializer.instance.marshal(message), opts) } end
ruby
def publish_to(exname, message, opts={}) EventMachine.schedule { ex = amq.exchanges[exname] || raise("Undefined exchange name : #{exname}") case ex.type when :topic unless opts.has_key? :key opts[:key] = '*' end end ex.publish(Serializer.instance.marshal(message), opts) } end
[ "def", "publish_to", "(", "exname", ",", "message", ",", "opts", "=", "{", "}", ")", "EventMachine", ".", "schedule", "{", "ex", "=", "amq", ".", "exchanges", "[", "exname", "]", "||", "raise", "(", "\"Undefined exchange name : #{exname}\"", ")", "case", "ex", ".", "type", "when", ":topic", "unless", "opts", ".", "has_key?", ":key", "opts", "[", ":key", "]", "=", "'*'", "end", "end", "ex", ".", "publish", "(", "Serializer", ".", "instance", ".", "marshal", "(", "message", ")", ",", "opts", ")", "}", "end" ]
Publish a message to the designated exchange. @param [String] exname The exchange name @param [String] message Message body to be sent @param [Hash] opts Options with the message. :key => 'keyname' @return [void] @example Want to broadcast the data to all bound queues: publish_to('topic exchange', 'data', :key=>'*') @example Want to send the data to the specific queue(s): publish_to('exchange name', 'group.1', 'data')
[ "Publish", "a", "message", "to", "the", "designated", "exchange", "." ]
0325eb1a46538b8eea63e80745a9161e2532b7cf
https://github.com/axsh/isono/blob/0325eb1a46538b8eea63e80745a9161e2532b7cf/lib/isono/amqp_client.rb#L180-L191
21,731
activenetwork-automation/vcoworkflows
lib/vcoworkflows/workflow.rb
VcoWorkflows.Workflow.required_parameters
def required_parameters required = {} @input_parameters.each_value { |v| required[v.name] = v if v.required? } required end
ruby
def required_parameters required = {} @input_parameters.each_value { |v| required[v.name] = v if v.required? } required end
[ "def", "required_parameters", "required", "=", "{", "}", "@input_parameters", ".", "each_value", "{", "|", "v", "|", "required", "[", "v", ".", "name", "]", "=", "v", "if", "v", ".", "required?", "}", "required", "end" ]
Get an array of the names of all the required input parameters @return [Hash] Hash of WorkflowParameter input parameters which are required for this workflow
[ "Get", "an", "array", "of", "the", "names", "of", "all", "the", "required", "input", "parameters" ]
01db57318c14e572dc47261f55c8d08341306642
https://github.com/activenetwork-automation/vcoworkflows/blob/01db57318c14e572dc47261f55c8d08341306642/lib/vcoworkflows/workflow.rb#L236-L240
21,732
activenetwork-automation/vcoworkflows
lib/vcoworkflows/workflow.rb
VcoWorkflows.Workflow.parameter
def parameter(parameter_name, parameter_value = nil) if @input_parameters.key?(parameter_name) @input_parameters[parameter_name].set parameter_value else $stderr.puts "\nAttempted to set a value for a non-existent WorkflowParameter!" $stderr.puts "It appears that there is no parameter \"#{parameter}\"." $stderr.puts "Valid parameter names are: #{@input_parameters.keys.join(', ')}" $stderr.puts '' fail(IOError, ERR[:no_such_parameter]) end unless parameter_value.nil? @input_parameters[parameter_name] end
ruby
def parameter(parameter_name, parameter_value = nil) if @input_parameters.key?(parameter_name) @input_parameters[parameter_name].set parameter_value else $stderr.puts "\nAttempted to set a value for a non-existent WorkflowParameter!" $stderr.puts "It appears that there is no parameter \"#{parameter}\"." $stderr.puts "Valid parameter names are: #{@input_parameters.keys.join(', ')}" $stderr.puts '' fail(IOError, ERR[:no_such_parameter]) end unless parameter_value.nil? @input_parameters[parameter_name] end
[ "def", "parameter", "(", "parameter_name", ",", "parameter_value", "=", "nil", ")", "if", "@input_parameters", ".", "key?", "(", "parameter_name", ")", "@input_parameters", "[", "parameter_name", "]", ".", "set", "parameter_value", "else", "$stderr", ".", "puts", "\"\\nAttempted to set a value for a non-existent WorkflowParameter!\"", "$stderr", ".", "puts", "\"It appears that there is no parameter \\\"#{parameter}\\\".\"", "$stderr", ".", "puts", "\"Valid parameter names are: #{@input_parameters.keys.join(', ')}\"", "$stderr", ".", "puts", "''", "fail", "(", "IOError", ",", "ERR", "[", ":no_such_parameter", "]", ")", "end", "unless", "parameter_value", ".", "nil?", "@input_parameters", "[", "parameter_name", "]", "end" ]
Get the parameter object named. If a value is provided, set the value and return the parameter object. To get a parameter value, use parameter(parameter_name).value @param [String] parameter_name Name of the parameter to get @param [Object, nil] parameter_value Optional value for parameter. @return [VcoWorkflows::WorkflowParameter] The resulting WorkflowParameter
[ "Get", "the", "parameter", "object", "named", ".", "If", "a", "value", "is", "provided", "set", "the", "value", "and", "return", "the", "parameter", "object", "." ]
01db57318c14e572dc47261f55c8d08341306642
https://github.com/activenetwork-automation/vcoworkflows/blob/01db57318c14e572dc47261f55c8d08341306642/lib/vcoworkflows/workflow.rb#L250-L261
21,733
activenetwork-automation/vcoworkflows
lib/vcoworkflows/workflow.rb
VcoWorkflows.Workflow.execute
def execute(workflow_service = nil) # If we're not given an explicit workflow service for this execution # request, use the one defined when we were created. workflow_service = @service if workflow_service.nil? # If we still have a nil workflow_service, go home. fail(IOError, ERR[:no_workflow_service_defined]) if workflow_service.nil? # Make sure we didn't forget any required parameters verify_parameters # Let's get this thing running! @execution_id = workflow_service.execute_workflow(@id, input_parameter_json) end
ruby
def execute(workflow_service = nil) # If we're not given an explicit workflow service for this execution # request, use the one defined when we were created. workflow_service = @service if workflow_service.nil? # If we still have a nil workflow_service, go home. fail(IOError, ERR[:no_workflow_service_defined]) if workflow_service.nil? # Make sure we didn't forget any required parameters verify_parameters # Let's get this thing running! @execution_id = workflow_service.execute_workflow(@id, input_parameter_json) end
[ "def", "execute", "(", "workflow_service", "=", "nil", ")", "# If we're not given an explicit workflow service for this execution", "# request, use the one defined when we were created.", "workflow_service", "=", "@service", "if", "workflow_service", ".", "nil?", "# If we still have a nil workflow_service, go home.", "fail", "(", "IOError", ",", "ERR", "[", ":no_workflow_service_defined", "]", ")", "if", "workflow_service", ".", "nil?", "# Make sure we didn't forget any required parameters", "verify_parameters", "# Let's get this thing running!", "@execution_id", "=", "workflow_service", ".", "execute_workflow", "(", "@id", ",", "input_parameter_json", ")", "end" ]
Execute this workflow @param [VcoWorkflows::WorkflowService] workflow_service @return [String] Workflow Execution ID
[ "Execute", "this", "workflow" ]
01db57318c14e572dc47261f55c8d08341306642
https://github.com/activenetwork-automation/vcoworkflows/blob/01db57318c14e572dc47261f55c8d08341306642/lib/vcoworkflows/workflow.rb#L306-L316
21,734
activenetwork-automation/vcoworkflows
lib/vcoworkflows/workflow.rb
VcoWorkflows.Workflow.log
def log(execution_id = nil) execution_id = @execution_id if execution_id.nil? log_json = @service.get_log(@id, execution_id) VcoWorkflows::WorkflowExecutionLog.new(log_json) end
ruby
def log(execution_id = nil) execution_id = @execution_id if execution_id.nil? log_json = @service.get_log(@id, execution_id) VcoWorkflows::WorkflowExecutionLog.new(log_json) end
[ "def", "log", "(", "execution_id", "=", "nil", ")", "execution_id", "=", "@execution_id", "if", "execution_id", ".", "nil?", "log_json", "=", "@service", ".", "get_log", "(", "@id", ",", "execution_id", ")", "VcoWorkflows", "::", "WorkflowExecutionLog", ".", "new", "(", "log_json", ")", "end" ]
Return logs for the given execution @param [String] execution_id optional execution id to get logs for @return [VcoWorkflows::WorkflowExecutionLog]
[ "Return", "logs", "for", "the", "given", "execution" ]
01db57318c14e572dc47261f55c8d08341306642
https://github.com/activenetwork-automation/vcoworkflows/blob/01db57318c14e572dc47261f55c8d08341306642/lib/vcoworkflows/workflow.rb#L336-L340
21,735
activenetwork-automation/vcoworkflows
lib/vcoworkflows/workflow.rb
VcoWorkflows.Workflow.input_parameter_json
def input_parameter_json tmp_params = [] @input_parameters.each_value { |v| tmp_params << v.as_struct if v.set? } param_struct = { parameters: tmp_params } param_struct.to_json end
ruby
def input_parameter_json tmp_params = [] @input_parameters.each_value { |v| tmp_params << v.as_struct if v.set? } param_struct = { parameters: tmp_params } param_struct.to_json end
[ "def", "input_parameter_json", "tmp_params", "=", "[", "]", "@input_parameters", ".", "each_value", "{", "|", "v", "|", "tmp_params", "<<", "v", ".", "as_struct", "if", "v", ".", "set?", "}", "param_struct", "=", "{", "parameters", ":", "tmp_params", "}", "param_struct", ".", "to_json", "end" ]
Convert the input parameters to a JSON document @return [String]
[ "Convert", "the", "input", "parameters", "to", "a", "JSON", "document" ]
01db57318c14e572dc47261f55c8d08341306642
https://github.com/activenetwork-automation/vcoworkflows/blob/01db57318c14e572dc47261f55c8d08341306642/lib/vcoworkflows/workflow.rb#L371-L376
21,736
activenetwork-automation/vcoworkflows
lib/vcoworkflows/workflow.rb
VcoWorkflows.Workflow.verify_parameters
def verify_parameters required_parameters.each do |name, wfparam| if wfparam.required? && (wfparam.value.nil? || wfparam.value.size == 0) fail(IOError, ERR[:param_verify_failed] << "#{name} required but not present.") # rubocop:disable Metrics/LineLength end end end
ruby
def verify_parameters required_parameters.each do |name, wfparam| if wfparam.required? && (wfparam.value.nil? || wfparam.value.size == 0) fail(IOError, ERR[:param_verify_failed] << "#{name} required but not present.") # rubocop:disable Metrics/LineLength end end end
[ "def", "verify_parameters", "required_parameters", ".", "each", "do", "|", "name", ",", "wfparam", "|", "if", "wfparam", ".", "required?", "&&", "(", "wfparam", ".", "value", ".", "nil?", "||", "wfparam", ".", "value", ".", "size", "==", "0", ")", "fail", "(", "IOError", ",", "ERR", "[", ":param_verify_failed", "]", "<<", "\"#{name} required but not present.\"", ")", "# rubocop:disable Metrics/LineLength", "end", "end", "end" ]
Verify that all mandatory input parameters have values
[ "Verify", "that", "all", "mandatory", "input", "parameters", "have", "values" ]
01db57318c14e572dc47261f55c8d08341306642
https://github.com/activenetwork-automation/vcoworkflows/blob/01db57318c14e572dc47261f55c8d08341306642/lib/vcoworkflows/workflow.rb#L379-L385
21,737
axsh/isono
lib/isono/util.rb
Isono.Util.default_gw_ipaddr
def default_gw_ipaddr ip = case `/bin/uname -s`.rstrip when 'Linux' `/sbin/ip route get 8.8.8.8`.split("\n")[0].split.last when 'SunOS' `/sbin/ifconfig $(/usr/sbin/route -n get 1.1.1.1 | awk '$1 == "interface:" {print $2}') | awk '$1 == "inet" { print $2 }'` else raise "Unsupported platform to detect gateway IP address: #{`/bin/uname`}" end ip = ip.rstrip raise "Failed to run command lines or empty result" if ip == '' || $?.exitstatus != 0 ip end
ruby
def default_gw_ipaddr ip = case `/bin/uname -s`.rstrip when 'Linux' `/sbin/ip route get 8.8.8.8`.split("\n")[0].split.last when 'SunOS' `/sbin/ifconfig $(/usr/sbin/route -n get 1.1.1.1 | awk '$1 == "interface:" {print $2}') | awk '$1 == "inet" { print $2 }'` else raise "Unsupported platform to detect gateway IP address: #{`/bin/uname`}" end ip = ip.rstrip raise "Failed to run command lines or empty result" if ip == '' || $?.exitstatus != 0 ip end
[ "def", "default_gw_ipaddr", "ip", "=", "case", "`", "`", ".", "rstrip", "when", "'Linux'", "`", "`", ".", "split", "(", "\"\\n\"", ")", "[", "0", "]", ".", "split", ".", "last", "when", "'SunOS'", "`", "`", "else", "raise", "\"Unsupported platform to detect gateway IP address: #{`/bin/uname`}\"", "end", "ip", "=", "ip", ".", "rstrip", "raise", "\"Failed to run command lines or empty result\"", "if", "ip", "==", "''", "||", "$?", ".", "exitstatus", "!=", "0", "ip", "end" ]
Return the IP address assigned to default gw interface
[ "Return", "the", "IP", "address", "assigned", "to", "default", "gw", "interface" ]
0325eb1a46538b8eea63e80745a9161e2532b7cf
https://github.com/axsh/isono/blob/0325eb1a46538b8eea63e80745a9161e2532b7cf/lib/isono/util.rb#L41-L53
21,738
nwjsmith/thumbtack
lib/thumbtack/notes.rb
Thumbtack.Notes.list
def list response = @client.get('/notes/list') response.fetch('notes', EMPTY_ARRAY).map do |note_hash| NoteSummary.from_hash(note_hash) end end
ruby
def list response = @client.get('/notes/list') response.fetch('notes', EMPTY_ARRAY).map do |note_hash| NoteSummary.from_hash(note_hash) end end
[ "def", "list", "response", "=", "@client", ".", "get", "(", "'/notes/list'", ")", "response", ".", "fetch", "(", "'notes'", ",", "EMPTY_ARRAY", ")", ".", "map", "do", "|", "note_hash", "|", "NoteSummary", ".", "from_hash", "(", "note_hash", ")", "end", "end" ]
Initialize a Notes @param [Client] client client to communicate with the Pinboard API @api private List of summaries of the user's notes @example summaries = notes.list @return [Array<NoteSummary>] @api public @see https://pinboard.in/api/#notes_list
[ "Initialize", "a", "Notes" ]
f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb
https://github.com/nwjsmith/thumbtack/blob/f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb/lib/thumbtack/notes.rb#L26-L31
21,739
nwjsmith/thumbtack
lib/thumbtack/posts.rb
Thumbtack.Posts.get
def get(options = EMPTY_HASH) parameters = Specification.new( tag: Types::Tags, dt: Types::Time, url: Types::URL, meta: Types::Boolean ).parameters(options) posts_from @client.get('/posts/get', parameters) end
ruby
def get(options = EMPTY_HASH) parameters = Specification.new( tag: Types::Tags, dt: Types::Time, url: Types::URL, meta: Types::Boolean ).parameters(options) posts_from @client.get('/posts/get', parameters) end
[ "def", "get", "(", "options", "=", "EMPTY_HASH", ")", "parameters", "=", "Specification", ".", "new", "(", "tag", ":", "Types", "::", "Tags", ",", "dt", ":", "Types", "::", "Time", ",", "url", ":", "Types", "::", "URL", ",", "meta", ":", "Types", "::", "Boolean", ")", ".", "parameters", "(", "options", ")", "posts_from", "@client", ".", "get", "(", "'/posts/get'", ",", "parameters", ")", "end" ]
Fetch one or more bookmarks @example bookmarks = posts.get(tag: ['one', 'two', 'three']) @param [Hash] options options to filter the results by @option options [Array<String>] :tag up to three tags to filter by @option options [Time] :dt which day the results were bookmarked @option options [String] :url the URL for this bookmark @option options [Boolean] :meta if true, include the change detection signature in the results @return [Array<Post>] @api public @see https://pinboard.in/api/#posts_get
[ "Fetch", "one", "or", "more", "bookmarks" ]
f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb
https://github.com/nwjsmith/thumbtack/blob/f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb/lib/thumbtack/posts.rb#L115-L123
21,740
nwjsmith/thumbtack
lib/thumbtack/posts.rb
Thumbtack.Posts.recent
def recent(options = EMPTY_HASH) parameters = Specification.new( tag: Types::Tags, count: Types::Integer ).parameters(options) posts_from @client.get('/posts/recent', parameters) end
ruby
def recent(options = EMPTY_HASH) parameters = Specification.new( tag: Types::Tags, count: Types::Integer ).parameters(options) posts_from @client.get('/posts/recent', parameters) end
[ "def", "recent", "(", "options", "=", "EMPTY_HASH", ")", "parameters", "=", "Specification", ".", "new", "(", "tag", ":", "Types", "::", "Tags", ",", "count", ":", "Types", "::", "Integer", ")", ".", "parameters", "(", "options", ")", "posts_from", "@client", ".", "get", "(", "'/posts/recent'", ",", "parameters", ")", "end" ]
List the most recent bookmarks @example bookmarks = posts.recent(tag: ['one', 'two', 'three'], count: 25) @param [Hash] options options to filter the results by @option options [Array<String>] :tag up to three tags to filter by @option options [Integer] :count the number of results to return @return [Array<Post>] @api public @see https://pinboard.in/api/#posts_recent
[ "List", "the", "most", "recent", "bookmarks" ]
f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb
https://github.com/nwjsmith/thumbtack/blob/f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb/lib/thumbtack/posts.rb#L142-L148
21,741
nwjsmith/thumbtack
lib/thumbtack/posts.rb
Thumbtack.Posts.all
def all(options = EMPTY_HASH) parameters = Specification.new( tag: Types::Tags, start: Types::Integer, results: Types::Integer, fromdt: Types::Time, todt: Types::Time, meta: Types::Boolean ).parameters(options) results = @client.get('/posts/all', parameters) results.map { |post_hash| Post.from_hash(post_hash) } end
ruby
def all(options = EMPTY_HASH) parameters = Specification.new( tag: Types::Tags, start: Types::Integer, results: Types::Integer, fromdt: Types::Time, todt: Types::Time, meta: Types::Boolean ).parameters(options) results = @client.get('/posts/all', parameters) results.map { |post_hash| Post.from_hash(post_hash) } end
[ "def", "all", "(", "options", "=", "EMPTY_HASH", ")", "parameters", "=", "Specification", ".", "new", "(", "tag", ":", "Types", "::", "Tags", ",", "start", ":", "Types", "::", "Integer", ",", "results", ":", "Types", "::", "Integer", ",", "fromdt", ":", "Types", "::", "Time", ",", "todt", ":", "Types", "::", "Time", ",", "meta", ":", "Types", "::", "Boolean", ")", ".", "parameters", "(", "options", ")", "results", "=", "@client", ".", "get", "(", "'/posts/all'", ",", "parameters", ")", "results", ".", "map", "{", "|", "post_hash", "|", "Post", ".", "from_hash", "(", "post_hash", ")", "}", "end" ]
List all bookmarks @example posts.all(todt: yesterday, meta: true, tag: ['one', 'two', 'three']) @param [Hash] options options to filter the results by @option options [Array<String>] :tag up to three tags to filter by @option options [Array<String>] :start an offset value @option options [Array<String>] :results number of results to return @option options [Time] :fromdt limit results to those created after this time @option options [Time] :todt limit results to those created before this time @option options [Boolean] :meta if true, include the change detection signature in the results @return [Array<Post>] @api public @see https://pinboard.in/api/#posts_all
[ "List", "all", "bookmarks" ]
f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb
https://github.com/nwjsmith/thumbtack/blob/f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb/lib/thumbtack/posts.rb#L175-L186
21,742
nwjsmith/thumbtack
lib/thumbtack/posts.rb
Thumbtack.Posts.suggest
def suggest(url) parameters = Specification.new(url: Types::URL).parameters(url: url) Suggestion.from_array(@client.get('/posts/suggest', parameters)) end
ruby
def suggest(url) parameters = Specification.new(url: Types::URL).parameters(url: url) Suggestion.from_array(@client.get('/posts/suggest', parameters)) end
[ "def", "suggest", "(", "url", ")", "parameters", "=", "Specification", ".", "new", "(", "url", ":", "Types", "::", "URL", ")", ".", "parameters", "(", "url", ":", "url", ")", "Suggestion", ".", "from_array", "(", "@client", ".", "get", "(", "'/posts/suggest'", ",", "parameters", ")", ")", "end" ]
List popular and recommended tags for a URL @example suggestion = posts.suggest(url) @param [String] url URL to fetch suggested tags for Returns a Hash with two entries, :popular is a list of popular tags, :recommended is a list of recommended tags. @return [Array<Suggestion>] @api public @see https://pinboard.in/api/#posts_suggest
[ "List", "popular", "and", "recommended", "tags", "for", "a", "URL" ]
f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb
https://github.com/nwjsmith/thumbtack/blob/f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb/lib/thumbtack/posts.rb#L204-L207
21,743
nwjsmith/thumbtack
lib/thumbtack/posts.rb
Thumbtack.Posts.dates
def dates(options = EMPTY_HASH) parameters = Specification.new(tag: Types::Tags).parameters(options) response = @client.get('/posts/dates', parameters) dates_with_counts_from(response) end
ruby
def dates(options = EMPTY_HASH) parameters = Specification.new(tag: Types::Tags).parameters(options) response = @client.get('/posts/dates', parameters) dates_with_counts_from(response) end
[ "def", "dates", "(", "options", "=", "EMPTY_HASH", ")", "parameters", "=", "Specification", ".", "new", "(", "tag", ":", "Types", "::", "Tags", ")", ".", "parameters", "(", "options", ")", "response", "=", "@client", ".", "get", "(", "'/posts/dates'", ",", "parameters", ")", "dates_with_counts_from", "(", "response", ")", "end" ]
List dates with the number of bookmarks created on each @example dates = posts.dates(tag: ['one', 'two', 'three']) @param [Hash] options options to filter the results by @option options [Array<String>] :tag up to three tags to filter by @return [Hash{Date => Integer}] dates on which bookmarks were created associated with the number of bookmarks created on that date @api public @see https://pinboard.in/api/#posts_dates
[ "List", "dates", "with", "the", "number", "of", "bookmarks", "created", "on", "each" ]
f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb
https://github.com/nwjsmith/thumbtack/blob/f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb/lib/thumbtack/posts.rb#L226-L230
21,744
nwjsmith/thumbtack
lib/thumbtack/posts.rb
Thumbtack.Posts.posts_from
def posts_from(response) response.fetch('posts', EMPTY_ARRAY).map do |post_hash| Post.from_hash(post_hash) end end
ruby
def posts_from(response) response.fetch('posts', EMPTY_ARRAY).map do |post_hash| Post.from_hash(post_hash) end end
[ "def", "posts_from", "(", "response", ")", "response", ".", "fetch", "(", "'posts'", ",", "EMPTY_ARRAY", ")", ".", "map", "do", "|", "post_hash", "|", "Post", ".", "from_hash", "(", "post_hash", ")", "end", "end" ]
Create Post objects from posts response @return [Array<Post>] @api private
[ "Create", "Post", "objects", "from", "posts", "response" ]
f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb
https://github.com/nwjsmith/thumbtack/blob/f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb/lib/thumbtack/posts.rb#L239-L243
21,745
nwjsmith/thumbtack
lib/thumbtack/posts.rb
Thumbtack.Posts.dates_with_counts_from
def dates_with_counts_from(response) entries = response.fetch('dates', EMPTY_HASH).map do |date, count| [Types::Date.deserialize(date), count.to_i] end Hash[entries] end
ruby
def dates_with_counts_from(response) entries = response.fetch('dates', EMPTY_HASH).map do |date, count| [Types::Date.deserialize(date), count.to_i] end Hash[entries] end
[ "def", "dates_with_counts_from", "(", "response", ")", "entries", "=", "response", ".", "fetch", "(", "'dates'", ",", "EMPTY_HASH", ")", ".", "map", "do", "|", "date", ",", "count", "|", "[", "Types", "::", "Date", ".", "deserialize", "(", "date", ")", ",", "count", ".", "to_i", "]", "end", "Hash", "[", "entries", "]", "end" ]
Create Hash of dates to counts from dates response @return [Hash{Date => Integer}] @api private
[ "Create", "Hash", "of", "dates", "to", "counts", "from", "dates", "response" ]
f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb
https://github.com/nwjsmith/thumbtack/blob/f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb/lib/thumbtack/posts.rb#L250-L255
21,746
kreynolds/phidgets-ffi
lib/phidgets-ffi/servo.rb
Phidgets.Servo.on_position_change
def on_position_change(obj=nil, &block) @on_position_change_obj = obj @on_position_change = Proc.new { |device, obj_ptr, index, position| yield self, @servos[index], position, object_for(obj_ptr) } Klass.set_OnPositionChange_Handler(@handle, @on_position_change, pointer_for(obj)) end
ruby
def on_position_change(obj=nil, &block) @on_position_change_obj = obj @on_position_change = Proc.new { |device, obj_ptr, index, position| yield self, @servos[index], position, object_for(obj_ptr) } Klass.set_OnPositionChange_Handler(@handle, @on_position_change, pointer_for(obj)) end
[ "def", "on_position_change", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_position_change_obj", "=", "obj", "@on_position_change", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "index", ",", "position", "|", "yield", "self", ",", "@servos", "[", "index", "]", ",", "position", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnPositionChange_Handler", "(", "@handle", ",", "@on_position_change", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets a position change handler callback function. This is called when a the servo position has changed. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example servo.on_position_change do |motor, position, obj| puts "Moving servo #{motor.index} to #{position}" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "a", "position", "change", "handler", "callback", "function", ".", "This", "is", "called", "when", "a", "the", "servo", "position", "has", "changed", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/servo.rb#L32-L38
21,747
kreynolds/phidgets-ffi
lib/phidgets-ffi/gps.rb
Phidgets.GPS.on_position_fix_status_change
def on_position_fix_status_change(obj=nil, &block) @on_position_fix_status_change_obj = obj @on_position_fix_status_change = Proc.new { |device, obj_ptr, fix_status| yield self, (fix_status == 0 ? false : true), object_for(obj_ptr) } Klass.set_OnPositionFixStatusChange_Handler(@handle, @on_position_fix_status_change, pointer_for(obj)) end
ruby
def on_position_fix_status_change(obj=nil, &block) @on_position_fix_status_change_obj = obj @on_position_fix_status_change = Proc.new { |device, obj_ptr, fix_status| yield self, (fix_status == 0 ? false : true), object_for(obj_ptr) } Klass.set_OnPositionFixStatusChange_Handler(@handle, @on_position_fix_status_change, pointer_for(obj)) end
[ "def", "on_position_fix_status_change", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_position_fix_status_change_obj", "=", "obj", "@on_position_fix_status_change", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "fix_status", "|", "yield", "self", ",", "(", "fix_status", "==", "0", "?", "false", ":", "true", ")", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnPositionFixStatusChange_Handler", "(", "@handle", ",", "@on_position_fix_status_change", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets an position fix status change handler callback function. This is called when the position fix status changes. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example gps.on_position_fix_status_change do |device, fix_status, obj| puts "Position fix status changed to: #{fix_status}" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "an", "position", "fix", "status", "change", "handler", "callback", "function", ".", "This", "is", "called", "when", "the", "position", "fix", "status", "changes", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/gps.rb#L87-L93
21,748
kreynolds/phidgets-ffi
lib/phidgets-ffi/gps.rb
Phidgets.GPS.on_position_change
def on_position_change(obj=nil, &block) @on_position_change_obj = obj @on_position_change = Proc.new { |device, obj_ptr, lat, long, alt| yield self, lat, long, alt, object_for(obj_ptr) } Klass.set_OnPositionChange_Handler(@handle, @on_position_change, pointer_for(obj)) end
ruby
def on_position_change(obj=nil, &block) @on_position_change_obj = obj @on_position_change = Proc.new { |device, obj_ptr, lat, long, alt| yield self, lat, long, alt, object_for(obj_ptr) } Klass.set_OnPositionChange_Handler(@handle, @on_position_change, pointer_for(obj)) end
[ "def", "on_position_change", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_position_change_obj", "=", "obj", "@on_position_change", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "lat", ",", "long", ",", "alt", "|", "yield", "self", ",", "lat", ",", "long", ",", "alt", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnPositionChange_Handler", "(", "@handle", ",", "@on_position_change", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets position change handler callback function. This is called when the latitude, longitude, or altitude changes. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example gps.on_position_change do |device, lat, long, alt, obj| puts "Latitude: #{lat} degrees, longitude: #{long} degrees, altitude: #{alt} m" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "position", "change", "handler", "callback", "function", ".", "This", "is", "called", "when", "the", "latitude", "longitude", "or", "altitude", "changes", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/gps.rb#L105-L111
21,749
kreynolds/phidgets-ffi
lib/phidgets-ffi/temperature_sensor.rb
Phidgets.TemperatureSensor.on_temperature_change
def on_temperature_change(obj=nil, &block) @on_temperature_change_obj = obj @on_temperature_change = Proc.new { |device, obj_ptr, index, temperature| yield self, @thermocouples[index], temperature, object_for(obj_ptr) } Klass.set_OnTemperatureChange_Handler(@handle, @on_temperature_change, pointer_for(obj)) end
ruby
def on_temperature_change(obj=nil, &block) @on_temperature_change_obj = obj @on_temperature_change = Proc.new { |device, obj_ptr, index, temperature| yield self, @thermocouples[index], temperature, object_for(obj_ptr) } Klass.set_OnTemperatureChange_Handler(@handle, @on_temperature_change, pointer_for(obj)) end
[ "def", "on_temperature_change", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_temperature_change_obj", "=", "obj", "@on_temperature_change", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "index", ",", "temperature", "|", "yield", "self", ",", "@thermocouples", "[", "index", "]", ",", "temperature", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnTemperatureChange_Handler", "(", "@handle", ",", "@on_temperature_change", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets a temperature change handler callback function. This is called when when the temperature has changed atleast by the sensitivity value that has been set. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example temp.on_temperature_change do |device, input, temperature, obj| puts "Input #{input.index}'s temperature changed to #{temperature}" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "a", "temperature", "change", "handler", "callback", "function", ".", "This", "is", "called", "when", "when", "the", "temperature", "has", "changed", "atleast", "by", "the", "sensitivity", "value", "that", "has", "been", "set", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/temperature_sensor.rb#L32-L38
21,750
manojmj92/fulfil-ruby
lib/fulfil/request.rb
Fulfil.Request.check_auth_params
def check_auth_params if (Fulfil.authentication.nil? || Fulfil.authentication[:subdomain].empty? || Fulfil.authentication[:api_key].empty?) raise Fulfil::AuthenticationError, "Please set your subdomain and api key" end end
ruby
def check_auth_params if (Fulfil.authentication.nil? || Fulfil.authentication[:subdomain].empty? || Fulfil.authentication[:api_key].empty?) raise Fulfil::AuthenticationError, "Please set your subdomain and api key" end end
[ "def", "check_auth_params", "if", "(", "Fulfil", ".", "authentication", ".", "nil?", "||", "Fulfil", ".", "authentication", "[", ":subdomain", "]", ".", "empty?", "||", "Fulfil", ".", "authentication", "[", ":api_key", "]", ".", "empty?", ")", "raise", "Fulfil", "::", "AuthenticationError", ",", "\"Please set your subdomain and api key\"", "end", "end" ]
USed to check if auth is done properly before making calls
[ "USed", "to", "check", "if", "auth", "is", "done", "properly", "before", "making", "calls" ]
f47832eeb4137c8cc531fab4c1f9a181e6be5652
https://github.com/manojmj92/fulfil-ruby/blob/f47832eeb4137c8cc531fab4c1f9a181e6be5652/lib/fulfil/request.rb#L37-L41
21,751
manojmj92/fulfil-ruby
lib/fulfil/request.rb
Fulfil.Request.request
def request(http_method, data={}, url="") final_url = @options[:base_url] << url begin case http_method when :get response = Curl.get(final_url, data) do |http| http.headers['x-api-key'] = @options[:api_key] http.headers['Accept'] = 'application/json' end end rescue Curl::Err::HostResolutionError raise Fulfil::HostResolutionError, "Invalid Subdomain" end parse_response response end
ruby
def request(http_method, data={}, url="") final_url = @options[:base_url] << url begin case http_method when :get response = Curl.get(final_url, data) do |http| http.headers['x-api-key'] = @options[:api_key] http.headers['Accept'] = 'application/json' end end rescue Curl::Err::HostResolutionError raise Fulfil::HostResolutionError, "Invalid Subdomain" end parse_response response end
[ "def", "request", "(", "http_method", ",", "data", "=", "{", "}", ",", "url", "=", "\"\"", ")", "final_url", "=", "@options", "[", ":base_url", "]", "<<", "url", "begin", "case", "http_method", "when", ":get", "response", "=", "Curl", ".", "get", "(", "final_url", ",", "data", ")", "do", "|", "http", "|", "http", ".", "headers", "[", "'x-api-key'", "]", "=", "@options", "[", ":api_key", "]", "http", ".", "headers", "[", "'Accept'", "]", "=", "'application/json'", "end", "end", "rescue", "Curl", "::", "Err", "::", "HostResolutionError", "raise", "Fulfil", "::", "HostResolutionError", ",", "\"Invalid Subdomain\"", "end", "parse_response", "response", "end" ]
Issue request and get response
[ "Issue", "request", "and", "get", "response" ]
f47832eeb4137c8cc531fab4c1f9a181e6be5652
https://github.com/manojmj92/fulfil-ruby/blob/f47832eeb4137c8cc531fab4c1f9a181e6be5652/lib/fulfil/request.rb#L44-L58
21,752
nwjsmith/thumbtack
lib/thumbtack/tags.rb
Thumbtack.Tags.get
def get response = @client.get('/tags/get') Hash[response.map { |tag, count| [tag, count.to_i] }] end
ruby
def get response = @client.get('/tags/get') Hash[response.map { |tag, count| [tag, count.to_i] }] end
[ "def", "get", "response", "=", "@client", ".", "get", "(", "'/tags/get'", ")", "Hash", "[", "response", ".", "map", "{", "|", "tag", ",", "count", "|", "[", "tag", ",", "count", ".", "to_i", "]", "}", "]", "end" ]
Initialize a Tags @param [Client] client client to communicate with the Pinboard API @api private List tags with their counts @example tag_counts = tags.get @return [Hash{String => Integer}] tags associated with the number of times they have been used @api public @see https://pinboard.in/api/#tags_get
[ "Initialize", "a", "Tags" ]
f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb
https://github.com/nwjsmith/thumbtack/blob/f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb/lib/thumbtack/tags.rb#L27-L30
21,753
nwjsmith/thumbtack
lib/thumbtack/tags.rb
Thumbtack.Tags.delete
def delete(tag) parameters = Specification.new(tag: Types::Tags).parameters(tag: tag) @client.action('/tags/delete', parameters) self end
ruby
def delete(tag) parameters = Specification.new(tag: Types::Tags).parameters(tag: tag) @client.action('/tags/delete', parameters) self end
[ "def", "delete", "(", "tag", ")", "parameters", "=", "Specification", ".", "new", "(", "tag", ":", "Types", "::", "Tags", ")", ".", "parameters", "(", "tag", ":", "tag", ")", "@client", ".", "action", "(", "'/tags/delete'", ",", "parameters", ")", "self", "end" ]
Delete a tag @example tags.delete(tag) @param [String] tag the tag to delete @return [self] @api public @see https://pinboard.in/api/#tags_delete
[ "Delete", "a", "tag" ]
f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb
https://github.com/nwjsmith/thumbtack/blob/f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb/lib/thumbtack/tags.rb#L45-L49
21,754
nwjsmith/thumbtack
lib/thumbtack/tags.rb
Thumbtack.Tags.rename
def rename(old, new) parameters = Specification.new( old: Types::Tags, new: Types::Tags ).parameters(old: old, new: new) @client.action('/tags/rename', parameters) self end
ruby
def rename(old, new) parameters = Specification.new( old: Types::Tags, new: Types::Tags ).parameters(old: old, new: new) @client.action('/tags/rename', parameters) self end
[ "def", "rename", "(", "old", ",", "new", ")", "parameters", "=", "Specification", ".", "new", "(", "old", ":", "Types", "::", "Tags", ",", "new", ":", "Types", "::", "Tags", ")", ".", "parameters", "(", "old", ":", "old", ",", "new", ":", "new", ")", "@client", ".", "action", "(", "'/tags/rename'", ",", "parameters", ")", "self", "end" ]
Rename a tag @example tags.rename(old, new) @param [String] old the tag to be renamed @param [String] new the new name for the tag @return [self] @api public @see https://pinboard.in/api/#tags_rename
[ "Rename", "a", "tag" ]
f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb
https://github.com/nwjsmith/thumbtack/blob/f7d5323b91b901c7d61daadb9ef9c1ed08a3a7cb/lib/thumbtack/tags.rb#L66-L73
21,755
axsh/isono
lib/isono/daemonize.rb
Wakame.Daemonize.change_privilege
def change_privilege(user, group=user) Wakame.log.info("Changing process privilege to #{user}:#{group}") uid, gid = Process.euid, Process.egid target_uid = Etc.getpwnam(user).uid target_gid = Etc.getgrnam(group).gid if uid != target_uid || gid != target_gid if pid_file && File.exist?(pid_file) && uid == 0 File.chown(target_uid, target_gid, pid_file) end # Change process ownership Process.initgroups(user, target_gid) Process::GID.change_privilege(target_gid) Process::UID.change_privilege(target_uid) end rescue Errno::EPERM => e Wakame.log.error("Couldn't change user and group to #{user}:#{group}: #{e}") end
ruby
def change_privilege(user, group=user) Wakame.log.info("Changing process privilege to #{user}:#{group}") uid, gid = Process.euid, Process.egid target_uid = Etc.getpwnam(user).uid target_gid = Etc.getgrnam(group).gid if uid != target_uid || gid != target_gid if pid_file && File.exist?(pid_file) && uid == 0 File.chown(target_uid, target_gid, pid_file) end # Change process ownership Process.initgroups(user, target_gid) Process::GID.change_privilege(target_gid) Process::UID.change_privilege(target_uid) end rescue Errno::EPERM => e Wakame.log.error("Couldn't change user and group to #{user}:#{group}: #{e}") end
[ "def", "change_privilege", "(", "user", ",", "group", "=", "user", ")", "Wakame", ".", "log", ".", "info", "(", "\"Changing process privilege to #{user}:#{group}\"", ")", "uid", ",", "gid", "=", "Process", ".", "euid", ",", "Process", ".", "egid", "target_uid", "=", "Etc", ".", "getpwnam", "(", "user", ")", ".", "uid", "target_gid", "=", "Etc", ".", "getgrnam", "(", "group", ")", ".", "gid", "if", "uid", "!=", "target_uid", "||", "gid", "!=", "target_gid", "if", "pid_file", "&&", "File", ".", "exist?", "(", "pid_file", ")", "&&", "uid", "==", "0", "File", ".", "chown", "(", "target_uid", ",", "target_gid", ",", "pid_file", ")", "end", "# Change process ownership", "Process", ".", "initgroups", "(", "user", ",", "target_gid", ")", "Process", "::", "GID", ".", "change_privilege", "(", "target_gid", ")", "Process", "::", "UID", ".", "change_privilege", "(", "target_uid", ")", "end", "rescue", "Errno", "::", "EPERM", "=>", "e", "Wakame", ".", "log", ".", "error", "(", "\"Couldn't change user and group to #{user}:#{group}: #{e}\"", ")", "end" ]
Change privileges of the process to the specified user and group.
[ "Change", "privileges", "of", "the", "process", "to", "the", "specified", "user", "and", "group", "." ]
0325eb1a46538b8eea63e80745a9161e2532b7cf
https://github.com/axsh/isono/blob/0325eb1a46538b8eea63e80745a9161e2532b7cf/lib/isono/daemonize.rb#L21-L40
21,756
activenetwork-automation/vcoworkflows
lib/vcoworkflows/config.rb
VcoWorkflows.Config.to_json
def to_json config = {} config['url'] = @url config['username'] = @username config['password'] = @password config['verify_ssl'] = @verify_ssl puts JSON.pretty_generate(config) end
ruby
def to_json config = {} config['url'] = @url config['username'] = @username config['password'] = @password config['verify_ssl'] = @verify_ssl puts JSON.pretty_generate(config) end
[ "def", "to_json", "config", "=", "{", "}", "config", "[", "'url'", "]", "=", "@url", "config", "[", "'username'", "]", "=", "@username", "config", "[", "'password'", "]", "=", "@password", "config", "[", "'verify_ssl'", "]", "=", "@verify_ssl", "puts", "JSON", ".", "pretty_generate", "(", "config", ")", "end" ]
Return a JSON document for this object
[ "Return", "a", "JSON", "document", "for", "this", "object" ]
01db57318c14e572dc47261f55c8d08341306642
https://github.com/activenetwork-automation/vcoworkflows/blob/01db57318c14e572dc47261f55c8d08341306642/lib/vcoworkflows/config.rb#L82-L89
21,757
kreynolds/phidgets-ffi
lib/phidgets-ffi/interface_kit.rb
Phidgets.InterfaceKit.on_sensor_change
def on_sensor_change(obj=nil, &block) @on_sensor_change_obj = obj @on_sensor_change = Proc.new { |device, obj_ptr, index, value| yield self, @sensors[index], value, object_for(obj_ptr) } Klass.set_OnSensorChange_Handler(@handle, @on_sensor_change, pointer_for(obj)) end
ruby
def on_sensor_change(obj=nil, &block) @on_sensor_change_obj = obj @on_sensor_change = Proc.new { |device, obj_ptr, index, value| yield self, @sensors[index], value, object_for(obj_ptr) } Klass.set_OnSensorChange_Handler(@handle, @on_sensor_change, pointer_for(obj)) end
[ "def", "on_sensor_change", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_sensor_change_obj", "=", "obj", "@on_sensor_change", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "index", ",", "value", "|", "yield", "self", ",", "@sensors", "[", "index", "]", ",", "value", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnSensorChange_Handler", "(", "@handle", ",", "@on_sensor_change", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets a sensor change handler callback function. This is called when a sensor on the PhidgetInterfaceKit has changed by at least the sensitivity value that has been set for this input. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example ifkit.on_sensor_change do |device, input, value, obj| print "Analog Input #{input.index}, changed to #{value}\n" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "a", "sensor", "change", "handler", "callback", "function", ".", "This", "is", "called", "when", "a", "sensor", "on", "the", "PhidgetInterfaceKit", "has", "changed", "by", "at", "least", "the", "sensitivity", "value", "that", "has", "been", "set", "for", "this", "input", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/interface_kit.rb#L79-L85
21,758
GlobalNamesArchitecture/dwca_hunter
lib/dwca_hunter/downloader.rb
DwcaHunter.Downloader.download
def download raise "#{@source_url} is not accessible" unless @url.valid? f = open(@file_path,'wb') count = 0 @url.net_http.request_get(@url.path) do |r| r.read_body do |s| @download_length += s.length f.write s if block_given? count += 1 if count % 100 == 0 yield @download_length end end end end f.close downloaded = @download_length @download_length = 0 downloaded end
ruby
def download raise "#{@source_url} is not accessible" unless @url.valid? f = open(@file_path,'wb') count = 0 @url.net_http.request_get(@url.path) do |r| r.read_body do |s| @download_length += s.length f.write s if block_given? count += 1 if count % 100 == 0 yield @download_length end end end end f.close downloaded = @download_length @download_length = 0 downloaded end
[ "def", "download", "raise", "\"#{@source_url} is not accessible\"", "unless", "@url", ".", "valid?", "f", "=", "open", "(", "@file_path", ",", "'wb'", ")", "count", "=", "0", "@url", ".", "net_http", ".", "request_get", "(", "@url", ".", "path", ")", "do", "|", "r", "|", "r", ".", "read_body", "do", "|", "s", "|", "@download_length", "+=", "s", ".", "length", "f", ".", "write", "s", "if", "block_given?", "count", "+=", "1", "if", "count", "%", "100", "==", "0", "yield", "@download_length", "end", "end", "end", "end", "f", ".", "close", "downloaded", "=", "@download_length", "@download_length", "=", "0", "downloaded", "end" ]
downloads a given file into a specified filename. If block is given returns download progress
[ "downloads", "a", "given", "file", "into", "a", "specified", "filename", ".", "If", "block", "is", "given", "returns", "download", "progress" ]
fa7665c2bf6a1033ac20097fa1ef372830ff5e2c
https://github.com/GlobalNamesArchitecture/dwca_hunter/blob/fa7665c2bf6a1033ac20097fa1ef372830ff5e2c/lib/dwca_hunter/downloader.rb#L17-L37
21,759
elektronaut/dynamic_image
lib/dynamic_image/helper.rb
DynamicImage.Helper.dynamic_image_tag
def dynamic_image_tag(record_or_array, options = {}) record = extract_dynamic_image_record(record_or_array) options = { alt: filename_to_alt(record.filename) }.merge(options) size = fit_size!(record_or_array, options) url_options = options.extract!(*allowed_dynamic_image_url_options) html_options = { size: size }.merge(options) image_tag(dynamic_image_path_with_size(record_or_array, size, url_options), html_options) end
ruby
def dynamic_image_tag(record_or_array, options = {}) record = extract_dynamic_image_record(record_or_array) options = { alt: filename_to_alt(record.filename) }.merge(options) size = fit_size!(record_or_array, options) url_options = options.extract!(*allowed_dynamic_image_url_options) html_options = { size: size }.merge(options) image_tag(dynamic_image_path_with_size(record_or_array, size, url_options), html_options) end
[ "def", "dynamic_image_tag", "(", "record_or_array", ",", "options", "=", "{", "}", ")", "record", "=", "extract_dynamic_image_record", "(", "record_or_array", ")", "options", "=", "{", "alt", ":", "filename_to_alt", "(", "record", ".", "filename", ")", "}", ".", "merge", "(", "options", ")", "size", "=", "fit_size!", "(", "record_or_array", ",", "options", ")", "url_options", "=", "options", ".", "extract!", "(", "allowed_dynamic_image_url_options", ")", "html_options", "=", "{", "size", ":", "size", "}", ".", "merge", "(", "options", ")", "image_tag", "(", "dynamic_image_path_with_size", "(", "record_or_array", ",", "size", ",", "url_options", ")", ",", "html_options", ")", "end" ]
Returns an HTML image tag for the record. If no size is given, it will render at the original size. ==== Options * <tt>:alt</tt>: If no alt text is given, it will default to the filename of the uploaded image. See +dynamic_image_url+ for info on how to size and cropping. Options supported by +polymorphic_url+ will be passed to the router. Any other options will be added as HTML attributes. ==== Examples image = Image.find(params[:id]) dynamic_image_tag(image) # => <img alt="My file" height="200" src="..." width="320" /> dynamic_image_tag(image, size: "100x100", alt="Avatar") # => <img alt="Avatar" height="62" src="..." width="100" />
[ "Returns", "an", "HTML", "image", "tag", "for", "the", "record", ".", "If", "no", "size", "is", "given", "it", "will", "render", "at", "the", "original", "size", "." ]
d711f8f5d8385fb36d7ff9a6012f3fd123005c18
https://github.com/elektronaut/dynamic_image/blob/d711f8f5d8385fb36d7ff9a6012f3fd123005c18/lib/dynamic_image/helper.rb#L32-L44
21,760
adamcooke/authie
lib/authie/session.rb
Authie.Session.touch!
def touch! self.check_security! self.last_activity_at = Time.now self.last_activity_ip = controller.request.ip self.last_activity_path = controller.request.path self.requests += 1 self.save! Authie.config.events.dispatch(:session_touched, self) true end
ruby
def touch! self.check_security! self.last_activity_at = Time.now self.last_activity_ip = controller.request.ip self.last_activity_path = controller.request.path self.requests += 1 self.save! Authie.config.events.dispatch(:session_touched, self) true end
[ "def", "touch!", "self", ".", "check_security!", "self", ".", "last_activity_at", "=", "Time", ".", "now", "self", ".", "last_activity_ip", "=", "controller", ".", "request", ".", "ip", "self", ".", "last_activity_path", "=", "controller", ".", "request", ".", "path", "self", ".", "requests", "+=", "1", "self", ".", "save!", "Authie", ".", "config", ".", "events", ".", "dispatch", "(", ":session_touched", ",", "self", ")", "true", "end" ]
This method should be called each time a user performs an action while authenticated with this session.
[ "This", "method", "should", "be", "called", "each", "time", "a", "user", "performs", "an", "action", "while", "authenticated", "with", "this", "session", "." ]
d88eb2096b584d6fa20da69b155da97c6f042d05
https://github.com/adamcooke/authie/blob/d88eb2096b584d6fa20da69b155da97c6f042d05/lib/authie/session.rb#L56-L65
21,761
adamcooke/authie
lib/authie/session.rb
Authie.Session.set_cookie!
def set_cookie! cookies[:user_session] = { :value => self.temporary_token, :secure => controller.request.ssl?, :httponly => true, :expires => self.expires_at } Authie.config.events.dispatch(:session_cookie_updated, self) true end
ruby
def set_cookie! cookies[:user_session] = { :value => self.temporary_token, :secure => controller.request.ssl?, :httponly => true, :expires => self.expires_at } Authie.config.events.dispatch(:session_cookie_updated, self) true end
[ "def", "set_cookie!", "cookies", "[", ":user_session", "]", "=", "{", ":value", "=>", "self", ".", "temporary_token", ",", ":secure", "=>", "controller", ".", "request", ".", "ssl?", ",", ":httponly", "=>", "true", ",", ":expires", "=>", "self", ".", "expires_at", "}", "Authie", ".", "config", ".", "events", ".", "dispatch", "(", ":session_cookie_updated", ",", "self", ")", "true", "end" ]
Sets the cookie on the associated controller.
[ "Sets", "the", "cookie", "on", "the", "associated", "controller", "." ]
d88eb2096b584d6fa20da69b155da97c6f042d05
https://github.com/adamcooke/authie/blob/d88eb2096b584d6fa20da69b155da97c6f042d05/lib/authie/session.rb#L68-L77
21,762
adamcooke/authie
lib/authie/session.rb
Authie.Session.check_security!
def check_security! if controller if cookies[:browser_id] != self.browser_id invalidate! Authie.config.events.dispatch(:browser_id_mismatch_error, self) raise BrowserMismatch, "Browser ID mismatch" end unless self.active? invalidate! Authie.config.events.dispatch(:invalid_session_error, self) raise InactiveSession, "Session is no longer active" end if self.expired? invalidate! Authie.config.events.dispatch(:expired_session_error, self) raise ExpiredSession, "Persistent session has expired" end if self.inactive? invalidate! Authie.config.events.dispatch(:inactive_session_error, self) raise InactiveSession, "Non-persistent session has expired" end if self.host && self.host != controller.request.host invalidate! Authie.config.events.dispatch(:host_mismatch_error, self) raise HostMismatch, "Session was created on #{self.host} but accessed using #{controller.request.host}" end end end
ruby
def check_security! if controller if cookies[:browser_id] != self.browser_id invalidate! Authie.config.events.dispatch(:browser_id_mismatch_error, self) raise BrowserMismatch, "Browser ID mismatch" end unless self.active? invalidate! Authie.config.events.dispatch(:invalid_session_error, self) raise InactiveSession, "Session is no longer active" end if self.expired? invalidate! Authie.config.events.dispatch(:expired_session_error, self) raise ExpiredSession, "Persistent session has expired" end if self.inactive? invalidate! Authie.config.events.dispatch(:inactive_session_error, self) raise InactiveSession, "Non-persistent session has expired" end if self.host && self.host != controller.request.host invalidate! Authie.config.events.dispatch(:host_mismatch_error, self) raise HostMismatch, "Session was created on #{self.host} but accessed using #{controller.request.host}" end end end
[ "def", "check_security!", "if", "controller", "if", "cookies", "[", ":browser_id", "]", "!=", "self", ".", "browser_id", "invalidate!", "Authie", ".", "config", ".", "events", ".", "dispatch", "(", ":browser_id_mismatch_error", ",", "self", ")", "raise", "BrowserMismatch", ",", "\"Browser ID mismatch\"", "end", "unless", "self", ".", "active?", "invalidate!", "Authie", ".", "config", ".", "events", ".", "dispatch", "(", ":invalid_session_error", ",", "self", ")", "raise", "InactiveSession", ",", "\"Session is no longer active\"", "end", "if", "self", ".", "expired?", "invalidate!", "Authie", ".", "config", ".", "events", ".", "dispatch", "(", ":expired_session_error", ",", "self", ")", "raise", "ExpiredSession", ",", "\"Persistent session has expired\"", "end", "if", "self", ".", "inactive?", "invalidate!", "Authie", ".", "config", ".", "events", ".", "dispatch", "(", ":inactive_session_error", ",", "self", ")", "raise", "InactiveSession", ",", "\"Non-persistent session has expired\"", "end", "if", "self", ".", "host", "&&", "self", ".", "host", "!=", "controller", ".", "request", ".", "host", "invalidate!", "Authie", ".", "config", ".", "events", ".", "dispatch", "(", ":host_mismatch_error", ",", "self", ")", "raise", "HostMismatch", ",", "\"Session was created on #{self.host} but accessed using #{controller.request.host}\"", "end", "end", "end" ]
Check the security of the session to ensure it can be used.
[ "Check", "the", "security", "of", "the", "session", "to", "ensure", "it", "can", "be", "used", "." ]
d88eb2096b584d6fa20da69b155da97c6f042d05
https://github.com/adamcooke/authie/blob/d88eb2096b584d6fa20da69b155da97c6f042d05/lib/authie/session.rb#L80-L112
21,763
adamcooke/authie
lib/authie/session.rb
Authie.Session.invalidate!
def invalidate! self.active = false self.save! if controller cookies.delete(:user_session) end Authie.config.events.dispatch(:session_invalidated, self) true end
ruby
def invalidate! self.active = false self.save! if controller cookies.delete(:user_session) end Authie.config.events.dispatch(:session_invalidated, self) true end
[ "def", "invalidate!", "self", ".", "active", "=", "false", "self", ".", "save!", "if", "controller", "cookies", ".", "delete", "(", ":user_session", ")", "end", "Authie", ".", "config", ".", "events", ".", "dispatch", "(", ":session_invalidated", ",", "self", ")", "true", "end" ]
Mark this session as invalid
[ "Mark", "this", "session", "as", "invalid" ]
d88eb2096b584d6fa20da69b155da97c6f042d05
https://github.com/adamcooke/authie/blob/d88eb2096b584d6fa20da69b155da97c6f042d05/lib/authie/session.rb#L147-L155
21,764
adamcooke/authie
lib/authie/session.rb
Authie.Session.see_password!
def see_password! self.password_seen_at = Time.now self.save! Authie.config.events.dispatch(:seen_password, self) true end
ruby
def see_password! self.password_seen_at = Time.now self.save! Authie.config.events.dispatch(:seen_password, self) true end
[ "def", "see_password!", "self", ".", "password_seen_at", "=", "Time", ".", "now", "self", ".", "save!", "Authie", ".", "config", ".", "events", ".", "dispatch", "(", ":seen_password", ",", "self", ")", "true", "end" ]
Note that we have just seen the user enter their password.
[ "Note", "that", "we", "have", "just", "seen", "the", "user", "enter", "their", "password", "." ]
d88eb2096b584d6fa20da69b155da97c6f042d05
https://github.com/adamcooke/authie/blob/d88eb2096b584d6fa20da69b155da97c6f042d05/lib/authie/session.rb#L177-L182
21,765
adamcooke/authie
lib/authie/session.rb
Authie.Session.mark_as_two_factored!
def mark_as_two_factored! self.two_factored_at = Time.now self.two_factored_ip = controller.request.ip self.save! Authie.config.events.dispatch(:marked_as_two_factored, self) true end
ruby
def mark_as_two_factored! self.two_factored_at = Time.now self.two_factored_ip = controller.request.ip self.save! Authie.config.events.dispatch(:marked_as_two_factored, self) true end
[ "def", "mark_as_two_factored!", "self", ".", "two_factored_at", "=", "Time", ".", "now", "self", ".", "two_factored_ip", "=", "controller", ".", "request", ".", "ip", "self", ".", "save!", "Authie", ".", "config", ".", "events", ".", "dispatch", "(", ":marked_as_two_factored", ",", "self", ")", "true", "end" ]
Mark this request as two factor authoritsed
[ "Mark", "this", "request", "as", "two", "factor", "authoritsed" ]
d88eb2096b584d6fa20da69b155da97c6f042d05
https://github.com/adamcooke/authie/blob/d88eb2096b584d6fa20da69b155da97c6f042d05/lib/authie/session.rb#L195-L201
21,766
adamcooke/authie
lib/authie/session.rb
Authie.Session.revert_to_parent!
def revert_to_parent! if self.parent self.invalidate! self.parent.activate! self.parent.controller = self.controller self.parent.set_cookie! self.parent else raise NoParentSessionForRevert, "Session does not have a parent therefore cannot be reverted." end end
ruby
def revert_to_parent! if self.parent self.invalidate! self.parent.activate! self.parent.controller = self.controller self.parent.set_cookie! self.parent else raise NoParentSessionForRevert, "Session does not have a parent therefore cannot be reverted." end end
[ "def", "revert_to_parent!", "if", "self", ".", "parent", "self", ".", "invalidate!", "self", ".", "parent", ".", "activate!", "self", ".", "parent", ".", "controller", "=", "self", ".", "controller", "self", ".", "parent", ".", "set_cookie!", "self", ".", "parent", "else", "raise", "NoParentSessionForRevert", ",", "\"Session does not have a parent therefore cannot be reverted.\"", "end", "end" ]
Revert back to the parent session
[ "Revert", "back", "to", "the", "parent", "session" ]
d88eb2096b584d6fa20da69b155da97c6f042d05
https://github.com/adamcooke/authie/blob/d88eb2096b584d6fa20da69b155da97c6f042d05/lib/authie/session.rb#L209-L219
21,767
dbgrandi/danger-prose
lib/danger_plugin.rb
Danger.DangerProse.lint_files
def lint_files(files = nil) # Installs a prose checker if needed system 'pip install --user proselint' unless proselint_installed? # Check that this is in the user's PATH after installing raise "proselint is not in the user's PATH, or it failed to install" unless proselint_installed? # Either use files provided, or use the modified + added markdown_files = get_files files proses = {} to_disable = disable_linters || ["misc.scare_quotes", "typography.symbols"] with_proselint_disabled(to_disable) do # Convert paths to proselint results result_jsons = Hash[markdown_files.to_a.uniq.collect { |v| [v, get_proselint_json(v)] }] proses = result_jsons.select { |_, prose| prose['data']['errors'].count > 0 } end # Get some metadata about the local setup current_slug = env.ci_source.repo_slug # We got some error reports back from proselint if proses.count > 0 message = "### Proselint found issues\n\n" proses.each do |path, prose| github_loc = "/#{current_slug}/tree/#{github.branch_for_head}/#{path}" message << "#### [#{path}](#{github_loc})\n\n" message << "Line | Message | Severity |\n" message << "| --- | ----- | ----- |\n" prose['data']['errors'].each do |error| message << "#{error['line']} | #{error['message']} | #{error['severity']}\n" end end markdown message end end
ruby
def lint_files(files = nil) # Installs a prose checker if needed system 'pip install --user proselint' unless proselint_installed? # Check that this is in the user's PATH after installing raise "proselint is not in the user's PATH, or it failed to install" unless proselint_installed? # Either use files provided, or use the modified + added markdown_files = get_files files proses = {} to_disable = disable_linters || ["misc.scare_quotes", "typography.symbols"] with_proselint_disabled(to_disable) do # Convert paths to proselint results result_jsons = Hash[markdown_files.to_a.uniq.collect { |v| [v, get_proselint_json(v)] }] proses = result_jsons.select { |_, prose| prose['data']['errors'].count > 0 } end # Get some metadata about the local setup current_slug = env.ci_source.repo_slug # We got some error reports back from proselint if proses.count > 0 message = "### Proselint found issues\n\n" proses.each do |path, prose| github_loc = "/#{current_slug}/tree/#{github.branch_for_head}/#{path}" message << "#### [#{path}](#{github_loc})\n\n" message << "Line | Message | Severity |\n" message << "| --- | ----- | ----- |\n" prose['data']['errors'].each do |error| message << "#{error['line']} | #{error['message']} | #{error['severity']}\n" end end markdown message end end
[ "def", "lint_files", "(", "files", "=", "nil", ")", "# Installs a prose checker if needed", "system", "'pip install --user proselint'", "unless", "proselint_installed?", "# Check that this is in the user's PATH after installing", "raise", "\"proselint is not in the user's PATH, or it failed to install\"", "unless", "proselint_installed?", "# Either use files provided, or use the modified + added", "markdown_files", "=", "get_files", "files", "proses", "=", "{", "}", "to_disable", "=", "disable_linters", "||", "[", "\"misc.scare_quotes\"", ",", "\"typography.symbols\"", "]", "with_proselint_disabled", "(", "to_disable", ")", "do", "# Convert paths to proselint results", "result_jsons", "=", "Hash", "[", "markdown_files", ".", "to_a", ".", "uniq", ".", "collect", "{", "|", "v", "|", "[", "v", ",", "get_proselint_json", "(", "v", ")", "]", "}", "]", "proses", "=", "result_jsons", ".", "select", "{", "|", "_", ",", "prose", "|", "prose", "[", "'data'", "]", "[", "'errors'", "]", ".", "count", ">", "0", "}", "end", "# Get some metadata about the local setup", "current_slug", "=", "env", ".", "ci_source", ".", "repo_slug", "# We got some error reports back from proselint", "if", "proses", ".", "count", ">", "0", "message", "=", "\"### Proselint found issues\\n\\n\"", "proses", ".", "each", "do", "|", "path", ",", "prose", "|", "github_loc", "=", "\"/#{current_slug}/tree/#{github.branch_for_head}/#{path}\"", "message", "<<", "\"#### [#{path}](#{github_loc})\\n\\n\"", "message", "<<", "\"Line | Message | Severity |\\n\"", "message", "<<", "\"| --- | ----- | ----- |\\n\"", "prose", "[", "'data'", "]", "[", "'errors'", "]", ".", "each", "do", "|", "error", "|", "message", "<<", "\"#{error['line']} | #{error['message']} | #{error['severity']}\\n\"", "end", "end", "markdown", "message", "end", "end" ]
Lints the globbed markdown files. Will fail if `proselint` cannot be installed correctly. Generates a `markdown` list of warnings for the prose in a corpus of .markdown and .md files. @param [String] files A globbed string which should return the files that you want to lint, defaults to nil. if nil, modified and added files from the diff will be used. @return [void]
[ "Lints", "the", "globbed", "markdown", "files", ".", "Will", "fail", "if", "proselint", "cannot", "be", "installed", "correctly", ".", "Generates", "a", "markdown", "list", "of", "warnings", "for", "the", "prose", "in", "a", "corpus", "of", ".", "markdown", "and", ".", "md", "files", "." ]
b32ddfe58194dfe16be327f3d1e4a0d85af714a9
https://github.com/dbgrandi/danger-prose/blob/b32ddfe58194dfe16be327f3d1e4a0d85af714a9/lib/danger_plugin.rb#L48-L86
21,768
dbgrandi/danger-prose
lib/danger_plugin.rb
Danger.DangerProse.with_proselint_disabled
def with_proselint_disabled(disable_linters) # Create the disabled linters JSON in ~/.proselintrc proselint_template = File.join(File.dirname(__FILE__), 'proselintrc') proselintJSON = JSON.parse(File.read(proselint_template)) # Disable individual linters disable_linters.each do |linter| proselintJSON['checks'][linter] = false end # Re-save the new JSON into the home dir temp_proselint_rc_path = File.join(Dir.home, '.proselintrc') File.write(temp_proselint_rc_path, JSON.pretty_generate(proselintJSON)) # Run the closure yield # Delete .proselintrc File.unlink temp_proselint_rc_path end
ruby
def with_proselint_disabled(disable_linters) # Create the disabled linters JSON in ~/.proselintrc proselint_template = File.join(File.dirname(__FILE__), 'proselintrc') proselintJSON = JSON.parse(File.read(proselint_template)) # Disable individual linters disable_linters.each do |linter| proselintJSON['checks'][linter] = false end # Re-save the new JSON into the home dir temp_proselint_rc_path = File.join(Dir.home, '.proselintrc') File.write(temp_proselint_rc_path, JSON.pretty_generate(proselintJSON)) # Run the closure yield # Delete .proselintrc File.unlink temp_proselint_rc_path end
[ "def", "with_proselint_disabled", "(", "disable_linters", ")", "# Create the disabled linters JSON in ~/.proselintrc", "proselint_template", "=", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'proselintrc'", ")", "proselintJSON", "=", "JSON", ".", "parse", "(", "File", ".", "read", "(", "proselint_template", ")", ")", "# Disable individual linters", "disable_linters", ".", "each", "do", "|", "linter", "|", "proselintJSON", "[", "'checks'", "]", "[", "linter", "]", "=", "false", "end", "# Re-save the new JSON into the home dir", "temp_proselint_rc_path", "=", "File", ".", "join", "(", "Dir", ".", "home", ",", "'.proselintrc'", ")", "File", ".", "write", "(", "temp_proselint_rc_path", ",", "JSON", ".", "pretty_generate", "(", "proselintJSON", ")", ")", "# Run the closure", "yield", "# Delete .proselintrc", "File", ".", "unlink", "temp_proselint_rc_path", "end" ]
Creates a temporary proselint settings file @return void
[ "Creates", "a", "temporary", "proselint", "settings", "file" ]
b32ddfe58194dfe16be327f3d1e4a0d85af714a9
https://github.com/dbgrandi/danger-prose/blob/b32ddfe58194dfe16be327f3d1e4a0d85af714a9/lib/danger_plugin.rb#L191-L210
21,769
jonmagic/grim
lib/grim/page.rb
Grim.Page.save
def save(path, options={}) raise PathMissing if path.nil? || path !~ /\S/ Grim.processor.save(@pdf, @index, path, options) end
ruby
def save(path, options={}) raise PathMissing if path.nil? || path !~ /\S/ Grim.processor.save(@pdf, @index, path, options) end
[ "def", "save", "(", "path", ",", "options", "=", "{", "}", ")", "raise", "PathMissing", "if", "path", ".", "nil?", "||", "path", "!~", "/", "\\S", "/", "Grim", ".", "processor", ".", "save", "(", "@pdf", ",", "@index", ",", "path", ",", "options", ")", "end" ]
Sets up some instance variables on new instance. pdf - the pdf this page belongs to index - the index of the page in the array of pages options - A Hash of options. :pdftotext_path - The String path of where to find the pdftotext binary to use when extracting text (default: "pdftotext"). Extracts the selected page and turns it into an image. Tested on png and jpeg. path - String of the path to save to options - Hash of options to customize the saving of the image (ie: width, density, and quality) For example: pdf[1].save(/path/to/save/image.png) # => true Returns a File.
[ "Sets", "up", "some", "instance", "variables", "on", "new", "instance", "." ]
45ffef3f762345ca1cbe8901f95898ac1de5e37c
https://github.com/jonmagic/grim/blob/45ffef3f762345ca1cbe8901f95898ac1de5e37c/lib/grim/page.rb#L37-L41
21,770
bitrise-io/ipa_analyzer
lib/ipa_analyzer/analyzer.rb
IpaAnalyzer.Analyzer.find_app_folder_in_ipa
def find_app_folder_in_ipa raise 'IPA is not open' unless self.open? # Check the most common location app_folder_in_ipa = "Payload/#{File.basename(@ipa_path, File.extname(@ipa_path))}.app" # mobileprovision_entry = @ipa_zipfile.find_entry("#{app_folder_in_ipa}/embedded.mobileprovision") info_plist_entry = @ipa_zipfile.find_entry("#{app_folder_in_ipa}/Info.plist") # if !mobileprovision_entry.nil? && !info_plist_entry.nil? return app_folder_in_ipa end # It's somewhere else - let's find it! @ipa_zipfile.dir.entries('Payload').each do |dir_entry| next unless dir_entry =~ /.app$/ app_folder_in_ipa = "Payload/#{dir_entry}" mobileprovision_entry = @ipa_zipfile.find_entry("#{app_folder_in_ipa}/embedded.mobileprovision") info_plist_entry = @ipa_zipfile.find_entry("#{app_folder_in_ipa}/Info.plist") break if !mobileprovision_entry.nil? && !info_plist_entry.nil? end if !mobileprovision_entry.nil? && !info_plist_entry.nil? return app_folder_in_ipa end return nil end
ruby
def find_app_folder_in_ipa raise 'IPA is not open' unless self.open? # Check the most common location app_folder_in_ipa = "Payload/#{File.basename(@ipa_path, File.extname(@ipa_path))}.app" # mobileprovision_entry = @ipa_zipfile.find_entry("#{app_folder_in_ipa}/embedded.mobileprovision") info_plist_entry = @ipa_zipfile.find_entry("#{app_folder_in_ipa}/Info.plist") # if !mobileprovision_entry.nil? && !info_plist_entry.nil? return app_folder_in_ipa end # It's somewhere else - let's find it! @ipa_zipfile.dir.entries('Payload').each do |dir_entry| next unless dir_entry =~ /.app$/ app_folder_in_ipa = "Payload/#{dir_entry}" mobileprovision_entry = @ipa_zipfile.find_entry("#{app_folder_in_ipa}/embedded.mobileprovision") info_plist_entry = @ipa_zipfile.find_entry("#{app_folder_in_ipa}/Info.plist") break if !mobileprovision_entry.nil? && !info_plist_entry.nil? end if !mobileprovision_entry.nil? && !info_plist_entry.nil? return app_folder_in_ipa end return nil end
[ "def", "find_app_folder_in_ipa", "raise", "'IPA is not open'", "unless", "self", ".", "open?", "# Check the most common location", "app_folder_in_ipa", "=", "\"Payload/#{File.basename(@ipa_path, File.extname(@ipa_path))}.app\"", "#", "mobileprovision_entry", "=", "@ipa_zipfile", ".", "find_entry", "(", "\"#{app_folder_in_ipa}/embedded.mobileprovision\"", ")", "info_plist_entry", "=", "@ipa_zipfile", ".", "find_entry", "(", "\"#{app_folder_in_ipa}/Info.plist\"", ")", "#", "if", "!", "mobileprovision_entry", ".", "nil?", "&&", "!", "info_plist_entry", ".", "nil?", "return", "app_folder_in_ipa", "end", "# It's somewhere else - let's find it!", "@ipa_zipfile", ".", "dir", ".", "entries", "(", "'Payload'", ")", ".", "each", "do", "|", "dir_entry", "|", "next", "unless", "dir_entry", "=~", "/", "/", "app_folder_in_ipa", "=", "\"Payload/#{dir_entry}\"", "mobileprovision_entry", "=", "@ipa_zipfile", ".", "find_entry", "(", "\"#{app_folder_in_ipa}/embedded.mobileprovision\"", ")", "info_plist_entry", "=", "@ipa_zipfile", ".", "find_entry", "(", "\"#{app_folder_in_ipa}/Info.plist\"", ")", "break", "if", "!", "mobileprovision_entry", ".", "nil?", "&&", "!", "info_plist_entry", ".", "nil?", "end", "if", "!", "mobileprovision_entry", ".", "nil?", "&&", "!", "info_plist_entry", ".", "nil?", "return", "app_folder_in_ipa", "end", "return", "nil", "end" ]
Find the .app folder which contains both the "embedded.mobileprovision" and "Info.plist" files.
[ "Find", "the", ".", "app", "folder", "which", "contains", "both", "the", "embedded", ".", "mobileprovision", "and", "Info", ".", "plist", "files", "." ]
70dbcbdbb2371b60c327931aa8fea587505e41bd
https://github.com/bitrise-io/ipa_analyzer/blob/70dbcbdbb2371b60c327931aa8fea587505e41bd/lib/ipa_analyzer/analyzer.rb#L105-L133
21,771
infosimples/deathbycaptcha
lib/deathbycaptcha/client.rb
DeathByCaptcha.Client.load_captcha
def load_captcha(options) if options[:raw64] options[:raw64] elsif options[:raw] Base64.encode64(options[:raw]) elsif options[:file] Base64.encode64(options[:file].read()) elsif options[:path] Base64.encode64(File.open(options[:path], 'rb').read) elsif options[:url] Base64.encode64(open_url(options[:url])) else '' end rescue '' end
ruby
def load_captcha(options) if options[:raw64] options[:raw64] elsif options[:raw] Base64.encode64(options[:raw]) elsif options[:file] Base64.encode64(options[:file].read()) elsif options[:path] Base64.encode64(File.open(options[:path], 'rb').read) elsif options[:url] Base64.encode64(open_url(options[:url])) else '' end rescue '' end
[ "def", "load_captcha", "(", "options", ")", "if", "options", "[", ":raw64", "]", "options", "[", ":raw64", "]", "elsif", "options", "[", ":raw", "]", "Base64", ".", "encode64", "(", "options", "[", ":raw", "]", ")", "elsif", "options", "[", ":file", "]", "Base64", ".", "encode64", "(", "options", "[", ":file", "]", ".", "read", "(", ")", ")", "elsif", "options", "[", ":path", "]", "Base64", ".", "encode64", "(", "File", ".", "open", "(", "options", "[", ":path", "]", ",", "'rb'", ")", ".", "read", ")", "elsif", "options", "[", ":url", "]", "Base64", ".", "encode64", "(", "open_url", "(", "options", "[", ":url", "]", ")", ")", "else", "''", "end", "rescue", "''", "end" ]
Load a captcha raw content encoded in base64 from options. @param [Hash] options Options hash. @option options [String] :url URL of the image to be decoded. @option options [String] :path File path of the image to be decoded. @option options [File] :file File instance with image to be decoded. @option options [String] :raw Binary content of the image to be decoded. @option options [String] :raw64 Binary content encoded in base64 of the image to be decoded. @return [String] The binary image base64 encoded.
[ "Load", "a", "captcha", "raw", "content", "encoded", "in", "base64", "from", "options", "." ]
b6fc9503025b24adaffb8c28843995a7f1715cb7
https://github.com/infosimples/deathbycaptcha/blob/b6fc9503025b24adaffb8c28843995a7f1715cb7/lib/deathbycaptcha/client.rb#L169-L185
21,772
infosimples/deathbycaptcha
lib/deathbycaptcha/client/socket.rb
DeathByCaptcha.Client::Socket.captcha
def captcha(captcha_id) response = perform('captcha', captcha: captcha_id) DeathByCaptcha::Captcha.new(response) end
ruby
def captcha(captcha_id) response = perform('captcha', captcha: captcha_id) DeathByCaptcha::Captcha.new(response) end
[ "def", "captcha", "(", "captcha_id", ")", "response", "=", "perform", "(", "'captcha'", ",", "captcha", ":", "captcha_id", ")", "DeathByCaptcha", "::", "Captcha", ".", "new", "(", "response", ")", "end" ]
Retrieve information from an uploaded captcha. @param [Integer] captcha_id Numeric ID of the captcha. @return [DeathByCaptcha::Captcha] The captcha object.
[ "Retrieve", "information", "from", "an", "uploaded", "captcha", "." ]
b6fc9503025b24adaffb8c28843995a7f1715cb7
https://github.com/infosimples/deathbycaptcha/blob/b6fc9503025b24adaffb8c28843995a7f1715cb7/lib/deathbycaptcha/client/socket.rb#L15-L18
21,773
infosimples/deathbycaptcha
lib/deathbycaptcha/client/socket.rb
DeathByCaptcha.Client::Socket.perform
def perform(action, payload = {}) payload.merge!( cmd: action, version: DeathByCaptcha::API_VERSION, username: self.username, password: self.password ) socket = create_socket() socket.puts(payload.to_json) response = socket.read() socket.close() begin response = JSON.parse(response) rescue raise DeathByCaptcha::APIResponseError.new("invalid JSON: #{response}") end if !(error = response['error'].to_s).empty? case error when 'not-logged-in', 'invalid-credentials', 'banned', 'insufficient-funds' raise DeathByCaptcha::APIForbidden when 'invalid-captcha' raise DeathByCaptcha::APIBadRequest when 'service-overload' raise DeathByCaptcha::APIServiceUnavailable else raise DeathByCaptcha::APIResponseError.new(error) end end response end
ruby
def perform(action, payload = {}) payload.merge!( cmd: action, version: DeathByCaptcha::API_VERSION, username: self.username, password: self.password ) socket = create_socket() socket.puts(payload.to_json) response = socket.read() socket.close() begin response = JSON.parse(response) rescue raise DeathByCaptcha::APIResponseError.new("invalid JSON: #{response}") end if !(error = response['error'].to_s).empty? case error when 'not-logged-in', 'invalid-credentials', 'banned', 'insufficient-funds' raise DeathByCaptcha::APIForbidden when 'invalid-captcha' raise DeathByCaptcha::APIBadRequest when 'service-overload' raise DeathByCaptcha::APIServiceUnavailable else raise DeathByCaptcha::APIResponseError.new(error) end end response end
[ "def", "perform", "(", "action", ",", "payload", "=", "{", "}", ")", "payload", ".", "merge!", "(", "cmd", ":", "action", ",", "version", ":", "DeathByCaptcha", "::", "API_VERSION", ",", "username", ":", "self", ".", "username", ",", "password", ":", "self", ".", "password", ")", "socket", "=", "create_socket", "(", ")", "socket", ".", "puts", "(", "payload", ".", "to_json", ")", "response", "=", "socket", ".", "read", "(", ")", "socket", ".", "close", "(", ")", "begin", "response", "=", "JSON", ".", "parse", "(", "response", ")", "rescue", "raise", "DeathByCaptcha", "::", "APIResponseError", ".", "new", "(", "\"invalid JSON: #{response}\"", ")", "end", "if", "!", "(", "error", "=", "response", "[", "'error'", "]", ".", "to_s", ")", ".", "empty?", "case", "error", "when", "'not-logged-in'", ",", "'invalid-credentials'", ",", "'banned'", ",", "'insufficient-funds'", "raise", "DeathByCaptcha", "::", "APIForbidden", "when", "'invalid-captcha'", "raise", "DeathByCaptcha", "::", "APIBadRequest", "when", "'service-overload'", "raise", "DeathByCaptcha", "::", "APIServiceUnavailable", "else", "raise", "DeathByCaptcha", "::", "APIResponseError", ".", "new", "(", "error", ")", "end", "end", "response", "end" ]
Perform a Socket communication with the DeathByCaptcha API. @param [String] action API method name. @param [Hash] payload Data to be exchanged in the communication. @return [Hash] Response from the DeathByCaptcha API.
[ "Perform", "a", "Socket", "communication", "with", "the", "DeathByCaptcha", "API", "." ]
b6fc9503025b24adaffb8c28843995a7f1715cb7
https://github.com/infosimples/deathbycaptcha/blob/b6fc9503025b24adaffb8c28843995a7f1715cb7/lib/deathbycaptcha/client/socket.rb#L74-L107
21,774
infosimples/deathbycaptcha
lib/deathbycaptcha/client/socket.rb
DeathByCaptcha.Client::Socket.create_socket
def create_socket socket = ::Socket.new(::Socket::AF_INET, ::Socket::SOCK_STREAM, 0) sockaddr = ::Socket.sockaddr_in(PORTS.sample, self.hostname) begin # emulate blocking connect socket.connect_nonblock(sockaddr) rescue IO::WaitWritable IO.select(nil, [socket]) # wait 3-way handshake completion begin socket.connect_nonblock(sockaddr) # check connection failure rescue Errno::EISCONN end end socket end
ruby
def create_socket socket = ::Socket.new(::Socket::AF_INET, ::Socket::SOCK_STREAM, 0) sockaddr = ::Socket.sockaddr_in(PORTS.sample, self.hostname) begin # emulate blocking connect socket.connect_nonblock(sockaddr) rescue IO::WaitWritable IO.select(nil, [socket]) # wait 3-way handshake completion begin socket.connect_nonblock(sockaddr) # check connection failure rescue Errno::EISCONN end end socket end
[ "def", "create_socket", "socket", "=", "::", "Socket", ".", "new", "(", "::", "Socket", "::", "AF_INET", ",", "::", "Socket", "::", "SOCK_STREAM", ",", "0", ")", "sockaddr", "=", "::", "Socket", ".", "sockaddr_in", "(", "PORTS", ".", "sample", ",", "self", ".", "hostname", ")", "begin", "# emulate blocking connect", "socket", ".", "connect_nonblock", "(", "sockaddr", ")", "rescue", "IO", "::", "WaitWritable", "IO", ".", "select", "(", "nil", ",", "[", "socket", "]", ")", "# wait 3-way handshake completion", "begin", "socket", ".", "connect_nonblock", "(", "sockaddr", ")", "# check connection failure", "rescue", "Errno", "::", "EISCONN", "end", "end", "socket", "end" ]
Create a new socket connection with DeathByCaptcha API. This method is necessary because Ruby 1.9.7 doesn't support connection timeout and only Ruby 2.2.0 fixes a bug with unsafe sockets threads. In Ruby >= 2.2.0, this could be implemented as simply as: ::Socket.tcp(HOST, PORTS.sample, connect_timeout: 0)
[ "Create", "a", "new", "socket", "connection", "with", "DeathByCaptcha", "API", ".", "This", "method", "is", "necessary", "because", "Ruby", "1", ".", "9", ".", "7", "doesn", "t", "support", "connection", "timeout", "and", "only", "Ruby", "2", ".", "2", ".", "0", "fixes", "a", "bug", "with", "unsafe", "sockets", "threads", "." ]
b6fc9503025b24adaffb8c28843995a7f1715cb7
https://github.com/infosimples/deathbycaptcha/blob/b6fc9503025b24adaffb8c28843995a7f1715cb7/lib/deathbycaptcha/client/socket.rb#L116-L129
21,775
infosimples/deathbycaptcha
lib/deathbycaptcha/client/http.rb
DeathByCaptcha.Client::HTTP.perform
def perform(action, method = :get, payload = {}) payload.merge!(username: self.username, password: self.password) headers = { 'User-Agent' => DeathByCaptcha::API_VERSION } if method == :post uri = URI("http://#{self.hostname}/api/#{action}") req = Net::HTTP::Post.new(uri.request_uri, headers) req.set_form_data(payload) elsif method == :post_multipart uri = URI("http://#{self.hostname}/api/#{action}") req = Net::HTTP::Post.new(uri.request_uri, headers) boundary, body = prepare_multipart_data(payload) req.content_type = "multipart/form-data; boundary=#{boundary}" req.body = body else uri = URI("http://#{self.hostname}/api/#{action}?#{URI.encode_www_form(payload)}") req = Net::HTTP::Get.new(uri.request_uri, headers) end res = Net::HTTP.start(uri.hostname, uri.port) do |http| http.request(req) end case res when Net::HTTPSuccess, Net::HTTPSeeOther Hash[URI.decode_www_form(res.body)] when Net::HTTPForbidden raise DeathByCaptcha::APIForbidden when Net::HTTPBadRequest raise DeathByCaptcha::APIBadRequest when Net::HTTPRequestEntityTooLarge raise DeathByCaptcha::APICaptchaTooLarge when Net::HTTPServiceUnavailable raise DeathByCaptcha::APIServiceUnavailable else raise DeathByCaptcha::APIResponseError.new(res.body) end end
ruby
def perform(action, method = :get, payload = {}) payload.merge!(username: self.username, password: self.password) headers = { 'User-Agent' => DeathByCaptcha::API_VERSION } if method == :post uri = URI("http://#{self.hostname}/api/#{action}") req = Net::HTTP::Post.new(uri.request_uri, headers) req.set_form_data(payload) elsif method == :post_multipart uri = URI("http://#{self.hostname}/api/#{action}") req = Net::HTTP::Post.new(uri.request_uri, headers) boundary, body = prepare_multipart_data(payload) req.content_type = "multipart/form-data; boundary=#{boundary}" req.body = body else uri = URI("http://#{self.hostname}/api/#{action}?#{URI.encode_www_form(payload)}") req = Net::HTTP::Get.new(uri.request_uri, headers) end res = Net::HTTP.start(uri.hostname, uri.port) do |http| http.request(req) end case res when Net::HTTPSuccess, Net::HTTPSeeOther Hash[URI.decode_www_form(res.body)] when Net::HTTPForbidden raise DeathByCaptcha::APIForbidden when Net::HTTPBadRequest raise DeathByCaptcha::APIBadRequest when Net::HTTPRequestEntityTooLarge raise DeathByCaptcha::APICaptchaTooLarge when Net::HTTPServiceUnavailable raise DeathByCaptcha::APIServiceUnavailable else raise DeathByCaptcha::APIResponseError.new(res.body) end end
[ "def", "perform", "(", "action", ",", "method", "=", ":get", ",", "payload", "=", "{", "}", ")", "payload", ".", "merge!", "(", "username", ":", "self", ".", "username", ",", "password", ":", "self", ".", "password", ")", "headers", "=", "{", "'User-Agent'", "=>", "DeathByCaptcha", "::", "API_VERSION", "}", "if", "method", "==", ":post", "uri", "=", "URI", "(", "\"http://#{self.hostname}/api/#{action}\"", ")", "req", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ".", "request_uri", ",", "headers", ")", "req", ".", "set_form_data", "(", "payload", ")", "elsif", "method", "==", ":post_multipart", "uri", "=", "URI", "(", "\"http://#{self.hostname}/api/#{action}\"", ")", "req", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ".", "request_uri", ",", "headers", ")", "boundary", ",", "body", "=", "prepare_multipart_data", "(", "payload", ")", "req", ".", "content_type", "=", "\"multipart/form-data; boundary=#{boundary}\"", "req", ".", "body", "=", "body", "else", "uri", "=", "URI", "(", "\"http://#{self.hostname}/api/#{action}?#{URI.encode_www_form(payload)}\"", ")", "req", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "uri", ".", "request_uri", ",", "headers", ")", "end", "res", "=", "Net", "::", "HTTP", ".", "start", "(", "uri", ".", "hostname", ",", "uri", ".", "port", ")", "do", "|", "http", "|", "http", ".", "request", "(", "req", ")", "end", "case", "res", "when", "Net", "::", "HTTPSuccess", ",", "Net", "::", "HTTPSeeOther", "Hash", "[", "URI", ".", "decode_www_form", "(", "res", ".", "body", ")", "]", "when", "Net", "::", "HTTPForbidden", "raise", "DeathByCaptcha", "::", "APIForbidden", "when", "Net", "::", "HTTPBadRequest", "raise", "DeathByCaptcha", "::", "APIBadRequest", "when", "Net", "::", "HTTPRequestEntityTooLarge", "raise", "DeathByCaptcha", "::", "APICaptchaTooLarge", "when", "Net", "::", "HTTPServiceUnavailable", "raise", "DeathByCaptcha", "::", "APIServiceUnavailable", "else", "raise", "DeathByCaptcha", "::", "APIResponseError", ".", "new", "(", "res", ".", "body", ")", "end", "end" ]
Perform an HTTP request to the DeathByCaptcha API. @param [String] action API method name. @param [Symbol] method HTTP method (:get, :post, :post_multipart). @param [Hash] payload Data to be sent through the HTTP request. @return [Hash] Response from the DeathByCaptcha API.
[ "Perform", "an", "HTTP", "request", "to", "the", "DeathByCaptcha", "API", "." ]
b6fc9503025b24adaffb8c28843995a7f1715cb7
https://github.com/infosimples/deathbycaptcha/blob/b6fc9503025b24adaffb8c28843995a7f1715cb7/lib/deathbycaptcha/client/http.rb#L86-L125
21,776
phcdevworks/phc-contactor
app/controllers/phccontactor/messages_controller.rb
Phccontactor.MessagesController.create
def create @message = Message.new(message_params) if @message.valid? MessageMailer.message_me(@message).deliver_now redirect_to new_message_path, notice: "Thank you for your message." else render :new end end
ruby
def create @message = Message.new(message_params) if @message.valid? MessageMailer.message_me(@message).deliver_now redirect_to new_message_path, notice: "Thank you for your message." else render :new end end
[ "def", "create", "@message", "=", "Message", ".", "new", "(", "message_params", ")", "if", "@message", ".", "valid?", "MessageMailer", ".", "message_me", "(", "@message", ")", ".", "deliver_now", "redirect_to", "new_message_path", ",", "notice", ":", "\"Thank you for your message.\"", "else", "render", ":new", "end", "end" ]
Create Message from Info Entered
[ "Create", "Message", "from", "Info", "Entered" ]
f7aaa1311cba592347a674c0198d86bc7c4660a7
https://github.com/phcdevworks/phc-contactor/blob/f7aaa1311cba592347a674c0198d86bc7c4660a7/app/controllers/phccontactor/messages_controller.rb#L12-L21
21,777
phcdevworks/phc-contactor
app/mailers/phccontactor/message_mailer.rb
Phccontactor.MessageMailer.message_me
def message_me(msg) @msg = msg mail from: @msg.email, subject: @msg.subject, body: @msg.content end
ruby
def message_me(msg) @msg = msg mail from: @msg.email, subject: @msg.subject, body: @msg.content end
[ "def", "message_me", "(", "msg", ")", "@msg", "=", "msg", "mail", "from", ":", "@msg", ".", "email", ",", "subject", ":", "@msg", ".", "subject", ",", "body", ":", "@msg", ".", "content", "end" ]
Put Togther Messange
[ "Put", "Togther", "Messange" ]
f7aaa1311cba592347a674c0198d86bc7c4660a7
https://github.com/phcdevworks/phc-contactor/blob/f7aaa1311cba592347a674c0198d86bc7c4660a7/app/mailers/phccontactor/message_mailer.rb#L8-L11
21,778
gsamokovarov/rvt
lib/rvt/slave.rb
RVT.Slave.send_input
def send_input(input) raise ArgumentError if input.nil? or input.try(:empty?) input.each_char { |char| @input.putc(char) } end
ruby
def send_input(input) raise ArgumentError if input.nil? or input.try(:empty?) input.each_char { |char| @input.putc(char) } end
[ "def", "send_input", "(", "input", ")", "raise", "ArgumentError", "if", "input", ".", "nil?", "or", "input", ".", "try", "(", ":empty?", ")", "input", ".", "each_char", "{", "|", "char", "|", "@input", ".", "putc", "(", "char", ")", "}", "end" ]
Sends input to the slave process STDIN. Returns immediately.
[ "Sends", "input", "to", "the", "slave", "process", "STDIN", "." ]
5fc5e331c250696acaab4a1812fdd12c3e08d8d4
https://github.com/gsamokovarov/rvt/blob/5fc5e331c250696acaab4a1812fdd12c3e08d8d4/lib/rvt/slave.rb#L58-L61
21,779
gsamokovarov/rvt
lib/rvt/slave.rb
RVT.Slave.pending_output
def pending_output(chunk_len = 49152) # Returns nil if there is no pending output. return unless pending_output? pending = String.new while chunk = @output.read_nonblock(chunk_len) pending << chunk end pending.force_encoding('UTF-8') rescue IO::WaitReadable pending.force_encoding('UTF-8') rescue raise Closed if READING_ON_CLOSED_END_ERRORS.any? { |exc| $!.is_a?(exc) } end
ruby
def pending_output(chunk_len = 49152) # Returns nil if there is no pending output. return unless pending_output? pending = String.new while chunk = @output.read_nonblock(chunk_len) pending << chunk end pending.force_encoding('UTF-8') rescue IO::WaitReadable pending.force_encoding('UTF-8') rescue raise Closed if READING_ON_CLOSED_END_ERRORS.any? { |exc| $!.is_a?(exc) } end
[ "def", "pending_output", "(", "chunk_len", "=", "49152", ")", "# Returns nil if there is no pending output.", "return", "unless", "pending_output?", "pending", "=", "String", ".", "new", "while", "chunk", "=", "@output", ".", "read_nonblock", "(", "chunk_len", ")", "pending", "<<", "chunk", "end", "pending", ".", "force_encoding", "(", "'UTF-8'", ")", "rescue", "IO", "::", "WaitReadable", "pending", ".", "force_encoding", "(", "'UTF-8'", ")", "rescue", "raise", "Closed", "if", "READING_ON_CLOSED_END_ERRORS", ".", "any?", "{", "|", "exc", "|", "$!", ".", "is_a?", "(", "exc", ")", "}", "end" ]
Gets the pending output of the process. The pending output is read in an non blocking way by chunks, in the size of +chunk_len+. By default, +chunk_len+ is 49152 bytes. Returns +nil+, if there is no pending output at the moment. Otherwise, returns the output that hasn't been read since the last invocation. Raises Errno:EIO on closed output stream. This can happen if the underlying process exits.
[ "Gets", "the", "pending", "output", "of", "the", "process", "." ]
5fc5e331c250696acaab4a1812fdd12c3e08d8d4
https://github.com/gsamokovarov/rvt/blob/5fc5e331c250696acaab4a1812fdd12c3e08d8d4/lib/rvt/slave.rb#L83-L96
21,780
gocardless/gocardless-legacy-ruby
lib/gocardless/utils.rb
GoCardless.Utils.flatten_params
def flatten_params(obj, ns=nil) case obj when Hash pairs = obj.map { |k,v| flatten_params(v, ns ? "#{ns}[#{k}]" : k) } pairs.empty? ? [] : pairs.inject(&:+) when Array obj.map { |v| flatten_params(v, "#{ns}[]") }.inject(&:+) || [] when Time [[ns.to_s, iso_format_time(obj)]] else [[ns.to_s, obj.to_s]] end end
ruby
def flatten_params(obj, ns=nil) case obj when Hash pairs = obj.map { |k,v| flatten_params(v, ns ? "#{ns}[#{k}]" : k) } pairs.empty? ? [] : pairs.inject(&:+) when Array obj.map { |v| flatten_params(v, "#{ns}[]") }.inject(&:+) || [] when Time [[ns.to_s, iso_format_time(obj)]] else [[ns.to_s, obj.to_s]] end end
[ "def", "flatten_params", "(", "obj", ",", "ns", "=", "nil", ")", "case", "obj", "when", "Hash", "pairs", "=", "obj", ".", "map", "{", "|", "k", ",", "v", "|", "flatten_params", "(", "v", ",", "ns", "?", "\"#{ns}[#{k}]\"", ":", "k", ")", "}", "pairs", ".", "empty?", "?", "[", "]", ":", "pairs", ".", "inject", "(", ":+", ")", "when", "Array", "obj", ".", "map", "{", "|", "v", "|", "flatten_params", "(", "v", ",", "\"#{ns}[]\"", ")", "}", ".", "inject", "(", ":+", ")", "||", "[", "]", "when", "Time", "[", "[", "ns", ".", "to_s", ",", "iso_format_time", "(", "obj", ")", "]", "]", "else", "[", "[", "ns", ".", "to_s", ",", "obj", ".", "to_s", "]", "]", "end", "end" ]
Flatten a hash containing nested hashes and arrays to a non-nested array of key-value pairs. Examples: flatten_params(a: 'b') # => [['a', 'b']] flatten_params(a: ['b', 'c']) # => [['a[]', 'b'], ['a[]', 'c']] flatten_params(a: {b: 'c'}) # => [['a[b]', 'c']] @param [Hash] obj the hash to flatten @return [Array] an array of key-value pairs (arrays of two strings)
[ "Flatten", "a", "hash", "containing", "nested", "hashes", "and", "arrays", "to", "a", "non", "-", "nested", "array", "of", "key", "-", "value", "pairs", "." ]
cf141f235eec43909ba68866c283803f84d6bc89
https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/utils.rb#L58-L70
21,781
gocardless/gocardless-legacy-ruby
lib/gocardless/utils.rb
GoCardless.Utils.iso_format_time
def iso_format_time(time) return time unless time.is_a? Time or time.is_a? Date time = time.getutc if time.is_a? Time time = time.new_offset(0) if time.is_a? DateTime time.strftime('%Y-%m-%dT%H:%M:%SZ') end
ruby
def iso_format_time(time) return time unless time.is_a? Time or time.is_a? Date time = time.getutc if time.is_a? Time time = time.new_offset(0) if time.is_a? DateTime time.strftime('%Y-%m-%dT%H:%M:%SZ') end
[ "def", "iso_format_time", "(", "time", ")", "return", "time", "unless", "time", ".", "is_a?", "Time", "or", "time", ".", "is_a?", "Date", "time", "=", "time", ".", "getutc", "if", "time", ".", "is_a?", "Time", "time", "=", "time", ".", "new_offset", "(", "0", ")", "if", "time", ".", "is_a?", "DateTime", "time", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", "end" ]
Format a Time object according to ISO 8601, and convert to UTC. @param [Time] time the time object to format @return [String] the ISO-formatted time
[ "Format", "a", "Time", "object", "according", "to", "ISO", "8601", "and", "convert", "to", "UTC", "." ]
cf141f235eec43909ba68866c283803f84d6bc89
https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/utils.rb#L120-L125
21,782
gocardless/gocardless-legacy-ruby
lib/gocardless/utils.rb
GoCardless.Utils.stringify_times
def stringify_times(obj) case obj when Hash Hash[obj.map { |k,v| [k, stringify_times(v)] }] when Array obj.map { |v| stringify_times(v) } else iso_format_time(obj) end end
ruby
def stringify_times(obj) case obj when Hash Hash[obj.map { |k,v| [k, stringify_times(v)] }] when Array obj.map { |v| stringify_times(v) } else iso_format_time(obj) end end
[ "def", "stringify_times", "(", "obj", ")", "case", "obj", "when", "Hash", "Hash", "[", "obj", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ",", "stringify_times", "(", "v", ")", "]", "}", "]", "when", "Array", "obj", ".", "map", "{", "|", "v", "|", "stringify_times", "(", "v", ")", "}", "else", "iso_format_time", "(", "obj", ")", "end", "end" ]
Recursively ISO format all time and date values. @param [Hash] obj the object containing date or time objects @return [Hash] the object with ISO-formatted time stings
[ "Recursively", "ISO", "format", "all", "time", "and", "date", "values", "." ]
cf141f235eec43909ba68866c283803f84d6bc89
https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/utils.rb#L131-L140
21,783
gocardless/gocardless-legacy-ruby
lib/gocardless/paginator.rb
GoCardless.Paginator.load_page
def load_page(page_num) params = @query.merge(pagination_params(page_num)) response = @client.api_request(:get, @path, :params => params) metadata = parse_metadata(response) @num_records, @num_pages = metadata['records'], metadata['pages'] Page.new(@resource_class, response.parsed, metadata['links']) end
ruby
def load_page(page_num) params = @query.merge(pagination_params(page_num)) response = @client.api_request(:get, @path, :params => params) metadata = parse_metadata(response) @num_records, @num_pages = metadata['records'], metadata['pages'] Page.new(@resource_class, response.parsed, metadata['links']) end
[ "def", "load_page", "(", "page_num", ")", "params", "=", "@query", ".", "merge", "(", "pagination_params", "(", "page_num", ")", ")", "response", "=", "@client", ".", "api_request", "(", ":get", ",", "@path", ",", ":params", "=>", "params", ")", "metadata", "=", "parse_metadata", "(", "response", ")", "@num_records", ",", "@num_pages", "=", "metadata", "[", "'records'", "]", ",", "metadata", "[", "'pages'", "]", "Page", ".", "new", "(", "@resource_class", ",", "response", ".", "parsed", ",", "metadata", "[", "'links'", "]", ")", "end" ]
Fetch and return a single page.
[ "Fetch", "and", "return", "a", "single", "page", "." ]
cf141f235eec43909ba68866c283803f84d6bc89
https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/paginator.rb#L35-L43
21,784
gocardless/gocardless-legacy-ruby
lib/gocardless/paginator.rb
GoCardless.Paginator.each_page
def each_page page_obj = load_page(1) loop do yield page_obj break unless page_obj.has_next? page_obj = load_page(page_obj.next_page) end end
ruby
def each_page page_obj = load_page(1) loop do yield page_obj break unless page_obj.has_next? page_obj = load_page(page_obj.next_page) end end
[ "def", "each_page", "page_obj", "=", "load_page", "(", "1", ")", "loop", "do", "yield", "page_obj", "break", "unless", "page_obj", ".", "has_next?", "page_obj", "=", "load_page", "(", "page_obj", ".", "next_page", ")", "end", "end" ]
Fetch and yield each page of results.
[ "Fetch", "and", "yield", "each", "page", "of", "results", "." ]
cf141f235eec43909ba68866c283803f84d6bc89
https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/paginator.rb#L55-L62
21,785
gocardless/gocardless-legacy-ruby
lib/gocardless/client.rb
GoCardless.Client.authorize_url
def authorize_url(options) raise ArgumentError, ':redirect_uri required' unless options[:redirect_uri] params = { :client_id => @app_id, :response_type => 'code', :scope => 'manage_merchant' } # Faraday doesn't flatten params in this case (Faraday issue #115) options = Hash[Utils.flatten_params(options)] @oauth_client.authorize_url(params.merge(options)) end
ruby
def authorize_url(options) raise ArgumentError, ':redirect_uri required' unless options[:redirect_uri] params = { :client_id => @app_id, :response_type => 'code', :scope => 'manage_merchant' } # Faraday doesn't flatten params in this case (Faraday issue #115) options = Hash[Utils.flatten_params(options)] @oauth_client.authorize_url(params.merge(options)) end
[ "def", "authorize_url", "(", "options", ")", "raise", "ArgumentError", ",", "':redirect_uri required'", "unless", "options", "[", ":redirect_uri", "]", "params", "=", "{", ":client_id", "=>", "@app_id", ",", ":response_type", "=>", "'code'", ",", ":scope", "=>", "'manage_merchant'", "}", "# Faraday doesn't flatten params in this case (Faraday issue #115)", "options", "=", "Hash", "[", "Utils", ".", "flatten_params", "(", "options", ")", "]", "@oauth_client", ".", "authorize_url", "(", "params", ".", "merge", "(", "options", ")", ")", "end" ]
Generate the OAuth authorize url @param [Hash] options parameters to be included in the url. +:redirect_uri+ is required. @return [String] the authorize url
[ "Generate", "the", "OAuth", "authorize", "url" ]
cf141f235eec43909ba68866c283803f84d6bc89
https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/client.rb#L47-L57
21,786
gocardless/gocardless-legacy-ruby
lib/gocardless/client.rb
GoCardless.Client.fetch_access_token
def fetch_access_token(auth_code, options) raise ArgumentError, ':redirect_uri required' unless options[:redirect_uri] # Exchange the auth code for an access token @access_token = @oauth_client.auth_code.get_token(auth_code, options) # Use the scope to figure out which merchant we're managing scope = @access_token.params[:scope] || @access_token.params['scope'] set_merchant_id_from_scope(scope) self.scoped_access_token end
ruby
def fetch_access_token(auth_code, options) raise ArgumentError, ':redirect_uri required' unless options[:redirect_uri] # Exchange the auth code for an access token @access_token = @oauth_client.auth_code.get_token(auth_code, options) # Use the scope to figure out which merchant we're managing scope = @access_token.params[:scope] || @access_token.params['scope'] set_merchant_id_from_scope(scope) self.scoped_access_token end
[ "def", "fetch_access_token", "(", "auth_code", ",", "options", ")", "raise", "ArgumentError", ",", "':redirect_uri required'", "unless", "options", "[", ":redirect_uri", "]", "# Exchange the auth code for an access token", "@access_token", "=", "@oauth_client", ".", "auth_code", ".", "get_token", "(", "auth_code", ",", "options", ")", "# Use the scope to figure out which merchant we're managing", "scope", "=", "@access_token", ".", "params", "[", ":scope", "]", "||", "@access_token", ".", "params", "[", "'scope'", "]", "set_merchant_id_from_scope", "(", "scope", ")", "self", ".", "scoped_access_token", "end" ]
Exchange the authorization code for an access token @param [String] auth_code to exchange for the access_token @return [String] the access_token required to make API calls to resources
[ "Exchange", "the", "authorization", "code", "for", "an", "access", "token" ]
cf141f235eec43909ba68866c283803f84d6bc89
https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/client.rb#L64-L74
21,787
gocardless/gocardless-legacy-ruby
lib/gocardless/client.rb
GoCardless.Client.access_token=
def access_token=(token) token, scope = token.sub(/^bearer\s+/i, '').split(' ', 2) if scope warn "[DEPRECATION] (gocardless-ruby) merchant_id is now a separate " + "attribute, the manage_merchant scope should no longer be " + "included in the 'token' attribute. See http://git.io/G9y37Q " + "for more info." else scope = '' end @access_token = OAuth2::AccessToken.new(@oauth_client, token) @access_token.params['scope'] = scope set_merchant_id_from_scope(scope) unless @merchant_id end
ruby
def access_token=(token) token, scope = token.sub(/^bearer\s+/i, '').split(' ', 2) if scope warn "[DEPRECATION] (gocardless-ruby) merchant_id is now a separate " + "attribute, the manage_merchant scope should no longer be " + "included in the 'token' attribute. See http://git.io/G9y37Q " + "for more info." else scope = '' end @access_token = OAuth2::AccessToken.new(@oauth_client, token) @access_token.params['scope'] = scope set_merchant_id_from_scope(scope) unless @merchant_id end
[ "def", "access_token", "=", "(", "token", ")", "token", ",", "scope", "=", "token", ".", "sub", "(", "/", "\\s", "/i", ",", "''", ")", ".", "split", "(", "' '", ",", "2", ")", "if", "scope", "warn", "\"[DEPRECATION] (gocardless-ruby) merchant_id is now a separate \"", "+", "\"attribute, the manage_merchant scope should no longer be \"", "+", "\"included in the 'token' attribute. See http://git.io/G9y37Q \"", "+", "\"for more info.\"", "else", "scope", "=", "''", "end", "@access_token", "=", "OAuth2", "::", "AccessToken", ".", "new", "(", "@oauth_client", ",", "token", ")", "@access_token", ".", "params", "[", "'scope'", "]", "=", "scope", "set_merchant_id_from_scope", "(", "scope", ")", "unless", "@merchant_id", "end" ]
Set the client's access token @param [String] token a string with format <code>"#{token}"</code> (as returned by {#access_token})
[ "Set", "the", "client", "s", "access", "token" ]
cf141f235eec43909ba68866c283803f84d6bc89
https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/client.rb#L105-L120
21,788
gocardless/gocardless-legacy-ruby
lib/gocardless/client.rb
GoCardless.Client.set_merchant_id_from_scope
def set_merchant_id_from_scope(scope) perm = scope.split.select {|p| p.start_with?('manage_merchant:') }.first @merchant_id = perm.split(':')[1] if perm end
ruby
def set_merchant_id_from_scope(scope) perm = scope.split.select {|p| p.start_with?('manage_merchant:') }.first @merchant_id = perm.split(':')[1] if perm end
[ "def", "set_merchant_id_from_scope", "(", "scope", ")", "perm", "=", "scope", ".", "split", ".", "select", "{", "|", "p", "|", "p", ".", "start_with?", "(", "'manage_merchant:'", ")", "}", ".", "first", "@merchant_id", "=", "perm", ".", "split", "(", "':'", ")", "[", "1", "]", "if", "perm", "end" ]
Pull the merchant id out of the access scope
[ "Pull", "the", "merchant", "id", "out", "of", "the", "access", "scope" ]
cf141f235eec43909ba68866c283803f84d6bc89
https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/client.rb#L349-L352
21,789
gocardless/gocardless-legacy-ruby
lib/gocardless/client.rb
GoCardless.Client.request
def request(method, path, opts = {}) raise ClientError, 'Access token missing' unless @access_token opts[:headers] = {} if opts[:headers].nil? opts[:headers]['Accept'] = 'application/json' opts[:headers]['Content-Type'] = 'application/json' unless method == :get opts[:headers]['User-Agent'] = user_agent opts[:body] = MultiJson.encode(opts[:data]) if !opts[:data].nil? path = URI.encode(path) # Reset the URL in case the environment / base URL has been changed. @oauth_client.site = base_url header_keys = opts[:headers].keys.map(&:to_s) if header_keys.map(&:downcase).include?('authorization') @oauth_client.request(method, path, opts) else @access_token.send(method, path, opts) end rescue OAuth2::Error => err raise GoCardless::ApiError.new(err.response) end
ruby
def request(method, path, opts = {}) raise ClientError, 'Access token missing' unless @access_token opts[:headers] = {} if opts[:headers].nil? opts[:headers]['Accept'] = 'application/json' opts[:headers]['Content-Type'] = 'application/json' unless method == :get opts[:headers]['User-Agent'] = user_agent opts[:body] = MultiJson.encode(opts[:data]) if !opts[:data].nil? path = URI.encode(path) # Reset the URL in case the environment / base URL has been changed. @oauth_client.site = base_url header_keys = opts[:headers].keys.map(&:to_s) if header_keys.map(&:downcase).include?('authorization') @oauth_client.request(method, path, opts) else @access_token.send(method, path, opts) end rescue OAuth2::Error => err raise GoCardless::ApiError.new(err.response) end
[ "def", "request", "(", "method", ",", "path", ",", "opts", "=", "{", "}", ")", "raise", "ClientError", ",", "'Access token missing'", "unless", "@access_token", "opts", "[", ":headers", "]", "=", "{", "}", "if", "opts", "[", ":headers", "]", ".", "nil?", "opts", "[", ":headers", "]", "[", "'Accept'", "]", "=", "'application/json'", "opts", "[", ":headers", "]", "[", "'Content-Type'", "]", "=", "'application/json'", "unless", "method", "==", ":get", "opts", "[", ":headers", "]", "[", "'User-Agent'", "]", "=", "user_agent", "opts", "[", ":body", "]", "=", "MultiJson", ".", "encode", "(", "opts", "[", ":data", "]", ")", "if", "!", "opts", "[", ":data", "]", ".", "nil?", "path", "=", "URI", ".", "encode", "(", "path", ")", "# Reset the URL in case the environment / base URL has been changed.", "@oauth_client", ".", "site", "=", "base_url", "header_keys", "=", "opts", "[", ":headers", "]", ".", "keys", ".", "map", "(", ":to_s", ")", "if", "header_keys", ".", "map", "(", ":downcase", ")", ".", "include?", "(", "'authorization'", ")", "@oauth_client", ".", "request", "(", "method", ",", "path", ",", "opts", ")", "else", "@access_token", ".", "send", "(", "method", ",", "path", ",", "opts", ")", "end", "rescue", "OAuth2", "::", "Error", "=>", "err", "raise", "GoCardless", "::", "ApiError", ".", "new", "(", "err", ".", "response", ")", "end" ]
Send a request to the GoCardless API servers @param [Symbol] method the HTTP method to use (e.g. +:get+, +:post+) @param [String] path the path fragment of the URL @option [Hash] opts query string parameters
[ "Send", "a", "request", "to", "the", "GoCardless", "API", "servers" ]
cf141f235eec43909ba68866c283803f84d6bc89
https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/client.rb#L359-L380
21,790
gocardless/gocardless-legacy-ruby
lib/gocardless/client.rb
GoCardless.Client.prepare_params
def prepare_params(params) # Create a new hash in case is a HashWithIndifferentAccess (keys are # always a String) params = Utils.symbolize_keys(Hash[params]) # Only pull out the relevant parameters, other won't be included in the # signature so will cause false negatives keys = [:resource_id, :resource_type, :resource_uri, :state, :signature] params = Hash[params.select { |k,v| keys.include? k }] (keys - [:state]).each do |key| raise ArgumentError, "Parameters missing #{key}" if !params.key?(key) end params end
ruby
def prepare_params(params) # Create a new hash in case is a HashWithIndifferentAccess (keys are # always a String) params = Utils.symbolize_keys(Hash[params]) # Only pull out the relevant parameters, other won't be included in the # signature so will cause false negatives keys = [:resource_id, :resource_type, :resource_uri, :state, :signature] params = Hash[params.select { |k,v| keys.include? k }] (keys - [:state]).each do |key| raise ArgumentError, "Parameters missing #{key}" if !params.key?(key) end params end
[ "def", "prepare_params", "(", "params", ")", "# Create a new hash in case is a HashWithIndifferentAccess (keys are", "# always a String)", "params", "=", "Utils", ".", "symbolize_keys", "(", "Hash", "[", "params", "]", ")", "# Only pull out the relevant parameters, other won't be included in the", "# signature so will cause false negatives", "keys", "=", "[", ":resource_id", ",", ":resource_type", ",", ":resource_uri", ",", ":state", ",", ":signature", "]", "params", "=", "Hash", "[", "params", ".", "select", "{", "|", "k", ",", "v", "|", "keys", ".", "include?", "k", "}", "]", "(", "keys", "-", "[", ":state", "]", ")", ".", "each", "do", "|", "key", "|", "raise", "ArgumentError", ",", "\"Parameters missing #{key}\"", "if", "!", "params", ".", "key?", "(", "key", ")", "end", "params", "end" ]
Prepare a Hash of parameters for signing. Presence of required parameters is checked and the others are discarded. @param [Hash] params the parameters to be prepared for signing @return [Hash] the prepared parameters
[ "Prepare", "a", "Hash", "of", "parameters", "for", "signing", ".", "Presence", "of", "required", "parameters", "is", "checked", "and", "the", "others", "are", "discarded", "." ]
cf141f235eec43909ba68866c283803f84d6bc89
https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/client.rb#L400-L412
21,791
gocardless/gocardless-legacy-ruby
lib/gocardless/client.rb
GoCardless.Client.new_limit_url
def new_limit_url(type, limit_params) url = URI.parse("#{base_url}/connect/#{type}s/new") limit_params[:merchant_id] = merchant_id redirect_uri = limit_params.delete(:redirect_uri) cancel_uri = limit_params.delete(:cancel_uri) state = limit_params.delete(:state) params = { :nonce => generate_nonce, :timestamp => Time.now.getutc.strftime('%Y-%m-%dT%H:%M:%SZ'), :client_id => @app_id, type => limit_params, } params[:redirect_uri] = redirect_uri unless redirect_uri.nil? params[:cancel_uri] = cancel_uri unless cancel_uri.nil? params[:state] = state unless state.nil? sign_params(params) url.query = Utils.normalize_params(params) url.to_s end
ruby
def new_limit_url(type, limit_params) url = URI.parse("#{base_url}/connect/#{type}s/new") limit_params[:merchant_id] = merchant_id redirect_uri = limit_params.delete(:redirect_uri) cancel_uri = limit_params.delete(:cancel_uri) state = limit_params.delete(:state) params = { :nonce => generate_nonce, :timestamp => Time.now.getutc.strftime('%Y-%m-%dT%H:%M:%SZ'), :client_id => @app_id, type => limit_params, } params[:redirect_uri] = redirect_uri unless redirect_uri.nil? params[:cancel_uri] = cancel_uri unless cancel_uri.nil? params[:state] = state unless state.nil? sign_params(params) url.query = Utils.normalize_params(params) url.to_s end
[ "def", "new_limit_url", "(", "type", ",", "limit_params", ")", "url", "=", "URI", ".", "parse", "(", "\"#{base_url}/connect/#{type}s/new\"", ")", "limit_params", "[", ":merchant_id", "]", "=", "merchant_id", "redirect_uri", "=", "limit_params", ".", "delete", "(", ":redirect_uri", ")", "cancel_uri", "=", "limit_params", ".", "delete", "(", ":cancel_uri", ")", "state", "=", "limit_params", ".", "delete", "(", ":state", ")", "params", "=", "{", ":nonce", "=>", "generate_nonce", ",", ":timestamp", "=>", "Time", ".", "now", ".", "getutc", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", ",", ":client_id", "=>", "@app_id", ",", "type", "=>", "limit_params", ",", "}", "params", "[", ":redirect_uri", "]", "=", "redirect_uri", "unless", "redirect_uri", ".", "nil?", "params", "[", ":cancel_uri", "]", "=", "cancel_uri", "unless", "cancel_uri", ".", "nil?", "params", "[", ":state", "]", "=", "state", "unless", "state", ".", "nil?", "sign_params", "(", "params", ")", "url", ".", "query", "=", "Utils", ".", "normalize_params", "(", "params", ")", "url", ".", "to_s", "end" ]
Generate the URL for creating a limit of type +type+, including the provided params, nonce, timestamp and signature @param [Symbol] type the limit type (+:subscription+, etc) @param [Hash] params the bill parameters @return [String] the generated URL
[ "Generate", "the", "URL", "for", "creating", "a", "limit", "of", "type", "+", "type", "+", "including", "the", "provided", "params", "nonce", "timestamp", "and", "signature" ]
cf141f235eec43909ba68866c283803f84d6bc89
https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/client.rb#L438-L460
21,792
apotonick/hooks
lib/hooks/hook.rb
Hooks.Hook.run
def run(scope, *args) inject(Results.new) do |results, callback| executed = execute_callback(scope, callback, *args) return results.halted! unless continue_execution?(executed) results << executed end end
ruby
def run(scope, *args) inject(Results.new) do |results, callback| executed = execute_callback(scope, callback, *args) return results.halted! unless continue_execution?(executed) results << executed end end
[ "def", "run", "(", "scope", ",", "*", "args", ")", "inject", "(", "Results", ".", "new", ")", "do", "|", "results", ",", "callback", "|", "executed", "=", "execute_callback", "(", "scope", ",", "callback", ",", "args", ")", "return", "results", ".", "halted!", "unless", "continue_execution?", "(", "executed", ")", "results", "<<", "executed", "end", "end" ]
The chain contains the return values of the executed callbacks. Example: class Person define_hook :before_eating before_eating :wash_hands before_eating :locate_food before_eating :sit_down def wash_hands; :washed_hands; end def locate_food; :located_food; false; end def sit_down; :sat_down; end end result = person.run_hook(:before_eating) result.chain #=> [:washed_hands, false, :sat_down] If <tt>:halts_on_falsey</tt> is enabled: class Person define_hook :before_eating, :halts_on_falsey => true # ... end result = person.run_hook(:before_eating) result.chain #=> [:washed_hands]
[ "The", "chain", "contains", "the", "return", "values", "of", "the", "executed", "callbacks", "." ]
b30e91e9b71ffc248d952ac6f5cdaef9fc577763
https://github.com/apotonick/hooks/blob/b30e91e9b71ffc248d952ac6f5cdaef9fc577763/lib/hooks/hook.rb#L38-L45
21,793
piotrmurach/tty-color
lib/tty/color.rb
TTY.Color.command?
def command?(cmd) !!system(cmd, out: ::File::NULL, err: ::File::NULL) end
ruby
def command?(cmd) !!system(cmd, out: ::File::NULL, err: ::File::NULL) end
[ "def", "command?", "(", "cmd", ")", "!", "!", "system", "(", "cmd", ",", "out", ":", "::", "File", "::", "NULL", ",", "err", ":", "::", "File", "::", "NULL", ")", "end" ]
Check if command can be run @return [Boolean] @api public
[ "Check", "if", "command", "can", "be", "run" ]
2447896bb667908bddffb03bfe3c2b0f963554e3
https://github.com/piotrmurach/tty-color/blob/2447896bb667908bddffb03bfe3c2b0f963554e3/lib/tty/color.rb#L56-L58
21,794
ryanong/spy
lib/spy/nest.rb
Spy.Nest.remove
def remove(spy) if @constant_spies[spy.constant_name] == spy @constant_spies.delete(spy.constant_name) else raise NoSpyError, "#{spy.constant_name} was not stubbed on #{base_module.name}" end self end
ruby
def remove(spy) if @constant_spies[spy.constant_name] == spy @constant_spies.delete(spy.constant_name) else raise NoSpyError, "#{spy.constant_name} was not stubbed on #{base_module.name}" end self end
[ "def", "remove", "(", "spy", ")", "if", "@constant_spies", "[", "spy", ".", "constant_name", "]", "==", "spy", "@constant_spies", ".", "delete", "(", "spy", ".", "constant_name", ")", "else", "raise", "NoSpyError", ",", "\"#{spy.constant_name} was not stubbed on #{base_module.name}\"", "end", "self", "end" ]
removes the spy from the records @param spy [Constant] @return [self]
[ "removes", "the", "spy", "from", "the", "records" ]
54ec54b604333c8991ab8d6df0a96fe57364f65c
https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/nest.rb#L35-L42
21,795
ryanong/spy
lib/spy/subroutine.rb
Spy.Subroutine.hook
def hook(opts = {}) raise AlreadyHookedError, "#{base_object} method '#{method_name}' has already been hooked" if self.class.get(base_object, method_name, singleton_method) @hook_opts = opts @original_method_visibility = method_visibility_of(method_name) hook_opts[:visibility] ||= original_method_visibility if original_method_visibility || !hook_opts[:force] @original_method = current_method end if original_method && original_method.owner == base_object original_method.owner.send(:remove_method, method_name) end if singleton_method base_object.define_singleton_method(method_name, override_method) else base_object.define_method(method_name, override_method) end if [:public, :protected, :private].include? hook_opts[:visibility] method_owner.send(hook_opts[:visibility], method_name) end Agency.instance.recruit(self) @was_hooked = true self end
ruby
def hook(opts = {}) raise AlreadyHookedError, "#{base_object} method '#{method_name}' has already been hooked" if self.class.get(base_object, method_name, singleton_method) @hook_opts = opts @original_method_visibility = method_visibility_of(method_name) hook_opts[:visibility] ||= original_method_visibility if original_method_visibility || !hook_opts[:force] @original_method = current_method end if original_method && original_method.owner == base_object original_method.owner.send(:remove_method, method_name) end if singleton_method base_object.define_singleton_method(method_name, override_method) else base_object.define_method(method_name, override_method) end if [:public, :protected, :private].include? hook_opts[:visibility] method_owner.send(hook_opts[:visibility], method_name) end Agency.instance.recruit(self) @was_hooked = true self end
[ "def", "hook", "(", "opts", "=", "{", "}", ")", "raise", "AlreadyHookedError", ",", "\"#{base_object} method '#{method_name}' has already been hooked\"", "if", "self", ".", "class", ".", "get", "(", "base_object", ",", "method_name", ",", "singleton_method", ")", "@hook_opts", "=", "opts", "@original_method_visibility", "=", "method_visibility_of", "(", "method_name", ")", "hook_opts", "[", ":visibility", "]", "||=", "original_method_visibility", "if", "original_method_visibility", "||", "!", "hook_opts", "[", ":force", "]", "@original_method", "=", "current_method", "end", "if", "original_method", "&&", "original_method", ".", "owner", "==", "base_object", "original_method", ".", "owner", ".", "send", "(", ":remove_method", ",", "method_name", ")", "end", "if", "singleton_method", "base_object", ".", "define_singleton_method", "(", "method_name", ",", "override_method", ")", "else", "base_object", ".", "define_method", "(", "method_name", ",", "override_method", ")", "end", "if", "[", ":public", ",", ":protected", ",", ":private", "]", ".", "include?", "hook_opts", "[", ":visibility", "]", "method_owner", ".", "send", "(", "hook_opts", "[", ":visibility", "]", ",", "method_name", ")", "end", "Agency", ".", "instance", ".", "recruit", "(", "self", ")", "@was_hooked", "=", "true", "self", "end" ]
set what object and method the spy should watch @param object @param method_name <Symbol> @param singleton_method <Boolean> spy on the singleton method or the normal method hooks the method into the object and stashes original method if it exists @param [Hash] opts what do do when hooking into a method @option opts [Boolean] force (false) if set to true will hook the method even if it doesn't exist @option opts [Symbol<:public, :protected, :private>] visibility overrides visibility with whatever method is given @return [self]
[ "set", "what", "object", "and", "method", "the", "spy", "should", "watch" ]
54ec54b604333c8991ab8d6df0a96fe57364f65c
https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/subroutine.rb#L44-L72
21,796
ryanong/spy
lib/spy/subroutine.rb
Spy.Subroutine.unhook
def unhook raise NeverHookedError, "'#{method_name}' method has not been hooked" unless hooked? method_owner.send(:remove_method, method_name) if original_method && method_owner == original_method.owner original_method.owner.send(:define_method, method_name, original_method) original_method.owner.send(original_method_visibility, method_name) if original_method_visibility end clear_method! Agency.instance.retire(self) self end
ruby
def unhook raise NeverHookedError, "'#{method_name}' method has not been hooked" unless hooked? method_owner.send(:remove_method, method_name) if original_method && method_owner == original_method.owner original_method.owner.send(:define_method, method_name, original_method) original_method.owner.send(original_method_visibility, method_name) if original_method_visibility end clear_method! Agency.instance.retire(self) self end
[ "def", "unhook", "raise", "NeverHookedError", ",", "\"'#{method_name}' method has not been hooked\"", "unless", "hooked?", "method_owner", ".", "send", "(", ":remove_method", ",", "method_name", ")", "if", "original_method", "&&", "method_owner", "==", "original_method", ".", "owner", "original_method", ".", "owner", ".", "send", "(", ":define_method", ",", "method_name", ",", "original_method", ")", "original_method", ".", "owner", ".", "send", "(", "original_method_visibility", ",", "method_name", ")", "if", "original_method_visibility", "end", "clear_method!", "Agency", ".", "instance", ".", "retire", "(", "self", ")", "self", "end" ]
unhooks method from object @return [self]
[ "unhooks", "method", "from", "object" ]
54ec54b604333c8991ab8d6df0a96fe57364f65c
https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/subroutine.rb#L76-L88
21,797
ryanong/spy
lib/spy/subroutine.rb
Spy.Subroutine.and_yield
def and_yield(*args) yield eval_context = Object.new if block_given? @plan = Proc.new do |&block| eval_context.instance_exec(*args, &block) end self end
ruby
def and_yield(*args) yield eval_context = Object.new if block_given? @plan = Proc.new do |&block| eval_context.instance_exec(*args, &block) end self end
[ "def", "and_yield", "(", "*", "args", ")", "yield", "eval_context", "=", "Object", ".", "new", "if", "block_given?", "@plan", "=", "Proc", ".", "new", "do", "|", "&", "block", "|", "eval_context", ".", "instance_exec", "(", "args", ",", "block", ")", "end", "self", "end" ]
Tells the object to yield one or more args to a block when the message is received. @return [self]
[ "Tells", "the", "object", "to", "yield", "one", "or", "more", "args", "to", "a", "block", "when", "the", "message", "is", "received", "." ]
54ec54b604333c8991ab8d6df0a96fe57364f65c
https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/subroutine.rb#L134-L140
21,798
ryanong/spy
lib/spy/subroutine.rb
Spy.Subroutine.and_call_through
def and_call_through if @base_object.is_a? Class @plan = Proc.new do |object, *args, &block| if original_method if original_method.is_a? UnboundMethod bound_method = original_method.bind(object) bound_method.call(*args, &block) else original_method.call(*args, &block) end else base_object.send(:method_missing, method_name, *args, &block) end end else @plan = Proc.new do |*args, &block| if original_method original_method.call(*args, &block) else base_object.send(:method_missing, method_name, *args, &block) end end end self end
ruby
def and_call_through if @base_object.is_a? Class @plan = Proc.new do |object, *args, &block| if original_method if original_method.is_a? UnboundMethod bound_method = original_method.bind(object) bound_method.call(*args, &block) else original_method.call(*args, &block) end else base_object.send(:method_missing, method_name, *args, &block) end end else @plan = Proc.new do |*args, &block| if original_method original_method.call(*args, &block) else base_object.send(:method_missing, method_name, *args, &block) end end end self end
[ "def", "and_call_through", "if", "@base_object", ".", "is_a?", "Class", "@plan", "=", "Proc", ".", "new", "do", "|", "object", ",", "*", "args", ",", "&", "block", "|", "if", "original_method", "if", "original_method", ".", "is_a?", "UnboundMethod", "bound_method", "=", "original_method", ".", "bind", "(", "object", ")", "bound_method", ".", "call", "(", "args", ",", "block", ")", "else", "original_method", ".", "call", "(", "args", ",", "block", ")", "end", "else", "base_object", ".", "send", "(", ":method_missing", ",", "method_name", ",", "args", ",", "block", ")", "end", "end", "else", "@plan", "=", "Proc", ".", "new", "do", "|", "*", "args", ",", "&", "block", "|", "if", "original_method", "original_method", ".", "call", "(", "args", ",", "block", ")", "else", "base_object", ".", "send", "(", ":method_missing", ",", "method_name", ",", "args", ",", "block", ")", "end", "end", "end", "self", "end" ]
tells the spy to call the original method @return [self]
[ "tells", "the", "spy", "to", "call", "the", "original", "method" ]
54ec54b604333c8991ab8d6df0a96fe57364f65c
https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/subroutine.rb#L144-L169
21,799
ryanong/spy
lib/spy/subroutine.rb
Spy.Subroutine.has_been_called_with?
def has_been_called_with?(*args) raise NeverHookedError unless @was_hooked match = block_given? ? Proc.new : proc { |call| call.args == args } calls.any?(&match) end
ruby
def has_been_called_with?(*args) raise NeverHookedError unless @was_hooked match = block_given? ? Proc.new : proc { |call| call.args == args } calls.any?(&match) end
[ "def", "has_been_called_with?", "(", "*", "args", ")", "raise", "NeverHookedError", "unless", "@was_hooked", "match", "=", "block_given?", "?", "Proc", ".", "new", ":", "proc", "{", "|", "call", "|", "call", ".", "args", "==", "args", "}", "calls", ".", "any?", "(", "match", ")", "end" ]
check if the method was called with the exact arguments @param args Arguments that should have been sent to the method @return [Boolean]
[ "check", "if", "the", "method", "was", "called", "with", "the", "exact", "arguments" ]
54ec54b604333c8991ab8d6df0a96fe57364f65c
https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/subroutine.rb#L218-L222