repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
ultraspeed/epp
lib/epp/server.rb
Epp.Server.login
def login raise SocketError, "Socket must be opened before logging in" if !@socket or @socket.closed? xml = new_epp_request xml.root << command = Node.new("command") command << login = Node.new("login") login << Node.new("clID", tag) login << Node.new("pw", password) login << options = Node.new("options") options << Node.new("version", version) options << Node.new("lang", lang) login << services = Node.new("svcs") services << Node.new("objURI", "urn:ietf:params:xml:ns:domain-1.0") services << Node.new("objURI", "urn:ietf:params:xml:ns:contact-1.0") services << Node.new("objURI", "urn:ietf:params:xml:ns:host-1.0") services << extensions_container = Node.new("svcExtension") unless extensions.empty? for uri in extensions extensions_container << Node.new("extURI", uri) end command << Node.new("clTRID", UUIDTools::UUID.timestamp_create.to_s) response = Hpricot::XML(send_request(xml.to_s)) handle_response(response) end
ruby
def login raise SocketError, "Socket must be opened before logging in" if !@socket or @socket.closed? xml = new_epp_request xml.root << command = Node.new("command") command << login = Node.new("login") login << Node.new("clID", tag) login << Node.new("pw", password) login << options = Node.new("options") options << Node.new("version", version) options << Node.new("lang", lang) login << services = Node.new("svcs") services << Node.new("objURI", "urn:ietf:params:xml:ns:domain-1.0") services << Node.new("objURI", "urn:ietf:params:xml:ns:contact-1.0") services << Node.new("objURI", "urn:ietf:params:xml:ns:host-1.0") services << extensions_container = Node.new("svcExtension") unless extensions.empty? for uri in extensions extensions_container << Node.new("extURI", uri) end command << Node.new("clTRID", UUIDTools::UUID.timestamp_create.to_s) response = Hpricot::XML(send_request(xml.to_s)) handle_response(response) end
[ "def", "login", "raise", "SocketError", ",", "\"Socket must be opened before logging in\"", "if", "!", "@socket", "or", "@socket", ".", "closed?", "xml", "=", "new_epp_request", "xml", ".", "root", "<<", "command", "=", "Node", ".", "new", "(", "\"command\"", ")", "command", "<<", "login", "=", "Node", ".", "new", "(", "\"login\"", ")", "login", "<<", "Node", ".", "new", "(", "\"clID\"", ",", "tag", ")", "login", "<<", "Node", ".", "new", "(", "\"pw\"", ",", "password", ")", "login", "<<", "options", "=", "Node", ".", "new", "(", "\"options\"", ")", "options", "<<", "Node", ".", "new", "(", "\"version\"", ",", "version", ")", "options", "<<", "Node", ".", "new", "(", "\"lang\"", ",", "lang", ")", "login", "<<", "services", "=", "Node", ".", "new", "(", "\"svcs\"", ")", "services", "<<", "Node", ".", "new", "(", "\"objURI\"", ",", "\"urn:ietf:params:xml:ns:domain-1.0\"", ")", "services", "<<", "Node", ".", "new", "(", "\"objURI\"", ",", "\"urn:ietf:params:xml:ns:contact-1.0\"", ")", "services", "<<", "Node", ".", "new", "(", "\"objURI\"", ",", "\"urn:ietf:params:xml:ns:host-1.0\"", ")", "services", "<<", "extensions_container", "=", "Node", ".", "new", "(", "\"svcExtension\"", ")", "unless", "extensions", ".", "empty?", "for", "uri", "in", "extensions", "extensions_container", "<<", "Node", ".", "new", "(", "\"extURI\"", ",", "uri", ")", "end", "command", "<<", "Node", ".", "new", "(", "\"clTRID\"", ",", "UUIDTools", "::", "UUID", ".", "timestamp_create", ".", "to_s", ")", "response", "=", "Hpricot", "::", "XML", "(", "send_request", "(", "xml", ".", "to_s", ")", ")", "handle_response", "(", "response", ")", "end" ]
Sends a standard login request to the EPP server.
[ "Sends", "a", "standard", "login", "request", "to", "the", "EPP", "server", "." ]
e23cec53148d0de0418eb91221b4560c0325bb3f
https://github.com/ultraspeed/epp/blob/e23cec53148d0de0418eb91221b4560c0325bb3f/lib/epp/server.rb#L136-L169
train
ultraspeed/epp
lib/epp/server.rb
Epp.Server.logout
def logout raise SocketError, "Socket must be opened before logging out" if !@socket or @socket.closed? xml = new_epp_request xml.root << command = Node.new("command") command << login = Node.new("logout") command << Node.new("clTRID", UUIDTools::UUID.timestamp_create.to_s) response = Hpricot::XML(send_request(xml.to_s)) handle_response(response, 1500) end
ruby
def logout raise SocketError, "Socket must be opened before logging out" if !@socket or @socket.closed? xml = new_epp_request xml.root << command = Node.new("command") command << login = Node.new("logout") command << Node.new("clTRID", UUIDTools::UUID.timestamp_create.to_s) response = Hpricot::XML(send_request(xml.to_s)) handle_response(response, 1500) end
[ "def", "logout", "raise", "SocketError", ",", "\"Socket must be opened before logging out\"", "if", "!", "@socket", "or", "@socket", ".", "closed?", "xml", "=", "new_epp_request", "xml", ".", "root", "<<", "command", "=", "Node", ".", "new", "(", "\"command\"", ")", "command", "<<", "login", "=", "Node", ".", "new", "(", "\"logout\"", ")", "command", "<<", "Node", ".", "new", "(", "\"clTRID\"", ",", "UUIDTools", "::", "UUID", ".", "timestamp_create", ".", "to_s", ")", "response", "=", "Hpricot", "::", "XML", "(", "send_request", "(", "xml", ".", "to_s", ")", ")", "handle_response", "(", "response", ",", "1500", ")", "end" ]
Sends a standard logout request to the EPP server.
[ "Sends", "a", "standard", "logout", "request", "to", "the", "EPP", "server", "." ]
e23cec53148d0de0418eb91221b4560c0325bb3f
https://github.com/ultraspeed/epp/blob/e23cec53148d0de0418eb91221b4560c0325bb3f/lib/epp/server.rb#L172-L185
train
nfo/zenpush
lib/zenpush/zendesk.rb
ZenPush.Zendesk.find_category
def find_category(category_name, options = {}) categories = self.categories if categories.is_a?(Array) categories.detect { |c| c['name'] == category_name } else raise "Could not retrieve categories: #{categories}" end end
ruby
def find_category(category_name, options = {}) categories = self.categories if categories.is_a?(Array) categories.detect { |c| c['name'] == category_name } else raise "Could not retrieve categories: #{categories}" end end
[ "def", "find_category", "(", "category_name", ",", "options", "=", "{", "}", ")", "categories", "=", "self", ".", "categories", "if", "categories", ".", "is_a?", "(", "Array", ")", "categories", ".", "detect", "{", "|", "c", "|", "c", "[", "'name'", "]", "==", "category_name", "}", "else", "raise", "\"Could not retrieve categories: #{categories}\"", "end", "end" ]
Find category by name
[ "Find", "category", "by", "name" ]
aadfca41e7c836e2843dce7fe553b01fe850d302
https://github.com/nfo/zenpush/blob/aadfca41e7c836e2843dce7fe553b01fe850d302/lib/zenpush/zendesk.rb#L85-L92
train
nfo/zenpush
lib/zenpush/zendesk.rb
ZenPush.Zendesk.find_forum
def find_forum(category_name, forum_name, options = {}) category = self.find_category(category_name, options) if category self.forums.detect {|f| f['category_id'] == category['id'] && f['name'] == forum_name } end end
ruby
def find_forum(category_name, forum_name, options = {}) category = self.find_category(category_name, options) if category self.forums.detect {|f| f['category_id'] == category['id'] && f['name'] == forum_name } end end
[ "def", "find_forum", "(", "category_name", ",", "forum_name", ",", "options", "=", "{", "}", ")", "category", "=", "self", ".", "find_category", "(", "category_name", ",", "options", ")", "if", "category", "self", ".", "forums", ".", "detect", "{", "|", "f", "|", "f", "[", "'category_id'", "]", "==", "category", "[", "'id'", "]", "&&", "f", "[", "'name'", "]", "==", "forum_name", "}", "end", "end" ]
Find forum by name, knowing the category name
[ "Find", "forum", "by", "name", "knowing", "the", "category", "name" ]
aadfca41e7c836e2843dce7fe553b01fe850d302
https://github.com/nfo/zenpush/blob/aadfca41e7c836e2843dce7fe553b01fe850d302/lib/zenpush/zendesk.rb#L102-L107
train
nfo/zenpush
lib/zenpush/zendesk.rb
ZenPush.Zendesk.find_or_create_forum
def find_or_create_forum(category_name, forum_name, options={ }) category = self.find_or_create_category(category_name, options) if category self.forums.detect { |f| f['category_id'] == category['id'] && f['name'] == forum_name } || post_forum(category['id'], forum_name) end end
ruby
def find_or_create_forum(category_name, forum_name, options={ }) category = self.find_or_create_category(category_name, options) if category self.forums.detect { |f| f['category_id'] == category['id'] && f['name'] == forum_name } || post_forum(category['id'], forum_name) end end
[ "def", "find_or_create_forum", "(", "category_name", ",", "forum_name", ",", "options", "=", "{", "}", ")", "category", "=", "self", ".", "find_or_create_category", "(", "category_name", ",", "options", ")", "if", "category", "self", ".", "forums", ".", "detect", "{", "|", "f", "|", "f", "[", "'category_id'", "]", "==", "category", "[", "'id'", "]", "&&", "f", "[", "'name'", "]", "==", "forum_name", "}", "||", "post_forum", "(", "category", "[", "'id'", "]", ",", "forum_name", ")", "end", "end" ]
Given a category name, find a forum by name. Create the category and forum either doesn't exist.
[ "Given", "a", "category", "name", "find", "a", "forum", "by", "name", ".", "Create", "the", "category", "and", "forum", "either", "doesn", "t", "exist", "." ]
aadfca41e7c836e2843dce7fe553b01fe850d302
https://github.com/nfo/zenpush/blob/aadfca41e7c836e2843dce7fe553b01fe850d302/lib/zenpush/zendesk.rb#L110-L115
train
nfo/zenpush
lib/zenpush/zendesk.rb
ZenPush.Zendesk.find_topic
def find_topic(category_name, forum_name, topic_title, options = {}) forum = self.find_forum(category_name, forum_name, options) if forum self.topics(forum['id'], options).detect {|t| t['title'] == topic_title} end end
ruby
def find_topic(category_name, forum_name, topic_title, options = {}) forum = self.find_forum(category_name, forum_name, options) if forum self.topics(forum['id'], options).detect {|t| t['title'] == topic_title} end end
[ "def", "find_topic", "(", "category_name", ",", "forum_name", ",", "topic_title", ",", "options", "=", "{", "}", ")", "forum", "=", "self", ".", "find_forum", "(", "category_name", ",", "forum_name", ",", "options", ")", "if", "forum", "self", ".", "topics", "(", "forum", "[", "'id'", "]", ",", "options", ")", ".", "detect", "{", "|", "t", "|", "t", "[", "'title'", "]", "==", "topic_title", "}", "end", "end" ]
Find topic by name, knowing the forum name and category name
[ "Find", "topic", "by", "name", "knowing", "the", "forum", "name", "and", "category", "name" ]
aadfca41e7c836e2843dce7fe553b01fe850d302
https://github.com/nfo/zenpush/blob/aadfca41e7c836e2843dce7fe553b01fe850d302/lib/zenpush/zendesk.rb#L118-L123
train
nfo/zenpush
lib/zenpush/zendesk.rb
ZenPush.Zendesk.post_forum
def post_forum(category_id, forum_name, options={ }) self.post('/forums.json', options.merge( :body => { :forum => { :name => forum_name, :category_id => category_id } }.to_json ) )['forum'] end
ruby
def post_forum(category_id, forum_name, options={ }) self.post('/forums.json', options.merge( :body => { :forum => { :name => forum_name, :category_id => category_id } }.to_json ) )['forum'] end
[ "def", "post_forum", "(", "category_id", ",", "forum_name", ",", "options", "=", "{", "}", ")", "self", ".", "post", "(", "'/forums.json'", ",", "options", ".", "merge", "(", ":body", "=>", "{", ":forum", "=>", "{", ":name", "=>", "forum_name", ",", ":category_id", "=>", "category_id", "}", "}", ".", "to_json", ")", ")", "[", "'forum'", "]", "end" ]
Create a forum in the given category id
[ "Create", "a", "forum", "in", "the", "given", "category", "id" ]
aadfca41e7c836e2843dce7fe553b01fe850d302
https://github.com/nfo/zenpush/blob/aadfca41e7c836e2843dce7fe553b01fe850d302/lib/zenpush/zendesk.rb#L137-L146
train
nfo/zenpush
lib/zenpush/zendesk.rb
ZenPush.Zendesk.post_topic
def post_topic(forum_id, title, body, options = { }) self.post("/topics.json", options.merge( :body => { :topic => { :forum_id => forum_id, :title => title, :body => body } }.to_json ) )['topic'] end
ruby
def post_topic(forum_id, title, body, options = { }) self.post("/topics.json", options.merge( :body => { :topic => { :forum_id => forum_id, :title => title, :body => body } }.to_json ) )['topic'] end
[ "def", "post_topic", "(", "forum_id", ",", "title", ",", "body", ",", "options", "=", "{", "}", ")", "self", ".", "post", "(", "\"/topics.json\"", ",", "options", ".", "merge", "(", ":body", "=>", "{", ":topic", "=>", "{", ":forum_id", "=>", "forum_id", ",", ":title", "=>", "title", ",", ":body", "=>", "body", "}", "}", ".", "to_json", ")", ")", "[", "'topic'", "]", "end" ]
Create a topic in the given forum id
[ "Create", "a", "topic", "in", "the", "given", "forum", "id" ]
aadfca41e7c836e2843dce7fe553b01fe850d302
https://github.com/nfo/zenpush/blob/aadfca41e7c836e2843dce7fe553b01fe850d302/lib/zenpush/zendesk.rb#L149-L157
train
factore/tenon
app/helpers/tenon/piece_helper.rb
Tenon.PieceHelper.responsive_image_tag
def responsive_image_tag(piece, options = {}, breakpoints) srcset = generate_srcset(piece) sizes = generate_sizes(piece, breakpoints) # Let's just use an plain image_tag if responsive styles haven't been # generated. We'll test for :x2000 to determine if that's the case if piece.image.attachment.exists?(computed_style(piece, 'x2000')) image_tag(piece.image.url(default_style(piece, breakpoints)), options.merge(srcset: srcset, sizes: sizes)) else image_tag(piece.image.url(:_medium), options) end end
ruby
def responsive_image_tag(piece, options = {}, breakpoints) srcset = generate_srcset(piece) sizes = generate_sizes(piece, breakpoints) # Let's just use an plain image_tag if responsive styles haven't been # generated. We'll test for :x2000 to determine if that's the case if piece.image.attachment.exists?(computed_style(piece, 'x2000')) image_tag(piece.image.url(default_style(piece, breakpoints)), options.merge(srcset: srcset, sizes: sizes)) else image_tag(piece.image.url(:_medium), options) end end
[ "def", "responsive_image_tag", "(", "piece", ",", "options", "=", "{", "}", ",", "breakpoints", ")", "srcset", "=", "generate_srcset", "(", "piece", ")", "sizes", "=", "generate_sizes", "(", "piece", ",", "breakpoints", ")", "if", "piece", ".", "image", ".", "attachment", ".", "exists?", "(", "computed_style", "(", "piece", ",", "'x2000'", ")", ")", "image_tag", "(", "piece", ".", "image", ".", "url", "(", "default_style", "(", "piece", ",", "breakpoints", ")", ")", ",", "options", ".", "merge", "(", "srcset", ":", "srcset", ",", "sizes", ":", "sizes", ")", ")", "else", "image_tag", "(", "piece", ".", "image", ".", "url", "(", ":_medium", ")", ",", "options", ")", "end", "end" ]
Returns the actual image_tag
[ "Returns", "the", "actual", "image_tag" ]
49907830c00524853d087566f60951b8b6a9aedf
https://github.com/factore/tenon/blob/49907830c00524853d087566f60951b8b6a9aedf/app/helpers/tenon/piece_helper.rb#L13-L23
train
zhimin/rwebspec
lib/rwebspec-common/assert.rb
RWebSpec.Assert.assert
def assert test, msg = nil msg ||= "Failed assertion, no message given." # comment out self.assertions += 1 to counting assertions unless test then msg = msg.call if Proc === msg raise RWebSpec::Assertion, msg end true end
ruby
def assert test, msg = nil msg ||= "Failed assertion, no message given." # comment out self.assertions += 1 to counting assertions unless test then msg = msg.call if Proc === msg raise RWebSpec::Assertion, msg end true end
[ "def", "assert", "test", ",", "msg", "=", "nil", "msg", "||=", "\"Failed assertion, no message given.\"", "unless", "test", "then", "msg", "=", "msg", ".", "call", "if", "Proc", "===", "msg", "raise", "RWebSpec", "::", "Assertion", ",", "msg", "end", "true", "end" ]
own assert method
[ "own", "assert", "method" ]
aafccee2ba66d17d591d04210067035feaf2f892
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/assert.rb#L6-L14
train
zhimin/rwebspec
lib/rwebspec-common/assert.rb
RWebSpec.Assert.assert_link_present_with_text
def assert_link_present_with_text(link_text) @web_browser.links.each { |link| return if link.text.include?(link_text) } fail( "can't find the link containing text: #{link_text}") end
ruby
def assert_link_present_with_text(link_text) @web_browser.links.each { |link| return if link.text.include?(link_text) } fail( "can't find the link containing text: #{link_text}") end
[ "def", "assert_link_present_with_text", "(", "link_text", ")", "@web_browser", ".", "links", ".", "each", "{", "|", "link", "|", "return", "if", "link", ".", "text", ".", "include?", "(", "link_text", ")", "}", "fail", "(", "\"can't find the link containing text: #{link_text}\"", ")", "end" ]
Assert a link containing specified text in the page <a href="">Click Me</a> assert_link_present_with_text("Click ") # =>
[ "Assert", "a", "link", "containing", "specified", "text", "in", "the", "page" ]
aafccee2ba66d17d591d04210067035feaf2f892
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/assert.rb#L86-L93
train
zhimin/rwebspec
lib/rwebspec-common/assert.rb
RWebSpec.Assert.assert_radio_option_not_present
def assert_radio_option_not_present(radio_group, radio_option) @web_browser.radios.each { |radio| the_element_name = element_name(radio) if (the_element_name == radio_group) then perform_assertion { assert(!(radio_option == element_value(radio) ), "unexpected radio option: " + radio_option + " found") } end } end
ruby
def assert_radio_option_not_present(radio_group, radio_option) @web_browser.radios.each { |radio| the_element_name = element_name(radio) if (the_element_name == radio_group) then perform_assertion { assert(!(radio_option == element_value(radio) ), "unexpected radio option: " + radio_option + " found") } end } end
[ "def", "assert_radio_option_not_present", "(", "radio_group", ",", "radio_option", ")", "@web_browser", ".", "radios", ".", "each", "{", "|", "radio", "|", "the_element_name", "=", "element_name", "(", "radio", ")", "if", "(", "the_element_name", "==", "radio_group", ")", "then", "perform_assertion", "{", "assert", "(", "!", "(", "radio_option", "==", "element_value", "(", "radio", ")", ")", ",", "\"unexpected radio option: \"", "+", "radio_option", "+", "\" found\"", ")", "}", "end", "}", "end" ]
radio radio_group is the name field, radio options 'value' field
[ "radio", "radio_group", "is", "the", "name", "field", "radio", "options", "value", "field" ]
aafccee2ba66d17d591d04210067035feaf2f892
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/assert.rb#L277-L284
train
asmallworldsite/jedis_rb
lib/jedis_rb/pool.rb
JedisRb.Pool.yield_connection
def yield_connection response = begin resource = @connection_pool.resource yield resource ensure resource.close if resource end if @convert_objects convert(response) else response end end
ruby
def yield_connection response = begin resource = @connection_pool.resource yield resource ensure resource.close if resource end if @convert_objects convert(response) else response end end
[ "def", "yield_connection", "response", "=", "begin", "resource", "=", "@connection_pool", ".", "resource", "yield", "resource", "ensure", "resource", ".", "close", "if", "resource", "end", "if", "@convert_objects", "convert", "(", "response", ")", "else", "response", "end", "end" ]
Construct a new JedisRb Pool. Possible options are: * config - (redis.clients.jedis.JedisPoolConfig/Wrapped::PoolConfig) the pool configuration * host - (String) Redis host * port - (Integer) Redis port * connection_timeout - (Integer) the connection timeout in milliseconds * password - (String) Redis password * database - (Integer) Redis database * client_name (String) the client name * convert_objects (Boolean) Ruby object casting By passing in convert_objects: true, Pool can convert return values to their Ruby type equivalent. Currently, the following are supported: * java.util.Set => Set * java.util.Map => Hash * java.util.List => Array Depending on your use case, this conversion may be costly, so it is not the default. Please evaluate your application's requirements carefully before opting in. Lease a connection from the pool and yield it to the given block. Leased connections will be automatically returned to the pool upon successful or unsuccessful execution of the block. Connections are of type redis.clients.jedis.Jedis. See the documentation[https://github.com/xetorthio/jedis/wiki] for more details.
[ "Construct", "a", "new", "JedisRb", "Pool", "." ]
0df54308637b1b5ce4ea5ef45110a06b97e3d281
https://github.com/asmallworldsite/jedis_rb/blob/0df54308637b1b5ce4ea5ef45110a06b97e3d281/lib/jedis_rb/pool.rb#L62-L75
train
asmallworldsite/jedis_rb
lib/jedis_rb/pool.rb
JedisRb.Pool.convert
def convert(value) case value when java.util.List then value.to_a when java.util.Set then value.to_set when java.util.Map then value.to_hash else value end end
ruby
def convert(value) case value when java.util.List then value.to_a when java.util.Set then value.to_set when java.util.Map then value.to_hash else value end end
[ "def", "convert", "(", "value", ")", "case", "value", "when", "java", ".", "util", ".", "List", "then", "value", ".", "to_a", "when", "java", ".", "util", ".", "Set", "then", "value", ".", "to_set", "when", "java", ".", "util", ".", "Map", "then", "value", ".", "to_hash", "else", "value", "end", "end" ]
Convert Java return values to their ruby equivalents.
[ "Convert", "Java", "return", "values", "to", "their", "ruby", "equivalents", "." ]
0df54308637b1b5ce4ea5ef45110a06b97e3d281
https://github.com/asmallworldsite/jedis_rb/blob/0df54308637b1b5ce4ea5ef45110a06b97e3d281/lib/jedis_rb/pool.rb#L90-L97
train
datasift/datasift-ruby
lib/historics_preview.rb
DataSift.HistoricsPreview.create
def create(hash, sources, parameters, start, end_time = nil) params = { :hash => hash, :sources => sources, :parameters => parameters, :start => start } requires params params.merge!(:end => end_time) unless end_time.nil? DataSift.request(:POST, 'preview/create', @config, params) end
ruby
def create(hash, sources, parameters, start, end_time = nil) params = { :hash => hash, :sources => sources, :parameters => parameters, :start => start } requires params params.merge!(:end => end_time) unless end_time.nil? DataSift.request(:POST, 'preview/create', @config, params) end
[ "def", "create", "(", "hash", ",", "sources", ",", "parameters", ",", "start", ",", "end_time", "=", "nil", ")", "params", "=", "{", ":hash", "=>", "hash", ",", ":sources", "=>", "sources", ",", ":parameters", "=>", "parameters", ",", ":start", "=>", "start", "}", "requires", "params", "params", ".", "merge!", "(", ":end", "=>", "end_time", ")", "unless", "end_time", ".", "nil?", "DataSift", ".", "request", "(", ":POST", ",", "'preview/create'", ",", "@config", ",", "params", ")", "end" ]
Create a new Historics Preview @param hash [String] Hash of compiled CSDL definition @param sources [String] Comma separated list of data sources you wish to perform this Historics Preview against @param parameters [String] Historics Preview parameters. See our {http://dev.datasift.com/docs/api/1/previewcreate /preview/create API Docs} for full documentation @param start [String] Start timestamp for your Historics Preview. Should be provided as Unix timestamp @param end_time [String] End timestamp for your Historics Preview. Should be provided as Unix timestamp
[ "Create", "a", "new", "Historics", "Preview" ]
d724e4ff15d178f196001ea5a517a981dc56c18c
https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/historics_preview.rb#L16-L27
train
johnfaucett/youtrack
lib/youtrack/client.rb
Youtrack.Client.connect!
def connect! @connection = HTTParty.post(File.join(url, "rest/user/login"), body: credentials_hash ) @cookies['Cookie'] = @connection.headers['set-cookie'] @connection.code end
ruby
def connect! @connection = HTTParty.post(File.join(url, "rest/user/login"), body: credentials_hash ) @cookies['Cookie'] = @connection.headers['set-cookie'] @connection.code end
[ "def", "connect!", "@connection", "=", "HTTParty", ".", "post", "(", "File", ".", "join", "(", "url", ",", "\"rest/user/login\"", ")", ",", "body", ":", "credentials_hash", ")", "@cookies", "[", "'Cookie'", "]", "=", "@connection", ".", "headers", "[", "'set-cookie'", "]", "@connection", ".", "code", "end" ]
Makes a login call and sets the Cookie headers Returns the status code of the connection call
[ "Makes", "a", "login", "call", "and", "sets", "the", "Cookie", "headers" ]
d4288a803c74a59984d616e12f147c10a4a24bf2
https://github.com/johnfaucett/youtrack/blob/d4288a803c74a59984d616e12f147c10a4a24bf2/lib/youtrack/client.rb#L53-L57
train
factore/tenon
lib/tenon/proxy_attachment.rb
Tenon.ProxyAttachment.url
def url(style = :original, *args) if style.to_sym == :original original_url(*args) else named_url(style, *args) end end
ruby
def url(style = :original, *args) if style.to_sym == :original original_url(*args) else named_url(style, *args) end end
[ "def", "url", "(", "style", "=", ":original", ",", "*", "args", ")", "if", "style", ".", "to_sym", "==", ":original", "original_url", "(", "*", "args", ")", "else", "named_url", "(", "style", ",", "*", "args", ")", "end", "end" ]
Prefix with an underscore to use base Asset styles
[ "Prefix", "with", "an", "underscore", "to", "use", "base", "Asset", "styles" ]
49907830c00524853d087566f60951b8b6a9aedf
https://github.com/factore/tenon/blob/49907830c00524853d087566f60951b8b6a9aedf/lib/tenon/proxy_attachment.rb#L20-L26
train
hopsoft/hero
lib/hero/observer.rb
Hero.Observer.log_step
def log_step(id, step, context, options, error=nil) return unless Hero.logger if error Hero.logger.error "HERO #{id.to_s.ljust(6)} #{formula_name} -> #{step.first} Context: #{context.inspect} Options: #{options.inspect} Error: #{error.message}" else Hero.logger.info "HERO #{id.to_s.ljust(6)} #{formula_name} -> #{step.first} Context: #{context.inspect} Options: #{options.inspect}" end end
ruby
def log_step(id, step, context, options, error=nil) return unless Hero.logger if error Hero.logger.error "HERO #{id.to_s.ljust(6)} #{formula_name} -> #{step.first} Context: #{context.inspect} Options: #{options.inspect} Error: #{error.message}" else Hero.logger.info "HERO #{id.to_s.ljust(6)} #{formula_name} -> #{step.first} Context: #{context.inspect} Options: #{options.inspect}" end end
[ "def", "log_step", "(", "id", ",", "step", ",", "context", ",", "options", ",", "error", "=", "nil", ")", "return", "unless", "Hero", ".", "logger", "if", "error", "Hero", ".", "logger", ".", "error", "\"HERO #{id.to_s.ljust(6)} #{formula_name} -> #{step.first} Context: #{context.inspect} Options: #{options.inspect} Error: #{error.message}\"", "else", "Hero", ".", "logger", ".", "info", "\"HERO #{id.to_s.ljust(6)} #{formula_name} -> #{step.first} Context: #{context.inspect} Options: #{options.inspect}\"", "end", "end" ]
Logs a step to the registered Hero.logger. @note Users info for the log level. @param [Symbol, String] id The identifier for the step. [:before, :after] @param [Object] step @param [Object] context @param [Object] options
[ "Logs", "a", "step", "to", "the", "registered", "Hero", ".", "logger", "." ]
e146a79ec9863faf509c633334f6ca77d1721fb5
https://github.com/hopsoft/hero/blob/e146a79ec9863faf509c633334f6ca77d1721fb5/lib/hero/observer.rb#L99-L106
train
datasift/datasift-ruby
lib/tasks.rb
DataSift.Task.create
def create(service:, type:, subscription_id:, name:, parameters:) DataSift.request(:POST, "pylon/#{service}/task", @config, { type: type, subscription_id: subscription_id, name: name, parameters: parameters }) end
ruby
def create(service:, type:, subscription_id:, name:, parameters:) DataSift.request(:POST, "pylon/#{service}/task", @config, { type: type, subscription_id: subscription_id, name: name, parameters: parameters }) end
[ "def", "create", "(", "service", ":", ",", "type", ":", ",", "subscription_id", ":", ",", "name", ":", ",", "parameters", ":", ")", "DataSift", ".", "request", "(", ":POST", ",", "\"pylon/#{service}/task\"", ",", "@config", ",", "{", "type", ":", "type", ",", "subscription_id", ":", "subscription_id", ",", "name", ":", "name", ",", "parameters", ":", "parameters", "}", ")", "end" ]
Creates a Task; this call requires use of an identity API key @param service [String] Service you wish to create a Task for @param type [String] Type of Task to be run @param subscription_id [String] Subscription ID as returned by /pylon/start @param name [String] Human identifier for this Task @param parameters [Hash] Object representing the parameters for the Task type @return [Object] API reponse object
[ "Creates", "a", "Task", ";", "this", "call", "requires", "use", "of", "an", "identity", "API", "key" ]
d724e4ff15d178f196001ea5a517a981dc56c18c
https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/tasks.rb#L13-L20
train
datasift/datasift-ruby
lib/tasks.rb
DataSift.Task.list
def list(service:, type: 'analysis', **opts) params = {} params[:per_page] = opts[:per_page] if opts.key?(:per_page) params[:page] = opts[:page] if opts.key?(:page) params[:status] = opts[:status] if opts.key?(:status) DataSift.request(:GET, "pylon/#{service}/task/#{type}", @config, params) end
ruby
def list(service:, type: 'analysis', **opts) params = {} params[:per_page] = opts[:per_page] if opts.key?(:per_page) params[:page] = opts[:page] if opts.key?(:page) params[:status] = opts[:status] if opts.key?(:status) DataSift.request(:GET, "pylon/#{service}/task/#{type}", @config, params) end
[ "def", "list", "(", "service", ":", ",", "type", ":", "'analysis'", ",", "**", "opts", ")", "params", "=", "{", "}", "params", "[", ":per_page", "]", "=", "opts", "[", ":per_page", "]", "if", "opts", ".", "key?", "(", ":per_page", ")", "params", "[", ":page", "]", "=", "opts", "[", ":page", "]", "if", "opts", ".", "key?", "(", ":page", ")", "params", "[", ":status", "]", "=", "opts", "[", ":status", "]", "if", "opts", ".", "key?", "(", ":status", ")", "DataSift", ".", "request", "(", ":GET", ",", "\"pylon/#{service}/task/#{type}\"", ",", "@config", ",", "params", ")", "end" ]
Gets a list of all current Tasks on the service. This call may be accessed using either a main or identity-level API key. @param service [String] Search Tasks by Service @param type [String] (Optional) Type of Task to be run (Default: 'analysis') @param per_page [Integer] (Optional) How many Tasks should be returned per page of results @param page [Integer] (Optional) Which page of results to return @param status [String] (Optional) Filter by Tasks on Status @return [Object] API reponse object
[ "Gets", "a", "list", "of", "all", "current", "Tasks", "on", "the", "service", ".", "This", "call", "may", "be", "accessed", "using", "either", "a", "main", "or", "identity", "-", "level", "API", "key", "." ]
d724e4ff15d178f196001ea5a517a981dc56c18c
https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/tasks.rb#L42-L49
train
faradayio/ecs_compose
lib/ecs_compose/task_definition.rb
EcsCompose.TaskDefinition.update
def update(cluster) deployed = primary_deployment(cluster) Ecs.update_service(cluster.name, name, register(deployed)) name end
ruby
def update(cluster) deployed = primary_deployment(cluster) Ecs.update_service(cluster.name, name, register(deployed)) name end
[ "def", "update", "(", "cluster", ")", "deployed", "=", "primary_deployment", "(", "cluster", ")", "Ecs", ".", "update_service", "(", "cluster", ".", "name", ",", "name", ",", "register", "(", "deployed", ")", ")", "name", "end" ]
Register this task definition with ECS, and update the corresponding service.
[ "Register", "this", "task", "definition", "with", "ECS", "and", "update", "the", "corresponding", "service", "." ]
5a897c85f3476e1d3d1ed01db0a301706a3e376d
https://github.com/faradayio/ecs_compose/blob/5a897c85f3476e1d3d1ed01db0a301706a3e376d/lib/ecs_compose/task_definition.rb#L93-L97
train
faradayio/ecs_compose
lib/ecs_compose/task_definition.rb
EcsCompose.TaskDefinition.scale
def scale(cluster, count) Ecs.update_service_desired_count(cluster.name, name, count) name end
ruby
def scale(cluster, count) Ecs.update_service_desired_count(cluster.name, name, count) name end
[ "def", "scale", "(", "cluster", ",", "count", ")", "Ecs", ".", "update_service_desired_count", "(", "cluster", ".", "name", ",", "name", ",", "count", ")", "name", "end" ]
Set the number of running copies of a service we want to have.
[ "Set", "the", "number", "of", "running", "copies", "of", "a", "service", "we", "want", "to", "have", "." ]
5a897c85f3476e1d3d1ed01db0a301706a3e376d
https://github.com/faradayio/ecs_compose/blob/5a897c85f3476e1d3d1ed01db0a301706a3e376d/lib/ecs_compose/task_definition.rb#L100-L103
train
faradayio/ecs_compose
lib/ecs_compose/task_definition.rb
EcsCompose.TaskDefinition.run
def run(cluster, started_by: nil, **args) overrides_json = json_generator.generate_override_json(**args) info = Ecs.run_task(cluster.name, register, started_by: started_by, overrides_json: overrides_json) info.fetch("tasks")[0].fetch("taskArn") end
ruby
def run(cluster, started_by: nil, **args) overrides_json = json_generator.generate_override_json(**args) info = Ecs.run_task(cluster.name, register, started_by: started_by, overrides_json: overrides_json) info.fetch("tasks")[0].fetch("taskArn") end
[ "def", "run", "(", "cluster", ",", "started_by", ":", "nil", ",", "**", "args", ")", "overrides_json", "=", "json_generator", ".", "generate_override_json", "(", "**", "args", ")", "info", "=", "Ecs", ".", "run_task", "(", "cluster", ".", "name", ",", "register", ",", "started_by", ":", "started_by", ",", "overrides_json", ":", "overrides_json", ")", "info", ".", "fetch", "(", "\"tasks\"", ")", "[", "0", "]", ".", "fetch", "(", "\"taskArn\"", ")", "end" ]
Run this task definition as a one-shot ECS task, with the specified overrides.
[ "Run", "this", "task", "definition", "as", "a", "one", "-", "shot", "ECS", "task", "with", "the", "specified", "overrides", "." ]
5a897c85f3476e1d3d1ed01db0a301706a3e376d
https://github.com/faradayio/ecs_compose/blob/5a897c85f3476e1d3d1ed01db0a301706a3e376d/lib/ecs_compose/task_definition.rb#L118-L124
train
Coffa/client_variable
lib/client_variable/rails/engine.rb
ClientVariable.TiltHandlebars.evaluate
def evaluate(scope, locals, &block) binding.pry template = data.dup template.gsub!(/"/, '\\"') template.gsub!(/\r?\n/, '\\n') template.gsub!(/\t/, '\\t') return 'console.log(1223);' end
ruby
def evaluate(scope, locals, &block) binding.pry template = data.dup template.gsub!(/"/, '\\"') template.gsub!(/\r?\n/, '\\n') template.gsub!(/\t/, '\\t') return 'console.log(1223);' end
[ "def", "evaluate", "(", "scope", ",", "locals", ",", "&", "block", ")", "binding", ".", "pry", "template", "=", "data", ".", "dup", "template", ".", "gsub!", "(", "/", "/", ",", "'\\\\\"'", ")", "template", ".", "gsub!", "(", "/", "\\r", "\\n", "/", ",", "'\\\\n'", ")", "template", ".", "gsub!", "(", "/", "\\t", "/", ",", "'\\\\t'", ")", "return", "'console.log(1223);'", "end" ]
Generates Javascript code from a HandlebarsJS template. The SC template name is derived from the lowercase logical asset path by replacing non-alphanum characheters by underscores.
[ "Generates", "Javascript", "code", "from", "a", "HandlebarsJS", "template", ".", "The", "SC", "template", "name", "is", "derived", "from", "the", "lowercase", "logical", "asset", "path", "by", "replacing", "non", "-", "alphanum", "characheters", "by", "underscores", "." ]
3e54480b05e05071e1e9d2fd06d289f5c15d5ce5
https://github.com/Coffa/client_variable/blob/3e54480b05e05071e1e9d2fd06d289f5c15d5ce5/lib/client_variable/rails/engine.rb#L23-L30
train
knaveofdiamonds/tealeaves
lib/tealeaves/moving_average.rb
TeaLeaves.ArrayMethods.moving_average
def moving_average(average_specifier) if average_specifier.kind_of?(Array) avg = MovingAverage.weighted(average_specifier) elsif average_specifier.kind_of?(Integer) avg = MovingAverage.simple(average_specifier) else raise ArgumentError.new("Unknown weights") end avg.calculate(self) end
ruby
def moving_average(average_specifier) if average_specifier.kind_of?(Array) avg = MovingAverage.weighted(average_specifier) elsif average_specifier.kind_of?(Integer) avg = MovingAverage.simple(average_specifier) else raise ArgumentError.new("Unknown weights") end avg.calculate(self) end
[ "def", "moving_average", "(", "average_specifier", ")", "if", "average_specifier", ".", "kind_of?", "(", "Array", ")", "avg", "=", "MovingAverage", ".", "weighted", "(", "average_specifier", ")", "elsif", "average_specifier", ".", "kind_of?", "(", "Integer", ")", "avg", "=", "MovingAverage", ".", "simple", "(", "average_specifier", ")", "else", "raise", "ArgumentError", ".", "new", "(", "\"Unknown weights\"", ")", "end", "avg", ".", "calculate", "(", "self", ")", "end" ]
Returns a moving average for this array, given either a number of terms or a list of weights. See MovingAverage for more detail.
[ "Returns", "a", "moving", "average", "for", "this", "array", "given", "either", "a", "number", "of", "terms", "or", "a", "list", "of", "weights", "." ]
226d61cbb5cfc61a16ae84679e261eebf9895358
https://github.com/knaveofdiamonds/tealeaves/blob/226d61cbb5cfc61a16ae84679e261eebf9895358/lib/tealeaves/moving_average.rb#L96-L106
train
knaveofdiamonds/tealeaves
lib/tealeaves/moving_average.rb
TeaLeaves.MovingAverage.calculate
def calculate(array) return [] if @span > array.length array.each_cons(@span).map do |window| window.zip(weights).map {|(a,b)| a * b }.inject(&:+) end end
ruby
def calculate(array) return [] if @span > array.length array.each_cons(@span).map do |window| window.zip(weights).map {|(a,b)| a * b }.inject(&:+) end end
[ "def", "calculate", "(", "array", ")", "return", "[", "]", "if", "@span", ">", "array", ".", "length", "array", ".", "each_cons", "(", "@span", ")", ".", "map", "do", "|", "window", "|", "window", ".", "zip", "(", "weights", ")", ".", "map", "{", "|", "(", "a", ",", "b", ")", "|", "a", "*", "b", "}", ".", "inject", "(", "&", ":+", ")", "end", "end" ]
Creates a new MovingAverage given a list of weights. See also the class methods simple and weighted. Calculates the moving average for the given array of numbers. Moving averages won't include values for terms at the beginning or end of the array, so there will be fewer numbers than in the original.
[ "Creates", "a", "new", "MovingAverage", "given", "a", "list", "of", "weights", "." ]
226d61cbb5cfc61a16ae84679e261eebf9895358
https://github.com/knaveofdiamonds/tealeaves/blob/226d61cbb5cfc61a16ae84679e261eebf9895358/lib/tealeaves/moving_average.rb#L64-L70
train
knaveofdiamonds/tealeaves
lib/tealeaves/moving_average.rb
TeaLeaves.MovingAverage.check_weights
def check_weights raise ArgumentError.new("Weights should be an odd list") unless @span.odd? sum = weights.inject(&:+) if sum < 0.999999 || sum > 1.000001 raise ArgumentError.new("Weights must sum to 1") end end
ruby
def check_weights raise ArgumentError.new("Weights should be an odd list") unless @span.odd? sum = weights.inject(&:+) if sum < 0.999999 || sum > 1.000001 raise ArgumentError.new("Weights must sum to 1") end end
[ "def", "check_weights", "raise", "ArgumentError", ".", "new", "(", "\"Weights should be an odd list\"", ")", "unless", "@span", ".", "odd?", "sum", "=", "weights", ".", "inject", "(", "&", ":+", ")", "if", "sum", "<", "0.999999", "||", "sum", ">", "1.000001", "raise", "ArgumentError", ".", "new", "(", "\"Weights must sum to 1\"", ")", "end", "end" ]
Error checking for weights
[ "Error", "checking", "for", "weights" ]
226d61cbb5cfc61a16ae84679e261eebf9895358
https://github.com/knaveofdiamonds/tealeaves/blob/226d61cbb5cfc61a16ae84679e261eebf9895358/lib/tealeaves/moving_average.rb#L75-L81
train
FTB-Gamepedia/MediaWiki-Butt-Ruby
lib/mediawiki/purge.rb
MediaWiki.Purge.purge_request
def purge_request(params, *titles) params[:action] = 'purge' params[:titles] = titles.join('|') post(params)['purge'].inject({}) do |result, hash| title = hash['title'] result[title] = hash.key?('purged') && !hash.key?('missing') warn "Invalid purge (#{title}) #{hash['invalidreason']}" if hash.key?('invalid') result end end
ruby
def purge_request(params, *titles) params[:action] = 'purge' params[:titles] = titles.join('|') post(params)['purge'].inject({}) do |result, hash| title = hash['title'] result[title] = hash.key?('purged') && !hash.key?('missing') warn "Invalid purge (#{title}) #{hash['invalidreason']}" if hash.key?('invalid') result end end
[ "def", "purge_request", "(", "params", ",", "*", "titles", ")", "params", "[", ":action", "]", "=", "'purge'", "params", "[", ":titles", "]", "=", "titles", ".", "join", "(", "'|'", ")", "post", "(", "params", ")", "[", "'purge'", "]", ".", "inject", "(", "{", "}", ")", "do", "|", "result", ",", "hash", "|", "title", "=", "hash", "[", "'title'", "]", "result", "[", "title", "]", "=", "hash", ".", "key?", "(", "'purged'", ")", "&&", "!", "hash", ".", "key?", "(", "'missing'", ")", "warn", "\"Invalid purge (#{title}) #{hash['invalidreason']}\"", "if", "hash", ".", "key?", "(", "'invalid'", ")", "result", "end", "end" ]
Sends a purge API request, and handles the return value and warnings. @param params [Hash<Object, Object>] The parameter hash to begin with. Cannot include the titles or action keys. @param (see #purge) @return (see #purge) @see (see #purge) @note (see #purge)
[ "Sends", "a", "purge", "API", "request", "and", "handles", "the", "return", "value", "and", "warnings", "." ]
d71c5dfdf9d349d025e1c3534286ce116777eaa4
https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/purge.rb#L40-L50
train
danryan/spice
lib/spice/config.rb
Spice.Config.reset
def reset self.user_agent = DEFAULT_USER_AGENT self.server_url = DEFAULT_SERVER_URL self.chef_version = DEFAULT_CHEF_VERSION self.client_name = DEFAULT_CLIENT_NAME self.client_key = DEFAULT_CLIENT_KEY self.connection_options = DEFAULT_CONNECTION_OPTIONS self.middleware = DEFAULT_MIDDLEWARE self end
ruby
def reset self.user_agent = DEFAULT_USER_AGENT self.server_url = DEFAULT_SERVER_URL self.chef_version = DEFAULT_CHEF_VERSION self.client_name = DEFAULT_CLIENT_NAME self.client_key = DEFAULT_CLIENT_KEY self.connection_options = DEFAULT_CONNECTION_OPTIONS self.middleware = DEFAULT_MIDDLEWARE self end
[ "def", "reset", "self", ".", "user_agent", "=", "DEFAULT_USER_AGENT", "self", ".", "server_url", "=", "DEFAULT_SERVER_URL", "self", ".", "chef_version", "=", "DEFAULT_CHEF_VERSION", "self", ".", "client_name", "=", "DEFAULT_CLIENT_NAME", "self", ".", "client_key", "=", "DEFAULT_CLIENT_KEY", "self", ".", "connection_options", "=", "DEFAULT_CONNECTION_OPTIONS", "self", ".", "middleware", "=", "DEFAULT_MIDDLEWARE", "self", "end" ]
def options Reset all config options to their defaults
[ "def", "options", "Reset", "all", "config", "options", "to", "their", "defaults" ]
6fbe443d95cc31e398a8e56d87b176afe8514b0b
https://github.com/danryan/spice/blob/6fbe443d95cc31e398a8e56d87b176afe8514b0b/lib/spice/config.rb#L77-L86
train
datasift/datasift-ruby
lib/datasift.rb
DataSift.Client.valid?
def valid?(csdl, boolResponse = true) requires({ :csdl => csdl }) res = DataSift.request(:POST, 'validate', @config, :csdl => csdl ) boolResponse ? res[:http][:status] == 200 : res end
ruby
def valid?(csdl, boolResponse = true) requires({ :csdl => csdl }) res = DataSift.request(:POST, 'validate', @config, :csdl => csdl ) boolResponse ? res[:http][:status] == 200 : res end
[ "def", "valid?", "(", "csdl", ",", "boolResponse", "=", "true", ")", "requires", "(", "{", ":csdl", "=>", "csdl", "}", ")", "res", "=", "DataSift", ".", "request", "(", ":POST", ",", "'validate'", ",", "@config", ",", ":csdl", "=>", "csdl", ")", "boolResponse", "?", "res", "[", ":http", "]", "[", ":status", "]", "==", "200", ":", "res", "end" ]
Checks if the syntax of the given CSDL is valid @param boolResponse [Boolean] If true a boolean is returned indicating whether the CSDL is valid, otherwise the full response object is returned
[ "Checks", "if", "the", "syntax", "of", "the", "given", "CSDL", "is", "valid" ]
d724e4ff15d178f196001ea5a517a981dc56c18c
https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/datasift.rb#L98-L102
train
datasift/datasift-ruby
lib/datasift.rb
DataSift.Client.dpu
def dpu(hash = '', historics_id = '') fail ArgumentError, 'Must pass a filter hash or Historics ID' if hash.empty? && historics_id.empty? fail ArgumentError, 'Must only pass hash or Historics ID; not both' unless hash.empty? || historics_id.empty? params = {} params.merge!(hash: hash) unless hash.empty? params.merge!(historics_id: historics_id) unless historics_id.empty? DataSift.request(:POST, 'dpu', @config, params) end
ruby
def dpu(hash = '', historics_id = '') fail ArgumentError, 'Must pass a filter hash or Historics ID' if hash.empty? && historics_id.empty? fail ArgumentError, 'Must only pass hash or Historics ID; not both' unless hash.empty? || historics_id.empty? params = {} params.merge!(hash: hash) unless hash.empty? params.merge!(historics_id: historics_id) unless historics_id.empty? DataSift.request(:POST, 'dpu', @config, params) end
[ "def", "dpu", "(", "hash", "=", "''", ",", "historics_id", "=", "''", ")", "fail", "ArgumentError", ",", "'Must pass a filter hash or Historics ID'", "if", "hash", ".", "empty?", "&&", "historics_id", ".", "empty?", "fail", "ArgumentError", ",", "'Must only pass hash or Historics ID; not both'", "unless", "hash", ".", "empty?", "||", "historics_id", ".", "empty?", "params", "=", "{", "}", "params", ".", "merge!", "(", "hash", ":", "hash", ")", "unless", "hash", ".", "empty?", "params", ".", "merge!", "(", "historics_id", ":", "historics_id", ")", "unless", "historics_id", ".", "empty?", "DataSift", ".", "request", "(", ":POST", ",", "'dpu'", ",", "@config", ",", "params", ")", "end" ]
Calculate the DPU cost of running a filter, or Historics query @param hash [String] CSDL hash for which you wish to find the DPU cost @param historics_id [String] ID of Historics query for which you wish to find the DPU cost @return [Object] API reponse object
[ "Calculate", "the", "DPU", "cost", "of", "running", "a", "filter", "or", "Historics", "query" ]
d724e4ff15d178f196001ea5a517a981dc56c18c
https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/datasift.rb#L127-L138
train
elpassion/danger-synx
lib/synx/plugin.rb
Danger.DangerSynx.synx_issues
def synx_issues (git.modified_files + git.added_files) .select { |f| f.include? '.xcodeproj' } .reduce([]) { |i, f| i + synx_project(f) } end
ruby
def synx_issues (git.modified_files + git.added_files) .select { |f| f.include? '.xcodeproj' } .reduce([]) { |i, f| i + synx_project(f) } end
[ "def", "synx_issues", "(", "git", ".", "modified_files", "+", "git", ".", "added_files", ")", ".", "select", "{", "|", "f", "|", "f", ".", "include?", "'.xcodeproj'", "}", ".", "reduce", "(", "[", "]", ")", "{", "|", "i", ",", "f", "|", "i", "+", "synx_project", "(", "f", ")", "}", "end" ]
Triggers Synx on all projects that were modified or added to the project. Returns accumulated list of issues for those projects. @return [Array<(String, String)>]
[ "Triggers", "Synx", "on", "all", "projects", "that", "were", "modified", "or", "added", "to", "the", "project", ".", "Returns", "accumulated", "list", "of", "issues", "for", "those", "projects", "." ]
3a70585cfe4dce5339e4fc362b86cb483b74530e
https://github.com/elpassion/danger-synx/blob/3a70585cfe4dce5339e4fc362b86cb483b74530e/lib/synx/plugin.rb#L66-L70
train
aidistan/ruby-teambition
lib/teambition/api.rb
Teambition.API.valid_token?
def valid_token? uri = URI.join(Teambition::API_DOMAIN, "/api/applications/#{Teambition.client_key}/tokens/check") req = Net::HTTP::Get.new(uri) req['Authorization'] = "OAuth2 #{token}" res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |https| https.request(req) end res.code == '200' end
ruby
def valid_token? uri = URI.join(Teambition::API_DOMAIN, "/api/applications/#{Teambition.client_key}/tokens/check") req = Net::HTTP::Get.new(uri) req['Authorization'] = "OAuth2 #{token}" res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |https| https.request(req) end res.code == '200' end
[ "def", "valid_token?", "uri", "=", "URI", ".", "join", "(", "Teambition", "::", "API_DOMAIN", ",", "\"/api/applications/#{Teambition.client_key}/tokens/check\"", ")", "req", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "uri", ")", "req", "[", "'Authorization'", "]", "=", "\"OAuth2 #{token}\"", "res", "=", "Net", "::", "HTTP", ".", "start", "(", "uri", ".", "hostname", ",", "uri", ".", "port", ",", "use_ssl", ":", "true", ")", "do", "|", "https", "|", "https", ".", "request", "(", "req", ")", "end", "res", ".", "code", "==", "'200'", "end" ]
Validate the token
[ "Validate", "the", "token" ]
7259a9e4335bf75f9faf1e760a0251abce7b6119
https://github.com/aidistan/ruby-teambition/blob/7259a9e4335bf75f9faf1e760a0251abce7b6119/lib/teambition/api.rb#L8-L18
train
factore/tenon
lib/tenon/s3_signature.rb
S3SwfUpload.Signature.core_sha1
def core_sha1(x, len) # append padding x[len >> 5] ||= 0 x[len >> 5] |= 0x80 << (24 - len % 32) x[((len + 64 >> 9) << 4) + 15] = len w = Array.new(80, 0) a = 1_732_584_193 b = -271_733_879 c = -1_732_584_194 d = 271_733_878 e = -1_009_589_776 # for(var i = 0; i < x.length; i += 16) i = 0 while i < x.length olda = a oldb = b oldc = c oldd = d olde = e # for(var j = 0; j < 80; j++) j = 0 while j < 80 if j < 16 w[j] = x[i + j] || 0 else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1) end t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j))) e = d d = c c = rol(b, 30) b = a a = t j += 1 end a = safe_add(a, olda) b = safe_add(b, oldb) c = safe_add(c, oldc) d = safe_add(d, oldd) e = safe_add(e, olde) i += 16 end [a, b, c, d, e] end
ruby
def core_sha1(x, len) # append padding x[len >> 5] ||= 0 x[len >> 5] |= 0x80 << (24 - len % 32) x[((len + 64 >> 9) << 4) + 15] = len w = Array.new(80, 0) a = 1_732_584_193 b = -271_733_879 c = -1_732_584_194 d = 271_733_878 e = -1_009_589_776 # for(var i = 0; i < x.length; i += 16) i = 0 while i < x.length olda = a oldb = b oldc = c oldd = d olde = e # for(var j = 0; j < 80; j++) j = 0 while j < 80 if j < 16 w[j] = x[i + j] || 0 else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1) end t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j))) e = d d = c c = rol(b, 30) b = a a = t j += 1 end a = safe_add(a, olda) b = safe_add(b, oldb) c = safe_add(c, oldc) d = safe_add(d, oldd) e = safe_add(e, olde) i += 16 end [a, b, c, d, e] end
[ "def", "core_sha1", "(", "x", ",", "len", ")", "x", "[", "len", ">>", "5", "]", "||=", "0", "x", "[", "len", ">>", "5", "]", "|=", "0x80", "<<", "(", "24", "-", "len", "%", "32", ")", "x", "[", "(", "(", "len", "+", "64", ">>", "9", ")", "<<", "4", ")", "+", "15", "]", "=", "len", "w", "=", "Array", ".", "new", "(", "80", ",", "0", ")", "a", "=", "1_732_584_193", "b", "=", "-", "271_733_879", "c", "=", "-", "1_732_584_194", "d", "=", "271_733_878", "e", "=", "-", "1_009_589_776", "i", "=", "0", "while", "i", "<", "x", ".", "length", "olda", "=", "a", "oldb", "=", "b", "oldc", "=", "c", "oldd", "=", "d", "olde", "=", "e", "j", "=", "0", "while", "j", "<", "80", "if", "j", "<", "16", "w", "[", "j", "]", "=", "x", "[", "i", "+", "j", "]", "||", "0", "else", "w", "[", "j", "]", "=", "rol", "(", "w", "[", "j", "-", "3", "]", "^", "w", "[", "j", "-", "8", "]", "^", "w", "[", "j", "-", "14", "]", "^", "w", "[", "j", "-", "16", "]", ",", "1", ")", "end", "t", "=", "safe_add", "(", "safe_add", "(", "rol", "(", "a", ",", "5", ")", ",", "sha1_ft", "(", "j", ",", "b", ",", "c", ",", "d", ")", ")", ",", "safe_add", "(", "safe_add", "(", "e", ",", "w", "[", "j", "]", ")", ",", "sha1_kt", "(", "j", ")", ")", ")", "e", "=", "d", "d", "=", "c", "c", "=", "rol", "(", "b", ",", "30", ")", "b", "=", "a", "a", "=", "t", "j", "+=", "1", "end", "a", "=", "safe_add", "(", "a", ",", "olda", ")", "b", "=", "safe_add", "(", "b", ",", "oldb", ")", "c", "=", "safe_add", "(", "c", ",", "oldc", ")", "d", "=", "safe_add", "(", "d", ",", "oldd", ")", "e", "=", "safe_add", "(", "e", ",", "olde", ")", "i", "+=", "16", "end", "[", "a", ",", "b", ",", "c", ",", "d", ",", "e", "]", "end" ]
Calculate the SHA-1 of an array of big-endian words, and a bit length
[ "Calculate", "the", "SHA", "-", "1", "of", "an", "array", "of", "big", "-", "endian", "words", "and", "a", "bit", "length" ]
49907830c00524853d087566f60951b8b6a9aedf
https://github.com/factore/tenon/blob/49907830c00524853d087566f60951b8b6a9aedf/lib/tenon/s3_signature.rb#L37-L86
train
factore/tenon
lib/tenon/s3_signature.rb
S3SwfUpload.Signature.sha1_ft
def sha1_ft(t, b, c, d) return (b & c) | ((~b) & d) if t < 20 return b ^ c ^ d if t < 40 return (b & c) | (b & d) | (c & d) if t < 60 b ^ c ^ d end
ruby
def sha1_ft(t, b, c, d) return (b & c) | ((~b) & d) if t < 20 return b ^ c ^ d if t < 40 return (b & c) | (b & d) | (c & d) if t < 60 b ^ c ^ d end
[ "def", "sha1_ft", "(", "t", ",", "b", ",", "c", ",", "d", ")", "return", "(", "b", "&", "c", ")", "|", "(", "(", "~", "b", ")", "&", "d", ")", "if", "t", "<", "20", "return", "b", "^", "c", "^", "d", "if", "t", "<", "40", "return", "(", "b", "&", "c", ")", "|", "(", "b", "&", "d", ")", "|", "(", "c", "&", "d", ")", "if", "t", "<", "60", "b", "^", "c", "^", "d", "end" ]
Perform the appropriate triplet combination function for the current iteration
[ "Perform", "the", "appropriate", "triplet", "combination", "function", "for", "the", "current", "iteration" ]
49907830c00524853d087566f60951b8b6a9aedf
https://github.com/factore/tenon/blob/49907830c00524853d087566f60951b8b6a9aedf/lib/tenon/s3_signature.rb#L90-L95
train
factore/tenon
lib/tenon/s3_signature.rb
S3SwfUpload.Signature.core_hmac_sha1
def core_hmac_sha1(key, data) bkey = str2binb(key) bkey = core_sha1(bkey, key.length * $chrsz) if bkey.length > 16 ipad = Array.new(16, 0) opad = Array.new(16, 0) # for(var i = 0; i < 16; i++) i = 0 while i < 16 ipad[i] = (bkey[i] || 0) ^ 0x36363636 opad[i] = (bkey[i] || 0) ^ 0x5C5C5C5C i += 1 end hash = core_sha1((ipad + str2binb(data)), 512 + data.length * $chrsz) core_sha1((opad + hash), 512 + 160) end
ruby
def core_hmac_sha1(key, data) bkey = str2binb(key) bkey = core_sha1(bkey, key.length * $chrsz) if bkey.length > 16 ipad = Array.new(16, 0) opad = Array.new(16, 0) # for(var i = 0; i < 16; i++) i = 0 while i < 16 ipad[i] = (bkey[i] || 0) ^ 0x36363636 opad[i] = (bkey[i] || 0) ^ 0x5C5C5C5C i += 1 end hash = core_sha1((ipad + str2binb(data)), 512 + data.length * $chrsz) core_sha1((opad + hash), 512 + 160) end
[ "def", "core_hmac_sha1", "(", "key", ",", "data", ")", "bkey", "=", "str2binb", "(", "key", ")", "bkey", "=", "core_sha1", "(", "bkey", ",", "key", ".", "length", "*", "$chrsz", ")", "if", "bkey", ".", "length", ">", "16", "ipad", "=", "Array", ".", "new", "(", "16", ",", "0", ")", "opad", "=", "Array", ".", "new", "(", "16", ",", "0", ")", "i", "=", "0", "while", "i", "<", "16", "ipad", "[", "i", "]", "=", "(", "bkey", "[", "i", "]", "||", "0", ")", "^", "0x36363636", "opad", "[", "i", "]", "=", "(", "bkey", "[", "i", "]", "||", "0", ")", "^", "0x5C5C5C5C", "i", "+=", "1", "end", "hash", "=", "core_sha1", "(", "(", "ipad", "+", "str2binb", "(", "data", ")", ")", ",", "512", "+", "data", ".", "length", "*", "$chrsz", ")", "core_sha1", "(", "(", "opad", "+", "hash", ")", ",", "512", "+", "160", ")", "end" ]
Calculate the HMAC-SHA1 of a key and some data
[ "Calculate", "the", "HMAC", "-", "SHA1", "of", "a", "key", "and", "some", "data" ]
49907830c00524853d087566f60951b8b6a9aedf
https://github.com/factore/tenon/blob/49907830c00524853d087566f60951b8b6a9aedf/lib/tenon/s3_signature.rb#L111-L127
train
factore/tenon
lib/tenon/s3_signature.rb
S3SwfUpload.Signature.str2binb
def str2binb(str) bin = [] mask = (1 << $chrsz) - 1 # for(var i = 0; i < str.length * $chrsz; i += $chrsz) i = 0 while i < str.length * $chrsz bin[i >> 5] ||= 0 bin[i >> 5] |= (str[i / $chrsz] & mask) << (32 - $chrsz - i % 32) i += $chrsz end bin end
ruby
def str2binb(str) bin = [] mask = (1 << $chrsz) - 1 # for(var i = 0; i < str.length * $chrsz; i += $chrsz) i = 0 while i < str.length * $chrsz bin[i >> 5] ||= 0 bin[i >> 5] |= (str[i / $chrsz] & mask) << (32 - $chrsz - i % 32) i += $chrsz end bin end
[ "def", "str2binb", "(", "str", ")", "bin", "=", "[", "]", "mask", "=", "(", "1", "<<", "$chrsz", ")", "-", "1", "i", "=", "0", "while", "i", "<", "str", ".", "length", "*", "$chrsz", "bin", "[", "i", ">>", "5", "]", "||=", "0", "bin", "[", "i", ">>", "5", "]", "|=", "(", "str", "[", "i", "/", "$chrsz", "]", "&", "mask", ")", "<<", "(", "32", "-", "$chrsz", "-", "i", "%", "32", ")", "i", "+=", "$chrsz", "end", "bin", "end" ]
Convert an 8-bit or 16-bit string to an array of big-endian words In 8-bit function, characters >255 have their hi-byte silently ignored.
[ "Convert", "an", "8", "-", "bit", "or", "16", "-", "bit", "string", "to", "an", "array", "of", "big", "-", "endian", "words", "In", "8", "-", "bit", "function", "characters", ">", "255", "have", "their", "hi", "-", "byte", "silently", "ignored", "." ]
49907830c00524853d087566f60951b8b6a9aedf
https://github.com/factore/tenon/blob/49907830c00524853d087566f60951b8b6a9aedf/lib/tenon/s3_signature.rb#L144-L155
train
factore/tenon
lib/tenon/s3_signature.rb
S3SwfUpload.Signature.binb2b64
def binb2b64(binarray) tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' str = '' # for(var i = 0; i < binarray.length * 4; i += 3) i = 0 while i < binarray.length * 4 triplet = (((binarray[i >> 2].to_i >> 8 * (3 - i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2].to_i >> 8 * (3 - (i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2].to_i >> 8 * (3 - (i + 2) % 4)) & 0xFF) # for(var j = 0; j < 4; j++) j = 0 while j < 4 if i * 8 + j * 6 > binarray.length * 32 str += $b64pad else str += tab[(triplet >> 6 * (3 - j)) & 0x3F].chr end j += 1 end i += 3 end str end
ruby
def binb2b64(binarray) tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' str = '' # for(var i = 0; i < binarray.length * 4; i += 3) i = 0 while i < binarray.length * 4 triplet = (((binarray[i >> 2].to_i >> 8 * (3 - i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2].to_i >> 8 * (3 - (i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2].to_i >> 8 * (3 - (i + 2) % 4)) & 0xFF) # for(var j = 0; j < 4; j++) j = 0 while j < 4 if i * 8 + j * 6 > binarray.length * 32 str += $b64pad else str += tab[(triplet >> 6 * (3 - j)) & 0x3F].chr end j += 1 end i += 3 end str end
[ "def", "binb2b64", "(", "binarray", ")", "tab", "=", "'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'", "str", "=", "''", "i", "=", "0", "while", "i", "<", "binarray", ".", "length", "*", "4", "triplet", "=", "(", "(", "(", "binarray", "[", "i", ">>", "2", "]", ".", "to_i", ">>", "8", "*", "(", "3", "-", "i", "%", "4", ")", ")", "&", "0xFF", ")", "<<", "16", ")", "|", "(", "(", "(", "binarray", "[", "i", "+", "1", ">>", "2", "]", ".", "to_i", ">>", "8", "*", "(", "3", "-", "(", "i", "+", "1", ")", "%", "4", ")", ")", "&", "0xFF", ")", "<<", "8", ")", "|", "(", "(", "binarray", "[", "i", "+", "2", ">>", "2", "]", ".", "to_i", ">>", "8", "*", "(", "3", "-", "(", "i", "+", "2", ")", "%", "4", ")", ")", "&", "0xFF", ")", "j", "=", "0", "while", "j", "<", "4", "if", "i", "*", "8", "+", "j", "*", "6", ">", "binarray", ".", "length", "*", "32", "str", "+=", "$b64pad", "else", "str", "+=", "tab", "[", "(", "triplet", ">>", "6", "*", "(", "3", "-", "j", ")", ")", "&", "0x3F", "]", ".", "chr", "end", "j", "+=", "1", "end", "i", "+=", "3", "end", "str", "end" ]
Convert an array of big-endian words to a base-64 string
[ "Convert", "an", "array", "of", "big", "-", "endian", "words", "to", "a", "base", "-", "64", "string" ]
49907830c00524853d087566f60951b8b6a9aedf
https://github.com/factore/tenon/blob/49907830c00524853d087566f60951b8b6a9aedf/lib/tenon/s3_signature.rb#L183-L206
train
datasift/datasift-ruby
lib/account_identity.rb
DataSift.AccountIdentity.create
def create(label = '', status = 'active', master = '') fail ArgumentError, 'label is missing' if label.empty? params = { label: label } params.merge!(status: status) unless status.empty? params.merge!(master: master) if [TrueClass, FalseClass].include?(master.class) DataSift.request(:POST, 'account/identity', @config, params) end
ruby
def create(label = '', status = 'active', master = '') fail ArgumentError, 'label is missing' if label.empty? params = { label: label } params.merge!(status: status) unless status.empty? params.merge!(master: master) if [TrueClass, FalseClass].include?(master.class) DataSift.request(:POST, 'account/identity', @config, params) end
[ "def", "create", "(", "label", "=", "''", ",", "status", "=", "'active'", ",", "master", "=", "''", ")", "fail", "ArgumentError", ",", "'label is missing'", "if", "label", ".", "empty?", "params", "=", "{", "label", ":", "label", "}", "params", ".", "merge!", "(", "status", ":", "status", ")", "unless", "status", ".", "empty?", "params", ".", "merge!", "(", "master", ":", "master", ")", "if", "[", "TrueClass", ",", "FalseClass", "]", ".", "include?", "(", "master", ".", "class", ")", "DataSift", ".", "request", "(", ":POST", ",", "'account/identity'", ",", "@config", ",", "params", ")", "end" ]
Creates a new Identity @param label [String] A unique identifier for this Identity @param status [String] (Optional, Default: "active") What status this Identity currently has. Possible values are 'active' and 'disabled' @param master [Boolean] (Optional, Default: false) Whether this is the master Identity for your account @return [Object] API reponse object
[ "Creates", "a", "new", "Identity" ]
d724e4ff15d178f196001ea5a517a981dc56c18c
https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/account_identity.rb#L13-L21
train
datasift/datasift-ruby
lib/account_identity.rb
DataSift.AccountIdentity.list
def list(label = '', per_page = '', page = '') params = {} params.merge!(label: label) unless label.empty? params.merge!(per_page: per_page) unless per_page.empty? params.merge!(page: page) unless page.empty? DataSift.request(:GET, 'account/identity', @config, params) end
ruby
def list(label = '', per_page = '', page = '') params = {} params.merge!(label: label) unless label.empty? params.merge!(per_page: per_page) unless per_page.empty? params.merge!(page: page) unless page.empty? DataSift.request(:GET, 'account/identity', @config, params) end
[ "def", "list", "(", "label", "=", "''", ",", "per_page", "=", "''", ",", "page", "=", "''", ")", "params", "=", "{", "}", "params", ".", "merge!", "(", "label", ":", "label", ")", "unless", "label", ".", "empty?", "params", ".", "merge!", "(", "per_page", ":", "per_page", ")", "unless", "per_page", ".", "empty?", "params", ".", "merge!", "(", "page", ":", "page", ")", "unless", "page", ".", "empty?", "DataSift", ".", "request", "(", ":GET", ",", "'account/identity'", ",", "@config", ",", "params", ")", "end" ]
Returns a list of Identities @param label [String] (Optional) Search by a given Identity label @param per_page [Integer] (Optional) How many Identities should be returned per page of results @param page [Integer] (Optional) Which page of results to return @return [Object] API reponse object
[ "Returns", "a", "list", "of", "Identities" ]
d724e4ff15d178f196001ea5a517a981dc56c18c
https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/account_identity.rb#L38-L45
train
getoutreach/embedded_associations
lib/embedded_associations.rb
EmbeddedAssociations.Processor.handle_resource
def handle_resource(definition, parent, parent_params) if definition.is_a? Array return definition.each{|d| handle_resource(d, parent, parent_params)} end # normalize to a hash unless definition.is_a? Hash definition = {definition => nil} end definition.each do |name, child_definition| if !parent_params || !parent_params.has_key?(name.to_s) next end reflection = parent.class.reflect_on_association(name) attrs = parent_params.delete(name.to_s) if reflection.collection? attrs ||= [] handle_plural_resource parent, name, attrs, child_definition else handle_singular_resource parent, name, attrs, child_definition end end end
ruby
def handle_resource(definition, parent, parent_params) if definition.is_a? Array return definition.each{|d| handle_resource(d, parent, parent_params)} end # normalize to a hash unless definition.is_a? Hash definition = {definition => nil} end definition.each do |name, child_definition| if !parent_params || !parent_params.has_key?(name.to_s) next end reflection = parent.class.reflect_on_association(name) attrs = parent_params.delete(name.to_s) if reflection.collection? attrs ||= [] handle_plural_resource parent, name, attrs, child_definition else handle_singular_resource parent, name, attrs, child_definition end end end
[ "def", "handle_resource", "(", "definition", ",", "parent", ",", "parent_params", ")", "if", "definition", ".", "is_a?", "Array", "return", "definition", ".", "each", "{", "|", "d", "|", "handle_resource", "(", "d", ",", "parent", ",", "parent_params", ")", "}", "end", "unless", "definition", ".", "is_a?", "Hash", "definition", "=", "{", "definition", "=>", "nil", "}", "end", "definition", ".", "each", "do", "|", "name", ",", "child_definition", "|", "if", "!", "parent_params", "||", "!", "parent_params", ".", "has_key?", "(", "name", ".", "to_s", ")", "next", "end", "reflection", "=", "parent", ".", "class", ".", "reflect_on_association", "(", "name", ")", "attrs", "=", "parent_params", ".", "delete", "(", "name", ".", "to_s", ")", "if", "reflection", ".", "collection?", "attrs", "||=", "[", "]", "handle_plural_resource", "parent", ",", "name", ",", "attrs", ",", "child_definition", "else", "handle_singular_resource", "parent", ",", "name", ",", "attrs", ",", "child_definition", "end", "end", "end" ]
Definition can be either a name, array, or hash.
[ "Definition", "can", "be", "either", "a", "name", "array", "or", "hash", "." ]
9ead98f5e8af2db3ea0f4ad7bb11540dbb4598a0
https://github.com/getoutreach/embedded_associations/blob/9ead98f5e8af2db3ea0f4ad7bb11540dbb4598a0/lib/embedded_associations.rb#L80-L105
train
rajcybage/google_book
lib/google_book/base.rb
GoogleBook.Book.search
def search(query,type = nil) checking_type(type) type = set_type(type) unless type.nil? if query.nil? puts 'Enter the text to search' text = gets end json = JSON.parse(connect_google(@api_key,type,query)) @total_count = json["totalItems"] @items = json["items"] end
ruby
def search(query,type = nil) checking_type(type) type = set_type(type) unless type.nil? if query.nil? puts 'Enter the text to search' text = gets end json = JSON.parse(connect_google(@api_key,type,query)) @total_count = json["totalItems"] @items = json["items"] end
[ "def", "search", "(", "query", ",", "type", "=", "nil", ")", "checking_type", "(", "type", ")", "type", "=", "set_type", "(", "type", ")", "unless", "type", ".", "nil?", "if", "query", ".", "nil?", "puts", "'Enter the text to search'", "text", "=", "gets", "end", "json", "=", "JSON", ".", "parse", "(", "connect_google", "(", "@api_key", ",", "type", ",", "query", ")", ")", "@total_count", "=", "json", "[", "\"totalItems\"", "]", "@items", "=", "json", "[", "\"items\"", "]", "end" ]
Google books search
[ "Google", "books", "search" ]
a49bb692d2c3374fd38c5c6c251d761c0e038b4a
https://github.com/rajcybage/google_book/blob/a49bb692d2c3374fd38c5c6c251d761c0e038b4a/lib/google_book/base.rb#L23-L33
train
rajcybage/google_book
lib/google_book/base.rb
GoogleBook.Book.filter
def filter(query, type = nil) checking_filter_type(type) filter_type = set_filter_type(type) unless type.nil? json = JSON.parse(connect_google(@api_key,nil,query,filter_type)) @total_count = json["totalItems"] @items = json["items"] end
ruby
def filter(query, type = nil) checking_filter_type(type) filter_type = set_filter_type(type) unless type.nil? json = JSON.parse(connect_google(@api_key,nil,query,filter_type)) @total_count = json["totalItems"] @items = json["items"] end
[ "def", "filter", "(", "query", ",", "type", "=", "nil", ")", "checking_filter_type", "(", "type", ")", "filter_type", "=", "set_filter_type", "(", "type", ")", "unless", "type", ".", "nil?", "json", "=", "JSON", ".", "parse", "(", "connect_google", "(", "@api_key", ",", "nil", ",", "query", ",", "filter_type", ")", ")", "@total_count", "=", "json", "[", "\"totalItems\"", "]", "@items", "=", "json", "[", "\"items\"", "]", "end" ]
Google books filtration
[ "Google", "books", "filtration" ]
a49bb692d2c3374fd38c5c6c251d761c0e038b4a
https://github.com/rajcybage/google_book/blob/a49bb692d2c3374fd38c5c6c251d761c0e038b4a/lib/google_book/base.rb#L36-L42
train
datasift/datasift-ruby
lib/push.rb
DataSift.Push.valid?
def valid?(params, bool_response = true) requires params res = DataSift.request(:POST, 'push/validate', @config, params) bool_response ? res[:http][:status] == 200 : res end
ruby
def valid?(params, bool_response = true) requires params res = DataSift.request(:POST, 'push/validate', @config, params) bool_response ? res[:http][:status] == 200 : res end
[ "def", "valid?", "(", "params", ",", "bool_response", "=", "true", ")", "requires", "params", "res", "=", "DataSift", ".", "request", "(", ":POST", ",", "'push/validate'", ",", "@config", ",", "params", ")", "bool_response", "?", "res", "[", ":http", "]", "[", ":status", "]", "==", "200", ":", "res", "end" ]
Check that a Push subscription definition is valid @param params [Hash] Hash of Push subscription parameters @param bool_response [Boolean] True if you want a boolean response. False if you want the full response object
[ "Check", "that", "a", "Push", "subscription", "definition", "is", "valid" ]
d724e4ff15d178f196001ea5a517a981dc56c18c
https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/push.rb#L15-L19
train
datasift/datasift-ruby
lib/push.rb
DataSift.Push.log_for
def log_for(id, page = 1, per_page = 20, order_by = :request_time, order_dir = :desc) params = { :id => id } requires params params.merge!( :page => page, :per_page => per_page, :order_by => order_by, :order_dir => order_dir ) DataSift.request(:GET, 'push/log', @config, params) end
ruby
def log_for(id, page = 1, per_page = 20, order_by = :request_time, order_dir = :desc) params = { :id => id } requires params params.merge!( :page => page, :per_page => per_page, :order_by => order_by, :order_dir => order_dir ) DataSift.request(:GET, 'push/log', @config, params) end
[ "def", "log_for", "(", "id", ",", "page", "=", "1", ",", "per_page", "=", "20", ",", "order_by", "=", ":request_time", ",", "order_dir", "=", ":desc", ")", "params", "=", "{", ":id", "=>", "id", "}", "requires", "params", "params", ".", "merge!", "(", ":page", "=>", "page", ",", ":per_page", "=>", "per_page", ",", ":order_by", "=>", "order_by", ",", ":order_dir", "=>", "order_dir", ")", "DataSift", ".", "request", "(", ":GET", ",", "'push/log'", ",", "@config", ",", "params", ")", "end" ]
Retrieve log messages for a specific subscription @param id [String] ID of the Push subscription to retrieve logs for @param page [Integer] Which page of logs to retreive @param per_page [Integer] How many logs to return per page @param order_by [String, Symbol] Which field to sort results by @param order_dir [String, Symbol] Order results in ascending or descending
[ "Retrieve", "log", "messages", "for", "a", "specific", "subscription" ]
d724e4ff15d178f196001ea5a517a981dc56c18c
https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/push.rb#L83-L95
train
datasift/datasift-ruby
lib/push.rb
DataSift.Push.log
def log(page = 1, per_page = 20, order_by = :request_time, order_dir = :desc) params = { :page => page, :per_page => per_page, :order_by => order_by, :order_dir => order_dir } DataSift.request(:GET, 'push/log', @config, params) end
ruby
def log(page = 1, per_page = 20, order_by = :request_time, order_dir = :desc) params = { :page => page, :per_page => per_page, :order_by => order_by, :order_dir => order_dir } DataSift.request(:GET, 'push/log', @config, params) end
[ "def", "log", "(", "page", "=", "1", ",", "per_page", "=", "20", ",", "order_by", "=", ":request_time", ",", "order_dir", "=", ":desc", ")", "params", "=", "{", ":page", "=>", "page", ",", ":per_page", "=>", "per_page", ",", ":order_by", "=>", "order_by", ",", ":order_dir", "=>", "order_dir", "}", "DataSift", ".", "request", "(", ":GET", ",", "'push/log'", ",", "@config", ",", "params", ")", "end" ]
Retrieve log messages for all subscriptions @param page [Integer] Which page of logs to retreive @param per_page [Integer] How many logs to return per page @param order_by [String, Symbol] Which field to sort results by @param order_dir [String, Symbol] Order results in ascending or descending
[ "Retrieve", "log", "messages", "for", "all", "subscriptions" ]
d724e4ff15d178f196001ea5a517a981dc56c18c
https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/push.rb#L103-L111
train
datasift/datasift-ruby
lib/push.rb
DataSift.Push.get_by_hash
def get_by_hash(hash, page = 1, per_page = 20, order_by = :created_at, order_dir = :desc, include_finished = 0, all = false) params = { :hash => hash } requires params params.merge!( :page => page, :per_page => per_page, :order_by => order_by, :order_dir => order_dir, :include_finished => include_finished, :all => all ) DataSift.request(:GET, 'push/get', @config, params) end
ruby
def get_by_hash(hash, page = 1, per_page = 20, order_by = :created_at, order_dir = :desc, include_finished = 0, all = false) params = { :hash => hash } requires params params.merge!( :page => page, :per_page => per_page, :order_by => order_by, :order_dir => order_dir, :include_finished => include_finished, :all => all ) DataSift.request(:GET, 'push/get', @config, params) end
[ "def", "get_by_hash", "(", "hash", ",", "page", "=", "1", ",", "per_page", "=", "20", ",", "order_by", "=", ":created_at", ",", "order_dir", "=", ":desc", ",", "include_finished", "=", "0", ",", "all", "=", "false", ")", "params", "=", "{", ":hash", "=>", "hash", "}", "requires", "params", "params", ".", "merge!", "(", ":page", "=>", "page", ",", ":per_page", "=>", "per_page", ",", ":order_by", "=>", "order_by", ",", ":order_dir", "=>", "order_dir", ",", ":include_finished", "=>", "include_finished", ",", ":all", "=>", "all", ")", "DataSift", ".", "request", "(", ":GET", ",", "'push/get'", ",", "@config", ",", "params", ")", "end" ]
Get details of the subscription with the given filter hash @param hash [String] CSDL filter hash @param page [Integer] Which page of logs to retreive @param per_page [Integer] How many logs to return per page @param order_by [String, Symbol] Which field to sort results by @param order_dir [String, Symbol] Order results in ascending or descending @param include_finished [Integer] Include Push subscriptions in a 'finished' state in your results @param all [Boolean] Also include Push subscriptions created via the web UI in your results
[ "Get", "details", "of", "the", "subscription", "with", "the", "given", "filter", "hash" ]
d724e4ff15d178f196001ea5a517a981dc56c18c
https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/push.rb#L132-L146
train
datasift/datasift-ruby
lib/push.rb
DataSift.Push.get_by_historics_id
def get_by_historics_id(historics_id, page = 1, per_page = 20, order_by = :created_at, order_dir = :desc, include_finished = 0, all = false) params = { :historics_id => historics_id, :page => page, :per_page => per_page, :order_by => order_by, :order_dir => order_dir, :include_finished => include_finished, :all => all } DataSift.request(:GET, 'push/get', @config, params) end
ruby
def get_by_historics_id(historics_id, page = 1, per_page = 20, order_by = :created_at, order_dir = :desc, include_finished = 0, all = false) params = { :historics_id => historics_id, :page => page, :per_page => per_page, :order_by => order_by, :order_dir => order_dir, :include_finished => include_finished, :all => all } DataSift.request(:GET, 'push/get', @config, params) end
[ "def", "get_by_historics_id", "(", "historics_id", ",", "page", "=", "1", ",", "per_page", "=", "20", ",", "order_by", "=", ":created_at", ",", "order_dir", "=", ":desc", ",", "include_finished", "=", "0", ",", "all", "=", "false", ")", "params", "=", "{", ":historics_id", "=>", "historics_id", ",", ":page", "=>", "page", ",", ":per_page", "=>", "per_page", ",", ":order_by", "=>", "order_by", ",", ":order_dir", "=>", "order_dir", ",", ":include_finished", "=>", "include_finished", ",", ":all", "=>", "all", "}", "DataSift", ".", "request", "(", ":GET", ",", "'push/get'", ",", "@config", ",", "params", ")", "end" ]
Get details of the subscription with the given Historics ID @param historics_id [String] ID of the Historics query for which you are searching for the related Push subscription @param page [Integer] Which page of logs to retreive @param per_page [Integer] How many logs to return per page @param order_by [String, Symbol] Which field to sort results by @param order_dir [String, Symbol] Order results in ascending or descending @param include_finished [Integer] Include Push subscriptions in a 'finished' state in your results @param all [Boolean] Also include Push subscriptions created via the web UI in your results
[ "Get", "details", "of", "the", "subscription", "with", "the", "given", "Historics", "ID" ]
d724e4ff15d178f196001ea5a517a981dc56c18c
https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/push.rb#L160-L171
train
datasift/datasift-ruby
lib/push.rb
DataSift.Push.get
def get(page = 1, per_page = 20, order_by = :created_at, order_dir = :desc, include_finished = 0, all = false) params = { :page => page, :per_page => per_page, :order_by => order_by, :order_dir => order_dir, :include_finished => include_finished, :all => all } DataSift.request(:GET, 'push/get', @config, params) end
ruby
def get(page = 1, per_page = 20, order_by = :created_at, order_dir = :desc, include_finished = 0, all = false) params = { :page => page, :per_page => per_page, :order_by => order_by, :order_dir => order_dir, :include_finished => include_finished, :all => all } DataSift.request(:GET, 'push/get', @config, params) end
[ "def", "get", "(", "page", "=", "1", ",", "per_page", "=", "20", ",", "order_by", "=", ":created_at", ",", "order_dir", "=", ":desc", ",", "include_finished", "=", "0", ",", "all", "=", "false", ")", "params", "=", "{", ":page", "=>", "page", ",", ":per_page", "=>", "per_page", ",", ":order_by", "=>", "order_by", ",", ":order_dir", "=>", "order_dir", ",", ":include_finished", "=>", "include_finished", ",", ":all", "=>", "all", "}", "DataSift", ".", "request", "(", ":GET", ",", "'push/get'", ",", "@config", ",", "params", ")", "end" ]
Get details of all subscriptions within the given page constraints @param page [Integer] Which page of logs to retreive @param per_page [Integer] How many logs to return per page @param order_by [String, Symbol] Which field to sort results by @param order_dir [String, Symbol] Order results in ascending or descending @param include_finished [Integer] Include Push subscriptions in a 'finished' state in your results @param all [Boolean] Also include Push subscriptions created via the web UI in your results
[ "Get", "details", "of", "all", "subscriptions", "within", "the", "given", "page", "constraints" ]
d724e4ff15d178f196001ea5a517a981dc56c18c
https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/push.rb#L183-L193
train
datasift/datasift-ruby
lib/push.rb
DataSift.Push.pull
def pull(id, size = 52_428_800, cursor = '', callback = nil) params = { :id => id } requires params params.merge!( :size => size, :cursor => cursor ) params.merge!({:on_interaction => callback}) unless callback.nil? DataSift.request(:GET, 'pull', @config, params, {}, 30, 30, true) end
ruby
def pull(id, size = 52_428_800, cursor = '', callback = nil) params = { :id => id } requires params params.merge!( :size => size, :cursor => cursor ) params.merge!({:on_interaction => callback}) unless callback.nil? DataSift.request(:GET, 'pull', @config, params, {}, 30, 30, true) end
[ "def", "pull", "(", "id", ",", "size", "=", "52_428_800", ",", "cursor", "=", "''", ",", "callback", "=", "nil", ")", "params", "=", "{", ":id", "=>", "id", "}", "requires", "params", "params", ".", "merge!", "(", ":size", "=>", "size", ",", ":cursor", "=>", "cursor", ")", "params", ".", "merge!", "(", "{", ":on_interaction", "=>", "callback", "}", ")", "unless", "callback", ".", "nil?", "DataSift", ".", "request", "(", ":GET", ",", "'pull'", ",", "@config", ",", "params", ",", "{", "}", ",", "30", ",", "30", ",", "true", ")", "end" ]
Pull data from a 'pull' type Push Subscription @param id [String] ID of the Push subscription to pull data from @param size [Integer] Max size (bytes) of the data that should be returned @param cursor [String] Point to a specific point in your Push buffer using a cursor @param callback [Method] Pass a callback to process each interaction returned from a successful pull request
[ "Pull", "data", "from", "a", "pull", "type", "Push", "Subscription" ]
d724e4ff15d178f196001ea5a517a981dc56c18c
https://github.com/datasift/datasift-ruby/blob/d724e4ff15d178f196001ea5a517a981dc56c18c/lib/push.rb#L203-L214
train
FTB-Gamepedia/MediaWiki-Butt-Ruby
lib/mediawiki/edit.rb
MediaWiki.Edit.edit
def edit(title, text, opts = {}) opts[:bot] = opts.key?(:bot) ? opts[:bot] : true params = { action: 'edit', title: title, text: text, nocreate: 1, format: 'json', token: get_token } params[:summary] ||= opts[:summary] params[:minor] = '1' if opts[:minor] params[:bot] = '1' if opts[:bot] response = post(params) if response.dig('edit', 'result') == 'Success' return false if response.dig('edit', 'nochange') return response.dig('edit', 'newrevid') end raise MediaWiki::Butt::EditError.new(response.dig('error', 'code') || 'Unknown error code') end
ruby
def edit(title, text, opts = {}) opts[:bot] = opts.key?(:bot) ? opts[:bot] : true params = { action: 'edit', title: title, text: text, nocreate: 1, format: 'json', token: get_token } params[:summary] ||= opts[:summary] params[:minor] = '1' if opts[:minor] params[:bot] = '1' if opts[:bot] response = post(params) if response.dig('edit', 'result') == 'Success' return false if response.dig('edit', 'nochange') return response.dig('edit', 'newrevid') end raise MediaWiki::Butt::EditError.new(response.dig('error', 'code') || 'Unknown error code') end
[ "def", "edit", "(", "title", ",", "text", ",", "opts", "=", "{", "}", ")", "opts", "[", ":bot", "]", "=", "opts", ".", "key?", "(", ":bot", ")", "?", "opts", "[", ":bot", "]", ":", "true", "params", "=", "{", "action", ":", "'edit'", ",", "title", ":", "title", ",", "text", ":", "text", ",", "nocreate", ":", "1", ",", "format", ":", "'json'", ",", "token", ":", "get_token", "}", "params", "[", ":summary", "]", "||=", "opts", "[", ":summary", "]", "params", "[", ":minor", "]", "=", "'1'", "if", "opts", "[", ":minor", "]", "params", "[", ":bot", "]", "=", "'1'", "if", "opts", "[", ":bot", "]", "response", "=", "post", "(", "params", ")", "if", "response", ".", "dig", "(", "'edit'", ",", "'result'", ")", "==", "'Success'", "return", "false", "if", "response", ".", "dig", "(", "'edit'", ",", "'nochange'", ")", "return", "response", ".", "dig", "(", "'edit'", ",", "'newrevid'", ")", "end", "raise", "MediaWiki", "::", "Butt", "::", "EditError", ".", "new", "(", "response", ".", "dig", "(", "'error'", ",", "'code'", ")", "||", "'Unknown error code'", ")", "end" ]
Performs a standard non-creation edit. @param title [String] The page title. @param text [String] The new content. @param opts [Hash<Symbol, Any>] The options hash for optional values in the request. @option opts [Boolean] :minor Will mark the edit as minor if true. @option opts [Boolean] :bot Will mark the edit as bot edit if true. Defaults to true. @option opts [String] :summary The edit summary. Optional. @see https://www.mediawiki.org/wiki/API:Changing_wiki_content Changing wiki content on the MediaWiki API documentation @see https://www.mediawiki.org/wiki/API:Edit MediaWiki Edit API Docs @since 0.2.0 @raise [EditError] if the edit failed somehow @return [String] The new revision ID @return [Boolean] False if there was no change in the edit.
[ "Performs", "a", "standard", "non", "-", "creation", "edit", "." ]
d71c5dfdf9d349d025e1c3534286ce116777eaa4
https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/edit.rb#L19-L42
train
FTB-Gamepedia/MediaWiki-Butt-Ruby
lib/mediawiki/edit.rb
MediaWiki.Edit.create_page
def create_page(title, text, opts = {}) opts[:bot] = opts.key?(:bot) ? opts[:bot] : true opts[:summary] ||= 'New page' params = { action: 'edit', title: title, text: text, summary: opts[:summary], createonly: 1, format: 'json', token: get_token } params[:bot] = '1' if opts[:bot] response = post(params) return response['edit']['pageid'] if response.dig('edit', 'result') == 'Success' raise MediaWiki::Butt::EditError.new(response.dig('error', 'code') || 'Unknown error code') end
ruby
def create_page(title, text, opts = {}) opts[:bot] = opts.key?(:bot) ? opts[:bot] : true opts[:summary] ||= 'New page' params = { action: 'edit', title: title, text: text, summary: opts[:summary], createonly: 1, format: 'json', token: get_token } params[:bot] = '1' if opts[:bot] response = post(params) return response['edit']['pageid'] if response.dig('edit', 'result') == 'Success' raise MediaWiki::Butt::EditError.new(response.dig('error', 'code') || 'Unknown error code') end
[ "def", "create_page", "(", "title", ",", "text", ",", "opts", "=", "{", "}", ")", "opts", "[", ":bot", "]", "=", "opts", ".", "key?", "(", ":bot", ")", "?", "opts", "[", ":bot", "]", ":", "true", "opts", "[", ":summary", "]", "||=", "'New page'", "params", "=", "{", "action", ":", "'edit'", ",", "title", ":", "title", ",", "text", ":", "text", ",", "summary", ":", "opts", "[", ":summary", "]", ",", "createonly", ":", "1", ",", "format", ":", "'json'", ",", "token", ":", "get_token", "}", "params", "[", ":bot", "]", "=", "'1'", "if", "opts", "[", ":bot", "]", "response", "=", "post", "(", "params", ")", "return", "response", "[", "'edit'", "]", "[", "'pageid'", "]", "if", "response", ".", "dig", "(", "'edit'", ",", "'result'", ")", "==", "'Success'", "raise", "MediaWiki", "::", "Butt", "::", "EditError", ".", "new", "(", "response", ".", "dig", "(", "'error'", ",", "'code'", ")", "||", "'Unknown error code'", ")", "end" ]
Creates a new page. @param title [String] The new page's title. @param text [String] The new page's content. @param opts [Hash<Symbol, Any>] The options hash for optional values in the request. @option opts [String] :summary The edit summary. Defaults to "New page". @option opts [Boolean] :bot Will mark the edit as a bot edit if true. Defaults to true. @see https://www.mediawiki.org/wiki/API:Changing_wiki_content Changing wiki content on the MediaWiki API documentation @see https://www.mediawiki.org/wiki/API:Edit MediaWiki Edit API Docs @since 0.3.0 @raise [EditError] If there was some error when creating the page. @return [String] The new page ID
[ "Creates", "a", "new", "page", "." ]
d71c5dfdf9d349d025e1c3534286ce116777eaa4
https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/edit.rb#L56-L75
train
FTB-Gamepedia/MediaWiki-Butt-Ruby
lib/mediawiki/edit.rb
MediaWiki.Edit.upload
def upload(url, filename = nil) params = { action: 'upload', url: url, token: get_token } filename = filename.nil? ? url.split('/')[-1] : filename.sub(/^File:/, '') ext = filename.split('.')[-1] allowed_extensions = get_allowed_file_extensions raise MediaWiki::Butt::UploadInvalidFileExtError.new unless allowed_extensions.include?(ext) params[:filename] = filename response = post(params) response.dig('upload', 'warnings')&.each do |warning| warn warning end return true if response.dig('upload', 'result') == 'Success' raise MediaWiki::Butt::EditError.new(response.dig('error', 'code') || 'Unknown error code') end
ruby
def upload(url, filename = nil) params = { action: 'upload', url: url, token: get_token } filename = filename.nil? ? url.split('/')[-1] : filename.sub(/^File:/, '') ext = filename.split('.')[-1] allowed_extensions = get_allowed_file_extensions raise MediaWiki::Butt::UploadInvalidFileExtError.new unless allowed_extensions.include?(ext) params[:filename] = filename response = post(params) response.dig('upload', 'warnings')&.each do |warning| warn warning end return true if response.dig('upload', 'result') == 'Success' raise MediaWiki::Butt::EditError.new(response.dig('error', 'code') || 'Unknown error code') end
[ "def", "upload", "(", "url", ",", "filename", "=", "nil", ")", "params", "=", "{", "action", ":", "'upload'", ",", "url", ":", "url", ",", "token", ":", "get_token", "}", "filename", "=", "filename", ".", "nil?", "?", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ":", "filename", ".", "sub", "(", "/", "/", ",", "''", ")", "ext", "=", "filename", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "allowed_extensions", "=", "get_allowed_file_extensions", "raise", "MediaWiki", "::", "Butt", "::", "UploadInvalidFileExtError", ".", "new", "unless", "allowed_extensions", ".", "include?", "(", "ext", ")", "params", "[", ":filename", "]", "=", "filename", "response", "=", "post", "(", "params", ")", "response", ".", "dig", "(", "'upload'", ",", "'warnings'", ")", "&.", "each", "do", "|", "warning", "|", "warn", "warning", "end", "return", "true", "if", "response", ".", "dig", "(", "'upload'", ",", "'result'", ")", "==", "'Success'", "raise", "MediaWiki", "::", "Butt", "::", "EditError", ".", "new", "(", "response", ".", "dig", "(", "'error'", ",", "'code'", ")", "||", "'Unknown error code'", ")", "end" ]
Uploads a file from a URL. @param url [String] The URL to the file. @param filename [String] The preferred filename. This can include File: at the beginning, but it will be removed through regex. Optional. If omitted, it will be everything after the last slash in the URL. @return [Boolean] Whether the upload was successful. It is likely that if it returns false, it also raised a warning. @raise [UploadInvalidFileExtError] When the file extension provided is not valid for the wiki. @raise [EditError] @see https://www.mediawiki.org/wiki/API:Changing_wiki_content Changing wiki content on the MediaWiki API documentation @see https://www.mediawiki.org/wiki/API:Upload MediaWiki Upload API Docs @since 0.3.0
[ "Uploads", "a", "file", "from", "a", "URL", "." ]
d71c5dfdf9d349d025e1c3534286ce116777eaa4
https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/edit.rb#L89-L112
train
FTB-Gamepedia/MediaWiki-Butt-Ruby
lib/mediawiki/edit.rb
MediaWiki.Edit.move
def move(from, to, opts = {}) opts[:talk] = opts.key?(:talk) ? opts[:talk] : true params = { action: 'move', from: from, to: to, token: get_token } params[:reason] ||= opts[:reason] params[:movetalk] = '1' if opts[:talk] params[:noredirect] = '1' if opts[:suppress_redirect] response = post(params) return true if response['move'] raise MediaWiki::Butt::EditError.new(response.dig('error', 'code') || 'Unknown error code') end
ruby
def move(from, to, opts = {}) opts[:talk] = opts.key?(:talk) ? opts[:talk] : true params = { action: 'move', from: from, to: to, token: get_token } params[:reason] ||= opts[:reason] params[:movetalk] = '1' if opts[:talk] params[:noredirect] = '1' if opts[:suppress_redirect] response = post(params) return true if response['move'] raise MediaWiki::Butt::EditError.new(response.dig('error', 'code') || 'Unknown error code') end
[ "def", "move", "(", "from", ",", "to", ",", "opts", "=", "{", "}", ")", "opts", "[", ":talk", "]", "=", "opts", ".", "key?", "(", ":talk", ")", "?", "opts", "[", ":talk", "]", ":", "true", "params", "=", "{", "action", ":", "'move'", ",", "from", ":", "from", ",", "to", ":", "to", ",", "token", ":", "get_token", "}", "params", "[", ":reason", "]", "||=", "opts", "[", ":reason", "]", "params", "[", ":movetalk", "]", "=", "'1'", "if", "opts", "[", ":talk", "]", "params", "[", ":noredirect", "]", "=", "'1'", "if", "opts", "[", ":suppress_redirect", "]", "response", "=", "post", "(", "params", ")", "return", "true", "if", "response", "[", "'move'", "]", "raise", "MediaWiki", "::", "Butt", "::", "EditError", ".", "new", "(", "response", ".", "dig", "(", "'error'", ",", "'code'", ")", "||", "'Unknown error code'", ")", "end" ]
Performs a move on a page. @param from [String] The page to be moved. @param to [String] The destination of the move. @param opts [Hash<Symbol, Any>] The options hash for optional values in the request. @option opts [String] :reason The reason for the move, which shows up in the log. @option opts [Boolean] :talk Whether to move the associated talk page. Defaults to true. @option opts [Boolean] :suppress_redirect Set to a truthy value in order to prevent the API from making a redirect page. @see https://www.mediawiki.org/wiki/API:Changing_wiki_content Changing wiki content on the MediaWiki API documentation @see https://www.mediawiki.org/wiki/API:Move MediaWiki Move API Docs @since 0.5.0 @raise [EditError] @return [Boolean] True if it was successful.
[ "Performs", "a", "move", "on", "a", "page", "." ]
d71c5dfdf9d349d025e1c3534286ce116777eaa4
https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/edit.rb#L128-L145
train
FTB-Gamepedia/MediaWiki-Butt-Ruby
lib/mediawiki/edit.rb
MediaWiki.Edit.delete
def delete(title, reason = nil) params = { action: 'delete', title: title, token: get_token } params[:reason] = reason unless reason.nil? response = post(params) return true if response['delete'] raise MediaWiki::Butt::EditError.new(response.dig('error', 'code') || 'Unknown error code') end
ruby
def delete(title, reason = nil) params = { action: 'delete', title: title, token: get_token } params[:reason] = reason unless reason.nil? response = post(params) return true if response['delete'] raise MediaWiki::Butt::EditError.new(response.dig('error', 'code') || 'Unknown error code') end
[ "def", "delete", "(", "title", ",", "reason", "=", "nil", ")", "params", "=", "{", "action", ":", "'delete'", ",", "title", ":", "title", ",", "token", ":", "get_token", "}", "params", "[", ":reason", "]", "=", "reason", "unless", "reason", ".", "nil?", "response", "=", "post", "(", "params", ")", "return", "true", "if", "response", "[", "'delete'", "]", "raise", "MediaWiki", "::", "Butt", "::", "EditError", ".", "new", "(", "response", ".", "dig", "(", "'error'", ",", "'code'", ")", "||", "'Unknown error code'", ")", "end" ]
Deletes a page. @param title [String] The page to delete. @param reason [String] The reason to be displayed in logs. Optional. @see https://www.mediawiki.org/wiki/API:Changing_wiki_content Changing wiki content on the MediaWiki API documentation @see https://www.mediawiki.org/wiki/API:Delete MediaWiki Delete API Docs @since 0.5.0 @raise [EditError] @return [Boolean] True if successful.
[ "Deletes", "a", "page", "." ]
d71c5dfdf9d349d025e1c3534286ce116777eaa4
https://github.com/FTB-Gamepedia/MediaWiki-Butt-Ruby/blob/d71c5dfdf9d349d025e1c3534286ce116777eaa4/lib/mediawiki/edit.rb#L156-L168
train
middlemac/middleman-targets
lib/middleman-targets/middleman-cli/list_all.rb
Middleman::Cli.ListAll.list_all
def list_all # Determine the valid targets. app = ::Middleman::Application.new do config[:exit_before_ready] = true end app_config = app.config.clone app.shutdown! # Because after_configuration won't run again until we # build, we'll fake the strings with the one given for # the default. So for each target, gsub the target for # the initial target already given in config. app_config[:targets].each do |target| target_org = app_config[:target].to_s target_req = target[0].to_s path_org = app_config[:build_dir] path_req = path_org.reverse.sub(target_org.reverse, target_req.reverse).reverse say "#{target_req}, #{File.expand_path(path_req)}", :cyan end end
ruby
def list_all # Determine the valid targets. app = ::Middleman::Application.new do config[:exit_before_ready] = true end app_config = app.config.clone app.shutdown! # Because after_configuration won't run again until we # build, we'll fake the strings with the one given for # the default. So for each target, gsub the target for # the initial target already given in config. app_config[:targets].each do |target| target_org = app_config[:target].to_s target_req = target[0].to_s path_org = app_config[:build_dir] path_req = path_org.reverse.sub(target_org.reverse, target_req.reverse).reverse say "#{target_req}, #{File.expand_path(path_req)}", :cyan end end
[ "def", "list_all", "app", "=", "::", "Middleman", "::", "Application", ".", "new", "do", "config", "[", ":exit_before_ready", "]", "=", "true", "end", "app_config", "=", "app", ".", "config", ".", "clone", "app", ".", "shutdown!", "app_config", "[", ":targets", "]", ".", "each", "do", "|", "target", "|", "target_org", "=", "app_config", "[", ":target", "]", ".", "to_s", "target_req", "=", "target", "[", "0", "]", ".", "to_s", "path_org", "=", "app_config", "[", ":build_dir", "]", "path_req", "=", "path_org", ".", "reverse", ".", "sub", "(", "target_org", ".", "reverse", ",", "target_req", ".", "reverse", ")", ".", "reverse", "say", "\"#{target_req}, #{File.expand_path(path_req)}\"", ",", ":cyan", "end", "end" ]
List all targets. @return [Void]
[ "List", "all", "targets", "." ]
ebba3fa304e6325724e63b100c396dac0e2d5328
https://github.com/middlemac/middleman-targets/blob/ebba3fa304e6325724e63b100c396dac0e2d5328/lib/middleman-targets/middleman-cli/list_all.rb#L20-L39
train
hlxwell/mail-engine
lib/mail_engine/action_mailer_patch.rb
ActionMailer.Base.render_with_layout_and_partials
def render_with_layout_and_partials(format) # looking for system mail. template = MailEngine::MailTemplate.where(:path => "#{controller_path}/#{action_name}", :format => format, :locale => I18n.locale, :partial => false, :for_marketing => false).first # looking for marketing mail. template = MailEngine::MailTemplate.where(:path => action_name, :format => format, :locale => I18n.locale, :partial => false, :for_marketing => true).first if template.blank? # if found db template set the layout and partial for it. if template related_partial_paths = {} # set @footer or @header template.template_partials.each do |tmp| related_partial_paths["#{tmp.placeholder_name}_path".to_sym] = tmp.partial.path end # set layout render :template => "#{controller_path}/#{action_name}", :layout => "layouts/mail_engine/mail_template_layouts/#{template.layout}", :locals => related_partial_paths else # if not found db template should render file template render(action_name) end end
ruby
def render_with_layout_and_partials(format) # looking for system mail. template = MailEngine::MailTemplate.where(:path => "#{controller_path}/#{action_name}", :format => format, :locale => I18n.locale, :partial => false, :for_marketing => false).first # looking for marketing mail. template = MailEngine::MailTemplate.where(:path => action_name, :format => format, :locale => I18n.locale, :partial => false, :for_marketing => true).first if template.blank? # if found db template set the layout and partial for it. if template related_partial_paths = {} # set @footer or @header template.template_partials.each do |tmp| related_partial_paths["#{tmp.placeholder_name}_path".to_sym] = tmp.partial.path end # set layout render :template => "#{controller_path}/#{action_name}", :layout => "layouts/mail_engine/mail_template_layouts/#{template.layout}", :locals => related_partial_paths else # if not found db template should render file template render(action_name) end end
[ "def", "render_with_layout_and_partials", "(", "format", ")", "template", "=", "MailEngine", "::", "MailTemplate", ".", "where", "(", ":path", "=>", "\"#{controller_path}/#{action_name}\"", ",", ":format", "=>", "format", ",", ":locale", "=>", "I18n", ".", "locale", ",", ":partial", "=>", "false", ",", ":for_marketing", "=>", "false", ")", ".", "first", "template", "=", "MailEngine", "::", "MailTemplate", ".", "where", "(", ":path", "=>", "action_name", ",", ":format", "=>", "format", ",", ":locale", "=>", "I18n", ".", "locale", ",", ":partial", "=>", "false", ",", ":for_marketing", "=>", "true", ")", ".", "first", "if", "template", ".", "blank?", "if", "template", "related_partial_paths", "=", "{", "}", "template", ".", "template_partials", ".", "each", "do", "|", "tmp", "|", "related_partial_paths", "[", "\"#{tmp.placeholder_name}_path\"", ".", "to_sym", "]", "=", "tmp", ".", "partial", ".", "path", "end", "render", ":template", "=>", "\"#{controller_path}/#{action_name}\"", ",", ":layout", "=>", "\"layouts/mail_engine/mail_template_layouts/#{template.layout}\"", ",", ":locals", "=>", "related_partial_paths", "else", "render", "(", "action_name", ")", "end", "end" ]
render template with layout and partials
[ "render", "template", "with", "layout", "and", "partials" ]
1c9f42ca1cb86c66789ff22fe4709e05d507b118
https://github.com/hlxwell/mail-engine/blob/1c9f42ca1cb86c66789ff22fe4709e05d507b118/lib/mail_engine/action_mailer_patch.rb#L75-L95
train
mnyrop/diane
lib/diane/recorder.rb
Diane.Recorder.record
def record if File.exist? DIFILE CSV.open(DIFILE, 'a') { |csv| csv << [@user, @message, @time] } else CSV.open(DIFILE, 'a') do |csv| csv << %w[user message time] csv << [@user, @message, @time] end end puts '✓'.green rescue StandardError => e abort 'Broken'.magenta + e end
ruby
def record if File.exist? DIFILE CSV.open(DIFILE, 'a') { |csv| csv << [@user, @message, @time] } else CSV.open(DIFILE, 'a') do |csv| csv << %w[user message time] csv << [@user, @message, @time] end end puts '✓'.green rescue StandardError => e abort 'Broken'.magenta + e end
[ "def", "record", "if", "File", ".", "exist?", "DIFILE", "CSV", ".", "open", "(", "DIFILE", ",", "'a'", ")", "{", "|", "csv", "|", "csv", "<<", "[", "@user", ",", "@message", ",", "@time", "]", "}", "else", "CSV", ".", "open", "(", "DIFILE", ",", "'a'", ")", "do", "|", "csv", "|", "csv", "<<", "%w[", "user", "message", "time", "]", "csv", "<<", "[", "@user", ",", "@message", ",", "@time", "]", "end", "end", "puts", "'✓'.g", "r", "een", "rescue", "StandardError", "=>", "e", "abort", "'Broken'", ".", "magenta", "+", "e", "end" ]
generates new recording as csv row to new or existing DIANE file
[ "generates", "new", "recording", "as", "csv", "row", "to", "new", "or", "existing", "DIANE", "file" ]
be98ff41b8e3c8b21a4a8548e9fba4007e64fc91
https://github.com/mnyrop/diane/blob/be98ff41b8e3c8b21a4a8548e9fba4007e64fc91/lib/diane/recorder.rb#L17-L29
train
mnyrop/diane
lib/diane/recorder.rb
Diane.Recorder.slug
def slug(user) abort 'User is nil. Fuck off.'.magenta if user.nil? user.downcase.strip.tr(' ', '_').gsub(/[^\w-]/, '') end
ruby
def slug(user) abort 'User is nil. Fuck off.'.magenta if user.nil? user.downcase.strip.tr(' ', '_').gsub(/[^\w-]/, '') end
[ "def", "slug", "(", "user", ")", "abort", "'User is nil. Fuck off.'", ".", "magenta", "if", "user", ".", "nil?", "user", ".", "downcase", ".", "strip", ".", "tr", "(", "' '", ",", "'_'", ")", ".", "gsub", "(", "/", "\\w", "/", ",", "''", ")", "end" ]
normalizes and slugifies recording user handle
[ "normalizes", "and", "slugifies", "recording", "user", "handle" ]
be98ff41b8e3c8b21a4a8548e9fba4007e64fc91
https://github.com/mnyrop/diane/blob/be98ff41b8e3c8b21a4a8548e9fba4007e64fc91/lib/diane/recorder.rb#L33-L36
train
jonathanchrisp/fredapi
lib/fredapi/connection.rb
FREDAPI.Connection.connection
def connection opts={} connection = Faraday.new(opts) do |conn| if opts[:force_urlencoded] conn.request :url_encoded else conn.request :json end conn.request :json conn.use FaradayMiddleware::FollowRedirects conn.use FaradayMiddleware::Mashify conn.use FaradayMiddleware::ParseJson, :content_type => /\bjson$/ conn.use FaradayMiddleware::ParseXml, :content_type => /\bxml$/ conn.adapter adapter end connection.headers[:user_agent] = user_agent connection end
ruby
def connection opts={} connection = Faraday.new(opts) do |conn| if opts[:force_urlencoded] conn.request :url_encoded else conn.request :json end conn.request :json conn.use FaradayMiddleware::FollowRedirects conn.use FaradayMiddleware::Mashify conn.use FaradayMiddleware::ParseJson, :content_type => /\bjson$/ conn.use FaradayMiddleware::ParseXml, :content_type => /\bxml$/ conn.adapter adapter end connection.headers[:user_agent] = user_agent connection end
[ "def", "connection", "opts", "=", "{", "}", "connection", "=", "Faraday", ".", "new", "(", "opts", ")", "do", "|", "conn", "|", "if", "opts", "[", ":force_urlencoded", "]", "conn", ".", "request", ":url_encoded", "else", "conn", ".", "request", ":json", "end", "conn", ".", "request", ":json", "conn", ".", "use", "FaradayMiddleware", "::", "FollowRedirects", "conn", ".", "use", "FaradayMiddleware", "::", "Mashify", "conn", ".", "use", "FaradayMiddleware", "::", "ParseJson", ",", ":content_type", "=>", "/", "\\b", "/", "conn", ".", "use", "FaradayMiddleware", "::", "ParseXml", ",", ":content_type", "=>", "/", "\\b", "/", "conn", ".", "adapter", "adapter", "end", "connection", ".", "headers", "[", ":user_agent", "]", "=", "user_agent", "connection", "end" ]
Create a connection to send request
[ "Create", "a", "connection", "to", "send", "request" ]
8eda87f0732d6c8b909c61fc0e260cd6848dbee3
https://github.com/jonathanchrisp/fredapi/blob/8eda87f0732d6c8b909c61fc0e260cd6848dbee3/lib/fredapi/connection.rb#L10-L29
train
emmanuel/aequitas
lib/aequitas/violation.rb
Aequitas.Violation.message
def message(transformer = Undefined) return @custom_message if @custom_message transformer = self.transformer if Undefined.equal?(transformer) transformer.transform(self) end
ruby
def message(transformer = Undefined) return @custom_message if @custom_message transformer = self.transformer if Undefined.equal?(transformer) transformer.transform(self) end
[ "def", "message", "(", "transformer", "=", "Undefined", ")", "return", "@custom_message", "if", "@custom_message", "transformer", "=", "self", ".", "transformer", "if", "Undefined", ".", "equal?", "(", "transformer", ")", "transformer", ".", "transform", "(", "self", ")", "end" ]
Configure a Violation instance @param [Object] resource the validated object @param [String, #call, Hash] message an optional custom message for this Violation @param [Hash] options options hash for configuring concrete subclasses @api public @api public
[ "Configure", "a", "Violation", "instance" ]
984f16a1db12e88c8e9a4a3605896b295e285a6b
https://github.com/emmanuel/aequitas/blob/984f16a1db12e88c8e9a4a3605896b295e285a6b/lib/aequitas/violation.rb#L62-L68
train
dotboris/eldritch
lib/eldritch/dsl.rb
Eldritch.DSL.together
def together old = Thread.current.eldritch_group group = Group.new Thread.current.eldritch_group = group yield group group.join_all Thread.current.eldritch_group = old end
ruby
def together old = Thread.current.eldritch_group group = Group.new Thread.current.eldritch_group = group yield group group.join_all Thread.current.eldritch_group = old end
[ "def", "together", "old", "=", "Thread", ".", "current", ".", "eldritch_group", "group", "=", "Group", ".", "new", "Thread", ".", "current", ".", "eldritch_group", "=", "group", "yield", "group", "group", ".", "join_all", "Thread", ".", "current", ".", "eldritch_group", "=", "old", "end" ]
Creates a group of async call and blocks When async blocks and calls are inside a together block, they can act as a group. A together block waits for all the async call/blocks that were started within itself to stop before continuing. together do 5.times do async { sleep(1) } end end # waits for all 5 async blocks to complete A together block will also yield a {Group}. This can be used to interact with the other async calls/blocks. together do |group| 5.times do async do # stop everyone else group.interrupt if something? end end end @yield [Group] group of async blocks/calls @see Group Group class
[ "Creates", "a", "group", "of", "async", "call", "and", "blocks" ]
799402a54b1bff85dfe8d314ec63fb6c0d341ba2
https://github.com/dotboris/eldritch/blob/799402a54b1bff85dfe8d314ec63fb6c0d341ba2/lib/eldritch/dsl.rb#L82-L92
train
LoyaltyNZ/alchemy-flux
lib/alchemy-flux.rb
AlchemyFlux.Service.start
def start return if @state != :stopped Service.start(@options[:ampq_uri], @options[:threadpool_size]) EM.run do @channel = AMQP::Channel.new(@@connection) @channel.on_error do |ch, channel_close| message = "Channel exception: [#{channel_close.reply_code}] #{channel_close.reply_text}" puts message raise message end @channel.prefetch(@options[:prefetch]) @channel.auto_recovery = true @service_queue = @channel.queue( @service_queue_name, {:durable => true}) @service_queue.subscribe({:ack => true}) do |metadata, payload| payload = JSON.parse(payload) process_service_queue_message(metadata, payload) end response_queue = @channel.queue(@response_queue_name, {:exclusive => true, :auto_delete => true}) response_queue.subscribe({}) do |metadata, payload| payload = JSON.parse(payload) process_response_queue_message(metadata, payload) end @channel.default_exchange.on_return do |basic_return, frame, payload| payload = JSON.parse(payload) process_returned_message(basic_return, frame.properties, payload) end # RESOURCES HANDLE @resources_exchange = @channel.topic("resources.exchange", {:durable => true}) @resources_exchange.on_return do |basic_return, frame, payload| payload = JSON.parse(payload) process_returned_message(basic_return, frame.properties, payload) end bound_resources = 0 for resource_path in @options[:resource_paths] binding_key = "#{path_to_routing_key(resource_path)}.#" @service_queue.bind(@resources_exchange, :key => binding_key) { bound_resources += 1 } end begin # simple loop to wait for the resources to be bound sleep(0.01) end until bound_resources == @options[:resource_paths].length @state = :started end end
ruby
def start return if @state != :stopped Service.start(@options[:ampq_uri], @options[:threadpool_size]) EM.run do @channel = AMQP::Channel.new(@@connection) @channel.on_error do |ch, channel_close| message = "Channel exception: [#{channel_close.reply_code}] #{channel_close.reply_text}" puts message raise message end @channel.prefetch(@options[:prefetch]) @channel.auto_recovery = true @service_queue = @channel.queue( @service_queue_name, {:durable => true}) @service_queue.subscribe({:ack => true}) do |metadata, payload| payload = JSON.parse(payload) process_service_queue_message(metadata, payload) end response_queue = @channel.queue(@response_queue_name, {:exclusive => true, :auto_delete => true}) response_queue.subscribe({}) do |metadata, payload| payload = JSON.parse(payload) process_response_queue_message(metadata, payload) end @channel.default_exchange.on_return do |basic_return, frame, payload| payload = JSON.parse(payload) process_returned_message(basic_return, frame.properties, payload) end # RESOURCES HANDLE @resources_exchange = @channel.topic("resources.exchange", {:durable => true}) @resources_exchange.on_return do |basic_return, frame, payload| payload = JSON.parse(payload) process_returned_message(basic_return, frame.properties, payload) end bound_resources = 0 for resource_path in @options[:resource_paths] binding_key = "#{path_to_routing_key(resource_path)}.#" @service_queue.bind(@resources_exchange, :key => binding_key) { bound_resources += 1 } end begin # simple loop to wait for the resources to be bound sleep(0.01) end until bound_resources == @options[:resource_paths].length @state = :started end end
[ "def", "start", "return", "if", "@state", "!=", ":stopped", "Service", ".", "start", "(", "@options", "[", ":ampq_uri", "]", ",", "@options", "[", ":threadpool_size", "]", ")", "EM", ".", "run", "do", "@channel", "=", "AMQP", "::", "Channel", ".", "new", "(", "@@connection", ")", "@channel", ".", "on_error", "do", "|", "ch", ",", "channel_close", "|", "message", "=", "\"Channel exception: [#{channel_close.reply_code}] #{channel_close.reply_text}\"", "puts", "message", "raise", "message", "end", "@channel", ".", "prefetch", "(", "@options", "[", ":prefetch", "]", ")", "@channel", ".", "auto_recovery", "=", "true", "@service_queue", "=", "@channel", ".", "queue", "(", "@service_queue_name", ",", "{", ":durable", "=>", "true", "}", ")", "@service_queue", ".", "subscribe", "(", "{", ":ack", "=>", "true", "}", ")", "do", "|", "metadata", ",", "payload", "|", "payload", "=", "JSON", ".", "parse", "(", "payload", ")", "process_service_queue_message", "(", "metadata", ",", "payload", ")", "end", "response_queue", "=", "@channel", ".", "queue", "(", "@response_queue_name", ",", "{", ":exclusive", "=>", "true", ",", ":auto_delete", "=>", "true", "}", ")", "response_queue", ".", "subscribe", "(", "{", "}", ")", "do", "|", "metadata", ",", "payload", "|", "payload", "=", "JSON", ".", "parse", "(", "payload", ")", "process_response_queue_message", "(", "metadata", ",", "payload", ")", "end", "@channel", ".", "default_exchange", ".", "on_return", "do", "|", "basic_return", ",", "frame", ",", "payload", "|", "payload", "=", "JSON", ".", "parse", "(", "payload", ")", "process_returned_message", "(", "basic_return", ",", "frame", ".", "properties", ",", "payload", ")", "end", "@resources_exchange", "=", "@channel", ".", "topic", "(", "\"resources.exchange\"", ",", "{", ":durable", "=>", "true", "}", ")", "@resources_exchange", ".", "on_return", "do", "|", "basic_return", ",", "frame", ",", "payload", "|", "payload", "=", "JSON", ".", "parse", "(", "payload", ")", "process_returned_message", "(", "basic_return", ",", "frame", ".", "properties", ",", "payload", ")", "end", "bound_resources", "=", "0", "for", "resource_path", "in", "@options", "[", ":resource_paths", "]", "binding_key", "=", "\"#{path_to_routing_key(resource_path)}.#\"", "@service_queue", ".", "bind", "(", "@resources_exchange", ",", ":key", "=>", "binding_key", ")", "{", "bound_resources", "+=", "1", "}", "end", "begin", "sleep", "(", "0.01", ")", "end", "until", "bound_resources", "==", "@options", "[", ":resource_paths", "]", ".", "length", "@state", "=", ":started", "end", "end" ]
start the service
[ "start", "the", "service" ]
3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120
https://github.com/LoyaltyNZ/alchemy-flux/blob/3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120/lib/alchemy-flux.rb#L125-L180
train
LoyaltyNZ/alchemy-flux
lib/alchemy-flux.rb
AlchemyFlux.Service.stop
def stop return if @state != :started # stop receiving new incoming messages @service_queue.unsubscribe # only stop the service if all incoming and outgoing messages are complete decisecond_timeout = @options[:timeout]/100 waited_deciseconds = 0 # guarantee that this loop will stop while (@transactions.length > 0 || @processing_messages > 0) && waited_deciseconds < decisecond_timeout sleep(0.1) # wait a decisecond to check the incoming and outgoing messages again waited_deciseconds += 1 end @channel.close @state = :stopped end
ruby
def stop return if @state != :started # stop receiving new incoming messages @service_queue.unsubscribe # only stop the service if all incoming and outgoing messages are complete decisecond_timeout = @options[:timeout]/100 waited_deciseconds = 0 # guarantee that this loop will stop while (@transactions.length > 0 || @processing_messages > 0) && waited_deciseconds < decisecond_timeout sleep(0.1) # wait a decisecond to check the incoming and outgoing messages again waited_deciseconds += 1 end @channel.close @state = :stopped end
[ "def", "stop", "return", "if", "@state", "!=", ":started", "@service_queue", ".", "unsubscribe", "decisecond_timeout", "=", "@options", "[", ":timeout", "]", "/", "100", "waited_deciseconds", "=", "0", "while", "(", "@transactions", ".", "length", ">", "0", "||", "@processing_messages", ">", "0", ")", "&&", "waited_deciseconds", "<", "decisecond_timeout", "sleep", "(", "0.1", ")", "waited_deciseconds", "+=", "1", "end", "@channel", ".", "close", "@state", "=", ":stopped", "end" ]
Stop the Service This method: * Stops receiving new messages * waits for processing incoming and outgoing messages to be completed * close the channel
[ "Stop", "the", "Service" ]
3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120
https://github.com/LoyaltyNZ/alchemy-flux/blob/3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120/lib/alchemy-flux.rb#L188-L202
train
LoyaltyNZ/alchemy-flux
lib/alchemy-flux.rb
AlchemyFlux.Service.process_service_queue_message
def process_service_queue_message(metadata, payload) service_to_reply_to = metadata.reply_to message_replying_to = metadata.message_id this_message_id = AlchemyFlux::Service.generateUUID() delivery_tag = metadata.delivery_tag operation = proc { @processing_messages += 1 begin response = @service_fn.call(payload) { 'status_code' => response['status_code'] || 200, 'body' => response['body'] || "", 'headers' => response['headers'] || {} } rescue AlchemyFlux::NAckError => e AlchemyFlux::NAckError rescue Exception => e e end } callback = proc { |result| if result == AlchemyFlux::NAckError @service_queue.reject(delivery_tag) elsif result.is_a?(Exception) # if there is an unhandled exception from the service, # raise it to force exit and container management can spin up a new one raise result else #if there is a service to reply to then reply, else ignore if service_to_reply_to send_message(@channel.default_exchange, service_to_reply_to, result, { :message_id => this_message_id, :correlation_id => message_replying_to, :type => 'http_response' }) end @processing_messages -= 1 @service_queue.acknowledge(delivery_tag) end } EventMachine.defer(operation, callback) end
ruby
def process_service_queue_message(metadata, payload) service_to_reply_to = metadata.reply_to message_replying_to = metadata.message_id this_message_id = AlchemyFlux::Service.generateUUID() delivery_tag = metadata.delivery_tag operation = proc { @processing_messages += 1 begin response = @service_fn.call(payload) { 'status_code' => response['status_code'] || 200, 'body' => response['body'] || "", 'headers' => response['headers'] || {} } rescue AlchemyFlux::NAckError => e AlchemyFlux::NAckError rescue Exception => e e end } callback = proc { |result| if result == AlchemyFlux::NAckError @service_queue.reject(delivery_tag) elsif result.is_a?(Exception) # if there is an unhandled exception from the service, # raise it to force exit and container management can spin up a new one raise result else #if there is a service to reply to then reply, else ignore if service_to_reply_to send_message(@channel.default_exchange, service_to_reply_to, result, { :message_id => this_message_id, :correlation_id => message_replying_to, :type => 'http_response' }) end @processing_messages -= 1 @service_queue.acknowledge(delivery_tag) end } EventMachine.defer(operation, callback) end
[ "def", "process_service_queue_message", "(", "metadata", ",", "payload", ")", "service_to_reply_to", "=", "metadata", ".", "reply_to", "message_replying_to", "=", "metadata", ".", "message_id", "this_message_id", "=", "AlchemyFlux", "::", "Service", ".", "generateUUID", "(", ")", "delivery_tag", "=", "metadata", ".", "delivery_tag", "operation", "=", "proc", "{", "@processing_messages", "+=", "1", "begin", "response", "=", "@service_fn", ".", "call", "(", "payload", ")", "{", "'status_code'", "=>", "response", "[", "'status_code'", "]", "||", "200", ",", "'body'", "=>", "response", "[", "'body'", "]", "||", "\"\"", ",", "'headers'", "=>", "response", "[", "'headers'", "]", "||", "{", "}", "}", "rescue", "AlchemyFlux", "::", "NAckError", "=>", "e", "AlchemyFlux", "::", "NAckError", "rescue", "Exception", "=>", "e", "e", "end", "}", "callback", "=", "proc", "{", "|", "result", "|", "if", "result", "==", "AlchemyFlux", "::", "NAckError", "@service_queue", ".", "reject", "(", "delivery_tag", ")", "elsif", "result", ".", "is_a?", "(", "Exception", ")", "raise", "result", "else", "if", "service_to_reply_to", "send_message", "(", "@channel", ".", "default_exchange", ",", "service_to_reply_to", ",", "result", ",", "{", ":message_id", "=>", "this_message_id", ",", ":correlation_id", "=>", "message_replying_to", ",", ":type", "=>", "'http_response'", "}", ")", "end", "@processing_messages", "-=", "1", "@service_queue", ".", "acknowledge", "(", "delivery_tag", ")", "end", "}", "EventMachine", ".", "defer", "(", "operation", ",", "callback", ")", "end" ]
RECIEVING MESSAGES process messages on the service queue
[ "RECIEVING", "MESSAGES", "process", "messages", "on", "the", "service", "queue" ]
3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120
https://github.com/LoyaltyNZ/alchemy-flux/blob/3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120/lib/alchemy-flux.rb#L212-L260
train
LoyaltyNZ/alchemy-flux
lib/alchemy-flux.rb
AlchemyFlux.Service.process_response_queue_message
def process_response_queue_message(metadata, payload) response_queue = @transactions.delete metadata.correlation_id response_queue << payload if response_queue end
ruby
def process_response_queue_message(metadata, payload) response_queue = @transactions.delete metadata.correlation_id response_queue << payload if response_queue end
[ "def", "process_response_queue_message", "(", "metadata", ",", "payload", ")", "response_queue", "=", "@transactions", ".", "delete", "metadata", ".", "correlation_id", "response_queue", "<<", "payload", "if", "response_queue", "end" ]
process a response message If a message is put on this services response queue its response will be pushed onto the blocking queue
[ "process", "a", "response", "message" ]
3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120
https://github.com/LoyaltyNZ/alchemy-flux/blob/3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120/lib/alchemy-flux.rb#L266-L269
train
LoyaltyNZ/alchemy-flux
lib/alchemy-flux.rb
AlchemyFlux.Service.process_returned_message
def process_returned_message(basic_return, metadata, payload) response_queue = @transactions.delete metadata[:message_id] response_queue << MessageNotDeliveredError if response_queue end
ruby
def process_returned_message(basic_return, metadata, payload) response_queue = @transactions.delete metadata[:message_id] response_queue << MessageNotDeliveredError if response_queue end
[ "def", "process_returned_message", "(", "basic_return", ",", "metadata", ",", "payload", ")", "response_queue", "=", "@transactions", ".", "delete", "metadata", "[", ":message_id", "]", "response_queue", "<<", "MessageNotDeliveredError", "if", "response_queue", "end" ]
process a returned message If a message is sent to a queue that cannot be found, rabbitmq returns that message to this method
[ "process", "a", "returned", "message" ]
3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120
https://github.com/LoyaltyNZ/alchemy-flux/blob/3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120/lib/alchemy-flux.rb#L275-L278
train
LoyaltyNZ/alchemy-flux
lib/alchemy-flux.rb
AlchemyFlux.Service.send_message
def send_message(exchange, routing_key, message, options) message_options = options.merge({:routing_key => routing_key}) message = message.to_json EventMachine.next_tick do exchange.publish message, message_options end end
ruby
def send_message(exchange, routing_key, message, options) message_options = options.merge({:routing_key => routing_key}) message = message.to_json EventMachine.next_tick do exchange.publish message, message_options end end
[ "def", "send_message", "(", "exchange", ",", "routing_key", ",", "message", ",", "options", ")", "message_options", "=", "options", ".", "merge", "(", "{", ":routing_key", "=>", "routing_key", "}", ")", "message", "=", "message", ".", "to_json", "EventMachine", ".", "next_tick", "do", "exchange", ".", "publish", "message", ",", "message_options", "end", "end" ]
send a message to an exchange with routing key *exchange*:: A AMQP exchange *routing_key*:: The routing key to use *message*:: The message to be sent *options*:: The message options
[ "send", "a", "message", "to", "an", "exchange", "with", "routing", "key" ]
3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120
https://github.com/LoyaltyNZ/alchemy-flux/blob/3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120/lib/alchemy-flux.rb#L292-L298
train
LoyaltyNZ/alchemy-flux
lib/alchemy-flux.rb
AlchemyFlux.Service.send_request_to_service
def send_request_to_service(service_name, message) if block_given? EventMachine.defer do yield send_request_to_service(service_name, message) end else send_HTTP_request(@channel.default_exchange, service_name, message) end end
ruby
def send_request_to_service(service_name, message) if block_given? EventMachine.defer do yield send_request_to_service(service_name, message) end else send_HTTP_request(@channel.default_exchange, service_name, message) end end
[ "def", "send_request_to_service", "(", "service_name", ",", "message", ")", "if", "block_given?", "EventMachine", ".", "defer", "do", "yield", "send_request_to_service", "(", "service_name", ",", "message", ")", "end", "else", "send_HTTP_request", "(", "@channel", ".", "default_exchange", ",", "service_name", ",", "message", ")", "end", "end" ]
send a request to a service, this will wait for a response *service_name*:: the name of the service *message*:: the message to be sent This method can optionally take a block which will be executed asynchronously and yielded the response
[ "send", "a", "request", "to", "a", "service", "this", "will", "wait", "for", "a", "response" ]
3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120
https://github.com/LoyaltyNZ/alchemy-flux/blob/3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120/lib/alchemy-flux.rb#L324-L332
train
LoyaltyNZ/alchemy-flux
lib/alchemy-flux.rb
AlchemyFlux.Service.send_request_to_resource
def send_request_to_resource(message) routing_key = path_to_routing_key(message['path']) if block_given? EventMachine.defer do yield send_request_to_resource(message) end else send_HTTP_request(@resources_exchange, routing_key, message) end end
ruby
def send_request_to_resource(message) routing_key = path_to_routing_key(message['path']) if block_given? EventMachine.defer do yield send_request_to_resource(message) end else send_HTTP_request(@resources_exchange, routing_key, message) end end
[ "def", "send_request_to_resource", "(", "message", ")", "routing_key", "=", "path_to_routing_key", "(", "message", "[", "'path'", "]", ")", "if", "block_given?", "EventMachine", ".", "defer", "do", "yield", "send_request_to_resource", "(", "message", ")", "end", "else", "send_HTTP_request", "(", "@resources_exchange", ",", "routing_key", ",", "message", ")", "end", "end" ]
send a message to a resource *message*:: HTTP formatted message to be sent, must contain `'path'` key with URL path This method can optionally take a block which will be executed asynchronously and yielded the response
[ "send", "a", "message", "to", "a", "resource" ]
3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120
https://github.com/LoyaltyNZ/alchemy-flux/blob/3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120/lib/alchemy-flux.rb#L339-L348
train
LoyaltyNZ/alchemy-flux
lib/alchemy-flux.rb
AlchemyFlux.Service.path_to_routing_key
def path_to_routing_key(path) new_path = "" path.split('').each_with_index do |c,i| if c == '/' and i != 0 and i != path.length-1 new_path += '.' elsif c != '/' new_path += c end end new_path end
ruby
def path_to_routing_key(path) new_path = "" path.split('').each_with_index do |c,i| if c == '/' and i != 0 and i != path.length-1 new_path += '.' elsif c != '/' new_path += c end end new_path end
[ "def", "path_to_routing_key", "(", "path", ")", "new_path", "=", "\"\"", "path", ".", "split", "(", "''", ")", ".", "each_with_index", "do", "|", "c", ",", "i", "|", "if", "c", "==", "'/'", "and", "i", "!=", "0", "and", "i", "!=", "path", ".", "length", "-", "1", "new_path", "+=", "'.'", "elsif", "c", "!=", "'/'", "new_path", "+=", "c", "end", "end", "new_path", "end" ]
Takes a path and converts it into a routing key *path*:: path string For example, path '/test/path' will convert to routing key 'test.path'
[ "Takes", "a", "path", "and", "converts", "it", "into", "a", "routing", "key" ]
3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120
https://github.com/LoyaltyNZ/alchemy-flux/blob/3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120/lib/alchemy-flux.rb#L358-L368
train
LoyaltyNZ/alchemy-flux
lib/alchemy-flux.rb
AlchemyFlux.Service.format_HTTP_message
def format_HTTP_message(message) message = { # Request Parameters 'body' => message['body'] || "", 'verb' => message['verb'] || "GET", 'headers' => message['headers'] || {}, 'path' => message['path'] || "/", 'query' => message['query'] || {}, # Location 'scheme' => message['protocol'] || 'http', 'host' => message['hostname'] || '127.0.0.1', 'port' => message['port'] || 8080, # Custom Authentication 'session' => message['session'] } message end
ruby
def format_HTTP_message(message) message = { # Request Parameters 'body' => message['body'] || "", 'verb' => message['verb'] || "GET", 'headers' => message['headers'] || {}, 'path' => message['path'] || "/", 'query' => message['query'] || {}, # Location 'scheme' => message['protocol'] || 'http', 'host' => message['hostname'] || '127.0.0.1', 'port' => message['port'] || 8080, # Custom Authentication 'session' => message['session'] } message end
[ "def", "format_HTTP_message", "(", "message", ")", "message", "=", "{", "'body'", "=>", "message", "[", "'body'", "]", "||", "\"\"", ",", "'verb'", "=>", "message", "[", "'verb'", "]", "||", "\"GET\"", ",", "'headers'", "=>", "message", "[", "'headers'", "]", "||", "{", "}", ",", "'path'", "=>", "message", "[", "'path'", "]", "||", "\"/\"", ",", "'query'", "=>", "message", "[", "'query'", "]", "||", "{", "}", ",", "'scheme'", "=>", "message", "[", "'protocol'", "]", "||", "'http'", ",", "'host'", "=>", "message", "[", "'hostname'", "]", "||", "'127.0.0.1'", ",", "'port'", "=>", "message", "[", "'port'", "]", "||", "8080", ",", "'session'", "=>", "message", "[", "'session'", "]", "}", "message", "end" ]
format the HTTP message The entire body is a JSON string with the keys: Request Information: 1. *body*: A string of body information 2. *verb*: The HTTP verb for the query, e.g. GET 3. *headers*: an object with headers in is, e.g. {"X-HEADER-KEY": "value"} 4. *path*: the path of the request, e.g. "/v1/users/1337" 5. *query*: an object with keys for query, e.g. {'search': 'flux'} Call information: 1. *scheme*: the scheme used for the call 2. *host*: the host called to make the call 3. *port*: the port the call was made on Authentication information: 1. *session*: undefined structure that can be passed in the message so that a service does not need to re-authenticate with each message
[ "format", "the", "HTTP", "message" ]
3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120
https://github.com/LoyaltyNZ/alchemy-flux/blob/3f4a433c7241a642d3eb8e7bb5fb74d3c6d33120/lib/alchemy-flux.rb#L393-L412
train
benmcredmond/OhEmbedr
lib/ohembedr.rb
OhEmbedr.OhEmbedr.gets
def gets begin data = make_http_request @hash = send(@@formats[@format][:oembed_parser], data) # Call the method specified in default_formats hash above rescue RuntimeError => e if e.message == "401" # Embedding disabled return nil elsif e.message == "501" # Format not supported raise UnsupportedError, "#{@format} not supported by #{@domain}" elsif e.message == "404" # Not found raise Error, "#{@url} not found" else raise e end end end
ruby
def gets begin data = make_http_request @hash = send(@@formats[@format][:oembed_parser], data) # Call the method specified in default_formats hash above rescue RuntimeError => e if e.message == "401" # Embedding disabled return nil elsif e.message == "501" # Format not supported raise UnsupportedError, "#{@format} not supported by #{@domain}" elsif e.message == "404" # Not found raise Error, "#{@url} not found" else raise e end end end
[ "def", "gets", "begin", "data", "=", "make_http_request", "@hash", "=", "send", "(", "@@formats", "[", "@format", "]", "[", ":oembed_parser", "]", ",", "data", ")", "rescue", "RuntimeError", "=>", "e", "if", "e", ".", "message", "==", "\"401\"", "return", "nil", "elsif", "e", ".", "message", "==", "\"501\"", "raise", "UnsupportedError", ",", "\"#{@format} not supported by #{@domain}\"", "elsif", "e", ".", "message", "==", "\"404\"", "raise", "Error", ",", "\"#{@url} not found\"", "else", "raise", "e", "end", "end", "end" ]
Calling +gets+ returns a hash containing the oembed data.
[ "Calling", "+", "gets", "+", "returns", "a", "hash", "containing", "the", "oembed", "data", "." ]
4c657a35ea7c7b1f23c22a3d6f9b118d4f8d04e6
https://github.com/benmcredmond/OhEmbedr/blob/4c657a35ea7c7b1f23c22a3d6f9b118d4f8d04e6/lib/ohembedr.rb#L100-L118
train
benmcredmond/OhEmbedr
lib/ohembedr.rb
OhEmbedr.OhEmbedr.load_format
def load_format requested_format = nil raise ArgumentError, "Requested format not supported" if !requested_format.nil? && @@formats[requested_format].nil? @format = requested_format || @@default_format attempted_formats = "" begin attempted_formats += @@formats[@format][:require] require @@formats[@format][:require] return true rescue LoadError # If the user requested the format and it failed. Just give up! raise Error("Please install: '#{@@formats[@format][:require]}' to use #{@format} format.") unless requested_format.nil? # Otherwise lets exhaust all our other options first available_formats = @@formats available_formats.delete(@format) available_formats.each_key do |format| begin attempted_formats += ", " require @@formats[format][:require] @format = format return true rescue LoadError attempted_formats += @@formats[format][:require] end end raise Error, "Could not find any suitable library to parse response with, tried: #{attempted_formats}. Please install one of these to use OEmbed." end end
ruby
def load_format requested_format = nil raise ArgumentError, "Requested format not supported" if !requested_format.nil? && @@formats[requested_format].nil? @format = requested_format || @@default_format attempted_formats = "" begin attempted_formats += @@formats[@format][:require] require @@formats[@format][:require] return true rescue LoadError # If the user requested the format and it failed. Just give up! raise Error("Please install: '#{@@formats[@format][:require]}' to use #{@format} format.") unless requested_format.nil? # Otherwise lets exhaust all our other options first available_formats = @@formats available_formats.delete(@format) available_formats.each_key do |format| begin attempted_formats += ", " require @@formats[format][:require] @format = format return true rescue LoadError attempted_formats += @@formats[format][:require] end end raise Error, "Could not find any suitable library to parse response with, tried: #{attempted_formats}. Please install one of these to use OEmbed." end end
[ "def", "load_format", "requested_format", "=", "nil", "raise", "ArgumentError", ",", "\"Requested format not supported\"", "if", "!", "requested_format", ".", "nil?", "&&", "@@formats", "[", "requested_format", "]", ".", "nil?", "@format", "=", "requested_format", "||", "@@default_format", "attempted_formats", "=", "\"\"", "begin", "attempted_formats", "+=", "@@formats", "[", "@format", "]", "[", ":require", "]", "require", "@@formats", "[", "@format", "]", "[", ":require", "]", "return", "true", "rescue", "LoadError", "raise", "Error", "(", "\"Please install: '#{@@formats[@format][:require]}' to use #{@format} format.\"", ")", "unless", "requested_format", ".", "nil?", "available_formats", "=", "@@formats", "available_formats", ".", "delete", "(", "@format", ")", "available_formats", ".", "each_key", "do", "|", "format", "|", "begin", "attempted_formats", "+=", "\", \"", "require", "@@formats", "[", "format", "]", "[", ":require", "]", "@format", "=", "format", "return", "true", "rescue", "LoadError", "attempted_formats", "+=", "@@formats", "[", "format", "]", "[", ":require", "]", "end", "end", "raise", "Error", ",", "\"Could not find any suitable library to parse response with, tried: #{attempted_formats}. Please install one of these to use OEmbed.\"", "end", "end" ]
Call with no argument to use default
[ "Call", "with", "no", "argument", "to", "use", "default" ]
4c657a35ea7c7b1f23c22a3d6f9b118d4f8d04e6
https://github.com/benmcredmond/OhEmbedr/blob/4c657a35ea7c7b1f23c22a3d6f9b118d4f8d04e6/lib/ohembedr.rb#L166-L197
train
browsermedia/bcms_blog
app/models/bcms_blog/blog_observer.rb
BcmsBlog.BlogObserver.create_post_portlet_page
def create_post_portlet_page page = Cms::Page.find_by_name(portlet_name = "#{@blog.name}: Post") || Cms::Page.create!( :name => portlet_name, :path => "/#{@blog.name_for_path}/post", :section => @section, :template_file_name => "default.html.erb", :hidden => true) page.publish create_route(page, portlet_name, "/#{@blog.name_for_path}/:year/:month/:day/:slug") create_portlet(page, portlet_name, BlogPostPortlet) end
ruby
def create_post_portlet_page page = Cms::Page.find_by_name(portlet_name = "#{@blog.name}: Post") || Cms::Page.create!( :name => portlet_name, :path => "/#{@blog.name_for_path}/post", :section => @section, :template_file_name => "default.html.erb", :hidden => true) page.publish create_route(page, portlet_name, "/#{@blog.name_for_path}/:year/:month/:day/:slug") create_portlet(page, portlet_name, BlogPostPortlet) end
[ "def", "create_post_portlet_page", "page", "=", "Cms", "::", "Page", ".", "find_by_name", "(", "portlet_name", "=", "\"#{@blog.name}: Post\"", ")", "||", "Cms", "::", "Page", ".", "create!", "(", ":name", "=>", "portlet_name", ",", ":path", "=>", "\"/#{@blog.name_for_path}/post\"", ",", ":section", "=>", "@section", ",", ":template_file_name", "=>", "\"default.html.erb\"", ",", ":hidden", "=>", "true", ")", "page", ".", "publish", "create_route", "(", "page", ",", "portlet_name", ",", "\"/#{@blog.name_for_path}/:year/:month/:day/:slug\"", ")", "create_portlet", "(", "page", ",", "portlet_name", ",", "BlogPostPortlet", ")", "end" ]
The second page that is created holds the BlogPostPortlet and displays the individual post view, along with it's comments.
[ "The", "second", "page", "that", "is", "created", "holds", "the", "BlogPostPortlet", "and", "displays", "the", "individual", "post", "view", "along", "with", "it", "s", "comments", "." ]
7deba71bc99b51da6aa48ca0064cb919f4a5c233
https://github.com/browsermedia/bcms_blog/blob/7deba71bc99b51da6aa48ca0064cb919f4a5c233/app/models/bcms_blog/blog_observer.rb#L76-L86
train
ideonetwork/evnt
lib/evnt/command.rb
Evnt.Command.err
def err(message, code: nil) @state[:result] = false @state[:errors].push( message: message, code: code ) # raise error if command needs exceptions raise message if @options[:exceptions] end
ruby
def err(message, code: nil) @state[:result] = false @state[:errors].push( message: message, code: code ) # raise error if command needs exceptions raise message if @options[:exceptions] end
[ "def", "err", "(", "message", ",", "code", ":", "nil", ")", "@state", "[", ":result", "]", "=", "false", "@state", "[", ":errors", "]", ".", "push", "(", "message", ":", "message", ",", "code", ":", "code", ")", "raise", "message", "if", "@options", "[", ":exceptions", "]", "end" ]
This function can be used to stop the command execution and add a new error. Using err inside a callback should not stop the execution but should avoid the call of the next callback. Every time you call this function, a new error should be added to the errors list. If the exceptions option is active, it should raise a new error. ==== Attributes * +message+ - The message string of the error. * +code+ - The error code.
[ "This", "function", "can", "be", "used", "to", "stop", "the", "command", "execution", "and", "add", "a", "new", "error", ".", "Using", "err", "inside", "a", "callback", "should", "not", "stop", "the", "execution", "but", "should", "avoid", "the", "call", "of", "the", "next", "callback", ".", "Every", "time", "you", "call", "this", "function", "a", "new", "error", "should", "be", "added", "to", "the", "errors", "list", ".", "If", "the", "exceptions", "option", "is", "active", "it", "should", "raise", "a", "new", "error", "." ]
01331ab48f3fe92c6189b6f4db256606d397d177
https://github.com/ideonetwork/evnt/blob/01331ab48f3fe92c6189b6f4db256606d397d177/lib/evnt/command.rb#L93-L102
train
ideonetwork/evnt
lib/evnt/command.rb
Evnt.Command._init_command_data
def _init_command_data(params) # set state @state = { result: true, errors: [] } # set options initial_options = { exceptions: false, nullify_empty_params: false } default_options = _safe_default_options || {} params_options = params[:_options] || {} @options = initial_options.merge(default_options) .merge(params_options) # set other data @params = params end
ruby
def _init_command_data(params) # set state @state = { result: true, errors: [] } # set options initial_options = { exceptions: false, nullify_empty_params: false } default_options = _safe_default_options || {} params_options = params[:_options] || {} @options = initial_options.merge(default_options) .merge(params_options) # set other data @params = params end
[ "def", "_init_command_data", "(", "params", ")", "@state", "=", "{", "result", ":", "true", ",", "errors", ":", "[", "]", "}", "initial_options", "=", "{", "exceptions", ":", "false", ",", "nullify_empty_params", ":", "false", "}", "default_options", "=", "_safe_default_options", "||", "{", "}", "params_options", "=", "params", "[", ":_options", "]", "||", "{", "}", "@options", "=", "initial_options", ".", "merge", "(", "default_options", ")", ".", "merge", "(", "params_options", ")", "@params", "=", "params", "end" ]
This function initializes the command required data.
[ "This", "function", "initializes", "the", "command", "required", "data", "." ]
01331ab48f3fe92c6189b6f4db256606d397d177
https://github.com/ideonetwork/evnt/blob/01331ab48f3fe92c6189b6f4db256606d397d177/lib/evnt/command.rb#L110-L129
train
ideonetwork/evnt
lib/evnt/command.rb
Evnt.Command._validate_single_params
def _validate_single_params validations = _safe_validations validations.each do |val| value_to_validate = _value_to_validate(val) validator = Evnt::Validator.new(value_to_validate, val[:options]) if validator.passed? @params[val[:param]] = validator.value else error = val[:options][:err] || "#{val[:param].capitalize} value not accepted" err_code = val[:options][:err_code] || val[:param].to_sym err(error, code: err_code) break end end @params end
ruby
def _validate_single_params validations = _safe_validations validations.each do |val| value_to_validate = _value_to_validate(val) validator = Evnt::Validator.new(value_to_validate, val[:options]) if validator.passed? @params[val[:param]] = validator.value else error = val[:options][:err] || "#{val[:param].capitalize} value not accepted" err_code = val[:options][:err_code] || val[:param].to_sym err(error, code: err_code) break end end @params end
[ "def", "_validate_single_params", "validations", "=", "_safe_validations", "validations", ".", "each", "do", "|", "val", "|", "value_to_validate", "=", "_value_to_validate", "(", "val", ")", "validator", "=", "Evnt", "::", "Validator", ".", "new", "(", "value_to_validate", ",", "val", "[", ":options", "]", ")", "if", "validator", ".", "passed?", "@params", "[", "val", "[", ":param", "]", "]", "=", "validator", ".", "value", "else", "error", "=", "val", "[", ":options", "]", "[", ":err", "]", "||", "\"#{val[:param].capitalize} value not accepted\"", "err_code", "=", "val", "[", ":options", "]", "[", ":err_code", "]", "||", "val", "[", ":param", "]", ".", "to_sym", "err", "(", "error", ",", "code", ":", "err_code", ")", "break", "end", "end", "@params", "end" ]
This function validates the single parameters sets with the "validates" method.
[ "This", "function", "validates", "the", "single", "parameters", "sets", "with", "the", "validates", "method", "." ]
01331ab48f3fe92c6189b6f4db256606d397d177
https://github.com/ideonetwork/evnt/blob/01331ab48f3fe92c6189b6f4db256606d397d177/lib/evnt/command.rb#L141-L158
train
jaymcgavren/rubyonacid
lib/rubyonacid/factory.rb
RubyOnAcid.Factory.choose
def choose(key, *choices) all_choices = choices.flatten index = (get_unit(key) * all_choices.length).floor index = all_choices.length - 1 if index > all_choices.length - 1 all_choices[index] end
ruby
def choose(key, *choices) all_choices = choices.flatten index = (get_unit(key) * all_choices.length).floor index = all_choices.length - 1 if index > all_choices.length - 1 all_choices[index] end
[ "def", "choose", "(", "key", ",", "*", "choices", ")", "all_choices", "=", "choices", ".", "flatten", "index", "=", "(", "get_unit", "(", "key", ")", "*", "all_choices", ".", "length", ")", ".", "floor", "index", "=", "all_choices", ".", "length", "-", "1", "if", "index", ">", "all_choices", ".", "length", "-", "1", "all_choices", "[", "index", "]", "end" ]
Calls get_unit with key to get value between 0.0 and 1.0, then converts that value to an index within the given list of choices. choices can be an array or an argument list of arbitrary size.
[ "Calls", "get_unit", "with", "key", "to", "get", "value", "between", "0", ".", "0", "and", "1", ".", "0", "then", "converts", "that", "value", "to", "an", "index", "within", "the", "given", "list", "of", "choices", ".", "choices", "can", "be", "an", "array", "or", "an", "argument", "list", "of", "arbitrary", "size", "." ]
2ee2af3e952b7290e18a4f7012f76af4a7fe059d
https://github.com/jaymcgavren/rubyonacid/blob/2ee2af3e952b7290e18a4f7012f76af4a7fe059d/lib/rubyonacid/factory.rb#L45-L50
train
permitters/permitters
lib/action_controller/permittance.rb
ActionController.Permittance.permitter
def permitter(pclass = permitter_class) pinstance = (@permitter_class_to_permitter ||= {})[pclass] return pinstance if pinstance current_authorizer_method = ActionController::Permitter.current_authorizer_method ? ActionController::Permitter.current_authorizer_method.to_sym : nil @permitter_class_to_permitter[pclass] = pclass.new(params, defined?(current_user) ? current_user : nil, current_authorizer_method && defined?(current_authorizer_method) ? __send__(current_authorizer_method) : nil) end
ruby
def permitter(pclass = permitter_class) pinstance = (@permitter_class_to_permitter ||= {})[pclass] return pinstance if pinstance current_authorizer_method = ActionController::Permitter.current_authorizer_method ? ActionController::Permitter.current_authorizer_method.to_sym : nil @permitter_class_to_permitter[pclass] = pclass.new(params, defined?(current_user) ? current_user : nil, current_authorizer_method && defined?(current_authorizer_method) ? __send__(current_authorizer_method) : nil) end
[ "def", "permitter", "(", "pclass", "=", "permitter_class", ")", "pinstance", "=", "(", "@permitter_class_to_permitter", "||=", "{", "}", ")", "[", "pclass", "]", "return", "pinstance", "if", "pinstance", "current_authorizer_method", "=", "ActionController", "::", "Permitter", ".", "current_authorizer_method", "?", "ActionController", "::", "Permitter", ".", "current_authorizer_method", ".", "to_sym", ":", "nil", "@permitter_class_to_permitter", "[", "pclass", "]", "=", "pclass", ".", "new", "(", "params", ",", "defined?", "(", "current_user", ")", "?", "current_user", ":", "nil", ",", "current_authorizer_method", "&&", "defined?", "(", "current_authorizer_method", ")", "?", "__send__", "(", "current_authorizer_method", ")", ":", "nil", ")", "end" ]
Returns a new instance of the permitter by initializing it with params, current_user, current_ability.
[ "Returns", "a", "new", "instance", "of", "the", "permitter", "by", "initializing", "it", "with", "params", "current_user", "current_ability", "." ]
f5229dd84e982ce1726b14b0e0757e695cb049ee
https://github.com/permitters/permitters/blob/f5229dd84e982ce1726b14b0e0757e695cb049ee/lib/action_controller/permittance.rb#L14-L19
train
opyh/motion-state-machine
lib/motion-state-machine/transition.rb
StateMachine.Transition.handle_in_source_state
def handle_in_source_state if @state_machine.initial_queue.nil? raise RuntimeError, "State machine not started yet." end if Dispatch::Queue.current.to_s != @state_machine.initial_queue.to_s raise RuntimeError, "#{self.class.event_type}:#{@event_trigger_value} must be "\ "called from the queue where the state machine was started." end @source_state.send :guarded_execute, self.class.event_type, @event_trigger_value end
ruby
def handle_in_source_state if @state_machine.initial_queue.nil? raise RuntimeError, "State machine not started yet." end if Dispatch::Queue.current.to_s != @state_machine.initial_queue.to_s raise RuntimeError, "#{self.class.event_type}:#{@event_trigger_value} must be "\ "called from the queue where the state machine was started." end @source_state.send :guarded_execute, self.class.event_type, @event_trigger_value end
[ "def", "handle_in_source_state", "if", "@state_machine", ".", "initial_queue", ".", "nil?", "raise", "RuntimeError", ",", "\"State machine not started yet.\"", "end", "if", "Dispatch", "::", "Queue", ".", "current", ".", "to_s", "!=", "@state_machine", ".", "initial_queue", ".", "to_s", "raise", "RuntimeError", ",", "\"#{self.class.event_type}:#{@event_trigger_value} must be \"", "\"called from the queue where the state machine was started.\"", "end", "@source_state", ".", "send", ":guarded_execute", ",", "self", ".", "class", ".", "event_type", ",", "@event_trigger_value", "end" ]
Delegates handling the transition to the source state, which makes sure that there are no ambiguous transitions for the same event.
[ "Delegates", "handling", "the", "transition", "to", "the", "source", "state", "which", "makes", "sure", "that", "there", "are", "no", "ambiguous", "transitions", "for", "the", "same", "event", "." ]
baafa93de4b05fe4ba91a3dbb944ab3d28b8913d
https://github.com/opyh/motion-state-machine/blob/baafa93de4b05fe4ba91a3dbb944ab3d28b8913d/lib/motion-state-machine/transition.rb#L189-L203
train
codykrieger/cube-ruby
lib/cube.rb
Cube.Client.actual_send
def actual_send(type, time, id, data) # Namespace support! prefix = "#{@namespace}_" unless @namespace.nil? # Get rid of any unwanted characters, and replace each of them with an _. type = type.to_s.gsub RESERVED_CHARS_REGEX, '_' # Start constructing the message to be sent to Cube over UDP. message = { type: "#{prefix}#{type}" } message[:time] = time.iso8601 unless time.nil? message[:id] = id unless id.nil? message[:data] = data unless data.nil? # JSONify it, log it, and send it off. message_str = message.to_json self.class.logger.debug { "Cube: #{message_str}" } if self.class.logger socket.send message_str, 0, @host, @port rescue => err self.class.logger.error { "Cube: #{err.class} #{err}" } if self.class.logger end
ruby
def actual_send(type, time, id, data) # Namespace support! prefix = "#{@namespace}_" unless @namespace.nil? # Get rid of any unwanted characters, and replace each of them with an _. type = type.to_s.gsub RESERVED_CHARS_REGEX, '_' # Start constructing the message to be sent to Cube over UDP. message = { type: "#{prefix}#{type}" } message[:time] = time.iso8601 unless time.nil? message[:id] = id unless id.nil? message[:data] = data unless data.nil? # JSONify it, log it, and send it off. message_str = message.to_json self.class.logger.debug { "Cube: #{message_str}" } if self.class.logger socket.send message_str, 0, @host, @port rescue => err self.class.logger.error { "Cube: #{err.class} #{err}" } if self.class.logger end
[ "def", "actual_send", "(", "type", ",", "time", ",", "id", ",", "data", ")", "prefix", "=", "\"#{@namespace}_\"", "unless", "@namespace", ".", "nil?", "type", "=", "type", ".", "to_s", ".", "gsub", "RESERVED_CHARS_REGEX", ",", "'_'", "message", "=", "{", "type", ":", "\"#{prefix}#{type}\"", "}", "message", "[", ":time", "]", "=", "time", ".", "iso8601", "unless", "time", ".", "nil?", "message", "[", ":id", "]", "=", "id", "unless", "id", ".", "nil?", "message", "[", ":data", "]", "=", "data", "unless", "data", ".", "nil?", "message_str", "=", "message", ".", "to_json", "self", ".", "class", ".", "logger", ".", "debug", "{", "\"Cube: #{message_str}\"", "}", "if", "self", ".", "class", ".", "logger", "socket", ".", "send", "message_str", ",", "0", ",", "@host", ",", "@port", "rescue", "=>", "err", "self", ".", "class", ".", "logger", ".", "error", "{", "\"Cube: #{err.class} #{err}\"", "}", "if", "self", ".", "class", ".", "logger", "end" ]
Actually send the given data to a socket, and potentially log it along the way. @param [String] The desired name of the new Cube event. @param [DateTime] Optional. A specific time when the Cube event occurred. @param [Object] Optional. Typically an integer, but can be any object. @param [Hash] Optional. Anything in this hash will be stored in the `data` subdocument of the Cube event.
[ "Actually", "send", "the", "given", "data", "to", "a", "socket", "and", "potentially", "log", "it", "along", "the", "way", "." ]
3368cfc746c2477e15c45b3492985725d726657c
https://github.com/codykrieger/cube-ruby/blob/3368cfc746c2477e15c45b3492985725d726657c/lib/cube.rb#L69-L90
train
rubaidh/google_analytics
lib/rubaidh/view_helpers.rb
Rubaidh.GoogleAnalyticsViewHelper.link_to_tracked
def link_to_tracked(name, track_path = "/", options = {}, html_options = {}) raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true html_options.merge!({:onclick => tracking_call(track_path)}) link_to name, options, html_options end
ruby
def link_to_tracked(name, track_path = "/", options = {}, html_options = {}) raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true html_options.merge!({:onclick => tracking_call(track_path)}) link_to name, options, html_options end
[ "def", "link_to_tracked", "(", "name", ",", "track_path", "=", "\"/\"", ",", "options", "=", "{", "}", ",", "html_options", "=", "{", "}", ")", "raise", "AnalyticsError", ".", "new", "(", "\"You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking\"", ")", "if", "GoogleAnalytics", ".", "defer_load", "==", "true", "html_options", ".", "merge!", "(", "{", ":onclick", "=>", "tracking_call", "(", "track_path", ")", "}", ")", "link_to", "name", ",", "options", ",", "html_options", "end" ]
Creates a link tag of the given +name+ using a URL created by the set of +options+, with outbound link tracking under +track_path+ in Google Analytics. The +html_options+ will accept a hash of attributes for the link tag.
[ "Creates", "a", "link", "tag", "of", "the", "given", "+", "name", "+", "using", "a", "URL", "created", "by", "the", "set", "of", "+", "options", "+", "with", "outbound", "link", "tracking", "under", "+", "track_path", "+", "in", "Google", "Analytics", ".", "The", "+", "html_options", "+", "will", "accept", "a", "hash", "of", "attributes", "for", "the", "link", "tag", "." ]
d834044d84a8954bf58d57663523b25c2a8cbbc6
https://github.com/rubaidh/google_analytics/blob/d834044d84a8954bf58d57663523b25c2a8cbbc6/lib/rubaidh/view_helpers.rb#L10-L14
train
rubaidh/google_analytics
lib/rubaidh/view_helpers.rb
Rubaidh.GoogleAnalyticsViewHelper.link_to_tracked_if
def link_to_tracked_if(condition, name, track_path = "/", options = {}, html_options = {}, &block) raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true html_options.merge!({:onclick => tracking_call(track_path)}) link_to_unless !condition, name, options, html_options, &block end
ruby
def link_to_tracked_if(condition, name, track_path = "/", options = {}, html_options = {}, &block) raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true html_options.merge!({:onclick => tracking_call(track_path)}) link_to_unless !condition, name, options, html_options, &block end
[ "def", "link_to_tracked_if", "(", "condition", ",", "name", ",", "track_path", "=", "\"/\"", ",", "options", "=", "{", "}", ",", "html_options", "=", "{", "}", ",", "&", "block", ")", "raise", "AnalyticsError", ".", "new", "(", "\"You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking\"", ")", "if", "GoogleAnalytics", ".", "defer_load", "==", "true", "html_options", ".", "merge!", "(", "{", ":onclick", "=>", "tracking_call", "(", "track_path", ")", "}", ")", "link_to_unless", "!", "condition", ",", "name", ",", "options", ",", "html_options", ",", "&", "block", "end" ]
Creates a link tag of the given +name+ using a URL created by the set of +options+ if +condition+ is true, with outbound link tracking under +track_path+ in Google Analytics. The +html_options+ will accept a hash of attributes for the link tag.
[ "Creates", "a", "link", "tag", "of", "the", "given", "+", "name", "+", "using", "a", "URL", "created", "by", "the", "set", "of", "+", "options", "+", "if", "+", "condition", "+", "is", "true", "with", "outbound", "link", "tracking", "under", "+", "track_path", "+", "in", "Google", "Analytics", ".", "The", "+", "html_options", "+", "will", "accept", "a", "hash", "of", "attributes", "for", "the", "link", "tag", "." ]
d834044d84a8954bf58d57663523b25c2a8cbbc6
https://github.com/rubaidh/google_analytics/blob/d834044d84a8954bf58d57663523b25c2a8cbbc6/lib/rubaidh/view_helpers.rb#L19-L23
train
rubaidh/google_analytics
lib/rubaidh/view_helpers.rb
Rubaidh.GoogleAnalyticsViewHelper.link_to_tracked_unless_current
def link_to_tracked_unless_current(name, track_path = "/", options = {}, html_options = {}, &block) raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true html_options.merge!({:onclick =>tracking_call(track_path)}) link_to_unless current_page?(options), name, options, html_options, &block end
ruby
def link_to_tracked_unless_current(name, track_path = "/", options = {}, html_options = {}, &block) raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true html_options.merge!({:onclick =>tracking_call(track_path)}) link_to_unless current_page?(options), name, options, html_options, &block end
[ "def", "link_to_tracked_unless_current", "(", "name", ",", "track_path", "=", "\"/\"", ",", "options", "=", "{", "}", ",", "html_options", "=", "{", "}", ",", "&", "block", ")", "raise", "AnalyticsError", ".", "new", "(", "\"You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking\"", ")", "if", "GoogleAnalytics", ".", "defer_load", "==", "true", "html_options", ".", "merge!", "(", "{", ":onclick", "=>", "tracking_call", "(", "track_path", ")", "}", ")", "link_to_unless", "current_page?", "(", "options", ")", ",", "name", ",", "options", ",", "html_options", ",", "&", "block", "end" ]
Creates a link tag of the given +name+ using a URL created by the set of +options+ unless the current request URI is the same as the link's, with outbound link tracking under +track_path+ in Google Analytics. If the request URI is the same as the link URI, only the name is returned, or the block is yielded, if one exists. The +html_options+ will accept a hash of attributes for the link tag.
[ "Creates", "a", "link", "tag", "of", "the", "given", "+", "name", "+", "using", "a", "URL", "created", "by", "the", "set", "of", "+", "options", "+", "unless", "the", "current", "request", "URI", "is", "the", "same", "as", "the", "link", "s", "with", "outbound", "link", "tracking", "under", "+", "track_path", "+", "in", "Google", "Analytics", ".", "If", "the", "request", "URI", "is", "the", "same", "as", "the", "link", "URI", "only", "the", "name", "is", "returned", "or", "the", "block", "is", "yielded", "if", "one", "exists", ".", "The", "+", "html_options", "+", "will", "accept", "a", "hash", "of", "attributes", "for", "the", "link", "tag", "." ]
d834044d84a8954bf58d57663523b25c2a8cbbc6
https://github.com/rubaidh/google_analytics/blob/d834044d84a8954bf58d57663523b25c2a8cbbc6/lib/rubaidh/view_helpers.rb#L39-L43
train
Latermedia/sidekiq_simple_delay
lib/sidekiq_simple_delay/delay_methods.rb
SidekiqSimpleDelay.DelayMethods.simple_sidekiq_delay_for
def simple_sidekiq_delay_for(interval, options = {}) Proxy.new(simple_delayed_worker, self, options.merge('at' => Time.now.to_f + interval.to_f)) end
ruby
def simple_sidekiq_delay_for(interval, options = {}) Proxy.new(simple_delayed_worker, self, options.merge('at' => Time.now.to_f + interval.to_f)) end
[ "def", "simple_sidekiq_delay_for", "(", "interval", ",", "options", "=", "{", "}", ")", "Proxy", ".", "new", "(", "simple_delayed_worker", ",", "self", ",", "options", ".", "merge", "(", "'at'", "=>", "Time", ".", "now", ".", "to_f", "+", "interval", ".", "to_f", ")", ")", "end" ]
Enqueue a job to handle the delayed action after an elapsed interval @param interval [#to_f] Number of seconds to wait. `to_f` will be called on this argument to convert to seconds. @param options [Hash] options similar to Sidekiq's `perform_in`
[ "Enqueue", "a", "job", "to", "handle", "the", "delayed", "action", "after", "an", "elapsed", "interval" ]
d50f47187535acdeaa5b1a386e011699be892ead
https://github.com/Latermedia/sidekiq_simple_delay/blob/d50f47187535acdeaa5b1a386e011699be892ead/lib/sidekiq_simple_delay/delay_methods.rb#L22-L24
train
Latermedia/sidekiq_simple_delay
lib/sidekiq_simple_delay/delay_methods.rb
SidekiqSimpleDelay.DelayMethods.simple_sidekiq_delay_until
def simple_sidekiq_delay_until(timestamp, options = {}) Proxy.new(simple_delayed_worker, self, options.merge('at' => timestamp.to_f)) end
ruby
def simple_sidekiq_delay_until(timestamp, options = {}) Proxy.new(simple_delayed_worker, self, options.merge('at' => timestamp.to_f)) end
[ "def", "simple_sidekiq_delay_until", "(", "timestamp", ",", "options", "=", "{", "}", ")", "Proxy", ".", "new", "(", "simple_delayed_worker", ",", "self", ",", "options", ".", "merge", "(", "'at'", "=>", "timestamp", ".", "to_f", ")", ")", "end" ]
Enqueue a job to handle the delayed action after at a certain time @param timestamp [#to_f] Timestamp to execute job at. `to_f` will be called on this argument to convert to a timestamp. @param options [Hash] options similar to Sidekiq's `perform_at`
[ "Enqueue", "a", "job", "to", "handle", "the", "delayed", "action", "after", "at", "a", "certain", "time" ]
d50f47187535acdeaa5b1a386e011699be892ead
https://github.com/Latermedia/sidekiq_simple_delay/blob/d50f47187535acdeaa5b1a386e011699be892ead/lib/sidekiq_simple_delay/delay_methods.rb#L31-L33
train
Latermedia/sidekiq_simple_delay
lib/sidekiq_simple_delay/delay_methods.rb
SidekiqSimpleDelay.DelayMethods.simple_sidekiq_delay_spread
def simple_sidekiq_delay_spread(options = {}) local_opts = options.dup spread_duration = Utils.extract_option(local_opts, :spread_duration, 1.hour).to_f spread_in = Utils.extract_option(local_opts, :spread_in, 0).to_f spread_at = Utils.extract_option(local_opts, :spread_at) spread_method = Utils.extract_option(local_opts, :spread_method, :rand) spread_mod_value = Utils.extract_option(local_opts, :spread_mod_value) spread_mod_method = Utils.extract_option(local_opts, :spread_mod_method) spread_duration = 0 if spread_duration < 0 spread_in = 0 if spread_in < 0 spread = # kick of immediately if the duration is 0 if spread_duration.zero? 0 else case spread_method.to_sym when :rand Utils.random_number(spread_duration) when :mod mod_value = # The mod value has been supplied if !spread_mod_value.nil? spread_mod_value # Call the supplied method on the target object to get mod value elsif !spread_mod_method.nil? send(spread_mod_method) # Call `spread_mod_method` on target object to get mod value elsif respond_to?(:spread_mod_method) send(send(:spread_mod_method)) else raise ArgumentError, 'must specify `spread_mod_value` or `spread_mod_method` or taget must respond to `spread_mod_method`' end # calculate the mod based offset mod_value % spread_duration else raise ArgumentError, "spread_method must :rand or :mod, `#{spread_method} is invalid`" end end t = if !spread_at.nil? # add spread to a timestamp spread_at.to_f + spread elsif !spread_in.nil? # add spread to no plus constant offset Time.now.to_f + spread_in.to_f + spread else # add spread to current time Time.now.to_f + spread end Proxy.new(SimpleDelayedWorker, self, local_opts.merge('at' => t)) end
ruby
def simple_sidekiq_delay_spread(options = {}) local_opts = options.dup spread_duration = Utils.extract_option(local_opts, :spread_duration, 1.hour).to_f spread_in = Utils.extract_option(local_opts, :spread_in, 0).to_f spread_at = Utils.extract_option(local_opts, :spread_at) spread_method = Utils.extract_option(local_opts, :spread_method, :rand) spread_mod_value = Utils.extract_option(local_opts, :spread_mod_value) spread_mod_method = Utils.extract_option(local_opts, :spread_mod_method) spread_duration = 0 if spread_duration < 0 spread_in = 0 if spread_in < 0 spread = # kick of immediately if the duration is 0 if spread_duration.zero? 0 else case spread_method.to_sym when :rand Utils.random_number(spread_duration) when :mod mod_value = # The mod value has been supplied if !spread_mod_value.nil? spread_mod_value # Call the supplied method on the target object to get mod value elsif !spread_mod_method.nil? send(spread_mod_method) # Call `spread_mod_method` on target object to get mod value elsif respond_to?(:spread_mod_method) send(send(:spread_mod_method)) else raise ArgumentError, 'must specify `spread_mod_value` or `spread_mod_method` or taget must respond to `spread_mod_method`' end # calculate the mod based offset mod_value % spread_duration else raise ArgumentError, "spread_method must :rand or :mod, `#{spread_method} is invalid`" end end t = if !spread_at.nil? # add spread to a timestamp spread_at.to_f + spread elsif !spread_in.nil? # add spread to no plus constant offset Time.now.to_f + spread_in.to_f + spread else # add spread to current time Time.now.to_f + spread end Proxy.new(SimpleDelayedWorker, self, local_opts.merge('at' => t)) end
[ "def", "simple_sidekiq_delay_spread", "(", "options", "=", "{", "}", ")", "local_opts", "=", "options", ".", "dup", "spread_duration", "=", "Utils", ".", "extract_option", "(", "local_opts", ",", ":spread_duration", ",", "1", ".", "hour", ")", ".", "to_f", "spread_in", "=", "Utils", ".", "extract_option", "(", "local_opts", ",", ":spread_in", ",", "0", ")", ".", "to_f", "spread_at", "=", "Utils", ".", "extract_option", "(", "local_opts", ",", ":spread_at", ")", "spread_method", "=", "Utils", ".", "extract_option", "(", "local_opts", ",", ":spread_method", ",", ":rand", ")", "spread_mod_value", "=", "Utils", ".", "extract_option", "(", "local_opts", ",", ":spread_mod_value", ")", "spread_mod_method", "=", "Utils", ".", "extract_option", "(", "local_opts", ",", ":spread_mod_method", ")", "spread_duration", "=", "0", "if", "spread_duration", "<", "0", "spread_in", "=", "0", "if", "spread_in", "<", "0", "spread", "=", "if", "spread_duration", ".", "zero?", "0", "else", "case", "spread_method", ".", "to_sym", "when", ":rand", "Utils", ".", "random_number", "(", "spread_duration", ")", "when", ":mod", "mod_value", "=", "if", "!", "spread_mod_value", ".", "nil?", "spread_mod_value", "elsif", "!", "spread_mod_method", ".", "nil?", "send", "(", "spread_mod_method", ")", "elsif", "respond_to?", "(", ":spread_mod_method", ")", "send", "(", "send", "(", ":spread_mod_method", ")", ")", "else", "raise", "ArgumentError", ",", "'must specify `spread_mod_value` or `spread_mod_method` or taget must respond to `spread_mod_method`'", "end", "mod_value", "%", "spread_duration", "else", "raise", "ArgumentError", ",", "\"spread_method must :rand or :mod, `#{spread_method} is invalid`\"", "end", "end", "t", "=", "if", "!", "spread_at", ".", "nil?", "spread_at", ".", "to_f", "+", "spread", "elsif", "!", "spread_in", ".", "nil?", "Time", ".", "now", ".", "to_f", "+", "spread_in", ".", "to_f", "+", "spread", "else", "Time", ".", "now", ".", "to_f", "+", "spread", "end", "Proxy", ".", "new", "(", "SimpleDelayedWorker", ",", "self", ",", "local_opts", ".", "merge", "(", "'at'", "=>", "t", ")", ")", "end" ]
Enqueue a job to handle the delayed action in a given timeframe @param timestamp [#to_f] Timestamp to execute job at. `to_f` will be called on this argument to convert to a timestamp. @param options [Hash] options similar to Sidekiq's `perform_at` @option options [Number] :spread_duration Size of window to spread workers out over @option options [Number] :spread_in Start of window offset from now @option options [Number] :spread_at Start of window offset timestamp @option options [rand|mod] :spread_method perform either a random or modulo spread, default: *:rand* @option options [Number] :spread_mod_value value to use for determining mod offset @option options [Symbol] :spread_mod_method method to call to get the value to use for determining mod offset
[ "Enqueue", "a", "job", "to", "handle", "the", "delayed", "action", "in", "a", "given", "timeframe" ]
d50f47187535acdeaa5b1a386e011699be892ead
https://github.com/Latermedia/sidekiq_simple_delay/blob/d50f47187535acdeaa5b1a386e011699be892ead/lib/sidekiq_simple_delay/delay_methods.rb#L48-L104
train
bogdanRada/celluloid_pubsub
lib/celluloid_pubsub/web_server.rb
CelluloidPubsub.WebServer.handle_dispatched_message
def handle_dispatched_message(reactor, data) log_debug "#{self.class} trying to dispatch message #{data.inspect}" message = reactor.parse_json_data(data) final_data = message.present? && message.is_a?(Hash) ? message.to_json : data.to_json reactor.websocket << final_data end
ruby
def handle_dispatched_message(reactor, data) log_debug "#{self.class} trying to dispatch message #{data.inspect}" message = reactor.parse_json_data(data) final_data = message.present? && message.is_a?(Hash) ? message.to_json : data.to_json reactor.websocket << final_data end
[ "def", "handle_dispatched_message", "(", "reactor", ",", "data", ")", "log_debug", "\"#{self.class} trying to dispatch message #{data.inspect}\"", "message", "=", "reactor", ".", "parse_json_data", "(", "data", ")", "final_data", "=", "message", ".", "present?", "&&", "message", ".", "is_a?", "(", "Hash", ")", "?", "message", ".", "to_json", ":", "data", ".", "to_json", "reactor", ".", "websocket", "<<", "final_data", "end" ]
If the message can be parsed into a Hash it will respond to the reactor's websocket connection with the same message in JSON format otherwise will try send the message how it is and escaped into JSON format @param [CelluloidPubsub::Reactor] reactor The reactor that received an unhandled message @param [Object] data The message that the reactor could not handle @return [void] @api public
[ "If", "the", "message", "can", "be", "parsed", "into", "a", "Hash", "it", "will", "respond", "to", "the", "reactor", "s", "websocket", "connection", "with", "the", "same", "message", "in", "JSON", "format", "otherwise", "will", "try", "send", "the", "message", "how", "it", "is", "and", "escaped", "into", "JSON", "format" ]
e5558257c04e553b49e08ce27c130d572ada210d
https://github.com/bogdanRada/celluloid_pubsub/blob/e5558257c04e553b49e08ce27c130d572ada210d/lib/celluloid_pubsub/web_server.rb#L306-L311
train
middlemac/middleman-targets
lib/middleman-targets/middleman-cli/build_all.rb
Middleman::Cli.BuildAll.build_all
def build_all # The first thing we want to do is create a temporary application # instance so that we can determine the valid targets. app = ::Middleman::Application.new do config[:exit_before_ready] = true end build_list = app.config[:targets].each_key.collect { |item| item.to_s } bad_builds = [] build_list.each do |target| bad_builds << target unless Build.start(['--target', target]) end unless bad_builds.count == 0 say say 'These targets produced errors during build:', :red bad_builds.each { |item| say " #{item}", :red} end bad_builds.count == 0 end
ruby
def build_all # The first thing we want to do is create a temporary application # instance so that we can determine the valid targets. app = ::Middleman::Application.new do config[:exit_before_ready] = true end build_list = app.config[:targets].each_key.collect { |item| item.to_s } bad_builds = [] build_list.each do |target| bad_builds << target unless Build.start(['--target', target]) end unless bad_builds.count == 0 say say 'These targets produced errors during build:', :red bad_builds.each { |item| say " #{item}", :red} end bad_builds.count == 0 end
[ "def", "build_all", "app", "=", "::", "Middleman", "::", "Application", ".", "new", "do", "config", "[", ":exit_before_ready", "]", "=", "true", "end", "build_list", "=", "app", ".", "config", "[", ":targets", "]", ".", "each_key", ".", "collect", "{", "|", "item", "|", "item", ".", "to_s", "}", "bad_builds", "=", "[", "]", "build_list", ".", "each", "do", "|", "target", "|", "bad_builds", "<<", "target", "unless", "Build", ".", "start", "(", "[", "'--target'", ",", "target", "]", ")", "end", "unless", "bad_builds", ".", "count", "==", "0", "say", "say", "'These targets produced errors during build:'", ",", ":red", "bad_builds", ".", "each", "{", "|", "item", "|", "say", "\" #{item}\"", ",", ":red", "}", "end", "bad_builds", ".", "count", "==", "0", "end" ]
Build all targets. @return [Void]
[ "Build", "all", "targets", "." ]
ebba3fa304e6325724e63b100c396dac0e2d5328
https://github.com/middlemac/middleman-targets/blob/ebba3fa304e6325724e63b100c396dac0e2d5328/lib/middleman-targets/middleman-cli/build_all.rb#L20-L41
train
logic-refinery/datatable
lib/datatable/helper.rb
Datatable.Helper.ruby_aocolumns
def ruby_aocolumns result = [] column_def_keys = %w[ asSorting bSearchable bSortable bUseRendered bVisible fnRender iDataSort mDataProp sClass sDefaultContent sName sSortDataType sTitle sType sWidth link_to ] index = 0 @datatable.columns.each_value do |column_hash| column_result = {} column_hash.each do |key,value| if column_def_keys.include?(key.to_s) column_result[key.to_s] = value end end # rewrite any link_to values as fnRender functions if column_result.include?('link_to') column_result['fnRender'] = %Q|function(oObj) { return replace('#{column_result['link_to']}', oObj.aData);}| column_result.delete('link_to') end if column_result.empty? result << nil else result << column_result end end result end
ruby
def ruby_aocolumns result = [] column_def_keys = %w[ asSorting bSearchable bSortable bUseRendered bVisible fnRender iDataSort mDataProp sClass sDefaultContent sName sSortDataType sTitle sType sWidth link_to ] index = 0 @datatable.columns.each_value do |column_hash| column_result = {} column_hash.each do |key,value| if column_def_keys.include?(key.to_s) column_result[key.to_s] = value end end # rewrite any link_to values as fnRender functions if column_result.include?('link_to') column_result['fnRender'] = %Q|function(oObj) { return replace('#{column_result['link_to']}', oObj.aData);}| column_result.delete('link_to') end if column_result.empty? result << nil else result << column_result end end result end
[ "def", "ruby_aocolumns", "result", "=", "[", "]", "column_def_keys", "=", "%w[", "asSorting", "bSearchable", "bSortable", "bUseRendered", "bVisible", "fnRender", "iDataSort", "mDataProp", "sClass", "sDefaultContent", "sName", "sSortDataType", "sTitle", "sType", "sWidth", "link_to", "]", "index", "=", "0", "@datatable", ".", "columns", ".", "each_value", "do", "|", "column_hash", "|", "column_result", "=", "{", "}", "column_hash", ".", "each", "do", "|", "key", ",", "value", "|", "if", "column_def_keys", ".", "include?", "(", "key", ".", "to_s", ")", "column_result", "[", "key", ".", "to_s", "]", "=", "value", "end", "end", "if", "column_result", ".", "include?", "(", "'link_to'", ")", "column_result", "[", "'fnRender'", "]", "=", "%Q|function(oObj) { return replace('#{column_result['link_to']}', oObj.aData);}|", "column_result", ".", "delete", "(", "'link_to'", ")", "end", "if", "column_result", ".", "empty?", "result", "<<", "nil", "else", "result", "<<", "column_result", "end", "end", "result", "end" ]
returns a ruby hash of
[ "returns", "a", "ruby", "hash", "of" ]
88c88e26694dc239f6032ff8de8f2b181158d41c
https://github.com/logic-refinery/datatable/blob/88c88e26694dc239f6032ff8de8f2b181158d41c/lib/datatable/helper.rb#L136-L164
train
activenetwork/gattica
lib/gattica/auth.rb
Gattica.Auth.parse_tokens
def parse_tokens(data) tokens = {} data.split("\n").each do |t| tokens.merge!({ t.split('=').first.downcase.to_sym => t.split('=').last }) end return tokens end
ruby
def parse_tokens(data) tokens = {} data.split("\n").each do |t| tokens.merge!({ t.split('=').first.downcase.to_sym => t.split('=').last }) end return tokens end
[ "def", "parse_tokens", "(", "data", ")", "tokens", "=", "{", "}", "data", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "t", "|", "tokens", ".", "merge!", "(", "{", "t", ".", "split", "(", "'='", ")", ".", "first", ".", "downcase", ".", "to_sym", "=>", "t", ".", "split", "(", "'='", ")", ".", "last", "}", ")", "end", "return", "tokens", "end" ]
Parse the authentication tokens out of the response and makes them available as a hash tokens[:auth] => Google requires this for every request (added to HTTP headers on GET requests) tokens[:sid] => Not used tokens[:lsid] => Not used
[ "Parse", "the", "authentication", "tokens", "out", "of", "the", "response", "and", "makes", "them", "available", "as", "a", "hash" ]
359a5a70eba67e0f9ddd6081cb4defbf14d2e74b
https://github.com/activenetwork/gattica/blob/359a5a70eba67e0f9ddd6081cb4defbf14d2e74b/lib/gattica/auth.rb#L43-L49
train
Avhana/allscripts_api
lib/allscripts_api/named_magic_methods.rb
AllscriptsApi.NamedMagicMethods.get_provider
def get_provider(provider_id = nil, user_name = nil) params = MagicParams.format( parameter1: provider_id, parameter2: user_name ) results = magic("GetProvider", magic_params: params) results["getproviderinfo"] end
ruby
def get_provider(provider_id = nil, user_name = nil) params = MagicParams.format( parameter1: provider_id, parameter2: user_name ) results = magic("GetProvider", magic_params: params) results["getproviderinfo"] end
[ "def", "get_provider", "(", "provider_id", "=", "nil", ",", "user_name", "=", "nil", ")", "params", "=", "MagicParams", ".", "format", "(", "parameter1", ":", "provider_id", ",", "parameter2", ":", "user_name", ")", "results", "=", "magic", "(", "\"GetProvider\"", ",", "magic_params", ":", "params", ")", "results", "[", "\"getproviderinfo\"", "]", "end" ]
a wrapper around GetProvider @param provider_id [String] optional Allscripts user id @param user_name [String] optional Allscripts user_name @return [Array<Hash>, Array, MagicError] a list of providers
[ "a", "wrapper", "around", "GetProvider" ]
b32da6df50565f63dbdac2c861dd6793000c3634
https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/named_magic_methods.rb#L14-L22
train
Avhana/allscripts_api
lib/allscripts_api/named_magic_methods.rb
AllscriptsApi.NamedMagicMethods.get_providers
def get_providers(security_filter = nil, name_filter = nil, show_only_providers_flag = "Y", internal_external = "I", ordering_authority = nil, real_provider = "N") params = MagicParams.format( parameter1: security_filter, parameter2: name_filter, parameter3: show_only_providers_flag, parameter4: internal_external, parameter5: ordering_authority, parameter6: real_provider ) results = magic("GetProviders", magic_params: params) results["getprovidersinfo"] end
ruby
def get_providers(security_filter = nil, name_filter = nil, show_only_providers_flag = "Y", internal_external = "I", ordering_authority = nil, real_provider = "N") params = MagicParams.format( parameter1: security_filter, parameter2: name_filter, parameter3: show_only_providers_flag, parameter4: internal_external, parameter5: ordering_authority, parameter6: real_provider ) results = magic("GetProviders", magic_params: params) results["getprovidersinfo"] end
[ "def", "get_providers", "(", "security_filter", "=", "nil", ",", "name_filter", "=", "nil", ",", "show_only_providers_flag", "=", "\"Y\"", ",", "internal_external", "=", "\"I\"", ",", "ordering_authority", "=", "nil", ",", "real_provider", "=", "\"N\"", ")", "params", "=", "MagicParams", ".", "format", "(", "parameter1", ":", "security_filter", ",", "parameter2", ":", "name_filter", ",", "parameter3", ":", "show_only_providers_flag", ",", "parameter4", ":", "internal_external", ",", "parameter5", ":", "ordering_authority", ",", "parameter6", ":", "real_provider", ")", "results", "=", "magic", "(", "\"GetProviders\"", ",", "magic_params", ":", "params", ")", "results", "[", "\"getprovidersinfo\"", "]", "end" ]
a wrapper around GetProviders @param security_filter [String] optional EntryCode of the Security_Code_DE dictionary for the providers being sought. A list of valid security codes can be obtained from GetDictionary on the Security_Code_DE dictionary. @param name_filter [String] optional If specified, will filter for providers with a lastname or entrycode that match. Defaults to %. @param show_only_providers_flag [String] optional (Y/N) Indicate whether or not to return only users that are also Providers. Defaults to Y. @param internal_external [String] optional I for Internal (User/providers that are internal to the enterprise). E for External (Referring physicians). Defaults to I. @param ordering_authority [String] optional Show only those users with an ordering provider level of X (which is a number) @param real_provider [String] optional Whether an NPI (National Provider ID) is required (Y/N). Y returns only actual providers. Default is N. @return [Array<Hash>, Array, MagicError] a list of providers
[ "a", "wrapper", "around", "GetProviders" ]
b32da6df50565f63dbdac2c861dd6793000c3634
https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/named_magic_methods.rb#L33-L50
train
Avhana/allscripts_api
lib/allscripts_api/named_magic_methods.rb
AllscriptsApi.NamedMagicMethods.get_patient_problems
def get_patient_problems(patient_id, show_by_encounter = "N", assessed = nil, encounter_id = nil, filter_on_id = nil, display_in_progress = nil) params = MagicParams.format( user_id: @allscripts_username, patient_id: patient_id, parameter1: show_by_encounter, parameter2: assessed, parameter3: encounter_id, parameter4: filter_on_id, parameter5: display_in_progress ) results = magic("GetPatientProblems", magic_params: params) results["getpatientproblemsinfo"] end
ruby
def get_patient_problems(patient_id, show_by_encounter = "N", assessed = nil, encounter_id = nil, filter_on_id = nil, display_in_progress = nil) params = MagicParams.format( user_id: @allscripts_username, patient_id: patient_id, parameter1: show_by_encounter, parameter2: assessed, parameter3: encounter_id, parameter4: filter_on_id, parameter5: display_in_progress ) results = magic("GetPatientProblems", magic_params: params) results["getpatientproblemsinfo"] end
[ "def", "get_patient_problems", "(", "patient_id", ",", "show_by_encounter", "=", "\"N\"", ",", "assessed", "=", "nil", ",", "encounter_id", "=", "nil", ",", "filter_on_id", "=", "nil", ",", "display_in_progress", "=", "nil", ")", "params", "=", "MagicParams", ".", "format", "(", "user_id", ":", "@allscripts_username", ",", "patient_id", ":", "patient_id", ",", "parameter1", ":", "show_by_encounter", ",", "parameter2", ":", "assessed", ",", "parameter3", ":", "encounter_id", ",", "parameter4", ":", "filter_on_id", ",", "parameter5", ":", "display_in_progress", ")", "results", "=", "magic", "(", "\"GetPatientProblems\"", ",", "magic_params", ":", "params", ")", "results", "[", "\"getpatientproblemsinfo\"", "]", "end" ]
a wrapper around GetPatientProblems @param patient_id [String] patient id @param show_by_encounter [String] Y or N (defaults to `N`) @param assessed [String] @param encounter_id [String] id for a specific patient encounter @param filter_on_id [String] @param display_in_progress [String] @return [Array<Hash>, Array, MagicError] a list of found problems, an empty array, or an error
[ "a", "wrapper", "around", "GetPatientProblems" ]
b32da6df50565f63dbdac2c861dd6793000c3634
https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/named_magic_methods.rb#L62-L79
train
Avhana/allscripts_api
lib/allscripts_api/named_magic_methods.rb
AllscriptsApi.NamedMagicMethods.get_results
def get_results(patient_id, since = nil) params = MagicParams.format( user_id: @allscripts_username, patient_id: patient_id, parameter1: since ) results = magic("GetResults", magic_params: params) results["getresultsinfo"] end
ruby
def get_results(patient_id, since = nil) params = MagicParams.format( user_id: @allscripts_username, patient_id: patient_id, parameter1: since ) results = magic("GetResults", magic_params: params) results["getresultsinfo"] end
[ "def", "get_results", "(", "patient_id", ",", "since", "=", "nil", ")", "params", "=", "MagicParams", ".", "format", "(", "user_id", ":", "@allscripts_username", ",", "patient_id", ":", "patient_id", ",", "parameter1", ":", "since", ")", "results", "=", "magic", "(", "\"GetResults\"", ",", "magic_params", ":", "params", ")", "results", "[", "\"getresultsinfo\"", "]", "end" ]
a wrapper around GetResults @param patient_id [String] patient id @param since [String] Specify a date/time combination to return only results that have been modified on or after that date/time. For example, 2014-01-01 or 2015-01-14 08:44:28.563. Defaults to nil @return [Array<Hash>, Array, MagicError] a list of found results (lab/imaging), an empty array, or an error
[ "a", "wrapper", "around", "GetResults" ]
b32da6df50565f63dbdac2c861dd6793000c3634
https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/named_magic_methods.rb#L88-L97
train
Avhana/allscripts_api
lib/allscripts_api/named_magic_methods.rb
AllscriptsApi.NamedMagicMethods.get_schedule
def get_schedule(start_date, end_date, other_username = nil) params = MagicParams.format( user_id: @allscripts_username, parameter1: format_date_range(start_date, end_date), parameter4: other_username ) results = magic("GetSchedule", magic_params: params) results["getscheduleinfo"] end
ruby
def get_schedule(start_date, end_date, other_username = nil) params = MagicParams.format( user_id: @allscripts_username, parameter1: format_date_range(start_date, end_date), parameter4: other_username ) results = magic("GetSchedule", magic_params: params) results["getscheduleinfo"] end
[ "def", "get_schedule", "(", "start_date", ",", "end_date", ",", "other_username", "=", "nil", ")", "params", "=", "MagicParams", ".", "format", "(", "user_id", ":", "@allscripts_username", ",", "parameter1", ":", "format_date_range", "(", "start_date", ",", "end_date", ")", ",", "parameter4", ":", "other_username", ")", "results", "=", "magic", "(", "\"GetSchedule\"", ",", "magic_params", ":", "params", ")", "results", "[", "\"getscheduleinfo\"", "]", "end" ]
a wrapper around GetSchedule, returns appointments scheduled under the the user for a given date range @param start_date [Date] start date inclusive @param end_date [Date] end date inclusive @return [Array<Hash>, Array, MagicError] a list of scheduled appointments, an empty array, or an error
[ "a", "wrapper", "around", "GetSchedule", "returns", "appointments", "scheduled", "under", "the", "the", "user", "for", "a", "given", "date", "range" ]
b32da6df50565f63dbdac2c861dd6793000c3634
https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/named_magic_methods.rb#L105-L114
train
Avhana/allscripts_api
lib/allscripts_api/named_magic_methods.rb
AllscriptsApi.NamedMagicMethods.get_encounter_list
def get_encounter_list(patient_id = "", encounter_type = "", when_or_limit = "", nostradamus = 0, show_past_flag = "Y", billing_provider_user_name = "") params = MagicParams.format( user_id: @allscripts_username, patient_id: patient_id, parameter1: encounter_type, # from Encounter_Type_DE parameter2: when_or_limit, parameter3: nostradamus, parameter4: show_past_flag, parameter5: billing_provider_user_name, ) results = magic("GetEncounterList", magic_params: params) results["getencounterlistinfo"] end
ruby
def get_encounter_list(patient_id = "", encounter_type = "", when_or_limit = "", nostradamus = 0, show_past_flag = "Y", billing_provider_user_name = "") params = MagicParams.format( user_id: @allscripts_username, patient_id: patient_id, parameter1: encounter_type, # from Encounter_Type_DE parameter2: when_or_limit, parameter3: nostradamus, parameter4: show_past_flag, parameter5: billing_provider_user_name, ) results = magic("GetEncounterList", magic_params: params) results["getencounterlistinfo"] end
[ "def", "get_encounter_list", "(", "patient_id", "=", "\"\"", ",", "encounter_type", "=", "\"\"", ",", "when_or_limit", "=", "\"\"", ",", "nostradamus", "=", "0", ",", "show_past_flag", "=", "\"Y\"", ",", "billing_provider_user_name", "=", "\"\"", ")", "params", "=", "MagicParams", ".", "format", "(", "user_id", ":", "@allscripts_username", ",", "patient_id", ":", "patient_id", ",", "parameter1", ":", "encounter_type", ",", "parameter2", ":", "when_or_limit", ",", "parameter3", ":", "nostradamus", ",", "parameter4", ":", "show_past_flag", ",", "parameter5", ":", "billing_provider_user_name", ",", ")", "results", "=", "magic", "(", "\"GetEncounterList\"", ",", "magic_params", ":", "params", ")", "results", "[", "\"getencounterlistinfo\"", "]", "end" ]
a wrapper around GetEncounterList @param patient_id [String] patient id @param encounter_type [String] encounter type to filter on from Encounter_Type_DE @param when_or_limit [String] filter by specified date @param nostradamus [String] how many days to look into the future. Defaults to 0. @param show_past_flag [String] show previous encounters, "Y" or "N". Defaults to Y @param billing_provider_user_name [String] filter by user name (if specified) @return [Array<Hash>, Array, MagicError] a list of encounters
[ "a", "wrapper", "around", "GetEncounterList" ]
b32da6df50565f63dbdac2c861dd6793000c3634
https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/named_magic_methods.rb#L125-L141
train
Avhana/allscripts_api
lib/allscripts_api/named_magic_methods.rb
AllscriptsApi.NamedMagicMethods.get_list_of_dictionaries
def get_list_of_dictionaries params = MagicParams.format(user_id: @allscripts_username) results = magic("GetListOfDictionaries", magic_params: params) results["getlistofdictionariesinfo"] end
ruby
def get_list_of_dictionaries params = MagicParams.format(user_id: @allscripts_username) results = magic("GetListOfDictionaries", magic_params: params) results["getlistofdictionariesinfo"] end
[ "def", "get_list_of_dictionaries", "params", "=", "MagicParams", ".", "format", "(", "user_id", ":", "@allscripts_username", ")", "results", "=", "magic", "(", "\"GetListOfDictionaries\"", ",", "magic_params", ":", "params", ")", "results", "[", "\"getlistofdictionariesinfo\"", "]", "end" ]
a wrapper around GetListOfDictionaries, which returns list of all dictionaries @return [Array<Hash>, Array, MagicError] a list of found dictionaries, an empty array, or an error
[ "a", "wrapper", "around", "GetListOfDictionaries", "which", "returns", "list", "of", "all", "dictionaries" ]
b32da6df50565f63dbdac2c861dd6793000c3634
https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/named_magic_methods.rb#L148-L152
train
Avhana/allscripts_api
lib/allscripts_api/named_magic_methods.rb
AllscriptsApi.NamedMagicMethods.get_dictionary
def get_dictionary(dictionary_name) params = MagicParams.format( user_id: @allscripts_username, parameter1: dictionary_name ) results = magic("GetDictionary", magic_params: params) results["getdictionaryinfo"] end
ruby
def get_dictionary(dictionary_name) params = MagicParams.format( user_id: @allscripts_username, parameter1: dictionary_name ) results = magic("GetDictionary", magic_params: params) results["getdictionaryinfo"] end
[ "def", "get_dictionary", "(", "dictionary_name", ")", "params", "=", "MagicParams", ".", "format", "(", "user_id", ":", "@allscripts_username", ",", "parameter1", ":", "dictionary_name", ")", "results", "=", "magic", "(", "\"GetDictionary\"", ",", "magic_params", ":", "params", ")", "results", "[", "\"getdictionaryinfo\"", "]", "end" ]
a wrapper around GetDictionary, which returnsentries from a specific dictionary. @param dictionary_name [String] the name of the desired dictionary, a "TableName" value from `get_list_of_dictionaries` @return [Array<Hash>, Array, MagicError] a list dictionary entries, an empty array, or an error
[ "a", "wrapper", "around", "GetDictionary", "which", "returnsentries", "from", "a", "specific", "dictionary", "." ]
b32da6df50565f63dbdac2c861dd6793000c3634
https://github.com/Avhana/allscripts_api/blob/b32da6df50565f63dbdac2c861dd6793000c3634/lib/allscripts_api/named_magic_methods.rb#L161-L168
train