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,100
OTL/rosruby
lib/ros/parameter_manager.rb
ROS.ParameterManager.get_param_names
def get_param_names code, message, value = @server.call("getParamNames", @caller_id) case code when 1 return value when -1 raise message else return false end end
ruby
def get_param_names code, message, value = @server.call("getParamNames", @caller_id) case code when 1 return value when -1 raise message else return false end end
[ "def", "get_param_names", "code", ",", "message", ",", "value", "=", "@server", ".", "call", "(", "\"getParamNames\"", ",", "@caller_id", ")", "case", "code", "when", "1", "return", "value", "when", "-", "1", "raise", "message", "else", "return", "false", "end", "end" ]
get the all keys of parameters @return [Array] all keys
[ "get", "the", "all", "keys", "of", "parameters" ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/parameter_manager.rb#L115-L125
21,101
OTL/rosruby
lib/ros/time.rb
ROS.Time.-
def -(other) d = ::ROS::Duration.new d.secs = @secs - other.secs d.nsecs = @nsecs - other.nsecs d.canonicalize end
ruby
def -(other) d = ::ROS::Duration.new d.secs = @secs - other.secs d.nsecs = @nsecs - other.nsecs d.canonicalize end
[ "def", "-", "(", "other", ")", "d", "=", "::", "ROS", "::", "Duration", ".", "new", "d", ".", "secs", "=", "@secs", "-", "other", ".", "secs", "d", ".", "nsecs", "=", "@nsecs", "-", "other", ".", "nsecs", "d", ".", "canonicalize", "end" ]
subtract time value. @param [Time] other @return [Duration] duration
[ "subtract", "time", "value", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/time.rb#L161-L166
21,102
OTL/rosruby
lib/ros/tcpros/service_client.rb
ROS::TCPROS.ServiceClient.call
def call(srv_request, srv_response) write_header(@socket, build_header) if check_header(read_header(@socket)) write_msg(@socket, srv_request) @socket.flush ok_byte = read_ok_byte if ok_byte == 1 srv_response.deserialize(read_all(@socket)) return true end false end false end
ruby
def call(srv_request, srv_response) write_header(@socket, build_header) if check_header(read_header(@socket)) write_msg(@socket, srv_request) @socket.flush ok_byte = read_ok_byte if ok_byte == 1 srv_response.deserialize(read_all(@socket)) return true end false end false end
[ "def", "call", "(", "srv_request", ",", "srv_response", ")", "write_header", "(", "@socket", ",", "build_header", ")", "if", "check_header", "(", "read_header", "(", "@socket", ")", ")", "write_msg", "(", "@socket", ",", "srv_request", ")", "@socket", ".", "flush", "ok_byte", "=", "read_ok_byte", "if", "ok_byte", "==", "1", "srv_response", ".", "deserialize", "(", "read_all", "(", "@socket", ")", ")", "return", "true", "end", "false", "end", "false", "end" ]
call the service by sending srv request message, and receive response message. @param [Message] srv_request call with this request @param [Message] srv_response response is stored in this message @return [Boolean] result of call
[ "call", "the", "service", "by", "sending", "srv", "request", "message", "and", "receive", "response", "message", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/tcpros/service_client.rb#L59-L72
21,103
OTL/rosruby
lib/ros/master.rb
ROS.Master.kill_same_name_node
def kill_same_name_node(caller_id, api) delete_api = nil [@publishers, @subscribers, @services].each do |list| list.each do |pub| if pub.caller_id == caller_id and pub.api != api puts "killing #{caller_id}" delete_api = pub.api break end end end if delete_api proxy = SlaveProxy.new('/master', delete_api) begin proxy.shutdown("registered new node #{delete_api}") rescue end # delete [@publishers, @subscribers, @services].each do |list| list.delete_if {|x| x.api == delete_api} end end end
ruby
def kill_same_name_node(caller_id, api) delete_api = nil [@publishers, @subscribers, @services].each do |list| list.each do |pub| if pub.caller_id == caller_id and pub.api != api puts "killing #{caller_id}" delete_api = pub.api break end end end if delete_api proxy = SlaveProxy.new('/master', delete_api) begin proxy.shutdown("registered new node #{delete_api}") rescue end # delete [@publishers, @subscribers, @services].each do |list| list.delete_if {|x| x.api == delete_api} end end end
[ "def", "kill_same_name_node", "(", "caller_id", ",", "api", ")", "delete_api", "=", "nil", "[", "@publishers", ",", "@subscribers", ",", "@services", "]", ".", "each", "do", "|", "list", "|", "list", ".", "each", "do", "|", "pub", "|", "if", "pub", ".", "caller_id", "==", "caller_id", "and", "pub", ".", "api", "!=", "api", "puts", "\"killing #{caller_id}\"", "delete_api", "=", "pub", ".", "api", "break", "end", "end", "end", "if", "delete_api", "proxy", "=", "SlaveProxy", ".", "new", "(", "'/master'", ",", "delete_api", ")", "begin", "proxy", ".", "shutdown", "(", "\"registered new node #{delete_api}\"", ")", "rescue", "end", "# delete", "[", "@publishers", ",", "@subscribers", ",", "@services", "]", ".", "each", "do", "|", "list", "|", "list", ".", "delete_if", "{", "|", "x", "|", "x", ".", "api", "==", "delete_api", "}", "end", "end", "end" ]
kill old node if the same caller_id node is exits. @param [String] caller_id new node's caller_id @param [String] api new node's XMLRPC URI
[ "kill", "old", "node", "if", "the", "same", "caller_id", "node", "is", "exits", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/master.rb#L159-L181
21,104
OTL/rosruby
lib/ros/graph_manager.rb
ROS.GraphManager.get_available_port
def get_available_port server = TCPServer.open(0) saddr = server.getsockname port = Socket.unpack_sockaddr_in(saddr)[0] server.close port end
ruby
def get_available_port server = TCPServer.open(0) saddr = server.getsockname port = Socket.unpack_sockaddr_in(saddr)[0] server.close port end
[ "def", "get_available_port", "server", "=", "TCPServer", ".", "open", "(", "0", ")", "saddr", "=", "server", ".", "getsockname", "port", "=", "Socket", ".", "unpack_sockaddr_in", "(", "saddr", ")", "[", "0", "]", "server", ".", "close", "port", "end" ]
get available port number by opening port 0. @return [Integer] port_num
[ "get", "available", "port", "number", "by", "opening", "port", "0", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/graph_manager.rb#L97-L103
21,105
OTL/rosruby
lib/ros/graph_manager.rb
ROS.GraphManager.wait_for_service
def wait_for_service(service_name, timeout_sec) begin timeout(timeout_sec) do while @is_ok if @master.lookup_service(service_name) return true end sleep(0.1) end end rescue Timeout::Error puts "time out for wait service #{service_name}" return nil rescue raise "connection with master failed. master = #{@master_uri}" end end
ruby
def wait_for_service(service_name, timeout_sec) begin timeout(timeout_sec) do while @is_ok if @master.lookup_service(service_name) return true end sleep(0.1) end end rescue Timeout::Error puts "time out for wait service #{service_name}" return nil rescue raise "connection with master failed. master = #{@master_uri}" end end
[ "def", "wait_for_service", "(", "service_name", ",", "timeout_sec", ")", "begin", "timeout", "(", "timeout_sec", ")", "do", "while", "@is_ok", "if", "@master", ".", "lookup_service", "(", "service_name", ")", "return", "true", "end", "sleep", "(", "0.1", ")", "end", "end", "rescue", "Timeout", "::", "Error", "puts", "\"time out for wait service #{service_name}\"", "return", "nil", "rescue", "raise", "\"connection with master failed. master = #{@master_uri}\"", "end", "end" ]
wait until service is available @param [String] service_name name of service for waiting @param [Float] timeout_sec wait for this seconds, then time out @return [Boolean] true: available, false: time out
[ "wait", "until", "service", "is", "available" ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/graph_manager.rb#L118-L134
21,106
OTL/rosruby
lib/ros/graph_manager.rb
ROS.GraphManager.add_service_server
def add_service_server(service_server) @master.register_service(service_server.service_name, service_server.service_uri) service_server.set_manager(self) @service_servers.push(service_server) service_server end
ruby
def add_service_server(service_server) @master.register_service(service_server.service_name, service_server.service_uri) service_server.set_manager(self) @service_servers.push(service_server) service_server end
[ "def", "add_service_server", "(", "service_server", ")", "@master", ".", "register_service", "(", "service_server", ".", "service_name", ",", "service_server", ".", "service_uri", ")", "service_server", ".", "set_manager", "(", "self", ")", "@service_servers", ".", "push", "(", "service_server", ")", "service_server", "end" ]
register a service to master, and add it in the controlling server list. raise if fail. @param [ServiceServer] service_server ServiceServer to be added @return [ServiceServer] service_server
[ "register", "a", "service", "to", "master", "and", "add", "it", "in", "the", "controlling", "server", "list", ".", "raise", "if", "fail", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/graph_manager.rb#L142-L148
21,107
OTL/rosruby
lib/ros/graph_manager.rb
ROS.GraphManager.add_subscriber
def add_subscriber(subscriber) uris = @master.register_subscriber(subscriber.topic_name, subscriber.topic_type.type) subscriber.set_manager(self) uris.each do |publisher_uri| subscriber.add_connection(publisher_uri) end @subscribers.push(subscriber) subscriber end
ruby
def add_subscriber(subscriber) uris = @master.register_subscriber(subscriber.topic_name, subscriber.topic_type.type) subscriber.set_manager(self) uris.each do |publisher_uri| subscriber.add_connection(publisher_uri) end @subscribers.push(subscriber) subscriber end
[ "def", "add_subscriber", "(", "subscriber", ")", "uris", "=", "@master", ".", "register_subscriber", "(", "subscriber", ".", "topic_name", ",", "subscriber", ".", "topic_type", ".", "type", ")", "subscriber", ".", "set_manager", "(", "self", ")", "uris", ".", "each", "do", "|", "publisher_uri", "|", "subscriber", ".", "add_connection", "(", "publisher_uri", ")", "end", "@subscribers", ".", "push", "(", "subscriber", ")", "subscriber", "end" ]
register a subscriber to master. raise if fail. @param [Subscriber] subscriber Subscriber to be added @return [Subscriber] subscriber
[ "register", "a", "subscriber", "to", "master", ".", "raise", "if", "fail", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/graph_manager.rb#L155-L164
21,108
OTL/rosruby
lib/ros/graph_manager.rb
ROS.GraphManager.add_parameter_subscriber
def add_parameter_subscriber(subscriber) subscriber.set_manager(self) @parameter_subscribers.push(subscriber) @master.subscribe_param(subscriber.key) subscriber end
ruby
def add_parameter_subscriber(subscriber) subscriber.set_manager(self) @parameter_subscribers.push(subscriber) @master.subscribe_param(subscriber.key) subscriber end
[ "def", "add_parameter_subscriber", "(", "subscriber", ")", "subscriber", ".", "set_manager", "(", "self", ")", "@parameter_subscribers", ".", "push", "(", "subscriber", ")", "@master", ".", "subscribe_param", "(", "subscriber", ".", "key", ")", "subscriber", "end" ]
register callback for paramUpdate @param [ParameterSubscriber] subscriber ParameterSubscriber instance to be added @return [ParameterSubscriber] subscriber
[ "register", "callback", "for", "paramUpdate" ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/graph_manager.rb#L170-L175
21,109
OTL/rosruby
lib/ros/graph_manager.rb
ROS.GraphManager.add_publisher
def add_publisher(publisher) @master.register_publisher(publisher.topic_name, publisher.topic_type.type) publisher.set_manager(self) @publishers.push(publisher) publisher end
ruby
def add_publisher(publisher) @master.register_publisher(publisher.topic_name, publisher.topic_type.type) publisher.set_manager(self) @publishers.push(publisher) publisher end
[ "def", "add_publisher", "(", "publisher", ")", "@master", ".", "register_publisher", "(", "publisher", ".", "topic_name", ",", "publisher", ".", "topic_type", ".", "type", ")", "publisher", ".", "set_manager", "(", "self", ")", "@publishers", ".", "push", "(", "publisher", ")", "publisher", "end" ]
register a publisher. raise if fail. @param [Publisher] publisher Publisher instance to be added @return [Publisher] publisher
[ "register", "a", "publisher", ".", "raise", "if", "fail", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/graph_manager.rb#L181-L187
21,110
OTL/rosruby
lib/ros/graph_manager.rb
ROS.GraphManager.shutdown_publisher
def shutdown_publisher(publisher) begin @master.unregister_publisher(publisher.topic_name) ensure @publishers.delete(publisher) do |pub| raise "publisher not found" end publisher.close end end
ruby
def shutdown_publisher(publisher) begin @master.unregister_publisher(publisher.topic_name) ensure @publishers.delete(publisher) do |pub| raise "publisher not found" end publisher.close end end
[ "def", "shutdown_publisher", "(", "publisher", ")", "begin", "@master", ".", "unregister_publisher", "(", "publisher", ".", "topic_name", ")", "ensure", "@publishers", ".", "delete", "(", "publisher", ")", "do", "|", "pub", "|", "raise", "\"publisher not found\"", "end", "publisher", ".", "close", "end", "end" ]
shutdown a publisher. @param [Publisher] publisher Publisher to be shutdown
[ "shutdown", "a", "publisher", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/graph_manager.rb#L201-L210
21,111
OTL/rosruby
lib/ros/graph_manager.rb
ROS.GraphManager.shutdown_subscriber
def shutdown_subscriber(subscriber) begin @master.unregister_subscriber(subscriber.topic_name) @subscribers.delete(subscriber) do |pub| raise "subscriber not found" end ensure subscriber.close end end
ruby
def shutdown_subscriber(subscriber) begin @master.unregister_subscriber(subscriber.topic_name) @subscribers.delete(subscriber) do |pub| raise "subscriber not found" end ensure subscriber.close end end
[ "def", "shutdown_subscriber", "(", "subscriber", ")", "begin", "@master", ".", "unregister_subscriber", "(", "subscriber", ".", "topic_name", ")", "@subscribers", ".", "delete", "(", "subscriber", ")", "do", "|", "pub", "|", "raise", "\"subscriber not found\"", "end", "ensure", "subscriber", ".", "close", "end", "end" ]
shutdown a subscriber. @param [Subscriber] subscriber Subscriber to be shutdown
[ "shutdown", "a", "subscriber", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/graph_manager.rb#L215-L224
21,112
OTL/rosruby
lib/ros/graph_manager.rb
ROS.GraphManager.shutdown_service_server
def shutdown_service_server(service) begin @master.unregister_service(service.service_name, service.service_uri) @service_servers.delete(service) do |pub| raise "service_server not found" end ensure service.close end end
ruby
def shutdown_service_server(service) begin @master.unregister_service(service.service_name, service.service_uri) @service_servers.delete(service) do |pub| raise "service_server not found" end ensure service.close end end
[ "def", "shutdown_service_server", "(", "service", ")", "begin", "@master", ".", "unregister_service", "(", "service", ".", "service_name", ",", "service", ".", "service_uri", ")", "@service_servers", ".", "delete", "(", "service", ")", "do", "|", "pub", "|", "raise", "\"service_server not found\"", "end", "ensure", "service", ".", "close", "end", "end" ]
shutdown a service server. @param [ServiceServer] service ServiceServer to be shutdown
[ "shutdown", "a", "service", "server", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/graph_manager.rb#L229-L239
21,113
OTL/rosruby
lib/ros/tcpros/client.rb
ROS::TCPROS.Client.start
def start write_header(@socket, build_header) read_header(@socket) @thread = Thread.start do while @is_running data = read_all(@socket) msg = @topic_type.new msg.deserialize(data) @byte_received += data.length @msg_queue.push(msg) end end end
ruby
def start write_header(@socket, build_header) read_header(@socket) @thread = Thread.start do while @is_running data = read_all(@socket) msg = @topic_type.new msg.deserialize(data) @byte_received += data.length @msg_queue.push(msg) end end end
[ "def", "start", "write_header", "(", "@socket", ",", "build_header", ")", "read_header", "(", "@socket", ")", "@thread", "=", "Thread", ".", "start", "do", "while", "@is_running", "data", "=", "read_all", "(", "@socket", ")", "msg", "=", "@topic_type", ".", "new", "msg", ".", "deserialize", "(", "data", ")", "@byte_received", "+=", "data", ".", "length", "@msg_queue", ".", "push", "(", "msg", ")", "end", "end", "end" ]
start recieving data. The received messages are pushed into a message queue.
[ "start", "recieving", "data", ".", "The", "received", "messages", "are", "pushed", "into", "a", "message", "queue", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/tcpros/client.rb#L68-L80
21,114
OTL/rosruby
lib/ros/tcpros/message.rb
ROS::TCPROS.Message.write_msg
def write_msg(socket, msg) sio = StringIO.new('', 'r+') len = msg.serialize(sio) sio.rewind data = sio.read len = data.length data = [len, data].pack("La#{len}") socket.write(data) data end
ruby
def write_msg(socket, msg) sio = StringIO.new('', 'r+') len = msg.serialize(sio) sio.rewind data = sio.read len = data.length data = [len, data].pack("La#{len}") socket.write(data) data end
[ "def", "write_msg", "(", "socket", ",", "msg", ")", "sio", "=", "StringIO", ".", "new", "(", "''", ",", "'r+'", ")", "len", "=", "msg", ".", "serialize", "(", "sio", ")", "sio", ".", "rewind", "data", "=", "sio", ".", "read", "len", "=", "data", ".", "length", "data", "=", "[", "len", ",", "data", "]", ".", "pack", "(", "\"La#{len}\"", ")", "socket", ".", "write", "(", "data", ")", "data", "end" ]
write message to socket. @param [IO] socket socket for writing @param [Message] msg message for writing @return [String] wrote data
[ "write", "message", "to", "socket", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/tcpros/message.rb#L26-L35
21,115
OTL/rosruby
lib/ros/tcpros/message.rb
ROS::TCPROS.Message.read_all
def read_all(socket) total_bytes = socket.recv(4).unpack("V")[0] if total_bytes and total_bytes > 0 socket.recv(total_bytes) else '' end end
ruby
def read_all(socket) total_bytes = socket.recv(4).unpack("V")[0] if total_bytes and total_bytes > 0 socket.recv(total_bytes) else '' end end
[ "def", "read_all", "(", "socket", ")", "total_bytes", "=", "socket", ".", "recv", "(", "4", ")", ".", "unpack", "(", "\"V\"", ")", "[", "0", "]", "if", "total_bytes", "and", "total_bytes", ">", "0", "socket", ".", "recv", "(", "total_bytes", ")", "else", "''", "end", "end" ]
read the size of data and read it from socket. @param [IO] socket socket for reading @return [String] received data
[ "read", "the", "size", "of", "data", "and", "read", "it", "from", "socket", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/tcpros/message.rb#L41-L48
21,116
OTL/rosruby
lib/ros/tcpros/message.rb
ROS::TCPROS.Message.read_header
def read_header(socket) header = ::ROS::TCPROS::Header.new header.deserialize(read_all(socket)) header end
ruby
def read_header(socket) header = ::ROS::TCPROS::Header.new header.deserialize(read_all(socket)) header end
[ "def", "read_header", "(", "socket", ")", "header", "=", "::", "ROS", "::", "TCPROS", "::", "Header", ".", "new", "header", ".", "deserialize", "(", "read_all", "(", "socket", ")", ")", "header", "end" ]
read a connection header from socket @param [String] socket socket for reading @return [Header] header
[ "read", "a", "connection", "header", "from", "socket" ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/tcpros/message.rb#L54-L58
21,117
OTL/rosruby
lib/ros/tcpros/header.rb
ROS::TCPROS.Header.push_data
def push_data(key, value) if (not key.kind_of?(String)) or (not value.kind_of?(String)) raise ArgumentError::new('header key and value must be string') end @data[key] = value self end
ruby
def push_data(key, value) if (not key.kind_of?(String)) or (not value.kind_of?(String)) raise ArgumentError::new('header key and value must be string') end @data[key] = value self end
[ "def", "push_data", "(", "key", ",", "value", ")", "if", "(", "not", "key", ".", "kind_of?", "(", "String", ")", ")", "or", "(", "not", "value", ".", "kind_of?", "(", "String", ")", ")", "raise", "ArgumentError", "::", "new", "(", "'header key and value must be string'", ")", "end", "@data", "[", "key", "]", "=", "value", "self", "end" ]
initialize with hash @param [Hash] data add key-value data to this header. @param [String] key key for header @param [String] value value for key @return [Header] self
[ "initialize", "with", "hash" ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/tcpros/header.rb#L30-L36
21,118
OTL/rosruby
lib/ros/tcpros/header.rb
ROS::TCPROS.Header.deserialize
def deserialize(data) while data.length > 0 len, data = data.unpack('Va*') msg = data[0..(len-1)] equal_position = msg.index('=') key = msg[0..(equal_position-1)] value = msg[(equal_position+1)..-1] @data[key] = value data = data[(len)..-1] end self end
ruby
def deserialize(data) while data.length > 0 len, data = data.unpack('Va*') msg = data[0..(len-1)] equal_position = msg.index('=') key = msg[0..(equal_position-1)] value = msg[(equal_position+1)..-1] @data[key] = value data = data[(len)..-1] end self end
[ "def", "deserialize", "(", "data", ")", "while", "data", ".", "length", ">", "0", "len", ",", "data", "=", "data", ".", "unpack", "(", "'Va*'", ")", "msg", "=", "data", "[", "0", "..", "(", "len", "-", "1", ")", "]", "equal_position", "=", "msg", ".", "index", "(", "'='", ")", "key", "=", "msg", "[", "0", "..", "(", "equal_position", "-", "1", ")", "]", "value", "=", "msg", "[", "(", "equal_position", "+", "1", ")", "..", "-", "1", "]", "@data", "[", "key", "]", "=", "value", "data", "=", "data", "[", "(", "len", ")", "..", "-", "1", "]", "end", "self", "end" ]
deserialize the data to header. this does not contain total byte number. @param [String] data @return [Header] self
[ "deserialize", "the", "data", "to", "header", ".", "this", "does", "not", "contain", "total", "byte", "number", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/tcpros/header.rb#L51-L62
21,119
OTL/rosruby
lib/ros/tcpros/header.rb
ROS::TCPROS.Header.serialize
def serialize(buff) serialized_data = '' @data.each_pair do |key, value| data_str = key + '=' + value serialized_data = serialized_data + [data_str.length, data_str].pack('Va*') end total_byte = serialized_data.length return buff.write([total_byte, serialized_data].pack('Va*')) end
ruby
def serialize(buff) serialized_data = '' @data.each_pair do |key, value| data_str = key + '=' + value serialized_data = serialized_data + [data_str.length, data_str].pack('Va*') end total_byte = serialized_data.length return buff.write([total_byte, serialized_data].pack('Va*')) end
[ "def", "serialize", "(", "buff", ")", "serialized_data", "=", "''", "@data", ".", "each_pair", "do", "|", "key", ",", "value", "|", "data_str", "=", "key", "+", "'='", "+", "value", "serialized_data", "=", "serialized_data", "+", "[", "data_str", ".", "length", ",", "data_str", "]", ".", "pack", "(", "'Va*'", ")", "end", "total_byte", "=", "serialized_data", ".", "length", "return", "buff", ".", "write", "(", "[", "total_byte", ",", "serialized_data", "]", ".", "pack", "(", "'Va*'", ")", ")", "end" ]
serialize the data into header. return the byte of the serialized data. @param [IO] buff where to write data @return [Integer] byte of serialized data
[ "serialize", "the", "data", "into", "header", ".", "return", "the", "byte", "of", "the", "serialized", "data", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/tcpros/header.rb#L78-L86
21,120
OTL/rosruby
lib/ros/master_proxy.rb
ROS.MasterProxy.unregister_service
def unregister_service(service, service_api) code, message, val = @proxy.unregisterService(@caller_id, service, service_api) if code == 1 return true elsif code == 0 puts message return true else raise message end end
ruby
def unregister_service(service, service_api) code, message, val = @proxy.unregisterService(@caller_id, service, service_api) if code == 1 return true elsif code == 0 puts message return true else raise message end end
[ "def", "unregister_service", "(", "service", ",", "service_api", ")", "code", ",", "message", ",", "val", "=", "@proxy", ".", "unregisterService", "(", "@caller_id", ",", "service", ",", "service_api", ")", "if", "code", "==", "1", "return", "true", "elsif", "code", "==", "0", "puts", "message", "return", "true", "else", "raise", "message", "end", "end" ]
unregister a service @param [String] service name of service @param [String] service_api service api uri @return [Boolean] true success @raise RuntimeError
[ "unregister", "a", "service" ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/master_proxy.rb#L57-L69
21,121
OTL/rosruby
lib/ros/master_proxy.rb
ROS.MasterProxy.register_subscriber
def register_subscriber(topic, topic_type) code, message,val = @proxy.registerSubscriber(@caller_id, topic, topic_type, @slave_uri) if code == 1 val elsif code == 0 puts message val else raise message end end
ruby
def register_subscriber(topic, topic_type) code, message,val = @proxy.registerSubscriber(@caller_id, topic, topic_type, @slave_uri) if code == 1 val elsif code == 0 puts message val else raise message end end
[ "def", "register_subscriber", "(", "topic", ",", "topic_type", ")", "code", ",", "message", ",", "val", "=", "@proxy", ".", "registerSubscriber", "(", "@caller_id", ",", "topic", ",", "topic_type", ",", "@slave_uri", ")", "if", "code", "==", "1", "val", "elsif", "code", "==", "0", "puts", "message", "val", "else", "raise", "message", "end", "end" ]
register a subscriber @param [String] topic topic name @param [String] topic_type topic type @return [Array] URI of current publishers @raise [RuntimeError] if error
[ "register", "a", "subscriber" ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/master_proxy.rb#L76-L89
21,122
OTL/rosruby
lib/ros/master_proxy.rb
ROS.MasterProxy.unregister_subscriber
def unregister_subscriber(topic) code, message,val = @proxy.unregisterSubscriber(@caller_id, topic, @slave_uri) if code == 1 return true elsif code == 0 puts message return true else raise message end end
ruby
def unregister_subscriber(topic) code, message,val = @proxy.unregisterSubscriber(@caller_id, topic, @slave_uri) if code == 1 return true elsif code == 0 puts message return true else raise message end end
[ "def", "unregister_subscriber", "(", "topic", ")", "code", ",", "message", ",", "val", "=", "@proxy", ".", "unregisterSubscriber", "(", "@caller_id", ",", "topic", ",", "@slave_uri", ")", "if", "code", "==", "1", "return", "true", "elsif", "code", "==", "0", "puts", "message", "return", "true", "else", "raise", "message", "end", "end" ]
unregister a subscriber @param [String] topic name of topic to unregister @return [Boolean] true @raise RuntimeError
[ "unregister", "a", "subscriber" ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/master_proxy.rb#L95-L107
21,123
OTL/rosruby
lib/ros/master_proxy.rb
ROS.MasterProxy.register_publisher
def register_publisher(topic, topic_type) code, message, uris = @proxy.registerPublisher(@caller_id, topic, topic_type, @slave_uri) if code == 1 uris else raise message end end
ruby
def register_publisher(topic, topic_type) code, message, uris = @proxy.registerPublisher(@caller_id, topic, topic_type, @slave_uri) if code == 1 uris else raise message end end
[ "def", "register_publisher", "(", "topic", ",", "topic_type", ")", "code", ",", "message", ",", "uris", "=", "@proxy", ".", "registerPublisher", "(", "@caller_id", ",", "topic", ",", "topic_type", ",", "@slave_uri", ")", "if", "code", "==", "1", "uris", "else", "raise", "message", "end", "end" ]
register a publisher @param [String] topic topic name of topic @param [String] topic_type type of topic @return [Array] URI of current subscribers @raise RuntimeError
[ "register", "a", "publisher" ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/master_proxy.rb#L114-L124
21,124
OTL/rosruby
lib/ros/master_proxy.rb
ROS.MasterProxy.unregister_publisher
def unregister_publisher(topic) code, message, val = @proxy.unregisterPublisher(@caller_id, topic, @slave_uri) if code == 1 return val elsif code == 0 puts message return true else raise message end return false end
ruby
def unregister_publisher(topic) code, message, val = @proxy.unregisterPublisher(@caller_id, topic, @slave_uri) if code == 1 return val elsif code == 0 puts message return true else raise message end return false end
[ "def", "unregister_publisher", "(", "topic", ")", "code", ",", "message", ",", "val", "=", "@proxy", ".", "unregisterPublisher", "(", "@caller_id", ",", "topic", ",", "@slave_uri", ")", "if", "code", "==", "1", "return", "val", "elsif", "code", "==", "0", "puts", "message", "return", "true", "else", "raise", "message", "end", "return", "false", "end" ]
unregister a publisher @param [String] topic name of topic @return [Boolean] true @raise RuntimeError
[ "unregister", "a", "publisher" ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/master_proxy.rb#L130-L143
21,125
OTL/rosruby
lib/ros/master_proxy.rb
ROS.MasterProxy.subscribe_param
def subscribe_param(key) code, message, uri = @proxy.subscribeParam(@caller_id, @slave_uri, key) if code == 1 return true else raise message end end
ruby
def subscribe_param(key) code, message, uri = @proxy.subscribeParam(@caller_id, @slave_uri, key) if code == 1 return true else raise message end end
[ "def", "subscribe_param", "(", "key", ")", "code", ",", "message", ",", "uri", "=", "@proxy", ".", "subscribeParam", "(", "@caller_id", ",", "@slave_uri", ",", "key", ")", "if", "code", "==", "1", "return", "true", "else", "raise", "message", "end", "end" ]
this method is not described in the wiki. subscribe to the parameter key. @param [String] key name of parameter @return [Boolean] true @raise [RuntimeError] if fail
[ "this", "method", "is", "not", "described", "in", "the", "wiki", ".", "subscribe", "to", "the", "parameter", "key", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/master_proxy.rb#L151-L158
21,126
OTL/rosruby
lib/ros/master_proxy.rb
ROS.MasterProxy.unsubscribe_param
def unsubscribe_param(key) code, message, uri = @proxy.unsubscribeParam(@caller_id, @slave_uri, key) if code == 1 return true else raise message end end
ruby
def unsubscribe_param(key) code, message, uri = @proxy.unsubscribeParam(@caller_id, @slave_uri, key) if code == 1 return true else raise message end end
[ "def", "unsubscribe_param", "(", "key", ")", "code", ",", "message", ",", "uri", "=", "@proxy", ".", "unsubscribeParam", "(", "@caller_id", ",", "@slave_uri", ",", "key", ")", "if", "code", "==", "1", "return", "true", "else", "raise", "message", "end", "end" ]
unsubscribe to the parameter key. this method is not described in the wiki. @param [String] key name of parameter key @return [Boolean] true @raise [RuntimeError] if failt
[ "unsubscribe", "to", "the", "parameter", "key", ".", "this", "method", "is", "not", "described", "in", "the", "wiki", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/master_proxy.rb#L166-L173
21,127
OTL/rosruby
lib/ros/master_proxy.rb
ROS.MasterProxy.get_published_topics
def get_published_topics(subgraph='') code, message, topics = @proxy.getPublishedTopics(@caller_id, subgraph) if code == 1 return topics elsif raise message end end
ruby
def get_published_topics(subgraph='') code, message, topics = @proxy.getPublishedTopics(@caller_id, subgraph) if code == 1 return topics elsif raise message end end
[ "def", "get_published_topics", "(", "subgraph", "=", "''", ")", "code", ",", "message", ",", "topics", "=", "@proxy", ".", "getPublishedTopics", "(", "@caller_id", ",", "subgraph", ")", "if", "code", "==", "1", "return", "topics", "elsif", "raise", "message", "end", "end" ]
get the all published topics @param [String] subgraph namespace for check @return [Array] topic names. @raise
[ "get", "the", "all", "published", "topics" ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/master_proxy.rb#L191-L198
21,128
OTL/rosruby
lib/ros/master_proxy.rb
ROS.MasterProxy.lookup_service
def lookup_service(service) code, message, uri = @proxy.lookupService(@caller_id, service) if code == 1 uri else false end end
ruby
def lookup_service(service) code, message, uri = @proxy.lookupService(@caller_id, service) if code == 1 uri else false end end
[ "def", "lookup_service", "(", "service", ")", "code", ",", "message", ",", "uri", "=", "@proxy", ".", "lookupService", "(", "@caller_id", ",", "service", ")", "if", "code", "==", "1", "uri", "else", "false", "end", "end" ]
look up a service by name @param [String] service name of service @return [String, nil] URI of service if found, nil not found.
[ "look", "up", "a", "service", "by", "name" ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/master_proxy.rb#L226-L233
21,129
OTL/rosruby
lib/ros/node.rb
ROS.Node.get_param
def get_param(key, default=nil) key = expand_local_name(@node_name, key) param = @parameter.get_param(key) if param param else default end end
ruby
def get_param(key, default=nil) key = expand_local_name(@node_name, key) param = @parameter.get_param(key) if param param else default end end
[ "def", "get_param", "(", "key", ",", "default", "=", "nil", ")", "key", "=", "expand_local_name", "(", "@node_name", ",", "key", ")", "param", "=", "@parameter", ".", "get_param", "(", "key", ")", "if", "param", "param", "else", "default", "end", "end" ]
get the param for key. You can set default value. That is uesed when the key is not set yet. @param [String] key key for search the parameters @param [String, Integer, Float, Boolean] default default value @return [String, Integer, Float, Boolean] parameter value for key
[ "get", "the", "param", "for", "key", ".", "You", "can", "set", "default", "value", ".", "That", "is", "uesed", "when", "the", "key", "is", "not", "set", "yet", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/node.rb#L141-L149
21,130
OTL/rosruby
lib/ros/node.rb
ROS.Node.advertise
def advertise(topic_name, topic_type, options={}) if options[:no_resolve] name = topic_name else name = resolve_name(topic_name) end publisher = Publisher.new(@node_name, name, topic_type, options[:latched], @manager.host) @manager.add_publisher(publisher) trap_signals publisher end
ruby
def advertise(topic_name, topic_type, options={}) if options[:no_resolve] name = topic_name else name = resolve_name(topic_name) end publisher = Publisher.new(@node_name, name, topic_type, options[:latched], @manager.host) @manager.add_publisher(publisher) trap_signals publisher end
[ "def", "advertise", "(", "topic_name", ",", "topic_type", ",", "options", "=", "{", "}", ")", "if", "options", "[", ":no_resolve", "]", "name", "=", "topic_name", "else", "name", "=", "resolve_name", "(", "topic_name", ")", "end", "publisher", "=", "Publisher", ".", "new", "(", "@node_name", ",", "name", ",", "topic_type", ",", "options", "[", ":latched", "]", ",", "@manager", ".", "host", ")", "@manager", ".", "add_publisher", "(", "publisher", ")", "trap_signals", "publisher", "end" ]
start publishing the topic. @param [String] topic_name name of topic (string) @param [Class] topic_type topic class @param [Hash] options :latched, :resolve @option options [Boolean] :latched (false) latched topic @option options [Boolean] :resolve (true) resolve topic_name or not. This is for publish /rosout with namespaced node. @return [Publisher] Publisher instance
[ "start", "publishing", "the", "topic", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/node.rb#L195-L209
21,131
OTL/rosruby
lib/ros/node.rb
ROS.Node.advertise_service
def advertise_service(service_name, service_type, &callback) server = ::ROS::ServiceServer.new(@node_name, resolve_name(service_name), service_type, callback, @manager.host) @manager.add_service_server(server) trap_signals server end
ruby
def advertise_service(service_name, service_type, &callback) server = ::ROS::ServiceServer.new(@node_name, resolve_name(service_name), service_type, callback, @manager.host) @manager.add_service_server(server) trap_signals server end
[ "def", "advertise_service", "(", "service_name", ",", "service_type", ",", "&", "callback", ")", "server", "=", "::", "ROS", "::", "ServiceServer", ".", "new", "(", "@node_name", ",", "resolve_name", "(", "service_name", ")", ",", "service_type", ",", "callback", ",", "@manager", ".", "host", ")", "@manager", ".", "add_service_server", "(", "server", ")", "trap_signals", "server", "end" ]
start service server. @param [String] service_name name of this service (string) @param [Service] service_type service class @param [Proc] callback service definition @return [ServiceServer] ServiceServer instance
[ "start", "service", "server", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/node.rb#L218-L227
21,132
OTL/rosruby
lib/ros/node.rb
ROS.Node.subscribe
def subscribe(topic_name, topic_type, &callback) sub = Subscriber.new(@node_name, resolve_name(topic_name), topic_type, callback) @manager.add_subscriber(sub) trap_signals sub end
ruby
def subscribe(topic_name, topic_type, &callback) sub = Subscriber.new(@node_name, resolve_name(topic_name), topic_type, callback) @manager.add_subscriber(sub) trap_signals sub end
[ "def", "subscribe", "(", "topic_name", ",", "topic_type", ",", "&", "callback", ")", "sub", "=", "Subscriber", ".", "new", "(", "@node_name", ",", "resolve_name", "(", "topic_name", ")", ",", "topic_type", ",", "callback", ")", "@manager", ".", "add_subscriber", "(", "sub", ")", "trap_signals", "sub", "end" ]
start to subscribe a topic. @param [String] topic_name name of topic (string) @param [Class] topic_type Topic instance @return [Subscriber] created Subscriber instance
[ "start", "to", "subscribe", "a", "topic", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/node.rb#L256-L264
21,133
OTL/rosruby
lib/ros/node.rb
ROS.Node.subscribe_parameter
def subscribe_parameter(param, &callback) sub = ParameterSubscriber.new(param, callback) @manager.add_parameter_subscriber(sub) sub end
ruby
def subscribe_parameter(param, &callback) sub = ParameterSubscriber.new(param, callback) @manager.add_parameter_subscriber(sub) sub end
[ "def", "subscribe_parameter", "(", "param", ",", "&", "callback", ")", "sub", "=", "ParameterSubscriber", ".", "new", "(", "param", ",", "callback", ")", "@manager", ".", "add_parameter_subscriber", "(", "sub", ")", "sub", "end" ]
subscribe to the parameter. @param [String] param name of parameter to subscribe @param [Proc] callback callback when parameter updated @return [ParameterSubscriber] created ParameterSubscriber instance
[ "subscribe", "to", "the", "parameter", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/node.rb#L272-L276
21,134
OTL/rosruby
lib/ros/node.rb
ROS.Node.convert_if_needed
def convert_if_needed(value) #:nodoc: if value =~ /^[+-]?\d+\.?\d*$/ # float value = value.to_f elsif value =~ /^[+-]?\d+$/ # int value = value.to_i else value end end
ruby
def convert_if_needed(value) #:nodoc: if value =~ /^[+-]?\d+\.?\d*$/ # float value = value.to_f elsif value =~ /^[+-]?\d+$/ # int value = value.to_i else value end end
[ "def", "convert_if_needed", "(", "value", ")", "#:nodoc:", "if", "value", "=~", "/", "\\d", "\\.", "\\d", "/", "# float", "value", "=", "value", ".", "to_f", "elsif", "value", "=~", "/", "\\d", "/", "# int", "value", "=", "value", ".", "to_i", "else", "value", "end", "end" ]
converts strings if it is float and int numbers. @example convert_if_needed('10') # => 10 convert_if_needed('0.1') # => 0.1 convert_if_needed('string') # => 'string' @param [String] value string @return [Float, Integer, String] return converted value.
[ "converts", "strings", "if", "it", "is", "float", "and", "int", "numbers", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/node.rb#L398-L406
21,135
OTL/rosruby
lib/ros/node.rb
ROS.Node.parse_args
def parse_args(args) #:nodoc: remapping = {} for arg in args splited = arg.split(':=') if splited.length == 2 key, value = splited if key == '__name' @node_name = resolve_name(value) elsif key == '__ip' @host = value elsif key == '__hostname' @host = value elsif key == '__master' @master_uri = value elsif key == '__ns' @ns = value elsif key[0] == '_'[0] # local name remaps key[0] = '~' remapping[resolve_name(key)] = convert_if_needed(value) else # remaps remapping[key] = convert_if_needed(value) end end end remapping end
ruby
def parse_args(args) #:nodoc: remapping = {} for arg in args splited = arg.split(':=') if splited.length == 2 key, value = splited if key == '__name' @node_name = resolve_name(value) elsif key == '__ip' @host = value elsif key == '__hostname' @host = value elsif key == '__master' @master_uri = value elsif key == '__ns' @ns = value elsif key[0] == '_'[0] # local name remaps key[0] = '~' remapping[resolve_name(key)] = convert_if_needed(value) else # remaps remapping[key] = convert_if_needed(value) end end end remapping end
[ "def", "parse_args", "(", "args", ")", "#:nodoc:", "remapping", "=", "{", "}", "for", "arg", "in", "args", "splited", "=", "arg", ".", "split", "(", "':='", ")", "if", "splited", ".", "length", "==", "2", "key", ",", "value", "=", "splited", "if", "key", "==", "'__name'", "@node_name", "=", "resolve_name", "(", "value", ")", "elsif", "key", "==", "'__ip'", "@host", "=", "value", "elsif", "key", "==", "'__hostname'", "@host", "=", "value", "elsif", "key", "==", "'__master'", "@master_uri", "=", "value", "elsif", "key", "==", "'__ns'", "@ns", "=", "value", "elsif", "key", "[", "0", "]", "==", "'_'", "[", "0", "]", "# local name remaps", "key", "[", "0", "]", "=", "'~'", "remapping", "[", "resolve_name", "(", "key", ")", "]", "=", "convert_if_needed", "(", "value", ")", "else", "# remaps", "remapping", "[", "key", "]", "=", "convert_if_needed", "(", "value", ")", "end", "end", "end", "remapping", "end" ]
parse all args. @param [Array] args arguments for parse
[ "parse", "all", "args", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/node.rb#L411-L438
21,136
OTL/rosruby
lib/ros/subscriber.rb
ROS.Subscriber.add_connection
def add_connection(uri) #:nodoc: publisher = SlaveProxy.new(@caller_id, uri) begin protocol, host, port = publisher.request_topic(@topic_name, [["TCPROS"]]) if protocol == "TCPROS" connection = TCPROS::Client.new(host, port, @caller_id, @topic_name, @topic_type, uri, @tcp_no_delay) connection.start else puts "not support protocol: #{protocol}" raise "not support protocol: #{protocol}" end connection.id = "#{@topic_name}_in_#{@connection_id_number}" @connection_id_number += 1 @connections.push(connection) return connection rescue # puts "request to #{uri} fail" return false end end
ruby
def add_connection(uri) #:nodoc: publisher = SlaveProxy.new(@caller_id, uri) begin protocol, host, port = publisher.request_topic(@topic_name, [["TCPROS"]]) if protocol == "TCPROS" connection = TCPROS::Client.new(host, port, @caller_id, @topic_name, @topic_type, uri, @tcp_no_delay) connection.start else puts "not support protocol: #{protocol}" raise "not support protocol: #{protocol}" end connection.id = "#{@topic_name}_in_#{@connection_id_number}" @connection_id_number += 1 @connections.push(connection) return connection rescue # puts "request to #{uri} fail" return false end end
[ "def", "add_connection", "(", "uri", ")", "#:nodoc:", "publisher", "=", "SlaveProxy", ".", "new", "(", "@caller_id", ",", "uri", ")", "begin", "protocol", ",", "host", ",", "port", "=", "publisher", ".", "request_topic", "(", "@topic_name", ",", "[", "[", "\"TCPROS\"", "]", "]", ")", "if", "protocol", "==", "\"TCPROS\"", "connection", "=", "TCPROS", "::", "Client", ".", "new", "(", "host", ",", "port", ",", "@caller_id", ",", "@topic_name", ",", "@topic_type", ",", "uri", ",", "@tcp_no_delay", ")", "connection", ".", "start", "else", "puts", "\"not support protocol: #{protocol}\"", "raise", "\"not support protocol: #{protocol}\"", "end", "connection", ".", "id", "=", "\"#{@topic_name}_in_#{@connection_id_number}\"", "@connection_id_number", "+=", "1", "@connections", ".", "push", "(", "connection", ")", "return", "connection", "rescue", "#\tputs \"request to #{uri} fail\"", "return", "false", "end", "end" ]
request topic to master and start connection with publisher. @param [String] uri uri to connect @return [TCPROS::Client] new connection
[ "request", "topic", "to", "master", "and", "start", "connection", "with", "publisher", "." ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/subscriber.rb#L75-L94
21,137
OTL/rosruby
lib/ros/subscriber.rb
ROS.Subscriber.get_connection_info
def get_connection_info info = [] @connections.each do |connection| info.push([connection.id, connection.target_uri, 'i', connection.protocol, @topic_name]) end info end
ruby
def get_connection_info info = [] @connections.each do |connection| info.push([connection.id, connection.target_uri, 'i', connection.protocol, @topic_name]) end info end
[ "def", "get_connection_info", "info", "=", "[", "]", "@connections", ".", "each", "do", "|", "connection", "|", "info", ".", "push", "(", "[", "connection", ".", "id", ",", "connection", ".", "target_uri", ",", "'i'", ",", "connection", ".", "protocol", ",", "@topic_name", "]", ")", "end", "info", "end" ]
connection information fro slave API @return [Array] connection info
[ "connection", "information", "fro", "slave", "API" ]
dc29af423241167ab9060b40366b4616a62c5f11
https://github.com/OTL/rosruby/blob/dc29af423241167ab9060b40366b4616a62c5f11/lib/ros/subscriber.rb#L115-L121
21,138
dradis/dradis-projects
lib/dradis/plugins/projects/export/v1/template.rb
Dradis::Plugins::Projects::Export::V1.Template.user_email_for_activity
def user_email_for_activity(activity) return activity.user if activity.user.is_a?(String) @user_emails ||= begin User.select([:id, :email]).all.each_with_object({}) do |user, hash| hash[user.id] = user.email end end @user_emails[activity.user_id] end
ruby
def user_email_for_activity(activity) return activity.user if activity.user.is_a?(String) @user_emails ||= begin User.select([:id, :email]).all.each_with_object({}) do |user, hash| hash[user.id] = user.email end end @user_emails[activity.user_id] end
[ "def", "user_email_for_activity", "(", "activity", ")", "return", "activity", ".", "user", "if", "activity", ".", "user", ".", "is_a?", "(", "String", ")", "@user_emails", "||=", "begin", "User", ".", "select", "(", "[", ":id", ",", ":email", "]", ")", ".", "all", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "user", ",", "hash", "|", "hash", "[", "user", ".", "id", "]", "=", "user", ".", "email", "end", "end", "@user_emails", "[", "activity", ".", "user_id", "]", "end" ]
Cache user emails so we don't have to make an extra SQL request for every activity
[ "Cache", "user", "emails", "so", "we", "don", "t", "have", "to", "make", "an", "extra", "SQL", "request", "for", "every", "activity" ]
c581357dd9fff7e65afdf30c05ea183c58362207
https://github.com/dradis/dradis-projects/blob/c581357dd9fff7e65afdf30c05ea183c58362207/lib/dradis/plugins/projects/export/v1/template.rb#L157-L166
21,139
emq/workable
lib/workable/client.rb
Workable.Client.create_job_candidate
def create_job_candidate(candidate, shortcode, stage_slug = nil) shortcode = "#{shortcode}/#{stage_slug}" if stage_slug response = post_request("jobs/#{shortcode}/candidates") do |request| request.body = @transform_from.apply(:candidate, candidate).to_json end @transform_to.apply(:candidate, response['candidate']) end
ruby
def create_job_candidate(candidate, shortcode, stage_slug = nil) shortcode = "#{shortcode}/#{stage_slug}" if stage_slug response = post_request("jobs/#{shortcode}/candidates") do |request| request.body = @transform_from.apply(:candidate, candidate).to_json end @transform_to.apply(:candidate, response['candidate']) end
[ "def", "create_job_candidate", "(", "candidate", ",", "shortcode", ",", "stage_slug", "=", "nil", ")", "shortcode", "=", "\"#{shortcode}/#{stage_slug}\"", "if", "stage_slug", "response", "=", "post_request", "(", "\"jobs/#{shortcode}/candidates\"", ")", "do", "|", "request", "|", "request", ".", "body", "=", "@transform_from", ".", "apply", "(", ":candidate", ",", "candidate", ")", ".", "to_json", "end", "@transform_to", ".", "apply", "(", ":candidate", ",", "response", "[", "'candidate'", "]", ")", "end" ]
create new candidate for given job @param candidate [Hash] the candidate data as described in https://workable.readme.io/docs/job-candidates-create including the `{"candidate"=>{}}` part @param shortcode [String] job short code @param stage_slug [String] optional stage slug @return [Hash] the candidate information without `{"candidate"=>{}}` part
[ "create", "new", "candidate", "for", "given", "job" ]
15b1410e97dd25ef28f6a0938f21efbb168f0ad2
https://github.com/emq/workable/blob/15b1410e97dd25ef28f6a0938f21efbb168f0ad2/lib/workable/client.rb#L126-L134
21,140
emq/workable
lib/workable/client.rb
Workable.Client.create_comment
def create_comment(candidate_id, member_id, comment_text, policy = [], attachment = nil) comment = { body: comment_text, policy: policy, attachment: attachment } post_request("candidates/#{candidate_id}/comments") do |request| request.body = { member_id: member_id, comment: comment }.to_json end end
ruby
def create_comment(candidate_id, member_id, comment_text, policy = [], attachment = nil) comment = { body: comment_text, policy: policy, attachment: attachment } post_request("candidates/#{candidate_id}/comments") do |request| request.body = { member_id: member_id, comment: comment }.to_json end end
[ "def", "create_comment", "(", "candidate_id", ",", "member_id", ",", "comment_text", ",", "policy", "=", "[", "]", ",", "attachment", "=", "nil", ")", "comment", "=", "{", "body", ":", "comment_text", ",", "policy", ":", "policy", ",", "attachment", ":", "attachment", "}", "post_request", "(", "\"candidates/#{candidate_id}/comments\"", ")", "do", "|", "request", "|", "request", ".", "body", "=", "{", "member_id", ":", "member_id", ",", "comment", ":", "comment", "}", ".", "to_json", "end", "end" ]
create a comment on the candidate's timeline @param candidate_id [String] the candidate's id @param member_id [String] id of the member leaving the comment @param comment_text [String] the comment's text @param policy [String] option to set the view rights of the comment @param attachment [Hash] optional attachment for the comment @param attachment :name [String] filename of the attachment @param attachment :data [String] payload of the attachment, encoded in base64
[ "create", "a", "comment", "on", "the", "candidate", "s", "timeline" ]
15b1410e97dd25ef28f6a0938f21efbb168f0ad2
https://github.com/emq/workable/blob/15b1410e97dd25ef28f6a0938f21efbb168f0ad2/lib/workable/client.rb#L144-L150
21,141
emq/workable
lib/workable/client.rb
Workable.Client.disqualify
def disqualify(candidate_id, member_id, reason = nil) post_request("candidates/#{candidate_id}/disqualify") do |request| request.body = { member_id: member_id, disqualification_reason: reason }.to_json end end
ruby
def disqualify(candidate_id, member_id, reason = nil) post_request("candidates/#{candidate_id}/disqualify") do |request| request.body = { member_id: member_id, disqualification_reason: reason }.to_json end end
[ "def", "disqualify", "(", "candidate_id", ",", "member_id", ",", "reason", "=", "nil", ")", "post_request", "(", "\"candidates/#{candidate_id}/disqualify\"", ")", "do", "|", "request", "|", "request", ".", "body", "=", "{", "member_id", ":", "member_id", ",", "disqualification_reason", ":", "reason", "}", ".", "to_json", "end", "end" ]
disqualify a candidate @param candidate_id [String] the candidate's id @param member_id [String] id of the member performing the disqualification @param reason [String] why the candidate should be disqualified
[ "disqualify", "a", "candidate" ]
15b1410e97dd25ef28f6a0938f21efbb168f0ad2
https://github.com/emq/workable/blob/15b1410e97dd25ef28f6a0938f21efbb168f0ad2/lib/workable/client.rb#L156-L160
21,142
emq/workable
lib/workable/client.rb
Workable.Client.revert
def revert(candidate_id, member_id) post_request("candidates/#{candidate_id}/revert") do |request| request.body = { member_id: member_id }.to_json end end
ruby
def revert(candidate_id, member_id) post_request("candidates/#{candidate_id}/revert") do |request| request.body = { member_id: member_id }.to_json end end
[ "def", "revert", "(", "candidate_id", ",", "member_id", ")", "post_request", "(", "\"candidates/#{candidate_id}/revert\"", ")", "do", "|", "request", "|", "request", ".", "body", "=", "{", "member_id", ":", "member_id", "}", ".", "to_json", "end", "end" ]
revert a candidate's disqualification @param candidate_id [String] the candidate's id @param member_id [String] id of the member reverting the disqualification
[ "revert", "a", "candidate", "s", "disqualification" ]
15b1410e97dd25ef28f6a0938f21efbb168f0ad2
https://github.com/emq/workable/blob/15b1410e97dd25ef28f6a0938f21efbb168f0ad2/lib/workable/client.rb#L165-L169
21,143
emq/workable
lib/workable/client.rb
Workable.Client.copy
def copy(candidate_id, member_id, shortcode, stage = nil) body = { member_id: member_id, target_job_shortcode: shortcode, target_stage: stage } response = post_request("candidates/#{candidate_id}/copy") do |request| request.body = body.to_json end @transform_to.apply(:candidate, response['candidate']) end
ruby
def copy(candidate_id, member_id, shortcode, stage = nil) body = { member_id: member_id, target_job_shortcode: shortcode, target_stage: stage } response = post_request("candidates/#{candidate_id}/copy") do |request| request.body = body.to_json end @transform_to.apply(:candidate, response['candidate']) end
[ "def", "copy", "(", "candidate_id", ",", "member_id", ",", "shortcode", ",", "stage", "=", "nil", ")", "body", "=", "{", "member_id", ":", "member_id", ",", "target_job_shortcode", ":", "shortcode", ",", "target_stage", ":", "stage", "}", "response", "=", "post_request", "(", "\"candidates/#{candidate_id}/copy\"", ")", "do", "|", "request", "|", "request", ".", "body", "=", "body", ".", "to_json", "end", "@transform_to", ".", "apply", "(", ":candidate", ",", "response", "[", "'candidate'", "]", ")", "end" ]
copy a candidate to another job @param candidate_id [String] the candidate's id @param member_id [String] id of the member performing the copy @param shortcode [String] shortcode of the job that the candidate will be copied to @param stage [String] stage the candidate should be copied to
[ "copy", "a", "candidate", "to", "another", "job" ]
15b1410e97dd25ef28f6a0938f21efbb168f0ad2
https://github.com/emq/workable/blob/15b1410e97dd25ef28f6a0938f21efbb168f0ad2/lib/workable/client.rb#L176-L188
21,144
emq/workable
lib/workable/client.rb
Workable.Client.move
def move(candidate_id, member_id, stage) post_request("candidates/#{candidate_id}/move") do |request| request.body = { member_id: member_id, target_stage: stage }.to_json end end
ruby
def move(candidate_id, member_id, stage) post_request("candidates/#{candidate_id}/move") do |request| request.body = { member_id: member_id, target_stage: stage }.to_json end end
[ "def", "move", "(", "candidate_id", ",", "member_id", ",", "stage", ")", "post_request", "(", "\"candidates/#{candidate_id}/move\"", ")", "do", "|", "request", "|", "request", ".", "body", "=", "{", "member_id", ":", "member_id", ",", "target_stage", ":", "stage", "}", ".", "to_json", "end", "end" ]
moves a candidate to another stage @param candidate_id [String] the candidate's id @param member_id [String] id of the member performing the move @param stage [String] stage the candidate should be moved to
[ "moves", "a", "candidate", "to", "another", "stage" ]
15b1410e97dd25ef28f6a0938f21efbb168f0ad2
https://github.com/emq/workable/blob/15b1410e97dd25ef28f6a0938f21efbb168f0ad2/lib/workable/client.rb#L213-L217
21,145
emq/workable
lib/workable/client.rb
Workable.Client.create_rating
def create_rating(candidate_id, member_id, comment, score) body = { member_id: member_id, comment: comment, score: score } post_request("candidates/#{candidate_id}/ratings") do |request| request.body = body.to_json end end
ruby
def create_rating(candidate_id, member_id, comment, score) body = { member_id: member_id, comment: comment, score: score } post_request("candidates/#{candidate_id}/ratings") do |request| request.body = body.to_json end end
[ "def", "create_rating", "(", "candidate_id", ",", "member_id", ",", "comment", ",", "score", ")", "body", "=", "{", "member_id", ":", "member_id", ",", "comment", ":", "comment", ",", "score", ":", "score", "}", "post_request", "(", "\"candidates/#{candidate_id}/ratings\"", ")", "do", "|", "request", "|", "request", ".", "body", "=", "body", ".", "to_json", "end", "end" ]
creates a rating for a candidate @param candidate_id [String] the candidate's id @param member_id [String] id of the member adding the rating @param comment [String] a comment about the scoring of the candidate @param score [String] one of 'negative', 'positive', or 'definitely'
[ "creates", "a", "rating", "for", "a", "candidate" ]
15b1410e97dd25ef28f6a0938f21efbb168f0ad2
https://github.com/emq/workable/blob/15b1410e97dd25ef28f6a0938f21efbb168f0ad2/lib/workable/client.rb#L224-L234
21,146
emq/workable
lib/workable/client.rb
Workable.Client.get_request
def get_request(url, params = {}) params = URI.encode_www_form(params.keep_if { |k, v| k && v }) full_url = params.empty? ? url : [url, params].join('?') do_request(full_url, Net::HTTP::Get) end
ruby
def get_request(url, params = {}) params = URI.encode_www_form(params.keep_if { |k, v| k && v }) full_url = params.empty? ? url : [url, params].join('?') do_request(full_url, Net::HTTP::Get) end
[ "def", "get_request", "(", "url", ",", "params", "=", "{", "}", ")", "params", "=", "URI", ".", "encode_www_form", "(", "params", ".", "keep_if", "{", "|", "k", ",", "v", "|", "k", "&&", "v", "}", ")", "full_url", "=", "params", ".", "empty?", "?", "url", ":", "[", "url", ",", "params", "]", ".", "join", "(", "'?'", ")", "do_request", "(", "full_url", ",", "Net", "::", "HTTP", "::", "Get", ")", "end" ]
do the get request to api
[ "do", "the", "get", "request", "to", "api" ]
15b1410e97dd25ef28f6a0938f21efbb168f0ad2
https://github.com/emq/workable/blob/15b1410e97dd25ef28f6a0938f21efbb168f0ad2/lib/workable/client.rb#L246-L250
21,147
emq/workable
lib/workable/client.rb
Workable.Client.post_request
def post_request(url) do_request(url, Net::HTTP::Post) do |request| yield(request) if block_given? end end
ruby
def post_request(url) do_request(url, Net::HTTP::Post) do |request| yield(request) if block_given? end end
[ "def", "post_request", "(", "url", ")", "do_request", "(", "url", ",", "Net", "::", "HTTP", "::", "Post", ")", "do", "|", "request", "|", "yield", "(", "request", ")", "if", "block_given?", "end", "end" ]
do the post request to api
[ "do", "the", "post", "request", "to", "api" ]
15b1410e97dd25ef28f6a0938f21efbb168f0ad2
https://github.com/emq/workable/blob/15b1410e97dd25ef28f6a0938f21efbb168f0ad2/lib/workable/client.rb#L253-L257
21,148
emq/workable
lib/workable/client.rb
Workable.Client.do_request
def do_request(url, type, &_block) uri = URI.parse("#{api_url}/#{url}") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = type.new(uri.request_uri, headers) yield request if block_given? response = http.request(request) parse!(response) end
ruby
def do_request(url, type, &_block) uri = URI.parse("#{api_url}/#{url}") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = type.new(uri.request_uri, headers) yield request if block_given? response = http.request(request) parse!(response) end
[ "def", "do_request", "(", "url", ",", "type", ",", "&", "_block", ")", "uri", "=", "URI", ".", "parse", "(", "\"#{api_url}/#{url}\"", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "http", ".", "use_ssl", "=", "true", "request", "=", "type", ".", "new", "(", "uri", ".", "request_uri", ",", "headers", ")", "yield", "request", "if", "block_given?", "response", "=", "http", ".", "request", "(", "request", ")", "parse!", "(", "response", ")", "end" ]
generic part of requesting api
[ "generic", "part", "of", "requesting", "api" ]
15b1410e97dd25ef28f6a0938f21efbb168f0ad2
https://github.com/emq/workable/blob/15b1410e97dd25ef28f6a0938f21efbb168f0ad2/lib/workable/client.rb#L260-L272
21,149
emq/workable
lib/workable/client.rb
Workable.Client.parse!
def parse!(response) case response.code.to_i when 204, 205 nil when 200...300 JSON.parse(response.body) if !response.body.to_s.empty? when 401 fail Errors::NotAuthorized, JSON.parse(response.body)['error'] when 404 fail Errors::NotFound, JSON.parse(response.body)['error'] when 422 handle_response_422(response) when 503 fail Errors::RequestToLong, response.body else fail Errors::InvalidResponse, "Response code: #{response.code} message: #{response.body}" end end
ruby
def parse!(response) case response.code.to_i when 204, 205 nil when 200...300 JSON.parse(response.body) if !response.body.to_s.empty? when 401 fail Errors::NotAuthorized, JSON.parse(response.body)['error'] when 404 fail Errors::NotFound, JSON.parse(response.body)['error'] when 422 handle_response_422(response) when 503 fail Errors::RequestToLong, response.body else fail Errors::InvalidResponse, "Response code: #{response.code} message: #{response.body}" end end
[ "def", "parse!", "(", "response", ")", "case", "response", ".", "code", ".", "to_i", "when", "204", ",", "205", "nil", "when", "200", "...", "300", "JSON", ".", "parse", "(", "response", ".", "body", ")", "if", "!", "response", ".", "body", ".", "to_s", ".", "empty?", "when", "401", "fail", "Errors", "::", "NotAuthorized", ",", "JSON", ".", "parse", "(", "response", ".", "body", ")", "[", "'error'", "]", "when", "404", "fail", "Errors", "::", "NotFound", ",", "JSON", ".", "parse", "(", "response", ".", "body", ")", "[", "'error'", "]", "when", "422", "handle_response_422", "(", "response", ")", "when", "503", "fail", "Errors", "::", "RequestToLong", ",", "response", ".", "body", "else", "fail", "Errors", "::", "InvalidResponse", ",", "\"Response code: #{response.code} message: #{response.body}\"", "end", "end" ]
parse the api response
[ "parse", "the", "api", "response" ]
15b1410e97dd25ef28f6a0938f21efbb168f0ad2
https://github.com/emq/workable/blob/15b1410e97dd25ef28f6a0938f21efbb168f0ad2/lib/workable/client.rb#L275-L292
21,150
ONLYOFFICE/onlyoffice_api_gem
lib/teamlab/modules/files.rb
Teamlab.Files.create_txt_in_my_docs
def create_txt_in_my_docs(title, content) @request.post(%w[@my text], title: title.to_s, content: content.to_s) end
ruby
def create_txt_in_my_docs(title, content) @request.post(%w[@my text], title: title.to_s, content: content.to_s) end
[ "def", "create_txt_in_my_docs", "(", "title", ",", "content", ")", "@request", ".", "post", "(", "%w[", "@my", "text", "]", ",", "title", ":", "title", ".", "to_s", ",", "content", ":", "content", ".", "to_s", ")", "end" ]
region File Creation
[ "region", "File", "Creation" ]
604a21eda5bdb994581b15d6030ed5317724794b
https://github.com/ONLYOFFICE/onlyoffice_api_gem/blob/604a21eda5bdb994581b15d6030ed5317724794b/lib/teamlab/modules/files.rb#L9-L11
21,151
emq/workable
lib/workable/transformation.rb
Workable.Transformation.apply
def apply(mapping, data) transformation = @mappings[mapping] return data unless transformation case data when nil data when Array data.map { |datas| transformation.call(datas) } else transformation.call(data) end end
ruby
def apply(mapping, data) transformation = @mappings[mapping] return data unless transformation case data when nil data when Array data.map { |datas| transformation.call(datas) } else transformation.call(data) end end
[ "def", "apply", "(", "mapping", ",", "data", ")", "transformation", "=", "@mappings", "[", "mapping", "]", "return", "data", "unless", "transformation", "case", "data", "when", "nil", "data", "when", "Array", "data", ".", "map", "{", "|", "datas", "|", "transformation", ".", "call", "(", "datas", ")", "}", "else", "transformation", ".", "call", "(", "data", ")", "end", "end" ]
selects transformation strategy based on the inputs @param transformation [Method|Proc|nil] the transformation to perform @param data [Hash|Array|nil] the data to transform @return [Object|nil] results of the transformation if given, raw data otherwise
[ "selects", "transformation", "strategy", "based", "on", "the", "inputs" ]
15b1410e97dd25ef28f6a0938f21efbb168f0ad2
https://github.com/emq/workable/blob/15b1410e97dd25ef28f6a0938f21efbb168f0ad2/lib/workable/transformation.rb#L12-L24
21,152
dradis/dradis-projects
lib/dradis/plugins/projects/export/template.rb
Dradis::Plugins::Projects::Export.Template.export
def export(args={}) builder = Builder::XmlMarkup.new builder.instruct! result = builder.tag!('dradis-template', version: version) do |template_builder| build_nodes(template_builder) build_issues(template_builder) build_methodologies(template_builder) build_categories(template_builder) build_tags(template_builder) build_report_content(template_builder) end return result end
ruby
def export(args={}) builder = Builder::XmlMarkup.new builder.instruct! result = builder.tag!('dradis-template', version: version) do |template_builder| build_nodes(template_builder) build_issues(template_builder) build_methodologies(template_builder) build_categories(template_builder) build_tags(template_builder) build_report_content(template_builder) end return result end
[ "def", "export", "(", "args", "=", "{", "}", ")", "builder", "=", "Builder", "::", "XmlMarkup", ".", "new", "builder", ".", "instruct!", "result", "=", "builder", ".", "tag!", "(", "'dradis-template'", ",", "version", ":", "version", ")", "do", "|", "template_builder", "|", "build_nodes", "(", "template_builder", ")", "build_issues", "(", "template_builder", ")", "build_methodologies", "(", "template_builder", ")", "build_categories", "(", "template_builder", ")", "build_tags", "(", "template_builder", ")", "build_report_content", "(", "template_builder", ")", "end", "return", "result", "end" ]
This method returns an XML representation of current repository which includes Categories, Nodes and Notes
[ "This", "method", "returns", "an", "XML", "representation", "of", "current", "repository", "which", "includes", "Categories", "Nodes", "and", "Notes" ]
c581357dd9fff7e65afdf30c05ea183c58362207
https://github.com/dradis/dradis-projects/blob/c581357dd9fff7e65afdf30c05ea183c58362207/lib/dradis/plugins/projects/export/template.rb#L5-L17
21,153
toptal/disqus_api
lib/disqus_api/response.rb
DisqusApi.Response.each_resource
def each_resource(&block) Enumerator.new do |result| each_page { |resources| resources.each { |resource| result << resource } } end.each(&block) end
ruby
def each_resource(&block) Enumerator.new do |result| each_page { |resources| resources.each { |resource| result << resource } } end.each(&block) end
[ "def", "each_resource", "(", "&", "block", ")", "Enumerator", ".", "new", "do", "|", "result", "|", "each_page", "{", "|", "resources", "|", "resources", ".", "each", "{", "|", "resource", "|", "result", "<<", "resource", "}", "}", "end", ".", "each", "(", "block", ")", "end" ]
Iterates through each response entry through all pages @return [Enumerator<Hash>]
[ "Iterates", "through", "each", "response", "entry", "through", "all", "pages" ]
818b0c2fd2fbbd7030fb11655bca8204ec3886fd
https://github.com/toptal/disqus_api/blob/818b0c2fd2fbbd7030fb11655bca8204ec3886fd/lib/disqus_api/response.rb#L23-L27
21,154
toptal/disqus_api
lib/disqus_api/response.rb
DisqusApi.Response.each_page
def each_page(&block) Enumerator.new do |result| next_response = self while next_response result << next_response.body.to_a next_response = next_response.next end end.each(&block) end
ruby
def each_page(&block) Enumerator.new do |result| next_response = self while next_response result << next_response.body.to_a next_response = next_response.next end end.each(&block) end
[ "def", "each_page", "(", "&", "block", ")", "Enumerator", ".", "new", "do", "|", "result", "|", "next_response", "=", "self", "while", "next_response", "result", "<<", "next_response", ".", "body", ".", "to_a", "next_response", "=", "next_response", ".", "next", "end", "end", ".", "each", "(", "block", ")", "end" ]
Iterates through every single page @return [Enumerator<Array<Hash>>]
[ "Iterates", "through", "every", "single", "page" ]
818b0c2fd2fbbd7030fb11655bca8204ec3886fd
https://github.com/toptal/disqus_api/blob/818b0c2fd2fbbd7030fb11655bca8204ec3886fd/lib/disqus_api/response.rb#L31-L40
21,155
toptal/disqus_api
lib/disqus_api/request.rb
DisqusApi.Request.perform
def perform(arguments = {}) case type.to_sym when :post, :get api.public_send(type, path, @arguments.merge(arguments)) else raise ArgumentError, "Unregistered request type #{request_type}" end end
ruby
def perform(arguments = {}) case type.to_sym when :post, :get api.public_send(type, path, @arguments.merge(arguments)) else raise ArgumentError, "Unregistered request type #{request_type}" end end
[ "def", "perform", "(", "arguments", "=", "{", "}", ")", "case", "type", ".", "to_sym", "when", ":post", ",", ":get", "api", ".", "public_send", "(", "type", ",", "path", ",", "@arguments", ".", "merge", "(", "arguments", ")", ")", "else", "raise", "ArgumentError", ",", "\"Unregistered request type #{request_type}\"", "end", "end" ]
Returns plain JSON response received from Disqus @param [Hash] arguments @return [String]
[ "Returns", "plain", "JSON", "response", "received", "from", "Disqus" ]
818b0c2fd2fbbd7030fb11655bca8204ec3886fd
https://github.com/toptal/disqus_api/blob/818b0c2fd2fbbd7030fb11655bca8204ec3886fd/lib/disqus_api/request.rb#L34-L41
21,156
zmbacker/enum_help
lib/enum_help/i18n.rb
EnumHelp.I18n.enum
def enum( definitions ) super( definitions ) definitions.each do |name, _| Helper.define_attr_i18n_method(self, name) Helper.define_collection_i18n_method(self, name) end end
ruby
def enum( definitions ) super( definitions ) definitions.each do |name, _| Helper.define_attr_i18n_method(self, name) Helper.define_collection_i18n_method(self, name) end end
[ "def", "enum", "(", "definitions", ")", "super", "(", "definitions", ")", "definitions", ".", "each", "do", "|", "name", ",", "_", "|", "Helper", ".", "define_attr_i18n_method", "(", "self", ",", "name", ")", "Helper", ".", "define_collection_i18n_method", "(", "self", ",", "name", ")", "end", "end" ]
overwrite the enum method
[ "overwrite", "the", "enum", "method" ]
35d3cc5d7a8ce9452f403728020e736ead9621da
https://github.com/zmbacker/enum_help/blob/35d3cc5d7a8ce9452f403728020e736ead9621da/lib/enum_help/i18n.rb#L6-L12
21,157
lanej/cistern
lib/cistern/attributes.rb
Cistern::Attributes.InstanceMethods.requires
def requires(*args) missing, required = missing_attributes(args) if missing.length == 1 fail(ArgumentError, "#{missing.keys.first} is required for this operation") elsif missing.any? fail(ArgumentError, "#{missing.keys[0...-1].join(', ')} and #{missing.keys[-1]} are required for this operation") end required end
ruby
def requires(*args) missing, required = missing_attributes(args) if missing.length == 1 fail(ArgumentError, "#{missing.keys.first} is required for this operation") elsif missing.any? fail(ArgumentError, "#{missing.keys[0...-1].join(', ')} and #{missing.keys[-1]} are required for this operation") end required end
[ "def", "requires", "(", "*", "args", ")", "missing", ",", "required", "=", "missing_attributes", "(", "args", ")", "if", "missing", ".", "length", "==", "1", "fail", "(", "ArgumentError", ",", "\"#{missing.keys.first} is required for this operation\"", ")", "elsif", "missing", ".", "any?", "fail", "(", "ArgumentError", ",", "\"#{missing.keys[0...-1].join(', ')} and #{missing.keys[-1]} are required for this operation\"", ")", "end", "required", "end" ]
Require specification of certain attributes @raise [ArgumentError] if any requested attribute does not have a value @return [Hash] of matching attributes
[ "Require", "specification", "of", "certain", "attributes" ]
15b618020961d397ae78027a317ffd68b8bc5abf
https://github.com/lanej/cistern/blob/15b618020961d397ae78027a317ffd68b8bc5abf/lib/cistern/attributes.rb#L231-L241
21,158
lanej/cistern
lib/cistern/attributes.rb
Cistern::Attributes.InstanceMethods.requires_one
def requires_one(*args) missing, required = missing_attributes(args) if missing.length == args.length fail(ArgumentError, "#{missing.keys[0...-1].join(', ')} or #{missing.keys[-1]} are required for this operation") end required end
ruby
def requires_one(*args) missing, required = missing_attributes(args) if missing.length == args.length fail(ArgumentError, "#{missing.keys[0...-1].join(', ')} or #{missing.keys[-1]} are required for this operation") end required end
[ "def", "requires_one", "(", "*", "args", ")", "missing", ",", "required", "=", "missing_attributes", "(", "args", ")", "if", "missing", ".", "length", "==", "args", ".", "length", "fail", "(", "ArgumentError", ",", "\"#{missing.keys[0...-1].join(', ')} or #{missing.keys[-1]} are required for this operation\"", ")", "end", "required", "end" ]
Require specification of one or more attributes. @raise [ArgumentError] if no requested attributes have values @return [Hash] of matching attributes
[ "Require", "specification", "of", "one", "or", "more", "attributes", "." ]
15b618020961d397ae78027a317ffd68b8bc5abf
https://github.com/lanej/cistern/blob/15b618020961d397ae78027a317ffd68b8bc5abf/lib/cistern/attributes.rb#L247-L255
21,159
esigler/lita-jira
lib/jirahelper/issue.rb
JiraHelper.Issue.fetch_issues
def fetch_issues(jql, suppress_exceptions = false) client.Issue.jql(jql) rescue StandardError => e throw e unless suppress_exceptions nil end
ruby
def fetch_issues(jql, suppress_exceptions = false) client.Issue.jql(jql) rescue StandardError => e throw e unless suppress_exceptions nil end
[ "def", "fetch_issues", "(", "jql", ",", "suppress_exceptions", "=", "false", ")", "client", ".", "Issue", ".", "jql", "(", "jql", ")", "rescue", "StandardError", "=>", "e", "throw", "e", "unless", "suppress_exceptions", "nil", "end" ]
Leverage the jira-ruby Issue.jql search feature @param [Type String] jql Valid JQL query @return [Type Array] 0-m JIRA Issues returned from query
[ "Leverage", "the", "jira", "-", "ruby", "Issue", ".", "jql", "search", "feature" ]
bf62e561828cd86c3ce7e29fb9f28f7de3854ed0
https://github.com/esigler/lita-jira/blob/bf62e561828cd86c3ce7e29fb9f28f7de3854ed0/lib/jirahelper/issue.rb#L18-L23
21,160
greshny/diffbot
lib/diffbot/request.rb
Diffbot.Request.build_request
def build_request(method, query_params={}) query = { token: token }.merge(query_params) request = { query: query, method: method, headers: {}, mock: @test_mode } if Diffbot.instrumentor request.update( instrumentor: Diffbot.instrumentor, instrumentor_name: "diffbot" ) end request end
ruby
def build_request(method, query_params={}) query = { token: token }.merge(query_params) request = { query: query, method: method, headers: {}, mock: @test_mode } if Diffbot.instrumentor request.update( instrumentor: Diffbot.instrumentor, instrumentor_name: "diffbot" ) end request end
[ "def", "build_request", "(", "method", ",", "query_params", "=", "{", "}", ")", "query", "=", "{", "token", ":", "token", "}", ".", "merge", "(", "query_params", ")", "request", "=", "{", "query", ":", "query", ",", "method", ":", "method", ",", "headers", ":", "{", "}", ",", "mock", ":", "@test_mode", "}", "if", "Diffbot", ".", "instrumentor", "request", ".", "update", "(", "instrumentor", ":", "Diffbot", ".", "instrumentor", ",", "instrumentor_name", ":", "\"diffbot\"", ")", "end", "request", "end" ]
Build the hash of options that Excon requires for an HTTP request. method - A Symbol with the HTTP method (:get, :post, etc). query_params - Any query parameters to add to the request. Returns a Hash.
[ "Build", "the", "hash", "of", "options", "that", "Excon", "requires", "for", "an", "HTTP", "request", "." ]
4e58dadecf53f397172ab85bd0bdd8c29b62b519
https://github.com/greshny/diffbot/blob/4e58dadecf53f397172ab85bd0bdd8c29b62b519/lib/diffbot/request.rb#L50-L62
21,161
bcoles/ssrf_proxy
lib/ssrf_proxy/server.rb
SSRFProxy.Server.port_open?
def port_open?(ip, port, seconds = 10) Timeout.timeout(seconds) do TCPSocket.new(ip, port).close true end rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, SocketError, Timeout::Error false end
ruby
def port_open?(ip, port, seconds = 10) Timeout.timeout(seconds) do TCPSocket.new(ip, port).close true end rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, SocketError, Timeout::Error false end
[ "def", "port_open?", "(", "ip", ",", "port", ",", "seconds", "=", "10", ")", "Timeout", ".", "timeout", "(", "seconds", ")", "do", "TCPSocket", ".", "new", "(", "ip", ",", "port", ")", ".", "close", "true", "end", "rescue", "Errno", "::", "ECONNREFUSED", ",", "Errno", "::", "EHOSTUNREACH", ",", "SocketError", ",", "Timeout", "::", "Error", "false", "end" ]
Start the local server and listen for connections @param [SSRFProxy::HTTP] ssrf A configured SSRFProxy::HTTP object @param [String] interface Listen interface (Default: 127.0.0.1) @param [Integer] port Listen port (Default: 8081) @raise [SSRFProxy::Server::Error::InvalidSsrf] Invalid SSRFProxy::SSRF object provided. @raise [SSRFProxy::Server::Error::ProxyRecursion] Proxy recursion error. SSRF Proxy cannot use itself as an upstream proxy. @raise [SSRFProxy::Server::Error::RemoteProxyUnresponsive] Could not connect to remote proxy. @raise [SSRFProxy::Server::Error::AddressInUse] Could not bind to the port on the specified interface as address already in use. @example Start SSRF Proxy server with the default options ssrf_proxy = SSRFProxy::Server.new( SSRFProxy::HTTP.new('http://example.local/?url=xxURLxx'), '127.0.0.1', 8081) ssrf_proxy.serve Checks if a port is open or not on a remote host From: https://gist.github.com/ashrithr/5305786 @param [String] ip connect to IP @param [Integer] port connect to port @param [Integer] seconds connection timeout
[ "Start", "the", "local", "server", "and", "listen", "for", "connections" ]
e79da7a449edaa6c898d2f4c9ef443bda93970b5
https://github.com/bcoles/ssrf_proxy/blob/e79da7a449edaa6c898d2f4c9ef443bda93970b5/lib/ssrf_proxy/server.rb#L123-L130
21,162
bcoles/ssrf_proxy
lib/ssrf_proxy/server.rb
SSRFProxy.Server.handle_connection
def handle_connection(socket) start_time = Time.now _, port, host = socket.peeraddr logger.debug("Client #{host}:#{port} connected") request = socket.read logger.debug("Received client request (#{request.length} bytes):\n" \ "#{request}") response = nil if request.to_s =~ /\ACONNECT ([_a-zA-Z0-9\.\-]+:[\d]+) .*$/ host = $1.to_s logger.info("Negotiating connection to #{host}") response = send_request("GET http://#{host}/ HTTP/1.0\n\n") if response['code'].to_i == 502 || response['code'].to_i == 504 logger.info("Connection to #{host} failed") socket.write("#{response['status_line']}\n" \ "#{response['headers']}\n" \ "#{response['body']}") raise Errno::ECONNRESET end logger.info("Connected to #{host} successfully") socket.write("HTTP/1.0 200 Connection established\r\n\r\n") request = socket.read logger.debug("Received client request (#{request.length} bytes):\n" \ "#{request}") # CHANGE_CIPHER_SPEC 20 0x14 # ALERT 21 0x15 # HANDSHAKE 22 0x16 # APPLICATION_DATA 23 0x17 if request.to_s.start_with?("\x14", "\x15", "\x16", "\x17") logger.warn("Received SSL/TLS client request. SSL/TLS tunneling is not supported. Aborted.") raise Errno::ECONNRESET end end response = send_request(request.to_s) socket.write("#{response['status_line']}\n" \ "#{response['headers']}\n" \ "#{response['body']}") raise Errno::ECONNRESET rescue EOFError, Errno::ECONNRESET, Errno::EPIPE socket.close logger.debug("Client #{host}:#{port} disconnected") end_time = Time.now duration = ((end_time - start_time) * 1000).round(3) if response.nil? logger.info("Served 0 bytes in #{duration} ms") else logger.info("Served #{response['body'].length} bytes in #{duration} ms") end end
ruby
def handle_connection(socket) start_time = Time.now _, port, host = socket.peeraddr logger.debug("Client #{host}:#{port} connected") request = socket.read logger.debug("Received client request (#{request.length} bytes):\n" \ "#{request}") response = nil if request.to_s =~ /\ACONNECT ([_a-zA-Z0-9\.\-]+:[\d]+) .*$/ host = $1.to_s logger.info("Negotiating connection to #{host}") response = send_request("GET http://#{host}/ HTTP/1.0\n\n") if response['code'].to_i == 502 || response['code'].to_i == 504 logger.info("Connection to #{host} failed") socket.write("#{response['status_line']}\n" \ "#{response['headers']}\n" \ "#{response['body']}") raise Errno::ECONNRESET end logger.info("Connected to #{host} successfully") socket.write("HTTP/1.0 200 Connection established\r\n\r\n") request = socket.read logger.debug("Received client request (#{request.length} bytes):\n" \ "#{request}") # CHANGE_CIPHER_SPEC 20 0x14 # ALERT 21 0x15 # HANDSHAKE 22 0x16 # APPLICATION_DATA 23 0x17 if request.to_s.start_with?("\x14", "\x15", "\x16", "\x17") logger.warn("Received SSL/TLS client request. SSL/TLS tunneling is not supported. Aborted.") raise Errno::ECONNRESET end end response = send_request(request.to_s) socket.write("#{response['status_line']}\n" \ "#{response['headers']}\n" \ "#{response['body']}") raise Errno::ECONNRESET rescue EOFError, Errno::ECONNRESET, Errno::EPIPE socket.close logger.debug("Client #{host}:#{port} disconnected") end_time = Time.now duration = ((end_time - start_time) * 1000).round(3) if response.nil? logger.info("Served 0 bytes in #{duration} ms") else logger.info("Served #{response['body'].length} bytes in #{duration} ms") end end
[ "def", "handle_connection", "(", "socket", ")", "start_time", "=", "Time", ".", "now", "_", ",", "port", ",", "host", "=", "socket", ".", "peeraddr", "logger", ".", "debug", "(", "\"Client #{host}:#{port} connected\"", ")", "request", "=", "socket", ".", "read", "logger", ".", "debug", "(", "\"Received client request (#{request.length} bytes):\\n\"", "\"#{request}\"", ")", "response", "=", "nil", "if", "request", ".", "to_s", "=~", "/", "\\A", "\\.", "\\-", "\\d", "/", "host", "=", "$1", ".", "to_s", "logger", ".", "info", "(", "\"Negotiating connection to #{host}\"", ")", "response", "=", "send_request", "(", "\"GET http://#{host}/ HTTP/1.0\\n\\n\"", ")", "if", "response", "[", "'code'", "]", ".", "to_i", "==", "502", "||", "response", "[", "'code'", "]", ".", "to_i", "==", "504", "logger", ".", "info", "(", "\"Connection to #{host} failed\"", ")", "socket", ".", "write", "(", "\"#{response['status_line']}\\n\"", "\"#{response['headers']}\\n\"", "\"#{response['body']}\"", ")", "raise", "Errno", "::", "ECONNRESET", "end", "logger", ".", "info", "(", "\"Connected to #{host} successfully\"", ")", "socket", ".", "write", "(", "\"HTTP/1.0 200 Connection established\\r\\n\\r\\n\"", ")", "request", "=", "socket", ".", "read", "logger", ".", "debug", "(", "\"Received client request (#{request.length} bytes):\\n\"", "\"#{request}\"", ")", "# CHANGE_CIPHER_SPEC 20 0x14", "# ALERT 21 0x15", "# HANDSHAKE 22 0x16", "# APPLICATION_DATA 23 0x17", "if", "request", ".", "to_s", ".", "start_with?", "(", "\"\\x14\"", ",", "\"\\x15\"", ",", "\"\\x16\"", ",", "\"\\x17\"", ")", "logger", ".", "warn", "(", "\"Received SSL/TLS client request. SSL/TLS tunneling is not supported. Aborted.\"", ")", "raise", "Errno", "::", "ECONNRESET", "end", "end", "response", "=", "send_request", "(", "request", ".", "to_s", ")", "socket", ".", "write", "(", "\"#{response['status_line']}\\n\"", "\"#{response['headers']}\\n\"", "\"#{response['body']}\"", ")", "raise", "Errno", "::", "ECONNRESET", "rescue", "EOFError", ",", "Errno", "::", "ECONNRESET", ",", "Errno", "::", "EPIPE", "socket", ".", "close", "logger", ".", "debug", "(", "\"Client #{host}:#{port} disconnected\"", ")", "end_time", "=", "Time", ".", "now", "duration", "=", "(", "(", "end_time", "-", "start_time", ")", "*", "1000", ")", ".", "round", "(", "3", ")", "if", "response", ".", "nil?", "logger", ".", "info", "(", "\"Served 0 bytes in #{duration} ms\"", ")", "else", "logger", ".", "info", "(", "\"Served #{response['body'].length} bytes in #{duration} ms\"", ")", "end", "end" ]
Handle client socket connection @param [Celluloid::IO::TCPSocket] socket client socket
[ "Handle", "client", "socket", "connection" ]
e79da7a449edaa6c898d2f4c9ef443bda93970b5
https://github.com/bcoles/ssrf_proxy/blob/e79da7a449edaa6c898d2f4c9ef443bda93970b5/lib/ssrf_proxy/server.rb#L180-L233
21,163
bcoles/ssrf_proxy
lib/ssrf_proxy/http.rb
SSRFProxy.HTTP.encode_ip
def encode_ip(url, mode) return if url.nil? new_host = nil host = URI.parse(url.to_s.split('?').first).host.to_s begin ip = IPAddress::IPv4.new(host) rescue logger.warn("Could not parse requested host as IPv4 address: #{host}") return url end case mode when 'int' new_host = url.to_s.gsub(host, ip.to_u32.to_s) when 'ipv6' new_host = url.to_s.gsub(host, "[#{ip.to_ipv6}]") when 'oct' new_host = url.to_s.gsub(host, "0#{ip.to_u32.to_s(8)}") when 'hex' new_host = url.to_s.gsub(host, "0x#{ip.to_u32.to_s(16)}") when 'dotted_hex' res = ip.octets.map { |i| "0x#{i.to_s(16).rjust(2, '0')}" }.join('.') new_host = url.to_s.gsub(host, res.to_s) unless res.nil? else logger.warn("Invalid IP encoding: #{mode}") end new_host end
ruby
def encode_ip(url, mode) return if url.nil? new_host = nil host = URI.parse(url.to_s.split('?').first).host.to_s begin ip = IPAddress::IPv4.new(host) rescue logger.warn("Could not parse requested host as IPv4 address: #{host}") return url end case mode when 'int' new_host = url.to_s.gsub(host, ip.to_u32.to_s) when 'ipv6' new_host = url.to_s.gsub(host, "[#{ip.to_ipv6}]") when 'oct' new_host = url.to_s.gsub(host, "0#{ip.to_u32.to_s(8)}") when 'hex' new_host = url.to_s.gsub(host, "0x#{ip.to_u32.to_s(16)}") when 'dotted_hex' res = ip.octets.map { |i| "0x#{i.to_s(16).rjust(2, '0')}" }.join('.') new_host = url.to_s.gsub(host, res.to_s) unless res.nil? else logger.warn("Invalid IP encoding: #{mode}") end new_host end
[ "def", "encode_ip", "(", "url", ",", "mode", ")", "return", "if", "url", ".", "nil?", "new_host", "=", "nil", "host", "=", "URI", ".", "parse", "(", "url", ".", "to_s", ".", "split", "(", "'?'", ")", ".", "first", ")", ".", "host", ".", "to_s", "begin", "ip", "=", "IPAddress", "::", "IPv4", ".", "new", "(", "host", ")", "rescue", "logger", ".", "warn", "(", "\"Could not parse requested host as IPv4 address: #{host}\"", ")", "return", "url", "end", "case", "mode", "when", "'int'", "new_host", "=", "url", ".", "to_s", ".", "gsub", "(", "host", ",", "ip", ".", "to_u32", ".", "to_s", ")", "when", "'ipv6'", "new_host", "=", "url", ".", "to_s", ".", "gsub", "(", "host", ",", "\"[#{ip.to_ipv6}]\"", ")", "when", "'oct'", "new_host", "=", "url", ".", "to_s", ".", "gsub", "(", "host", ",", "\"0#{ip.to_u32.to_s(8)}\"", ")", "when", "'hex'", "new_host", "=", "url", ".", "to_s", ".", "gsub", "(", "host", ",", "\"0x#{ip.to_u32.to_s(16)}\"", ")", "when", "'dotted_hex'", "res", "=", "ip", ".", "octets", ".", "map", "{", "|", "i", "|", "\"0x#{i.to_s(16).rjust(2, '0')}\"", "}", ".", "join", "(", "'.'", ")", "new_host", "=", "url", ".", "to_s", ".", "gsub", "(", "host", ",", "res", ".", "to_s", ")", "unless", "res", ".", "nil?", "else", "logger", ".", "warn", "(", "\"Invalid IP encoding: #{mode}\"", ")", "end", "new_host", "end" ]
Encode IP address of a given URL @param [String] url target URL @param [String] mode encoding (int, ipv6, oct, hex, dotted_hex) @return [String] encoded IP address
[ "Encode", "IP", "address", "of", "a", "given", "URL" ]
e79da7a449edaa6c898d2f4c9ef443bda93970b5
https://github.com/bcoles/ssrf_proxy/blob/e79da7a449edaa6c898d2f4c9ef443bda93970b5/lib/ssrf_proxy/http.rb#L910-L936
21,164
bcoles/ssrf_proxy
lib/ssrf_proxy/http.rb
SSRFProxy.HTTP.run_rules
def run_rules(url, rules) str = url.to_s return str if rules.nil? rules.each do |rule| case rule when 'noproto' str = str.gsub(%r{^https?://}, '') when 'nossl', 'http' str = str.gsub(%r{^https://}, 'http://') when 'ssl', 'https' str = str.gsub(%r{^http://}, 'https://') when 'base32' str = Base32.encode(str).to_s when 'base64' str = Base64.encode64(str).delete("\n") when 'md4' str = OpenSSL::Digest::MD4.hexdigest(str) when 'md5' md5 = Digest::MD5.new md5.update str str = md5.hexdigest when 'sha1' str = Digest::SHA1.hexdigest(str) when 'reverse' str = str.reverse when 'upcase' str = str.upcase when 'downcase' str = str.downcase when 'rot13' str = str.tr('A-Za-z', 'N-ZA-Mn-za-m') when 'urlencode' str = CGI.escape(str).gsub(/\+/, '%20') when 'urldecode' str = CGI.unescape(str) when 'append-hash' str = "#{str}##{rand(36**6).to_s(36)}" when 'append-method-get' separator = str.include?('?') ? '&' : '?' str = "#{str}#{separator}method=get&_method=get" else logger.warn("Unknown rule: #{rule}") end end str end
ruby
def run_rules(url, rules) str = url.to_s return str if rules.nil? rules.each do |rule| case rule when 'noproto' str = str.gsub(%r{^https?://}, '') when 'nossl', 'http' str = str.gsub(%r{^https://}, 'http://') when 'ssl', 'https' str = str.gsub(%r{^http://}, 'https://') when 'base32' str = Base32.encode(str).to_s when 'base64' str = Base64.encode64(str).delete("\n") when 'md4' str = OpenSSL::Digest::MD4.hexdigest(str) when 'md5' md5 = Digest::MD5.new md5.update str str = md5.hexdigest when 'sha1' str = Digest::SHA1.hexdigest(str) when 'reverse' str = str.reverse when 'upcase' str = str.upcase when 'downcase' str = str.downcase when 'rot13' str = str.tr('A-Za-z', 'N-ZA-Mn-za-m') when 'urlencode' str = CGI.escape(str).gsub(/\+/, '%20') when 'urldecode' str = CGI.unescape(str) when 'append-hash' str = "#{str}##{rand(36**6).to_s(36)}" when 'append-method-get' separator = str.include?('?') ? '&' : '?' str = "#{str}#{separator}method=get&_method=get" else logger.warn("Unknown rule: #{rule}") end end str end
[ "def", "run_rules", "(", "url", ",", "rules", ")", "str", "=", "url", ".", "to_s", "return", "str", "if", "rules", ".", "nil?", "rules", ".", "each", "do", "|", "rule", "|", "case", "rule", "when", "'noproto'", "str", "=", "str", ".", "gsub", "(", "%r{", "}", ",", "''", ")", "when", "'nossl'", ",", "'http'", "str", "=", "str", ".", "gsub", "(", "%r{", "}", ",", "'http://'", ")", "when", "'ssl'", ",", "'https'", "str", "=", "str", ".", "gsub", "(", "%r{", "}", ",", "'https://'", ")", "when", "'base32'", "str", "=", "Base32", ".", "encode", "(", "str", ")", ".", "to_s", "when", "'base64'", "str", "=", "Base64", ".", "encode64", "(", "str", ")", ".", "delete", "(", "\"\\n\"", ")", "when", "'md4'", "str", "=", "OpenSSL", "::", "Digest", "::", "MD4", ".", "hexdigest", "(", "str", ")", "when", "'md5'", "md5", "=", "Digest", "::", "MD5", ".", "new", "md5", ".", "update", "str", "str", "=", "md5", ".", "hexdigest", "when", "'sha1'", "str", "=", "Digest", "::", "SHA1", ".", "hexdigest", "(", "str", ")", "when", "'reverse'", "str", "=", "str", ".", "reverse", "when", "'upcase'", "str", "=", "str", ".", "upcase", "when", "'downcase'", "str", "=", "str", ".", "downcase", "when", "'rot13'", "str", "=", "str", ".", "tr", "(", "'A-Za-z'", ",", "'N-ZA-Mn-za-m'", ")", "when", "'urlencode'", "str", "=", "CGI", ".", "escape", "(", "str", ")", ".", "gsub", "(", "/", "\\+", "/", ",", "'%20'", ")", "when", "'urldecode'", "str", "=", "CGI", ".", "unescape", "(", "str", ")", "when", "'append-hash'", "str", "=", "\"#{str}##{rand(36**6).to_s(36)}\"", "when", "'append-method-get'", "separator", "=", "str", ".", "include?", "(", "'?'", ")", "?", "'&'", ":", "'?'", "str", "=", "\"#{str}#{separator}method=get&_method=get\"", "else", "logger", ".", "warn", "(", "\"Unknown rule: #{rule}\"", ")", "end", "end", "str", "end" ]
Run a specified URL through SSRF rules @param [String] url request URL @param [String] rules comma separated list of rules @return [String] modified request URL
[ "Run", "a", "specified", "URL", "through", "SSRF", "rules" ]
e79da7a449edaa6c898d2f4c9ef443bda93970b5
https://github.com/bcoles/ssrf_proxy/blob/e79da7a449edaa6c898d2f4c9ef443bda93970b5/lib/ssrf_proxy/http.rb#L946-L991
21,165
bcoles/ssrf_proxy
lib/ssrf_proxy/http.rb
SSRFProxy.HTTP.guess_mime
def guess_mime(ext) content_types = WEBrick::HTTPUtils::DefaultMimeTypes common_content_types = { 'ico' => 'image/x-icon' } content_types.merge!(common_content_types) content_types.each do |k, v| return v.to_s if ext.eql?(".#{k}") end nil end
ruby
def guess_mime(ext) content_types = WEBrick::HTTPUtils::DefaultMimeTypes common_content_types = { 'ico' => 'image/x-icon' } content_types.merge!(common_content_types) content_types.each do |k, v| return v.to_s if ext.eql?(".#{k}") end nil end
[ "def", "guess_mime", "(", "ext", ")", "content_types", "=", "WEBrick", "::", "HTTPUtils", "::", "DefaultMimeTypes", "common_content_types", "=", "{", "'ico'", "=>", "'image/x-icon'", "}", "content_types", ".", "merge!", "(", "common_content_types", ")", "content_types", ".", "each", "do", "|", "k", ",", "v", "|", "return", "v", ".", "to_s", "if", "ext", ".", "eql?", "(", "\".#{k}\"", ")", "end", "nil", "end" ]
Guess content type based on file extension @param [String] ext File extension including dots @example Return mime type for extension '.png' guess_mime('favicon.png') @return [String] content-type value
[ "Guess", "content", "type", "based", "on", "file", "extension" ]
e79da7a449edaa6c898d2f4c9ef443bda93970b5
https://github.com/bcoles/ssrf_proxy/blob/e79da7a449edaa6c898d2f4c9ef443bda93970b5/lib/ssrf_proxy/http.rb#L1368-L1376
21,166
bcoles/ssrf_proxy
lib/ssrf_proxy/http.rb
SSRFProxy.HTTP.sniff_mime
def sniff_mime(content) m = MimeMagic.by_magic(content) return if m.nil? # Overwrite incorrect mime types case m.type.to_s when 'application/xhtml+xml' return 'text/html' when 'text/x-csrc' return 'text/css' end m.type rescue nil end
ruby
def sniff_mime(content) m = MimeMagic.by_magic(content) return if m.nil? # Overwrite incorrect mime types case m.type.to_s when 'application/xhtml+xml' return 'text/html' when 'text/x-csrc' return 'text/css' end m.type rescue nil end
[ "def", "sniff_mime", "(", "content", ")", "m", "=", "MimeMagic", ".", "by_magic", "(", "content", ")", "return", "if", "m", ".", "nil?", "# Overwrite incorrect mime types", "case", "m", ".", "type", ".", "to_s", "when", "'application/xhtml+xml'", "return", "'text/html'", "when", "'text/x-csrc'", "return", "'text/css'", "end", "m", ".", "type", "rescue", "nil", "end" ]
Guess content type based on magic bytes @param [String] content File contents @return [String] content-type value
[ "Guess", "content", "type", "based", "on", "magic", "bytes" ]
e79da7a449edaa6c898d2f4c9ef443bda93970b5
https://github.com/bcoles/ssrf_proxy/blob/e79da7a449edaa6c898d2f4c9ef443bda93970b5/lib/ssrf_proxy/http.rb#L1385-L1400
21,167
hunterae/blocks
lib/blocks/renderers/abstract_renderer.rb
Blocks.AbstractRenderer.without_haml_interference
def without_haml_interference(&block) if defined?(::Haml) && view.instance_variables.include?(:@haml_buffer) haml_buffer = view.instance_variable_get(:@haml_buffer) if haml_buffer was_active = haml_buffer.active? haml_buffer.active = false else haml_buffer = Haml::Buffer.new(nil, Haml::Options.new.for_buffer) haml_buffer.active = false kill_buffer = true view.instance_variable_set(:@haml_buffer, haml_buffer) end end yield ensure haml_buffer.active = was_active if haml_buffer end
ruby
def without_haml_interference(&block) if defined?(::Haml) && view.instance_variables.include?(:@haml_buffer) haml_buffer = view.instance_variable_get(:@haml_buffer) if haml_buffer was_active = haml_buffer.active? haml_buffer.active = false else haml_buffer = Haml::Buffer.new(nil, Haml::Options.new.for_buffer) haml_buffer.active = false kill_buffer = true view.instance_variable_set(:@haml_buffer, haml_buffer) end end yield ensure haml_buffer.active = was_active if haml_buffer end
[ "def", "without_haml_interference", "(", "&", "block", ")", "if", "defined?", "(", "::", "Haml", ")", "&&", "view", ".", "instance_variables", ".", "include?", "(", ":@haml_buffer", ")", "haml_buffer", "=", "view", ".", "instance_variable_get", "(", ":@haml_buffer", ")", "if", "haml_buffer", "was_active", "=", "haml_buffer", ".", "active?", "haml_buffer", ".", "active", "=", "false", "else", "haml_buffer", "=", "Haml", "::", "Buffer", ".", "new", "(", "nil", ",", "Haml", "::", "Options", ".", "new", ".", "for_buffer", ")", "haml_buffer", ".", "active", "=", "false", "kill_buffer", "=", "true", "view", ".", "instance_variable_set", "(", ":@haml_buffer", ",", "haml_buffer", ")", "end", "end", "yield", "ensure", "haml_buffer", ".", "active", "=", "was_active", "if", "haml_buffer", "end" ]
Complete hack to get around issues with Haml Haml does some hacking to ActionView's with_output_buffer and output_buffer. In doing so, they make certain assumptions about the layout and the view template. The Blocks gem doesn't capture blocks immediately but rather stores them for later capturing. This can produce an issue if a block that is stored was in Haml but the Layout is in ERB. Haml will think that any blocks it captures while rendering the layout will be in ERB format. However, the block would need to be captured in Haml using a Haml buffer. This workaround accomplishes that.
[ "Complete", "hack", "to", "get", "around", "issues", "with", "Haml", "Haml", "does", "some", "hacking", "to", "ActionView", "s", "with_output_buffer", "and", "output_buffer", ".", "In", "doing", "so", "they", "make", "certain", "assumptions", "about", "the", "layout", "and", "the", "view", "template", ".", "The", "Blocks", "gem", "doesn", "t", "capture", "blocks", "immediately", "but", "rather", "stores", "them", "for", "later", "capturing", ".", "This", "can", "produce", "an", "issue", "if", "a", "block", "that", "is", "stored", "was", "in", "Haml", "but", "the", "Layout", "is", "in", "ERB", ".", "Haml", "will", "think", "that", "any", "blocks", "it", "captures", "while", "rendering", "the", "layout", "will", "be", "in", "ERB", "format", ".", "However", "the", "block", "would", "need", "to", "be", "captured", "in", "Haml", "using", "a", "Haml", "buffer", ".", "This", "workaround", "accomplishes", "that", "." ]
17aa1b0f9a68839435d2a2e9bcfdf73a7c62a70e
https://github.com/hunterae/blocks/blob/17aa1b0f9a68839435d2a2e9bcfdf73a7c62a70e/lib/blocks/renderers/abstract_renderer.rb#L51-L67
21,168
thumblemonks/riot
lib/riot/context_helpers.rb
Riot.ContextHelpers.setup
def setup(premium=false, &definition) setup = Setup.new(&definition) premium ? @setups.unshift(setup) : @setups.push(setup) setup end
ruby
def setup(premium=false, &definition) setup = Setup.new(&definition) premium ? @setups.unshift(setup) : @setups.push(setup) setup end
[ "def", "setup", "(", "premium", "=", "false", ",", "&", "definition", ")", "setup", "=", "Setup", ".", "new", "(", "definition", ")", "premium", "?", "@setups", ".", "unshift", "(", "setup", ")", ":", "@setups", ".", "push", "(", "setup", ")", "setup", "end" ]
Add a setup block. A setup block defines the topic of the context. There can be multiple setup blocks; each can access the previous topic through the +topic+ attribute. context "A string" do setup { "foo" } setup { topic * 2 } asserts(:length).equals(6) end If you provide +true+ as the first argument, the setup will be unshifted onto the list of setups, ensuring it will be run before any other setups. This is really only useful for context middlewares. @param [Boolean] premium indicates importance of the setup @return [Riot::Setup]
[ "Add", "a", "setup", "block", "." ]
e99a8965f2d28730fc863c647ca40b3bffb9e562
https://github.com/thumblemonks/riot/blob/e99a8965f2d28730fc863c647ca40b3bffb9e562/lib/riot/context_helpers.rb#L20-L24
21,169
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.move_cursor
def move_cursor(row = nil) if row if (prev_item = items[current_row]) main.draw_item prev_item end page = row / max_items switch_page page if page != current_page main.activate_pane row / maxy @current_row = row else @current_row = 0 end item = items[current_row] main.draw_item item, current: true main.display current_page header_l.draw_current_file_info item @current_row end
ruby
def move_cursor(row = nil) if row if (prev_item = items[current_row]) main.draw_item prev_item end page = row / max_items switch_page page if page != current_page main.activate_pane row / maxy @current_row = row else @current_row = 0 end item = items[current_row] main.draw_item item, current: true main.display current_page header_l.draw_current_file_info item @current_row end
[ "def", "move_cursor", "(", "row", "=", "nil", ")", "if", "row", "if", "(", "prev_item", "=", "items", "[", "current_row", "]", ")", "main", ".", "draw_item", "prev_item", "end", "page", "=", "row", "/", "max_items", "switch_page", "page", "if", "page", "!=", "current_page", "main", ".", "activate_pane", "row", "/", "maxy", "@current_row", "=", "row", "else", "@current_row", "=", "0", "end", "item", "=", "items", "[", "current_row", "]", "main", ".", "draw_item", "item", ",", "current", ":", "true", "main", ".", "display", "current_page", "header_l", ".", "draw_current_file_info", "item", "@current_row", "end" ]
Move the cursor to specified row. The main window and the headers will be updated reflecting the displayed files and directories. The row number can be out of range of the current page.
[ "Move", "the", "cursor", "to", "specified", "row", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L151-L170
21,170
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.cd
def cd(dir = '~', pushd: true) dir = load_item path: expand_path(dir) unless dir.is_a? Item unless dir.zip? Dir.chdir dir @current_zip = nil else @current_zip = dir end @dir_history << current_dir if current_dir && pushd @current_dir, @current_page, @current_row = dir, 0, nil main.activate_pane 0 ls @current_dir end
ruby
def cd(dir = '~', pushd: true) dir = load_item path: expand_path(dir) unless dir.is_a? Item unless dir.zip? Dir.chdir dir @current_zip = nil else @current_zip = dir end @dir_history << current_dir if current_dir && pushd @current_dir, @current_page, @current_row = dir, 0, nil main.activate_pane 0 ls @current_dir end
[ "def", "cd", "(", "dir", "=", "'~'", ",", "pushd", ":", "true", ")", "dir", "=", "load_item", "path", ":", "expand_path", "(", "dir", ")", "unless", "dir", ".", "is_a?", "Item", "unless", "dir", ".", "zip?", "Dir", ".", "chdir", "dir", "@current_zip", "=", "nil", "else", "@current_zip", "=", "dir", "end", "@dir_history", "<<", "current_dir", "if", "current_dir", "&&", "pushd", "@current_dir", ",", "@current_page", ",", "@current_row", "=", "dir", ",", "0", ",", "nil", "main", ".", "activate_pane", "0", "ls", "@current_dir", "end" ]
Change the current directory.
[ "Change", "the", "current", "directory", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L173-L186
21,171
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.ls
def ls fetch_items_from_filesystem_or_zip sort_items_according_to_current_direction @current_page ||= 0 draw_items move_cursor (current_row ? [current_row, items.size - 1].min : nil) draw_marked_items draw_total_items true end
ruby
def ls fetch_items_from_filesystem_or_zip sort_items_according_to_current_direction @current_page ||= 0 draw_items move_cursor (current_row ? [current_row, items.size - 1].min : nil) draw_marked_items draw_total_items true end
[ "def", "ls", "fetch_items_from_filesystem_or_zip", "sort_items_according_to_current_direction", "@current_page", "||=", "0", "draw_items", "move_cursor", "(", "current_row", "?", "[", "current_row", ",", "items", ".", "size", "-", "1", "]", ".", "min", ":", "nil", ")", "draw_marked_items", "draw_total_items", "true", "end" ]
Fetch files from current directory. Then update each windows reflecting the newest information.
[ "Fetch", "files", "from", "current", "directory", ".", "Then", "update", "each", "windows", "reflecting", "the", "newest", "information", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L195-L206
21,172
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.chmod
def chmod(mode = nil) return unless mode begin Integer mode mode = Integer mode.size == 3 ? "0#{mode}" : mode rescue ArgumentError end FileUtils.chmod mode, selected_items.map(&:path) ls end
ruby
def chmod(mode = nil) return unless mode begin Integer mode mode = Integer mode.size == 3 ? "0#{mode}" : mode rescue ArgumentError end FileUtils.chmod mode, selected_items.map(&:path) ls end
[ "def", "chmod", "(", "mode", "=", "nil", ")", "return", "unless", "mode", "begin", "Integer", "mode", "mode", "=", "Integer", "mode", ".", "size", "==", "3", "?", "\"0#{mode}\"", ":", "mode", "rescue", "ArgumentError", "end", "FileUtils", ".", "chmod", "mode", ",", "selected_items", ".", "map", "(", ":path", ")", "ls", "end" ]
Change the file permission of the selected files and directories. ==== Parameters * +mode+ - Unix chmod string (e.g. +w, g-r, 755, 0644)
[ "Change", "the", "file", "permission", "of", "the", "selected", "files", "and", "directories", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L235-L244
21,173
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.chown
def chown(user_and_group) return unless user_and_group user, group = user_and_group.split(':').map {|s| s == '' ? nil : s} FileUtils.chown user, group, selected_items.map(&:path) ls end
ruby
def chown(user_and_group) return unless user_and_group user, group = user_and_group.split(':').map {|s| s == '' ? nil : s} FileUtils.chown user, group, selected_items.map(&:path) ls end
[ "def", "chown", "(", "user_and_group", ")", "return", "unless", "user_and_group", "user", ",", "group", "=", "user_and_group", ".", "split", "(", "':'", ")", ".", "map", "{", "|", "s", "|", "s", "==", "''", "?", "nil", ":", "s", "}", "FileUtils", ".", "chown", "user", ",", "group", ",", "selected_items", ".", "map", "(", ":path", ")", "ls", "end" ]
Change the file owner of the selected files and directories. ==== Parameters * +user_and_group+ - user name and group name separated by : (e.g. alice, nobody:nobody, :admin)
[ "Change", "the", "file", "owner", "of", "the", "selected", "files", "and", "directories", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L250-L255
21,174
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.fetch_items_from_filesystem_or_zip
def fetch_items_from_filesystem_or_zip unless in_zip? @items = Dir.foreach(current_dir).map {|fn| load_item dir: current_dir, name: fn }.to_a.partition {|i| %w(. ..).include? i.name}.flatten else @items = [load_item(dir: current_dir, name: '.', stat: File.stat(current_dir)), load_item(dir: current_dir, name: '..', stat: File.stat(File.dirname(current_dir)))] zf = Zip::File.new current_dir zf.each {|entry| next if entry.name_is_directory? stat = zf.file.stat entry.name @items << load_item(dir: current_dir, name: entry.name, stat: stat) } end end
ruby
def fetch_items_from_filesystem_or_zip unless in_zip? @items = Dir.foreach(current_dir).map {|fn| load_item dir: current_dir, name: fn }.to_a.partition {|i| %w(. ..).include? i.name}.flatten else @items = [load_item(dir: current_dir, name: '.', stat: File.stat(current_dir)), load_item(dir: current_dir, name: '..', stat: File.stat(File.dirname(current_dir)))] zf = Zip::File.new current_dir zf.each {|entry| next if entry.name_is_directory? stat = zf.file.stat entry.name @items << load_item(dir: current_dir, name: entry.name, stat: stat) } end end
[ "def", "fetch_items_from_filesystem_or_zip", "unless", "in_zip?", "@items", "=", "Dir", ".", "foreach", "(", "current_dir", ")", ".", "map", "{", "|", "fn", "|", "load_item", "dir", ":", "current_dir", ",", "name", ":", "fn", "}", ".", "to_a", ".", "partition", "{", "|", "i", "|", "%w(", ".", "..", ")", ".", "include?", "i", ".", "name", "}", ".", "flatten", "else", "@items", "=", "[", "load_item", "(", "dir", ":", "current_dir", ",", "name", ":", "'.'", ",", "stat", ":", "File", ".", "stat", "(", "current_dir", ")", ")", ",", "load_item", "(", "dir", ":", "current_dir", ",", "name", ":", "'..'", ",", "stat", ":", "File", ".", "stat", "(", "File", ".", "dirname", "(", "current_dir", ")", ")", ")", "]", "zf", "=", "Zip", "::", "File", ".", "new", "current_dir", "zf", ".", "each", "{", "|", "entry", "|", "next", "if", "entry", ".", "name_is_directory?", "stat", "=", "zf", ".", "file", ".", "stat", "entry", ".", "name", "@items", "<<", "load_item", "(", "dir", ":", "current_dir", ",", "name", ":", "entry", ".", "name", ",", "stat", ":", "stat", ")", "}", "end", "end" ]
Fetch files from current directory or current .zip file.
[ "Fetch", "files", "from", "current", "directory", "or", "current", ".", "zip", "file", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L258-L273
21,175
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.find
def find(str) index = items.index {|i| i.index > current_row && i.name.start_with?(str)} || items.index {|i| i.name.start_with? str} move_cursor index if index end
ruby
def find(str) index = items.index {|i| i.index > current_row && i.name.start_with?(str)} || items.index {|i| i.name.start_with? str} move_cursor index if index end
[ "def", "find", "(", "str", ")", "index", "=", "items", ".", "index", "{", "|", "i", "|", "i", ".", "index", ">", "current_row", "&&", "i", ".", "name", ".", "start_with?", "(", "str", ")", "}", "||", "items", ".", "index", "{", "|", "i", "|", "i", ".", "name", ".", "start_with?", "str", "}", "move_cursor", "index", "if", "index", "end" ]
Focus at the first file or directory of which name starts with the given String.
[ "Focus", "at", "the", "first", "file", "or", "directory", "of", "which", "name", "starts", "with", "the", "given", "String", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L276-L279
21,176
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.find_reverse
def find_reverse(str) index = items.reverse.index {|i| i.index < current_row && i.name.start_with?(str)} || items.reverse.index {|i| i.name.start_with? str} move_cursor items.size - index - 1 if index end
ruby
def find_reverse(str) index = items.reverse.index {|i| i.index < current_row && i.name.start_with?(str)} || items.reverse.index {|i| i.name.start_with? str} move_cursor items.size - index - 1 if index end
[ "def", "find_reverse", "(", "str", ")", "index", "=", "items", ".", "reverse", ".", "index", "{", "|", "i", "|", "i", ".", "index", "<", "current_row", "&&", "i", ".", "name", ".", "start_with?", "(", "str", ")", "}", "||", "items", ".", "reverse", ".", "index", "{", "|", "i", "|", "i", ".", "name", ".", "start_with?", "str", "}", "move_cursor", "items", ".", "size", "-", "index", "-", "1", "if", "index", "end" ]
Focus at the last file or directory of which name starts with the given String.
[ "Focus", "at", "the", "last", "file", "or", "directory", "of", "which", "name", "starts", "with", "the", "given", "String", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L282-L285
21,177
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.draw_items
def draw_items main.newpad items @displayed_items = items[current_page * max_items, max_items] main.display current_page header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages end
ruby
def draw_items main.newpad items @displayed_items = items[current_page * max_items, max_items] main.display current_page header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages end
[ "def", "draw_items", "main", ".", "newpad", "items", "@displayed_items", "=", "items", "[", "current_page", "*", "max_items", ",", "max_items", "]", "main", ".", "display", "current_page", "header_l", ".", "draw_path_and_page_number", "path", ":", "current_dir", ".", "path", ",", "current", ":", "current_page", "+", "1", ",", "total", ":", "total_pages", "end" ]
Update the main window with the loaded files and directories. Also update the header.
[ "Update", "the", "main", "window", "with", "the", "loaded", "files", "and", "directories", ".", "Also", "update", "the", "header", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L298-L303
21,178
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.sort_items_according_to_current_direction
def sort_items_according_to_current_direction case @direction when nil @items = items.shift(2) + items.partition(&:directory?).flat_map(&:sort) when 'r' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort.reverse} when 'S', 's' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by {|i| -i.size}} when 'Sr', 'sr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:size)} when 't' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.mtime <=> x.mtime}} when 'tr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:mtime)} when 'c' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.ctime <=> x.ctime}} when 'cr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:ctime)} when 'u' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.atime <=> x.atime}} when 'ur' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:atime)} when 'e' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.extname <=> x.extname}} when 'er' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:extname)} end items.each.with_index {|item, index| item.index = index} end
ruby
def sort_items_according_to_current_direction case @direction when nil @items = items.shift(2) + items.partition(&:directory?).flat_map(&:sort) when 'r' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort.reverse} when 'S', 's' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by {|i| -i.size}} when 'Sr', 'sr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:size)} when 't' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.mtime <=> x.mtime}} when 'tr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:mtime)} when 'c' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.ctime <=> x.ctime}} when 'cr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:ctime)} when 'u' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.atime <=> x.atime}} when 'ur' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:atime)} when 'e' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.extname <=> x.extname}} when 'er' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:extname)} end items.each.with_index {|item, index| item.index = index} end
[ "def", "sort_items_according_to_current_direction", "case", "@direction", "when", "nil", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", ":directory?", ")", ".", "flat_map", "(", ":sort", ")", "when", "'r'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort", ".", "reverse", "}", "when", "'S'", ",", "'s'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort_by", "{", "|", "i", "|", "-", "i", ".", "size", "}", "}", "when", "'Sr'", ",", "'sr'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort_by", "(", ":size", ")", "}", "when", "'t'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort", "{", "|", "x", ",", "y", "|", "y", ".", "mtime", "<=>", "x", ".", "mtime", "}", "}", "when", "'tr'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort_by", "(", ":mtime", ")", "}", "when", "'c'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort", "{", "|", "x", ",", "y", "|", "y", ".", "ctime", "<=>", "x", ".", "ctime", "}", "}", "when", "'cr'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort_by", "(", ":ctime", ")", "}", "when", "'u'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort", "{", "|", "x", ",", "y", "|", "y", ".", "atime", "<=>", "x", ".", "atime", "}", "}", "when", "'ur'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort_by", "(", ":atime", ")", "}", "when", "'e'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort", "{", "|", "x", ",", "y", "|", "y", ".", "extname", "<=>", "x", ".", "extname", "}", "}", "when", "'er'", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "partition", "(", ":directory?", ")", ".", "flat_map", "{", "|", "arr", "|", "arr", ".", "sort_by", "(", ":extname", ")", "}", "end", "items", ".", "each", ".", "with_index", "{", "|", "item", ",", "index", "|", "item", ".", "index", "=", "index", "}", "end" ]
Sort the loaded files and directories in already given sort order.
[ "Sort", "the", "loaded", "files", "and", "directories", "in", "already", "given", "sort", "order", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L306-L334
21,179
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.grep
def grep(pattern = '.*') regexp = Regexp.new(pattern) fetch_items_from_filesystem_or_zip @items = items.shift(2) + items.select {|i| i.name =~ regexp} sort_items_according_to_current_direction draw_items draw_total_items switch_page 0 move_cursor 0 end
ruby
def grep(pattern = '.*') regexp = Regexp.new(pattern) fetch_items_from_filesystem_or_zip @items = items.shift(2) + items.select {|i| i.name =~ regexp} sort_items_according_to_current_direction draw_items draw_total_items switch_page 0 move_cursor 0 end
[ "def", "grep", "(", "pattern", "=", "'.*'", ")", "regexp", "=", "Regexp", ".", "new", "(", "pattern", ")", "fetch_items_from_filesystem_or_zip", "@items", "=", "items", ".", "shift", "(", "2", ")", "+", "items", ".", "select", "{", "|", "i", "|", "i", ".", "name", "=~", "regexp", "}", "sort_items_according_to_current_direction", "draw_items", "draw_total_items", "switch_page", "0", "move_cursor", "0", "end" ]
Search files and directories from the current directory, and update the screen. * +pattern+ - Search pattern against file names in Ruby Regexp string. === Example a : Search files that contains the letter "a" in their file name .*\.pdf$ : Search PDF files
[ "Search", "files", "and", "directories", "from", "the", "current", "directory", "and", "update", "the", "screen", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L344-L353
21,180
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.cp
def cp(dest) unless in_zip? src = (m = marked_items).any? ? m.map(&:path) : current_item FileUtils.cp_r src, expand_path(dest) else raise 'cping multiple items in .zip is not supported.' if selected_items.size > 1 Zip::File.open(current_zip) do |zip| entry = zip.find_entry(selected_items.first.name).dup entry.name, entry.name_length = dest, dest.size zip.instance_variable_get(:@entry_set) << entry end end ls end
ruby
def cp(dest) unless in_zip? src = (m = marked_items).any? ? m.map(&:path) : current_item FileUtils.cp_r src, expand_path(dest) else raise 'cping multiple items in .zip is not supported.' if selected_items.size > 1 Zip::File.open(current_zip) do |zip| entry = zip.find_entry(selected_items.first.name).dup entry.name, entry.name_length = dest, dest.size zip.instance_variable_get(:@entry_set) << entry end end ls end
[ "def", "cp", "(", "dest", ")", "unless", "in_zip?", "src", "=", "(", "m", "=", "marked_items", ")", ".", "any?", "?", "m", ".", "map", "(", ":path", ")", ":", "current_item", "FileUtils", ".", "cp_r", "src", ",", "expand_path", "(", "dest", ")", "else", "raise", "'cping multiple items in .zip is not supported.'", "if", "selected_items", ".", "size", ">", "1", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "entry", "=", "zip", ".", "find_entry", "(", "selected_items", ".", "first", ".", "name", ")", ".", "dup", "entry", ".", "name", ",", "entry", ".", "name_length", "=", "dest", ",", "dest", ".", "size", "zip", ".", "instance_variable_get", "(", ":@entry_set", ")", "<<", "entry", "end", "end", "ls", "end" ]
Copy selected files and directories to the destination.
[ "Copy", "selected", "files", "and", "directories", "to", "the", "destination", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L356-L369
21,181
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.mv
def mv(dest) unless in_zip? src = (m = marked_items).any? ? m.map(&:path) : current_item FileUtils.mv src, expand_path(dest) else raise 'mving multiple items in .zip is not supported.' if selected_items.size > 1 rename "#{selected_items.first.name}/#{dest}" end ls end
ruby
def mv(dest) unless in_zip? src = (m = marked_items).any? ? m.map(&:path) : current_item FileUtils.mv src, expand_path(dest) else raise 'mving multiple items in .zip is not supported.' if selected_items.size > 1 rename "#{selected_items.first.name}/#{dest}" end ls end
[ "def", "mv", "(", "dest", ")", "unless", "in_zip?", "src", "=", "(", "m", "=", "marked_items", ")", ".", "any?", "?", "m", ".", "map", "(", ":path", ")", ":", "current_item", "FileUtils", ".", "mv", "src", ",", "expand_path", "(", "dest", ")", "else", "raise", "'mving multiple items in .zip is not supported.'", "if", "selected_items", ".", "size", ">", "1", "rename", "\"#{selected_items.first.name}/#{dest}\"", "end", "ls", "end" ]
Move selected files and directories to the destination.
[ "Move", "selected", "files", "and", "directories", "to", "the", "destination", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L372-L381
21,182
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.rename
def rename(pattern) from, to = pattern.sub(/^\//, '').sub(/\/$/, '').split '/' if to.nil? from, to = current_item.name, from else from = Regexp.new from end unless in_zip? selected_items.each do |item| name = item.name.gsub from, to FileUtils.mv item, current_dir.join(name) if item.name != name end else Zip::File.open(current_zip) do |zip| selected_items.each do |item| name = item.name.gsub from, to zip.rename item.name, name end end end ls end
ruby
def rename(pattern) from, to = pattern.sub(/^\//, '').sub(/\/$/, '').split '/' if to.nil? from, to = current_item.name, from else from = Regexp.new from end unless in_zip? selected_items.each do |item| name = item.name.gsub from, to FileUtils.mv item, current_dir.join(name) if item.name != name end else Zip::File.open(current_zip) do |zip| selected_items.each do |item| name = item.name.gsub from, to zip.rename item.name, name end end end ls end
[ "def", "rename", "(", "pattern", ")", "from", ",", "to", "=", "pattern", ".", "sub", "(", "/", "\\/", "/", ",", "''", ")", ".", "sub", "(", "/", "\\/", "/", ",", "''", ")", ".", "split", "'/'", "if", "to", ".", "nil?", "from", ",", "to", "=", "current_item", ".", "name", ",", "from", "else", "from", "=", "Regexp", ".", "new", "from", "end", "unless", "in_zip?", "selected_items", ".", "each", "do", "|", "item", "|", "name", "=", "item", ".", "name", ".", "gsub", "from", ",", "to", "FileUtils", ".", "mv", "item", ",", "current_dir", ".", "join", "(", "name", ")", "if", "item", ".", "name", "!=", "name", "end", "else", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "selected_items", ".", "each", "do", "|", "item", "|", "name", "=", "item", ".", "name", ".", "gsub", "from", ",", "to", "zip", ".", "rename", "item", ".", "name", ",", "name", "end", "end", "end", "ls", "end" ]
Rename selected files and directories. ==== Parameters * +pattern+ - new filename, or a shash separated Regexp like string
[ "Rename", "selected", "files", "and", "directories", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L387-L408
21,183
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.trash
def trash unless in_zip? if osx? FileUtils.mv selected_items.map(&:path), File.expand_path('~/.Trash/') else #TODO support other OS FileUtils.rm_rf selected_items.map(&:path) end else return unless ask %Q[Trashing zip entries is not supported. Actually the files will be deleted. Are you sure want to proceed? (y/n)] delete end @current_row -= selected_items.count {|i| i.index <= current_row} ls end
ruby
def trash unless in_zip? if osx? FileUtils.mv selected_items.map(&:path), File.expand_path('~/.Trash/') else #TODO support other OS FileUtils.rm_rf selected_items.map(&:path) end else return unless ask %Q[Trashing zip entries is not supported. Actually the files will be deleted. Are you sure want to proceed? (y/n)] delete end @current_row -= selected_items.count {|i| i.index <= current_row} ls end
[ "def", "trash", "unless", "in_zip?", "if", "osx?", "FileUtils", ".", "mv", "selected_items", ".", "map", "(", ":path", ")", ",", "File", ".", "expand_path", "(", "'~/.Trash/'", ")", "else", "#TODO support other OS", "FileUtils", ".", "rm_rf", "selected_items", ".", "map", "(", ":path", ")", "end", "else", "return", "unless", "ask", "%Q[Trashing zip entries is not supported. Actually the files will be deleted. Are you sure want to proceed? (y/n)]", "delete", "end", "@current_row", "-=", "selected_items", ".", "count", "{", "|", "i", "|", "i", ".", "index", "<=", "current_row", "}", "ls", "end" ]
Soft delete selected files and directories. If the OS is not OSX, performs the same as `delete` command.
[ "Soft", "delete", "selected", "files", "and", "directories", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L413-L427
21,184
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.delete
def delete unless in_zip? FileUtils.rm_rf selected_items.map(&:path) else Zip::File.open(current_zip) do |zip| zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry| if entry.name_is_directory? zip.dir.delete entry.to_s else zip.file.delete entry.to_s end end end end @current_row -= selected_items.count {|i| i.index <= current_row} ls end
ruby
def delete unless in_zip? FileUtils.rm_rf selected_items.map(&:path) else Zip::File.open(current_zip) do |zip| zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry| if entry.name_is_directory? zip.dir.delete entry.to_s else zip.file.delete entry.to_s end end end end @current_row -= selected_items.count {|i| i.index <= current_row} ls end
[ "def", "delete", "unless", "in_zip?", "FileUtils", ".", "rm_rf", "selected_items", ".", "map", "(", ":path", ")", "else", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "zip", ".", "select", "{", "|", "e", "|", "selected_items", ".", "map", "(", ":name", ")", ".", "include?", "e", ".", "to_s", "}", ".", "each", "do", "|", "entry", "|", "if", "entry", ".", "name_is_directory?", "zip", ".", "dir", ".", "delete", "entry", ".", "to_s", "else", "zip", ".", "file", ".", "delete", "entry", ".", "to_s", "end", "end", "end", "end", "@current_row", "-=", "selected_items", ".", "count", "{", "|", "i", "|", "i", ".", "index", "<=", "current_row", "}", "ls", "end" ]
Delete selected files and directories.
[ "Delete", "selected", "files", "and", "directories", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L430-L446
21,185
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.mkdir
def mkdir(dir) unless in_zip? FileUtils.mkdir_p current_dir.join(dir) else Zip::File.open(current_zip) do |zip| zip.dir.mkdir dir end end ls end
ruby
def mkdir(dir) unless in_zip? FileUtils.mkdir_p current_dir.join(dir) else Zip::File.open(current_zip) do |zip| zip.dir.mkdir dir end end ls end
[ "def", "mkdir", "(", "dir", ")", "unless", "in_zip?", "FileUtils", ".", "mkdir_p", "current_dir", ".", "join", "(", "dir", ")", "else", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "zip", ".", "dir", ".", "mkdir", "dir", "end", "end", "ls", "end" ]
Create a new directory.
[ "Create", "a", "new", "directory", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L449-L458
21,186
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.touch
def touch(filename) unless in_zip? FileUtils.touch current_dir.join(filename) else Zip::File.open(current_zip) do |zip| # zip.file.open(filename, 'w') {|_f| } #HAXX this code creates an unneeded temporary file zip.instance_variable_get(:@entry_set) << Zip::Entry.new(current_zip, filename) end end ls end
ruby
def touch(filename) unless in_zip? FileUtils.touch current_dir.join(filename) else Zip::File.open(current_zip) do |zip| # zip.file.open(filename, 'w') {|_f| } #HAXX this code creates an unneeded temporary file zip.instance_variable_get(:@entry_set) << Zip::Entry.new(current_zip, filename) end end ls end
[ "def", "touch", "(", "filename", ")", "unless", "in_zip?", "FileUtils", ".", "touch", "current_dir", ".", "join", "(", "filename", ")", "else", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "# zip.file.open(filename, 'w') {|_f| } #HAXX this code creates an unneeded temporary file", "zip", ".", "instance_variable_get", "(", ":@entry_set", ")", "<<", "Zip", "::", "Entry", ".", "new", "(", "current_zip", ",", "filename", ")", "end", "end", "ls", "end" ]
Create a new empty file.
[ "Create", "a", "new", "empty", "file", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L461-L471
21,187
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.zip
def zip(zipfile_name) return unless zipfile_name zipfile_name += '.zip' unless zipfile_name.end_with? '.zip' Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile| selected_items.each do |item| next if item.symlink? if item.directory? Dir[item.join('**/**')].each do |file| zipfile.add file.sub("#{current_dir}/", ''), file end else zipfile.add item.name, item end end end ls end
ruby
def zip(zipfile_name) return unless zipfile_name zipfile_name += '.zip' unless zipfile_name.end_with? '.zip' Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile| selected_items.each do |item| next if item.symlink? if item.directory? Dir[item.join('**/**')].each do |file| zipfile.add file.sub("#{current_dir}/", ''), file end else zipfile.add item.name, item end end end ls end
[ "def", "zip", "(", "zipfile_name", ")", "return", "unless", "zipfile_name", "zipfile_name", "+=", "'.zip'", "unless", "zipfile_name", ".", "end_with?", "'.zip'", "Zip", "::", "File", ".", "open", "(", "zipfile_name", ",", "Zip", "::", "File", "::", "CREATE", ")", "do", "|", "zipfile", "|", "selected_items", ".", "each", "do", "|", "item", "|", "next", "if", "item", ".", "symlink?", "if", "item", ".", "directory?", "Dir", "[", "item", ".", "join", "(", "'**/**'", ")", "]", ".", "each", "do", "|", "file", "|", "zipfile", ".", "add", "file", ".", "sub", "(", "\"#{current_dir}/\"", ",", "''", ")", ",", "file", "end", "else", "zipfile", ".", "add", "item", ".", "name", ",", "item", "end", "end", "end", "ls", "end" ]
Archive selected files and directories into a .zip file.
[ "Archive", "selected", "files", "and", "directories", "into", "a", ".", "zip", "file", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L513-L530
21,188
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.unarchive
def unarchive unless in_zip? zips, gzs = selected_items.partition(&:zip?).tap {|z, others| break [z, *others.partition(&:gz?)]} zips.each do |item| FileUtils.mkdir_p current_dir.join(item.basename) Zip::File.open(item) do |zip| zip.each do |entry| FileUtils.mkdir_p File.join(item.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(item.basename, entry.to_s)) { true } end end end gzs.each do |item| Zlib::GzipReader.open(item) do |gz| Gem::Package::TarReader.new(gz) do |tar| dest_dir = current_dir.join (gz.orig_name || item.basename).sub(/\.tar$/, '') tar.each do |entry| dest = nil if entry.full_name == '././@LongLink' dest = File.join dest_dir, entry.read.strip next end dest ||= File.join dest_dir, entry.full_name if entry.directory? FileUtils.mkdir_p dest, :mode => entry.header.mode elsif entry.file? FileUtils.mkdir_p dest_dir File.open(dest, 'wb') {|f| f.print entry.read} FileUtils.chmod entry.header.mode, dest elsif entry.header.typeflag == '2' # symlink File.symlink entry.header.linkname, dest end unless Dir.exist? dest_dir FileUtils.mkdir_p dest_dir File.open(File.join(dest_dir, gz.orig_name || item.basename), 'wb') {|f| f.print gz.read} end end end end end else Zip::File.open(current_zip) do |zip| zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry| FileUtils.mkdir_p File.join(current_zip.dir, current_zip.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(current_zip.dir, current_zip.basename, entry.to_s)) { true } end end end ls end
ruby
def unarchive unless in_zip? zips, gzs = selected_items.partition(&:zip?).tap {|z, others| break [z, *others.partition(&:gz?)]} zips.each do |item| FileUtils.mkdir_p current_dir.join(item.basename) Zip::File.open(item) do |zip| zip.each do |entry| FileUtils.mkdir_p File.join(item.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(item.basename, entry.to_s)) { true } end end end gzs.each do |item| Zlib::GzipReader.open(item) do |gz| Gem::Package::TarReader.new(gz) do |tar| dest_dir = current_dir.join (gz.orig_name || item.basename).sub(/\.tar$/, '') tar.each do |entry| dest = nil if entry.full_name == '././@LongLink' dest = File.join dest_dir, entry.read.strip next end dest ||= File.join dest_dir, entry.full_name if entry.directory? FileUtils.mkdir_p dest, :mode => entry.header.mode elsif entry.file? FileUtils.mkdir_p dest_dir File.open(dest, 'wb') {|f| f.print entry.read} FileUtils.chmod entry.header.mode, dest elsif entry.header.typeflag == '2' # symlink File.symlink entry.header.linkname, dest end unless Dir.exist? dest_dir FileUtils.mkdir_p dest_dir File.open(File.join(dest_dir, gz.orig_name || item.basename), 'wb') {|f| f.print gz.read} end end end end end else Zip::File.open(current_zip) do |zip| zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry| FileUtils.mkdir_p File.join(current_zip.dir, current_zip.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(current_zip.dir, current_zip.basename, entry.to_s)) { true } end end end ls end
[ "def", "unarchive", "unless", "in_zip?", "zips", ",", "gzs", "=", "selected_items", ".", "partition", "(", ":zip?", ")", ".", "tap", "{", "|", "z", ",", "others", "|", "break", "[", "z", ",", "others", ".", "partition", "(", ":gz?", ")", "]", "}", "zips", ".", "each", "do", "|", "item", "|", "FileUtils", ".", "mkdir_p", "current_dir", ".", "join", "(", "item", ".", "basename", ")", "Zip", "::", "File", ".", "open", "(", "item", ")", "do", "|", "zip", "|", "zip", ".", "each", "do", "|", "entry", "|", "FileUtils", ".", "mkdir_p", "File", ".", "join", "(", "item", ".", "basename", ",", "File", ".", "dirname", "(", "entry", ".", "to_s", ")", ")", "zip", ".", "extract", "(", "entry", ",", "File", ".", "join", "(", "item", ".", "basename", ",", "entry", ".", "to_s", ")", ")", "{", "true", "}", "end", "end", "end", "gzs", ".", "each", "do", "|", "item", "|", "Zlib", "::", "GzipReader", ".", "open", "(", "item", ")", "do", "|", "gz", "|", "Gem", "::", "Package", "::", "TarReader", ".", "new", "(", "gz", ")", "do", "|", "tar", "|", "dest_dir", "=", "current_dir", ".", "join", "(", "gz", ".", "orig_name", "||", "item", ".", "basename", ")", ".", "sub", "(", "/", "\\.", "/", ",", "''", ")", "tar", ".", "each", "do", "|", "entry", "|", "dest", "=", "nil", "if", "entry", ".", "full_name", "==", "'././@LongLink'", "dest", "=", "File", ".", "join", "dest_dir", ",", "entry", ".", "read", ".", "strip", "next", "end", "dest", "||=", "File", ".", "join", "dest_dir", ",", "entry", ".", "full_name", "if", "entry", ".", "directory?", "FileUtils", ".", "mkdir_p", "dest", ",", ":mode", "=>", "entry", ".", "header", ".", "mode", "elsif", "entry", ".", "file?", "FileUtils", ".", "mkdir_p", "dest_dir", "File", ".", "open", "(", "dest", ",", "'wb'", ")", "{", "|", "f", "|", "f", ".", "print", "entry", ".", "read", "}", "FileUtils", ".", "chmod", "entry", ".", "header", ".", "mode", ",", "dest", "elsif", "entry", ".", "header", ".", "typeflag", "==", "'2'", "# symlink", "File", ".", "symlink", "entry", ".", "header", ".", "linkname", ",", "dest", "end", "unless", "Dir", ".", "exist?", "dest_dir", "FileUtils", ".", "mkdir_p", "dest_dir", "File", ".", "open", "(", "File", ".", "join", "(", "dest_dir", ",", "gz", ".", "orig_name", "||", "item", ".", "basename", ")", ",", "'wb'", ")", "{", "|", "f", "|", "f", ".", "print", "gz", ".", "read", "}", "end", "end", "end", "end", "end", "else", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "zip", ".", "select", "{", "|", "e", "|", "selected_items", ".", "map", "(", ":name", ")", ".", "include?", "e", ".", "to_s", "}", ".", "each", "do", "|", "entry", "|", "FileUtils", ".", "mkdir_p", "File", ".", "join", "(", "current_zip", ".", "dir", ",", "current_zip", ".", "basename", ",", "File", ".", "dirname", "(", "entry", ".", "to_s", ")", ")", "zip", ".", "extract", "(", "entry", ",", "File", ".", "join", "(", "current_zip", ".", "dir", ",", "current_zip", ".", "basename", ",", "entry", ".", "to_s", ")", ")", "{", "true", "}", "end", "end", "end", "ls", "end" ]
Unarchive .zip and .tar.gz files within selected files and directories into current_directory.
[ "Unarchive", ".", "zip", "and", ".", "tar", ".", "gz", "files", "within", "selected", "files", "and", "directories", "into", "current_directory", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L533-L582
21,189
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.switch_page
def switch_page(page) main.display (@current_page = page) @displayed_items = items[current_page * max_items, max_items] header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages end
ruby
def switch_page(page) main.display (@current_page = page) @displayed_items = items[current_page * max_items, max_items] header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages end
[ "def", "switch_page", "(", "page", ")", "main", ".", "display", "(", "@current_page", "=", "page", ")", "@displayed_items", "=", "items", "[", "current_page", "*", "max_items", ",", "max_items", "]", "header_l", ".", "draw_path_and_page_number", "path", ":", "current_dir", ".", "path", ",", "current", ":", "current_page", "+", "1", ",", "total", ":", "total_pages", "end" ]
Move to the given page number. ==== Parameters * +page+ - Target page number
[ "Move", "to", "the", "given", "page", "number", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L603-L607
21,190
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.draw_marked_items
def draw_marked_items items = marked_items header_r.draw_marked_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size} end
ruby
def draw_marked_items items = marked_items header_r.draw_marked_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size} end
[ "def", "draw_marked_items", "items", "=", "marked_items", "header_r", ".", "draw_marked_items", "count", ":", "items", ".", "size", ",", "size", ":", "items", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "i", "|", "sum", "+=", "i", ".", "size", "}", "end" ]
Update the header information concerning currently marked files or directories.
[ "Update", "the", "header", "information", "concerning", "currently", "marked", "files", "or", "directories", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L610-L613
21,191
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.draw_total_items
def draw_total_items header_r.draw_total_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size} end
ruby
def draw_total_items header_r.draw_total_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size} end
[ "def", "draw_total_items", "header_r", ".", "draw_total_items", "count", ":", "items", ".", "size", ",", "size", ":", "items", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "i", "|", "sum", "+=", "i", ".", "size", "}", "end" ]
Update the header information concerning total files and directories in the current directory.
[ "Update", "the", "header", "information", "concerning", "total", "files", "and", "directories", "in", "the", "current", "directory", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L616-L618
21,192
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.process_command_line
def process_command_line(preset_command: nil) prompt = preset_command ? ":#{preset_command} " : ':' command_line.set_prompt prompt cmd, *args = command_line.get_command(prompt: prompt).split(' ') if cmd && !cmd.empty? && respond_to?(cmd) ret = self.public_send cmd, *args clear_command_line ret end rescue Interrupt clear_command_line end
ruby
def process_command_line(preset_command: nil) prompt = preset_command ? ":#{preset_command} " : ':' command_line.set_prompt prompt cmd, *args = command_line.get_command(prompt: prompt).split(' ') if cmd && !cmd.empty? && respond_to?(cmd) ret = self.public_send cmd, *args clear_command_line ret end rescue Interrupt clear_command_line end
[ "def", "process_command_line", "(", "preset_command", ":", "nil", ")", "prompt", "=", "preset_command", "?", "\":#{preset_command} \"", ":", "':'", "command_line", ".", "set_prompt", "prompt", "cmd", ",", "*", "args", "=", "command_line", ".", "get_command", "(", "prompt", ":", "prompt", ")", ".", "split", "(", "' '", ")", "if", "cmd", "&&", "!", "cmd", ".", "empty?", "&&", "respond_to?", "(", "cmd", ")", "ret", "=", "self", ".", "public_send", "cmd", ",", "args", "clear_command_line", "ret", "end", "rescue", "Interrupt", "clear_command_line", "end" ]
Accept user input, and directly execute it as a Ruby method call to the controller. ==== Parameters * +preset_command+ - A command that would be displayed at the command line before user input.
[ "Accept", "user", "input", "and", "directly", "execute", "it", "as", "a", "Ruby", "method", "call", "to", "the", "controller", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L641-L652
21,193
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.process_shell_command
def process_shell_command command_line.set_prompt ':!' cmd = command_line.get_command(prompt: ':!')[1..-1] execute_external_command pause: true do system cmd end rescue Interrupt ensure command_line.clear command_line.noutrefresh end
ruby
def process_shell_command command_line.set_prompt ':!' cmd = command_line.get_command(prompt: ':!')[1..-1] execute_external_command pause: true do system cmd end rescue Interrupt ensure command_line.clear command_line.noutrefresh end
[ "def", "process_shell_command", "command_line", ".", "set_prompt", "':!'", "cmd", "=", "command_line", ".", "get_command", "(", "prompt", ":", "':!'", ")", "[", "1", "..", "-", "1", "]", "execute_external_command", "pause", ":", "true", "do", "system", "cmd", "end", "rescue", "Interrupt", "ensure", "command_line", ".", "clear", "command_line", ".", "noutrefresh", "end" ]
Accept user input, and directly execute it in an external shell.
[ "Accept", "user", "input", "and", "directly", "execute", "it", "in", "an", "external", "shell", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L655-L665
21,194
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.ask
def ask(prompt = '(y/n)') command_line.set_prompt prompt command_line.refresh while (c = Curses.getch) next unless [?N, ?Y, ?n, ?y, 3, 27] .include? c # N, Y, n, y, ^c, esc command_line.clear command_line.noutrefresh break (c == 'y') || (c == 'Y') end end
ruby
def ask(prompt = '(y/n)') command_line.set_prompt prompt command_line.refresh while (c = Curses.getch) next unless [?N, ?Y, ?n, ?y, 3, 27] .include? c # N, Y, n, y, ^c, esc command_line.clear command_line.noutrefresh break (c == 'y') || (c == 'Y') end end
[ "def", "ask", "(", "prompt", "=", "'(y/n)'", ")", "command_line", ".", "set_prompt", "prompt", "command_line", ".", "refresh", "while", "(", "c", "=", "Curses", ".", "getch", ")", "next", "unless", "[", "?N", ",", "?Y", ",", "?n", ",", "?y", ",", "3", ",", "27", "]", ".", "include?", "c", "# N, Y, n, y, ^c, esc", "command_line", ".", "clear", "command_line", ".", "noutrefresh", "break", "(", "c", "==", "'y'", ")", "||", "(", "c", "==", "'Y'", ")", "end", "end" ]
Let the user answer y or n. ==== Parameters * +prompt+ - Prompt message
[ "Let", "the", "user", "answer", "y", "or", "n", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L671-L680
21,195
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.edit
def edit execute_external_command do editor = ENV['EDITOR'] || 'vim' unless in_zip? system %Q[#{editor} "#{current_item.path}"] else begin tmpdir, tmpfile_name = nil Zip::File.open(current_zip) do |zip| tmpdir = Dir.mktmpdir FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name)) tmpfile_name = File.join(tmpdir, current_item.name) File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)} system %Q[#{editor} "#{tmpfile_name}"] zip.add(current_item.name, tmpfile_name) { true } end ls ensure FileUtils.remove_entry_secure tmpdir if tmpdir end end end end
ruby
def edit execute_external_command do editor = ENV['EDITOR'] || 'vim' unless in_zip? system %Q[#{editor} "#{current_item.path}"] else begin tmpdir, tmpfile_name = nil Zip::File.open(current_zip) do |zip| tmpdir = Dir.mktmpdir FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name)) tmpfile_name = File.join(tmpdir, current_item.name) File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)} system %Q[#{editor} "#{tmpfile_name}"] zip.add(current_item.name, tmpfile_name) { true } end ls ensure FileUtils.remove_entry_secure tmpdir if tmpdir end end end end
[ "def", "edit", "execute_external_command", "do", "editor", "=", "ENV", "[", "'EDITOR'", "]", "||", "'vim'", "unless", "in_zip?", "system", "%Q[#{editor} \"#{current_item.path}\"]", "else", "begin", "tmpdir", ",", "tmpfile_name", "=", "nil", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "tmpdir", "=", "Dir", ".", "mktmpdir", "FileUtils", ".", "mkdir_p", "File", ".", "join", "(", "tmpdir", ",", "File", ".", "dirname", "(", "current_item", ".", "name", ")", ")", "tmpfile_name", "=", "File", ".", "join", "(", "tmpdir", ",", "current_item", ".", "name", ")", "File", ".", "open", "(", "tmpfile_name", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "puts", "zip", ".", "file", ".", "read", "(", "current_item", ".", "name", ")", "}", "system", "%Q[#{editor} \"#{tmpfile_name}\"]", "zip", ".", "add", "(", "current_item", ".", "name", ",", "tmpfile_name", ")", "{", "true", "}", "end", "ls", "ensure", "FileUtils", ".", "remove_entry_secure", "tmpdir", "if", "tmpdir", "end", "end", "end", "end" ]
Open current file or directory with the editor.
[ "Open", "current", "file", "or", "directory", "with", "the", "editor", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L683-L705
21,196
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.view
def view pager = ENV['PAGER'] || 'less' execute_external_command do unless in_zip? system %Q[#{pager} "#{current_item.path}"] else begin tmpdir, tmpfile_name = nil Zip::File.open(current_zip) do |zip| tmpdir = Dir.mktmpdir FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name)) tmpfile_name = File.join(tmpdir, current_item.name) File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)} end system %Q[#{pager} "#{tmpfile_name}"] ensure FileUtils.remove_entry_secure tmpdir if tmpdir end end end end
ruby
def view pager = ENV['PAGER'] || 'less' execute_external_command do unless in_zip? system %Q[#{pager} "#{current_item.path}"] else begin tmpdir, tmpfile_name = nil Zip::File.open(current_zip) do |zip| tmpdir = Dir.mktmpdir FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name)) tmpfile_name = File.join(tmpdir, current_item.name) File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)} end system %Q[#{pager} "#{tmpfile_name}"] ensure FileUtils.remove_entry_secure tmpdir if tmpdir end end end end
[ "def", "view", "pager", "=", "ENV", "[", "'PAGER'", "]", "||", "'less'", "execute_external_command", "do", "unless", "in_zip?", "system", "%Q[#{pager} \"#{current_item.path}\"]", "else", "begin", "tmpdir", ",", "tmpfile_name", "=", "nil", "Zip", "::", "File", ".", "open", "(", "current_zip", ")", "do", "|", "zip", "|", "tmpdir", "=", "Dir", ".", "mktmpdir", "FileUtils", ".", "mkdir_p", "File", ".", "join", "(", "tmpdir", ",", "File", ".", "dirname", "(", "current_item", ".", "name", ")", ")", "tmpfile_name", "=", "File", ".", "join", "(", "tmpdir", ",", "current_item", ".", "name", ")", "File", ".", "open", "(", "tmpfile_name", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "puts", "zip", ".", "file", ".", "read", "(", "current_item", ".", "name", ")", "}", "end", "system", "%Q[#{pager} \"#{tmpfile_name}\"]", "ensure", "FileUtils", ".", "remove_entry_secure", "tmpdir", "if", "tmpdir", "end", "end", "end", "end" ]
Open current file or directory with the viewer.
[ "Open", "current", "file", "or", "directory", "with", "the", "viewer", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L708-L728
21,197
thumblemonks/riot
lib/riot/assertion.rb
Riot.Assertion.run
def run(situation) @expectings << situation.evaluate(&@expectation_block) if @expectation_block actual = situation.evaluate(&definition) assert((@macro.expects_exception? ? nil : actual), *@expectings) rescue Exception => e @macro.expects_exception? ? assert(e, *@expectings) : @macro.error(e) end
ruby
def run(situation) @expectings << situation.evaluate(&@expectation_block) if @expectation_block actual = situation.evaluate(&definition) assert((@macro.expects_exception? ? nil : actual), *@expectings) rescue Exception => e @macro.expects_exception? ? assert(e, *@expectings) : @macro.error(e) end
[ "def", "run", "(", "situation", ")", "@expectings", "<<", "situation", ".", "evaluate", "(", "@expectation_block", ")", "if", "@expectation_block", "actual", "=", "situation", ".", "evaluate", "(", "definition", ")", "assert", "(", "(", "@macro", ".", "expects_exception?", "?", "nil", ":", "actual", ")", ",", "@expectings", ")", "rescue", "Exception", "=>", "e", "@macro", ".", "expects_exception?", "?", "assert", "(", "e", ",", "@expectings", ")", ":", "@macro", ".", "error", "(", "e", ")", "end" ]
Setups a new Assertion. By default, the assertion will be a "positive" one, which means +evaluate+ will be call on the associated assertion macro. If +negative+ is true, +devaluate+ will be called instead. Not providing a definition block is just kind of silly since it's used to generate the +actual+ value for evaluation by a macro. @param [String] definition A small description of what this assertion is testing @param [Boolean] negative Determines whether this is a positive or negative assertion @param [lambda] definition The block that will return the +actual+ value when eval'ed Given a {Riot::Situation}, execute the assertion definition provided to this Assertion, hand off to an assertion macro for evaluation, and then return a status tuple. If the macro to be used expects any exception, catch the exception and send to the macro; else just return it back. Currently supporting 3 evaluation states: :pass, :fail, and :error @param [Riot::Situation] situation An instance of a {Riot::Situation} @return [Array<Symbol, String>] array containing evaluation state and a descriptive explanation
[ "Setups", "a", "new", "Assertion", ".", "By", "default", "the", "assertion", "will", "be", "a", "positive", "one", "which", "means", "+", "evaluate", "+", "will", "be", "call", "on", "the", "associated", "assertion", "macro", ".", "If", "+", "negative", "+", "is", "true", "+", "devaluate", "+", "will", "be", "called", "instead", ".", "Not", "providing", "a", "definition", "block", "is", "just", "kind", "of", "silly", "since", "it", "s", "used", "to", "generate", "the", "+", "actual", "+", "value", "for", "evaluation", "by", "a", "macro", "." ]
e99a8965f2d28730fc863c647ca40b3bffb9e562
https://github.com/thumblemonks/riot/blob/e99a8965f2d28730fc863c647ca40b3bffb9e562/lib/riot/assertion.rb#L49-L55
21,198
thumblemonks/riot
lib/riot/reporter/io.rb
Riot.IOReporter.format_error
def format_error(e) format = [" #{e.class.name} occurred", "#{e.to_s}"] filter_backtrace(e.backtrace) { |line| format << " at #{line}" } format.join("\n") end
ruby
def format_error(e) format = [" #{e.class.name} occurred", "#{e.to_s}"] filter_backtrace(e.backtrace) { |line| format << " at #{line}" } format.join("\n") end
[ "def", "format_error", "(", "e", ")", "format", "=", "[", "\" #{e.class.name} occurred\"", ",", "\"#{e.to_s}\"", "]", "filter_backtrace", "(", "e", ".", "backtrace", ")", "{", "|", "line", "|", "format", "<<", "\" at #{line}\"", "}", "format", ".", "join", "(", "\"\\n\"", ")", "end" ]
Generates a message for assertions that error out. However, in the additional stacktrace, any mentions of Riot and Rake framework methods calls are removed. Makes for a more readable error response. @param [Exception] e the exception to generate the backtrace from @return [String] the error response message
[ "Generates", "a", "message", "for", "assertions", "that", "error", "out", ".", "However", "in", "the", "additional", "stacktrace", "any", "mentions", "of", "Riot", "and", "Rake", "framework", "methods", "calls", "are", "removed", ".", "Makes", "for", "a", "more", "readable", "error", "response", "." ]
e99a8965f2d28730fc863c647ca40b3bffb9e562
https://github.com/thumblemonks/riot/blob/e99a8965f2d28730fc863c647ca40b3bffb9e562/lib/riot/reporter/io.rb#L53-L57
21,199
amatsuda/rfd
lib/rfd/commands.rb
Rfd.Commands.O
def O dir = current_item.directory? ? current_item.path : current_dir.path system %Q[osascript -e 'tell app "Terminal" do script "cd #{dir}" end tell'] if osx? end
ruby
def O dir = current_item.directory? ? current_item.path : current_dir.path system %Q[osascript -e 'tell app "Terminal" do script "cd #{dir}" end tell'] if osx? end
[ "def", "O", "dir", "=", "current_item", ".", "directory?", "?", "current_item", ".", "path", ":", "current_dir", ".", "path", "system", "%Q[osascript -e 'tell app \"Terminal\"\n do script \"cd #{dir}\"\n end tell']", "if", "osx?", "end" ]
"O"pen terminal here.
[ "O", "pen", "terminal", "here", "." ]
403c0bc0ff0a9da1d21220b479d5a42008512b78
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd/commands.rb#L177-L182