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
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
MattRyder/tableau | lib/tableau/baseparser.rb | Tableau.BaseParser.create_class | def create_class(class_element)
begin
tt_class = Tableau::Class.new(@day, @time)
data = class_element.xpath('table/tr/td//text()')
raise "Misformed cell for #{module_id}" if data.count < 4
rescue Exception => e
p "EXCEPTION: #{e.message}", "Data Parsed:", data
return nil
end
# If the weeks are in the 2nd index, it's a core timetable
if @@WEEKS_REGEX.match(data[1].text())
tt_class.code = data[0].text().match(/^[A-Za-z0-9\-]+/).to_s
tt_class.type = data[0].text().gsub(tt_class.code, '').gsub('/', '')
tt_class.weeks = create_class_weeks(data[1].text())
tt_class.location = data[2].text()
tt_class.name = data[3].text()
else # this is a module timetable, laid out differently
if data[0].to_s != ""
tt_class.code = data[0].text().match(/^[A-Za-z0-9\-]+/).to_s
tt_class.type = data[0].text().gsub(tt_class.code, '').gsub('/', '')
end
tt_class.location = data[1].text()
tt_class.name = data[2].text()
tt_class.weeks = create_class_weeks(data[3].text())
end
# Same attribute on both timetables, DRY'd here
tt_class.tutor = data[4] ? data[4].text() : nil
if intervals = class_element.attribute('colspan').value
tt_class.intervals = intervals.to_i
end
tt_class
end | ruby | def create_class(class_element)
begin
tt_class = Tableau::Class.new(@day, @time)
data = class_element.xpath('table/tr/td//text()')
raise "Misformed cell for #{module_id}" if data.count < 4
rescue Exception => e
p "EXCEPTION: #{e.message}", "Data Parsed:", data
return nil
end
# If the weeks are in the 2nd index, it's a core timetable
if @@WEEKS_REGEX.match(data[1].text())
tt_class.code = data[0].text().match(/^[A-Za-z0-9\-]+/).to_s
tt_class.type = data[0].text().gsub(tt_class.code, '').gsub('/', '')
tt_class.weeks = create_class_weeks(data[1].text())
tt_class.location = data[2].text()
tt_class.name = data[3].text()
else # this is a module timetable, laid out differently
if data[0].to_s != ""
tt_class.code = data[0].text().match(/^[A-Za-z0-9\-]+/).to_s
tt_class.type = data[0].text().gsub(tt_class.code, '').gsub('/', '')
end
tt_class.location = data[1].text()
tt_class.name = data[2].text()
tt_class.weeks = create_class_weeks(data[3].text())
end
# Same attribute on both timetables, DRY'd here
tt_class.tutor = data[4] ? data[4].text() : nil
if intervals = class_element.attribute('colspan').value
tt_class.intervals = intervals.to_i
end
tt_class
end | [
"def",
"create_class",
"(",
"class_element",
")",
"begin",
"tt_class",
"=",
"Tableau",
"::",
"Class",
".",
"new",
"(",
"@day",
",",
"@time",
")",
"data",
"=",
"class_element",
".",
"xpath",
"(",
"'table/tr/td//text()'",
")",
"raise",
"\"Misformed cell for #{module_id}\"",
"if",
"data",
".",
"count",
"<",
"4",
"rescue",
"Exception",
"=>",
"e",
"p",
"\"EXCEPTION: #{e.message}\"",
",",
"\"Data Parsed:\"",
",",
"data",
"return",
"nil",
"end",
"if",
"@@WEEKS_REGEX",
".",
"match",
"(",
"data",
"[",
"1",
"]",
".",
"text",
"(",
")",
")",
"tt_class",
".",
"code",
"=",
"data",
"[",
"0",
"]",
".",
"text",
"(",
")",
".",
"match",
"(",
"/",
"\\-",
"/",
")",
".",
"to_s",
"tt_class",
".",
"type",
"=",
"data",
"[",
"0",
"]",
".",
"text",
"(",
")",
".",
"gsub",
"(",
"tt_class",
".",
"code",
",",
"''",
")",
".",
"gsub",
"(",
"'/'",
",",
"''",
")",
"tt_class",
".",
"weeks",
"=",
"create_class_weeks",
"(",
"data",
"[",
"1",
"]",
".",
"text",
"(",
")",
")",
"tt_class",
".",
"location",
"=",
"data",
"[",
"2",
"]",
".",
"text",
"(",
")",
"tt_class",
".",
"name",
"=",
"data",
"[",
"3",
"]",
".",
"text",
"(",
")",
"else",
"if",
"data",
"[",
"0",
"]",
".",
"to_s",
"!=",
"\"\"",
"tt_class",
".",
"code",
"=",
"data",
"[",
"0",
"]",
".",
"text",
"(",
")",
".",
"match",
"(",
"/",
"\\-",
"/",
")",
".",
"to_s",
"tt_class",
".",
"type",
"=",
"data",
"[",
"0",
"]",
".",
"text",
"(",
")",
".",
"gsub",
"(",
"tt_class",
".",
"code",
",",
"''",
")",
".",
"gsub",
"(",
"'/'",
",",
"''",
")",
"end",
"tt_class",
".",
"location",
"=",
"data",
"[",
"1",
"]",
".",
"text",
"(",
")",
"tt_class",
".",
"name",
"=",
"data",
"[",
"2",
"]",
".",
"text",
"(",
")",
"tt_class",
".",
"weeks",
"=",
"create_class_weeks",
"(",
"data",
"[",
"3",
"]",
".",
"text",
"(",
")",
")",
"end",
"tt_class",
".",
"tutor",
"=",
"data",
"[",
"4",
"]",
"?",
"data",
"[",
"4",
"]",
".",
"text",
"(",
")",
":",
"nil",
"if",
"intervals",
"=",
"class_element",
".",
"attribute",
"(",
"'colspan'",
")",
".",
"value",
"tt_class",
".",
"intervals",
"=",
"intervals",
".",
"to_i",
"end",
"tt_class",
"end"
] | Create a Class from the given data element | [
"Create",
"a",
"Class",
"from",
"the",
"given",
"data",
"element"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/baseparser.rb#L51-L88 | train |
MattRyder/tableau | lib/tableau/baseparser.rb | Tableau.BaseParser.create_class_weeks | def create_class_weeks(week_data)
week_span_regex = /([\d]{2}-[\d]{2})/
week_start_regex = /^[0-9]{2}/
week_end_regex = /[0-9]{2}$/
week_single_regex = /[\d]{2}/
class_weeks = Array.new
week_data.scan(@@WEEKS_REGEX).each do |weekspan|
# if it's a 28-39 week span
if weekspan =~ week_span_regex
start = week_start_regex.match(weekspan)[0].to_i
finish = week_end_regex.match(weekspan)[0].to_i
while start <= finish
class_weeks << start
start += 1
end
# some single week (30, 31, 32 etc) support
elsif weekspan =~ week_single_regex
class_weeks << week_single_regex.match(weekspan)[0].to_i
end
end
class_weeks
end | ruby | def create_class_weeks(week_data)
week_span_regex = /([\d]{2}-[\d]{2})/
week_start_regex = /^[0-9]{2}/
week_end_regex = /[0-9]{2}$/
week_single_regex = /[\d]{2}/
class_weeks = Array.new
week_data.scan(@@WEEKS_REGEX).each do |weekspan|
# if it's a 28-39 week span
if weekspan =~ week_span_regex
start = week_start_regex.match(weekspan)[0].to_i
finish = week_end_regex.match(weekspan)[0].to_i
while start <= finish
class_weeks << start
start += 1
end
# some single week (30, 31, 32 etc) support
elsif weekspan =~ week_single_regex
class_weeks << week_single_regex.match(weekspan)[0].to_i
end
end
class_weeks
end | [
"def",
"create_class_weeks",
"(",
"week_data",
")",
"week_span_regex",
"=",
"/",
"\\d",
"\\d",
"/",
"week_start_regex",
"=",
"/",
"/",
"week_end_regex",
"=",
"/",
"/",
"week_single_regex",
"=",
"/",
"\\d",
"/",
"class_weeks",
"=",
"Array",
".",
"new",
"week_data",
".",
"scan",
"(",
"@@WEEKS_REGEX",
")",
".",
"each",
"do",
"|",
"weekspan",
"|",
"if",
"weekspan",
"=~",
"week_span_regex",
"start",
"=",
"week_start_regex",
".",
"match",
"(",
"weekspan",
")",
"[",
"0",
"]",
".",
"to_i",
"finish",
"=",
"week_end_regex",
".",
"match",
"(",
"weekspan",
")",
"[",
"0",
"]",
".",
"to_i",
"while",
"start",
"<=",
"finish",
"class_weeks",
"<<",
"start",
"start",
"+=",
"1",
"end",
"elsif",
"weekspan",
"=~",
"week_single_regex",
"class_weeks",
"<<",
"week_single_regex",
".",
"match",
"(",
"weekspan",
")",
"[",
"0",
"]",
".",
"to_i",
"end",
"end",
"class_weeks",
"end"
] | Create the week range array for the given week string | [
"Create",
"the",
"week",
"range",
"array",
"for",
"the",
"given",
"week",
"string"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/baseparser.rb#L91-L118 | train |
Kuniri/kuniri | lib/kuniri/parser/output_format.rb | Parser.OutputFormat.create_all_data | def create_all_data(pParser)
return nil unless pParser
wrapper = self
# Go through each file
pParser.fileLanguage.each do |listOfFile|
# Inspect each element
listOfFile.fileElements.each do |singleElement|
@outputEngine.kuniri do
wrapper.handle_element(singleElement)
end
currentFilePathAndName = singleElement.name
write_file(currentFilePathAndName)
@outputEngine.reset_engine
end
end
end | ruby | def create_all_data(pParser)
return nil unless pParser
wrapper = self
# Go through each file
pParser.fileLanguage.each do |listOfFile|
# Inspect each element
listOfFile.fileElements.each do |singleElement|
@outputEngine.kuniri do
wrapper.handle_element(singleElement)
end
currentFilePathAndName = singleElement.name
write_file(currentFilePathAndName)
@outputEngine.reset_engine
end
end
end | [
"def",
"create_all_data",
"(",
"pParser",
")",
"return",
"nil",
"unless",
"pParser",
"wrapper",
"=",
"self",
"pParser",
".",
"fileLanguage",
".",
"each",
"do",
"|",
"listOfFile",
"|",
"listOfFile",
".",
"fileElements",
".",
"each",
"do",
"|",
"singleElement",
"|",
"@outputEngine",
".",
"kuniri",
"do",
"wrapper",
".",
"handle_element",
"(",
"singleElement",
")",
"end",
"currentFilePathAndName",
"=",
"singleElement",
".",
"name",
"write_file",
"(",
"currentFilePathAndName",
")",
"@outputEngine",
".",
"reset_engine",
"end",
"end",
"end"
] | Go through all the data, and generate the output
@param pParser
@return | [
"Go",
"through",
"all",
"the",
"data",
"and",
"generate",
"the",
"output"
] | 8b840ab307dc6bec48edd272c732b28c98f93f45 | https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/parser/output_format.rb#L28-L44 | train |
kul1/jinda | lib/jinda/helpers.rb | Jinda.Helpers.markdown | def markdown(text)
erbified = ERB.new(text.html_safe).result(binding)
red = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true)
red.render(erbified).html_safe
end | ruby | def markdown(text)
erbified = ERB.new(text.html_safe).result(binding)
red = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true)
red.render(erbified).html_safe
end | [
"def",
"markdown",
"(",
"text",
")",
"erbified",
"=",
"ERB",
".",
"new",
"(",
"text",
".",
"html_safe",
")",
".",
"result",
"(",
"binding",
")",
"red",
"=",
"Redcarpet",
"::",
"Markdown",
".",
"new",
"(",
"Redcarpet",
"::",
"Render",
"::",
"HTML",
",",
":autolink",
"=>",
"true",
",",
":space_after_headers",
"=>",
"true",
")",
"red",
".",
"render",
"(",
"erbified",
")",
".",
"html_safe",
"end"
] | methods from application_helper | [
"methods",
"from",
"application_helper"
] | 97cbf13fa5f9c8b6afdc50c61fc76a4d21f1d7f6 | https://github.com/kul1/jinda/blob/97cbf13fa5f9c8b6afdc50c61fc76a4d21f1d7f6/lib/jinda/helpers.rb#L178-L182 | train |
kul1/jinda | lib/jinda/helpers.rb | Jinda.Helpers.gen_views | def gen_views
t = ["*** generate ui ***"]
# create array of files to be tested
$afile = Array.new
Jinda::Module.all.each do |m|
m.services.each do |s|
dir ="app/views/#{s.module.code}"
unless gen_view_file_exist?(dir)
gen_view_mkdir(dir,t)
end
if s.code=='link'
f= "app/views/#{s.module.code}/index.haml"
$afile << f
unless gen_view_file_exist?(f)
sv = "app/jinda/template/linkview.haml"
f= "app/views/#{s.module.code}/index.haml"
gen_view_createfile(sv,f,t)
end
next
end
dir ="app/views/#{s.module.code}/#{s.code}"
unless gen_view_file_exist?(dir)
gen_view_mkdir(dir,t)
end
xml= REXML::Document.new(s.xml)
xml.elements.each('*/node') do |activity|
icon = activity.elements['icon']
next unless icon
action= freemind2action(icon.attributes['BUILTIN'])
next unless ui_action?(action)
code_name = activity.attributes["TEXT"].to_s
next if code_name.comment?
code= name2code(code_name)
if action=="pdf"
f= "app/views/#{s.module.code}/#{s.code}/#{code}.pdf.prawn"
else
f= "app/views/#{s.module.code}/#{s.code}/#{code}.html.erb"
end
$afile << f
unless gen_view_file_exist?(f)
sv = "app/jinda/template/view.html.erb"
gen_view_createfile(sv,f,t)
end
end
end
end
puts $afile.join("\n")
puts t.join("\n")
return $afile
end | ruby | def gen_views
t = ["*** generate ui ***"]
# create array of files to be tested
$afile = Array.new
Jinda::Module.all.each do |m|
m.services.each do |s|
dir ="app/views/#{s.module.code}"
unless gen_view_file_exist?(dir)
gen_view_mkdir(dir,t)
end
if s.code=='link'
f= "app/views/#{s.module.code}/index.haml"
$afile << f
unless gen_view_file_exist?(f)
sv = "app/jinda/template/linkview.haml"
f= "app/views/#{s.module.code}/index.haml"
gen_view_createfile(sv,f,t)
end
next
end
dir ="app/views/#{s.module.code}/#{s.code}"
unless gen_view_file_exist?(dir)
gen_view_mkdir(dir,t)
end
xml= REXML::Document.new(s.xml)
xml.elements.each('*/node') do |activity|
icon = activity.elements['icon']
next unless icon
action= freemind2action(icon.attributes['BUILTIN'])
next unless ui_action?(action)
code_name = activity.attributes["TEXT"].to_s
next if code_name.comment?
code= name2code(code_name)
if action=="pdf"
f= "app/views/#{s.module.code}/#{s.code}/#{code}.pdf.prawn"
else
f= "app/views/#{s.module.code}/#{s.code}/#{code}.html.erb"
end
$afile << f
unless gen_view_file_exist?(f)
sv = "app/jinda/template/view.html.erb"
gen_view_createfile(sv,f,t)
end
end
end
end
puts $afile.join("\n")
puts t.join("\n")
return $afile
end | [
"def",
"gen_views",
"t",
"=",
"[",
"\"*** generate ui ***\"",
"]",
"$afile",
"=",
"Array",
".",
"new",
"Jinda",
"::",
"Module",
".",
"all",
".",
"each",
"do",
"|",
"m",
"|",
"m",
".",
"services",
".",
"each",
"do",
"|",
"s",
"|",
"dir",
"=",
"\"app/views/#{s.module.code}\"",
"unless",
"gen_view_file_exist?",
"(",
"dir",
")",
"gen_view_mkdir",
"(",
"dir",
",",
"t",
")",
"end",
"if",
"s",
".",
"code",
"==",
"'link'",
"f",
"=",
"\"app/views/#{s.module.code}/index.haml\"",
"$afile",
"<<",
"f",
"unless",
"gen_view_file_exist?",
"(",
"f",
")",
"sv",
"=",
"\"app/jinda/template/linkview.haml\"",
"f",
"=",
"\"app/views/#{s.module.code}/index.haml\"",
"gen_view_createfile",
"(",
"sv",
",",
"f",
",",
"t",
")",
"end",
"next",
"end",
"dir",
"=",
"\"app/views/#{s.module.code}/#{s.code}\"",
"unless",
"gen_view_file_exist?",
"(",
"dir",
")",
"gen_view_mkdir",
"(",
"dir",
",",
"t",
")",
"end",
"xml",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"s",
".",
"xml",
")",
"xml",
".",
"elements",
".",
"each",
"(",
"'*/node'",
")",
"do",
"|",
"activity",
"|",
"icon",
"=",
"activity",
".",
"elements",
"[",
"'icon'",
"]",
"next",
"unless",
"icon",
"action",
"=",
"freemind2action",
"(",
"icon",
".",
"attributes",
"[",
"'BUILTIN'",
"]",
")",
"next",
"unless",
"ui_action?",
"(",
"action",
")",
"code_name",
"=",
"activity",
".",
"attributes",
"[",
"\"TEXT\"",
"]",
".",
"to_s",
"next",
"if",
"code_name",
".",
"comment?",
"code",
"=",
"name2code",
"(",
"code_name",
")",
"if",
"action",
"==",
"\"pdf\"",
"f",
"=",
"\"app/views/#{s.module.code}/#{s.code}/#{code}.pdf.prawn\"",
"else",
"f",
"=",
"\"app/views/#{s.module.code}/#{s.code}/#{code}.html.erb\"",
"end",
"$afile",
"<<",
"f",
"unless",
"gen_view_file_exist?",
"(",
"f",
")",
"sv",
"=",
"\"app/jinda/template/view.html.erb\"",
"gen_view_createfile",
"(",
"sv",
",",
"f",
",",
"t",
")",
"end",
"end",
"end",
"end",
"puts",
"$afile",
".",
"join",
"(",
"\"\\n\"",
")",
"puts",
"t",
".",
"join",
"(",
"\"\\n\"",
")",
"return",
"$afile",
"end"
] | Jinda Rake Task | [
"Jinda",
"Rake",
"Task"
] | 97cbf13fa5f9c8b6afdc50c61fc76a4d21f1d7f6 | https://github.com/kul1/jinda/blob/97cbf13fa5f9c8b6afdc50c61fc76a4d21f1d7f6/lib/jinda/helpers.rb#L380-L434 | train |
ndlib/rof | lib/rof/utility.rb | ROF.Utility.decode_work_type | def decode_work_type(obj)
if obj['type'] =~ WORK_TYPE_WITH_PREFIX_PATTERN
return 'GenericWork' if Regexp.last_match(2).nil?
Regexp.last_match(2)
else
# this will return nil if key t does not exist
work_type = obj['type'].downcase
WORK_TYPES[work_type]
end
end | ruby | def decode_work_type(obj)
if obj['type'] =~ WORK_TYPE_WITH_PREFIX_PATTERN
return 'GenericWork' if Regexp.last_match(2).nil?
Regexp.last_match(2)
else
# this will return nil if key t does not exist
work_type = obj['type'].downcase
WORK_TYPES[work_type]
end
end | [
"def",
"decode_work_type",
"(",
"obj",
")",
"if",
"obj",
"[",
"'type'",
"]",
"=~",
"WORK_TYPE_WITH_PREFIX_PATTERN",
"return",
"'GenericWork'",
"if",
"Regexp",
".",
"last_match",
"(",
"2",
")",
".",
"nil?",
"Regexp",
".",
"last_match",
"(",
"2",
")",
"else",
"work_type",
"=",
"obj",
"[",
"'type'",
"]",
".",
"downcase",
"WORK_TYPES",
"[",
"work_type",
"]",
"end",
"end"
] | Given an object's type, detrmine and return its af-model | [
"Given",
"an",
"object",
"s",
"type",
"detrmine",
"and",
"return",
"its",
"af",
"-",
"model"
] | 18a8cc009540a868447952eed82de035451025e8 | https://github.com/ndlib/rof/blob/18a8cc009540a868447952eed82de035451025e8/lib/rof/utility.rb#L36-L45 | train |
stepheneb/jnlp | lib/jnlp/otrunk.rb | Jnlp.Otrunk.run_local | def run_local(argument=@argument, main_class='net.sf.sail.emf.launch.EMFLauncher2')
if RUBY_PLATFORM =~ /java/
java.lang.Thread.currentThread.setContextClassLoader(JRuby.runtime.jruby_class_loader)
require_resources
configUrl = URL.new(JavaIO::File.new("dummy.txt").toURL, argument)
# configUrl = URL.new("document-edit.config")
unless @bundleManager
@bundleManager = SailCoreBundle::BundleManager.new
@serviceContext = @bundleManager.getServiceContext
@bundleManager.setContextURL(configUrl)
#
# Add the <code>bundles</code> configured in this bundles xml file. The format of the file
# is XMLEncoder
#
@bundleManager.addBundles(configUrl.openStream)
#
# Have all the bundles register their services, and then do any linking
# to other registered services
#
@bundleManager.initializeBundles
#
# Start the session manager
#
@manager = @serviceContext.getService(SailCoreService::SessionManager.java_class)
end
@manager.start(@serviceContext)
else
command = "java -classpath #{local_classpath} #{main_class} '#{argument}'"
$pid = fork { exec command }
end
end | ruby | def run_local(argument=@argument, main_class='net.sf.sail.emf.launch.EMFLauncher2')
if RUBY_PLATFORM =~ /java/
java.lang.Thread.currentThread.setContextClassLoader(JRuby.runtime.jruby_class_loader)
require_resources
configUrl = URL.new(JavaIO::File.new("dummy.txt").toURL, argument)
# configUrl = URL.new("document-edit.config")
unless @bundleManager
@bundleManager = SailCoreBundle::BundleManager.new
@serviceContext = @bundleManager.getServiceContext
@bundleManager.setContextURL(configUrl)
#
# Add the <code>bundles</code> configured in this bundles xml file. The format of the file
# is XMLEncoder
#
@bundleManager.addBundles(configUrl.openStream)
#
# Have all the bundles register their services, and then do any linking
# to other registered services
#
@bundleManager.initializeBundles
#
# Start the session manager
#
@manager = @serviceContext.getService(SailCoreService::SessionManager.java_class)
end
@manager.start(@serviceContext)
else
command = "java -classpath #{local_classpath} #{main_class} '#{argument}'"
$pid = fork { exec command }
end
end | [
"def",
"run_local",
"(",
"argument",
"=",
"@argument",
",",
"main_class",
"=",
"'net.sf.sail.emf.launch.EMFLauncher2'",
")",
"if",
"RUBY_PLATFORM",
"=~",
"/",
"/",
"java",
".",
"lang",
".",
"Thread",
".",
"currentThread",
".",
"setContextClassLoader",
"(",
"JRuby",
".",
"runtime",
".",
"jruby_class_loader",
")",
"require_resources",
"configUrl",
"=",
"URL",
".",
"new",
"(",
"JavaIO",
"::",
"File",
".",
"new",
"(",
"\"dummy.txt\"",
")",
".",
"toURL",
",",
"argument",
")",
"unless",
"@bundleManager",
"@bundleManager",
"=",
"SailCoreBundle",
"::",
"BundleManager",
".",
"new",
"@serviceContext",
"=",
"@bundleManager",
".",
"getServiceContext",
"@bundleManager",
".",
"setContextURL",
"(",
"configUrl",
")",
"@bundleManager",
".",
"addBundles",
"(",
"configUrl",
".",
"openStream",
")",
"@bundleManager",
".",
"initializeBundles",
"@manager",
"=",
"@serviceContext",
".",
"getService",
"(",
"SailCoreService",
"::",
"SessionManager",
".",
"java_class",
")",
"end",
"@manager",
".",
"start",
"(",
"@serviceContext",
")",
"else",
"command",
"=",
"\"java -classpath #{local_classpath} #{main_class} '#{argument}'\"",
"$pid",
"=",
"fork",
"{",
"exec",
"command",
"}",
"end",
"end"
] | This will start the jnlp locally in Java without
using Java Web Start
This method works in MRI by forking and using exec
to start a separate javavm process.
JRuby Note:
In JRuby the jars are required which makes them available
to JRuby -- but to make this work you will need to also
included them on the CLASSPATH.
The convienence method Jnlp#write_local_classpath_shell_script
can be used to create a shell script to set the classpath.
If you are using the JRuby interactive console you will need to
exclude any reference to a separate jruby included in the jnlp.
Example in JRuby jirb:
j = Jnlp::Otrunk.new('http://rails.dev.concord.org/sds/2/offering/144/jnlp/540/view?sailotrunk.otmlurl=http://continuum.concord.org/otrunk/examples/BasicExamples/document-edit.otml&sailotrunk.hidetree=false', 'cache'); nil
j.write_local_classpath_shell_script('document-edit_classpath.sh', :remove_jruby => true)
Now exit jirb and execute this in the shell:
source document-edit_classpath.sh
Now restart jirb:
j = Jnlp::Otrunk.new('http://rails.dev.concord.org/sds/2/offering/144/jnlp/540/view?sailotrunk.otmlurl=http://continuum.concord.org/otrunk/examples/BasicExamples/document-edit.otml&sailotrunk.hidetree=false', 'cache'); nil
j.run_local
You can optionally pass in jnlp and main-class arguments
If these paramaters are not present Otrunk#run_local will
use:
net.sf.sail.emf.launch.EMFLauncher2
as the default main class and the default argument in
the original jnlp. | [
"This",
"will",
"start",
"the",
"jnlp",
"locally",
"in",
"Java",
"without",
"using",
"Java",
"Web",
"Start"
] | 9d78fe8b0ebf5bcc68105513d35ce43199607ac4 | https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/otrunk.rb#L142-L174 | train |
ljcooke/putqr | lib/putqr.rb | PutQR.QRCode.render_image_iterm2 | def render_image_iterm2
return nil unless valid?
# References:
# https://iterm2.com/documentation-images.html
# https://iterm2.com/utilities/imgcat
# tmux requires some extra work for unrecognised escape code sequences
screen = ENV['TERM'].start_with? 'screen'
prefix = screen ? "\ePtmux;\e\e]" : "\e]"
suffix = screen ? "\a\e\\" : "\a"
png = qrcode.as_png(size: 600)
png_base64 = Base64.encode64(png.to_s).chomp
options = 'inline=1'
"#{prefix}1337;File=#{options}:#{png_base64}#{suffix}"
end | ruby | def render_image_iterm2
return nil unless valid?
# References:
# https://iterm2.com/documentation-images.html
# https://iterm2.com/utilities/imgcat
# tmux requires some extra work for unrecognised escape code sequences
screen = ENV['TERM'].start_with? 'screen'
prefix = screen ? "\ePtmux;\e\e]" : "\e]"
suffix = screen ? "\a\e\\" : "\a"
png = qrcode.as_png(size: 600)
png_base64 = Base64.encode64(png.to_s).chomp
options = 'inline=1'
"#{prefix}1337;File=#{options}:#{png_base64}#{suffix}"
end | [
"def",
"render_image_iterm2",
"return",
"nil",
"unless",
"valid?",
"screen",
"=",
"ENV",
"[",
"'TERM'",
"]",
".",
"start_with?",
"'screen'",
"prefix",
"=",
"screen",
"?",
"\"\\ePtmux;\\e\\e]\"",
":",
"\"\\e]\"",
"suffix",
"=",
"screen",
"?",
"\"\\a\\e\\\\\"",
":",
"\"\\a\"",
"png",
"=",
"qrcode",
".",
"as_png",
"(",
"size",
":",
"600",
")",
"png_base64",
"=",
"Base64",
".",
"encode64",
"(",
"png",
".",
"to_s",
")",
".",
"chomp",
"options",
"=",
"'inline=1'",
"\"#{prefix}1337;File=#{options}:#{png_base64}#{suffix}\"",
"end"
] | Render the QR code as an inline image for iTerm2.
Returns a string. | [
"Render",
"the",
"QR",
"code",
"as",
"an",
"inline",
"image",
"for",
"iTerm2",
".",
"Returns",
"a",
"string",
"."
] | 0305d63b52130ff78ba433ac9f6c327d1abd3d27 | https://github.com/ljcooke/putqr/blob/0305d63b52130ff78ba433ac9f6c327d1abd3d27/lib/putqr.rb#L47-L63 | train |
MattRyder/tableau | lib/tableau/timetable.rb | Tableau.Timetable.remove_class | def remove_class(rem_class)
@modules.each do |m|
if m.name == rem_class.name
m.classes.delete(rem_class)
break
end
end
end | ruby | def remove_class(rem_class)
@modules.each do |m|
if m.name == rem_class.name
m.classes.delete(rem_class)
break
end
end
end | [
"def",
"remove_class",
"(",
"rem_class",
")",
"@modules",
".",
"each",
"do",
"|",
"m",
"|",
"if",
"m",
".",
"name",
"==",
"rem_class",
".",
"name",
"m",
".",
"classes",
".",
"delete",
"(",
"rem_class",
")",
"break",
"end",
"end",
"end"
] | Removes a class from the timetable | [
"Removes",
"a",
"class",
"from",
"the",
"timetable"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/timetable.rb#L29-L36 | train |
MattRyder/tableau | lib/tableau/timetable.rb | Tableau.Timetable.classes_for_day | def classes_for_day(day)
classes = Tableau::ClassArray.new
@modules.each do |mod|
cfd = mod.classes_for_day(day)
cfd.each { |cl| classes << cl } if cfd
end
classes.count > 0 ? classes : nil
end | ruby | def classes_for_day(day)
classes = Tableau::ClassArray.new
@modules.each do |mod|
cfd = mod.classes_for_day(day)
cfd.each { |cl| classes << cl } if cfd
end
classes.count > 0 ? classes : nil
end | [
"def",
"classes_for_day",
"(",
"day",
")",
"classes",
"=",
"Tableau",
"::",
"ClassArray",
".",
"new",
"@modules",
".",
"each",
"do",
"|",
"mod",
"|",
"cfd",
"=",
"mod",
".",
"classes_for_day",
"(",
"day",
")",
"cfd",
".",
"each",
"{",
"|",
"cl",
"|",
"classes",
"<<",
"cl",
"}",
"if",
"cfd",
"end",
"classes",
".",
"count",
">",
"0",
"?",
"classes",
":",
"nil",
"end"
] | Returns an array of the given day's classes | [
"Returns",
"an",
"array",
"of",
"the",
"given",
"day",
"s",
"classes"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/timetable.rb#L39-L48 | train |
MattRyder/tableau | lib/tableau/timetable.rb | Tableau.Timetable.class_for_time | def class_for_time(day, time)
cfd = self.classes_for_day(day)
cfd.each { |c| return c if c.time == time }
nil
end | ruby | def class_for_time(day, time)
cfd = self.classes_for_day(day)
cfd.each { |c| return c if c.time == time }
nil
end | [
"def",
"class_for_time",
"(",
"day",
",",
"time",
")",
"cfd",
"=",
"self",
".",
"classes_for_day",
"(",
"day",
")",
"cfd",
".",
"each",
"{",
"|",
"c",
"|",
"return",
"c",
"if",
"c",
".",
"time",
"==",
"time",
"}",
"nil",
"end"
] | Returns the class at the given day & time | [
"Returns",
"the",
"class",
"at",
"the",
"given",
"day",
"&",
"time"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/timetable.rb#L51-L55 | train |
MattRyder/tableau | lib/tableau/timetable.rb | Tableau.Timetable.earliest_class | def earliest_class
earliest_classes = Tableau::ClassArray.new
@modules.each { |m| earliest_classes << m.earliest_class }
earliest = earliest_classes.first
earliest_classes.each { |c| earliest = c if c.time < earliest.time }
earliest
end | ruby | def earliest_class
earliest_classes = Tableau::ClassArray.new
@modules.each { |m| earliest_classes << m.earliest_class }
earliest = earliest_classes.first
earliest_classes.each { |c| earliest = c if c.time < earliest.time }
earliest
end | [
"def",
"earliest_class",
"earliest_classes",
"=",
"Tableau",
"::",
"ClassArray",
".",
"new",
"@modules",
".",
"each",
"{",
"|",
"m",
"|",
"earliest_classes",
"<<",
"m",
".",
"earliest_class",
"}",
"earliest",
"=",
"earliest_classes",
".",
"first",
"earliest_classes",
".",
"each",
"{",
"|",
"c",
"|",
"earliest",
"=",
"c",
"if",
"c",
".",
"time",
"<",
"earliest",
".",
"time",
"}",
"earliest",
"end"
] | Returns the earliest class on the timetable | [
"Returns",
"the",
"earliest",
"class",
"on",
"the",
"timetable"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/timetable.rb#L70-L77 | train |
MattRyder/tableau | lib/tableau/timetable.rb | Tableau.Timetable.conflicts | def conflicts
conflicts = Tableau::ClassArray.new
(0..4).each do |day|
days_classes = self.classes_for_day(day)
next if !days_classes || days_classes.count == 0
# get the last element index
last = days_classes.count - 1
for i in 0..last
i_c = days_classes[i]
time_range = i_c.time..(i_c.time + 3600 * i_c.duration)
for j in (i+1)..last
if time_range.cover?(days_classes[j].time)
conflicts << [days_classes[i], days_classes[j]]
end
end
end
end
conflicts # return the conflicts
end | ruby | def conflicts
conflicts = Tableau::ClassArray.new
(0..4).each do |day|
days_classes = self.classes_for_day(day)
next if !days_classes || days_classes.count == 0
# get the last element index
last = days_classes.count - 1
for i in 0..last
i_c = days_classes[i]
time_range = i_c.time..(i_c.time + 3600 * i_c.duration)
for j in (i+1)..last
if time_range.cover?(days_classes[j].time)
conflicts << [days_classes[i], days_classes[j]]
end
end
end
end
conflicts # return the conflicts
end | [
"def",
"conflicts",
"conflicts",
"=",
"Tableau",
"::",
"ClassArray",
".",
"new",
"(",
"0",
"..",
"4",
")",
".",
"each",
"do",
"|",
"day",
"|",
"days_classes",
"=",
"self",
".",
"classes_for_day",
"(",
"day",
")",
"next",
"if",
"!",
"days_classes",
"||",
"days_classes",
".",
"count",
"==",
"0",
"last",
"=",
"days_classes",
".",
"count",
"-",
"1",
"for",
"i",
"in",
"0",
"..",
"last",
"i_c",
"=",
"days_classes",
"[",
"i",
"]",
"time_range",
"=",
"i_c",
".",
"time",
"..",
"(",
"i_c",
".",
"time",
"+",
"3600",
"*",
"i_c",
".",
"duration",
")",
"for",
"j",
"in",
"(",
"i",
"+",
"1",
")",
"..",
"last",
"if",
"time_range",
".",
"cover?",
"(",
"days_classes",
"[",
"j",
"]",
".",
"time",
")",
"conflicts",
"<<",
"[",
"days_classes",
"[",
"i",
"]",
",",
"days_classes",
"[",
"j",
"]",
"]",
"end",
"end",
"end",
"end",
"conflicts",
"end"
] | Returns an array of time conflicts found in the timetable | [
"Returns",
"an",
"array",
"of",
"time",
"conflicts",
"found",
"in",
"the",
"timetable"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/timetable.rb#L90-L112 | train |
rsanheim/chatterbox | lib/chatterbox/exception_notification/presenter.rb | Chatterbox::ExceptionNotification.Presenter.render_hash | def render_hash(hsh)
str = ""
indiff_hsh = hsh.with_indifferent_access
indiff_hsh.keys.sort.each do |key|
str << "#{key}: "
value = indiff_hsh[key]
PP::pp(value, str)
end
str
end | ruby | def render_hash(hsh)
str = ""
indiff_hsh = hsh.with_indifferent_access
indiff_hsh.keys.sort.each do |key|
str << "#{key}: "
value = indiff_hsh[key]
PP::pp(value, str)
end
str
end | [
"def",
"render_hash",
"(",
"hsh",
")",
"str",
"=",
"\"\"",
"indiff_hsh",
"=",
"hsh",
".",
"with_indifferent_access",
"indiff_hsh",
".",
"keys",
".",
"sort",
".",
"each",
"do",
"|",
"key",
"|",
"str",
"<<",
"\"#{key}: \"",
"value",
"=",
"indiff_hsh",
"[",
"key",
"]",
"PP",
"::",
"pp",
"(",
"value",
",",
"str",
")",
"end",
"str",
"end"
] | renders hashes with keys in alpha-sorted order | [
"renders",
"hashes",
"with",
"keys",
"in",
"alpha",
"-",
"sorted",
"order"
] | 89f9596656a2724f399936017cf0a807ec284134 | https://github.com/rsanheim/chatterbox/blob/89f9596656a2724f399936017cf0a807ec284134/lib/chatterbox/exception_notification/presenter.rb#L74-L83 | train |
furunkel/gv | lib/gv.rb | GV.Component.html | def html(string)
ptr = Libcgraph.agstrdup_html(graph.ptr, string)
string = ptr.read_string
Libcgraph.agstrfree graph.ptr, ptr
string
end | ruby | def html(string)
ptr = Libcgraph.agstrdup_html(graph.ptr, string)
string = ptr.read_string
Libcgraph.agstrfree graph.ptr, ptr
string
end | [
"def",
"html",
"(",
"string",
")",
"ptr",
"=",
"Libcgraph",
".",
"agstrdup_html",
"(",
"graph",
".",
"ptr",
",",
"string",
")",
"string",
"=",
"ptr",
".",
"read_string",
"Libcgraph",
".",
"agstrfree",
"graph",
".",
"ptr",
",",
"ptr",
"string",
"end"
] | Creates an HTML label
@param string [String] the HTML to parse
@return [Object] a HTML label | [
"Creates",
"an",
"HTML",
"label"
] | 3a744032ee806d5ef78f94ff2dde290a2541029a | https://github.com/furunkel/gv/blob/3a744032ee806d5ef78f94ff2dde290a2541029a/lib/gv.rb#L75-L81 | train |
furunkel/gv | lib/gv.rb | GV.BaseGraph.edge | def edge(name, tail, head, attrs = {})
component Edge, [name, tail, head], attrs
end | ruby | def edge(name, tail, head, attrs = {})
component Edge, [name, tail, head], attrs
end | [
"def",
"edge",
"(",
"name",
",",
"tail",
",",
"head",
",",
"attrs",
"=",
"{",
"}",
")",
"component",
"Edge",
",",
"[",
"name",
",",
"tail",
",",
"head",
"]",
",",
"attrs",
"end"
] | Creates a new edge
@param name [String] the name (identifier) of the edge
@param tail [Node] the edge's tail node
@param head [Node] the edge's head node
@param attrs [Hash{String, Symbol => Object}] the attributes
to associate with this edge
@see http://www.graphviz.org/doc/info/attrs.html Node, Edge and Graph Attributes
@return [Edge] the newly created edge | [
"Creates",
"a",
"new",
"edge"
] | 3a744032ee806d5ef78f94ff2dde290a2541029a | https://github.com/furunkel/gv/blob/3a744032ee806d5ef78f94ff2dde290a2541029a/lib/gv.rb#L172-L174 | train |
furunkel/gv | lib/gv.rb | GV.BaseGraph.sub_graph | def sub_graph(name, attrs = {})
graph = component SubGraph, [name], attrs
yield graph if block_given?
graph
end | ruby | def sub_graph(name, attrs = {})
graph = component SubGraph, [name], attrs
yield graph if block_given?
graph
end | [
"def",
"sub_graph",
"(",
"name",
",",
"attrs",
"=",
"{",
"}",
")",
"graph",
"=",
"component",
"SubGraph",
",",
"[",
"name",
"]",
",",
"attrs",
"yield",
"graph",
"if",
"block_given?",
"graph",
"end"
] | Creates a new sub-graph
@param name [String] the name (identifier) of the sub-graph
@param attrs [Hash{String, Symbol => Object}] the attributes
to associate with this sub-graph
@see http://www.graphviz.org/doc/info/attrs.html Node, Edge and Graph Attributes
@return [SubGraph] the newly created sub-graph | [
"Creates",
"a",
"new",
"sub",
"-",
"graph"
] | 3a744032ee806d5ef78f94ff2dde290a2541029a | https://github.com/furunkel/gv/blob/3a744032ee806d5ef78f94ff2dde290a2541029a/lib/gv.rb#L182-L187 | train |
furunkel/gv | lib/gv.rb | GV.Graph.save | def save(filename, format = 'png', layout = 'dot')
Libgvc.gvLayout(@@gvc, ptr, layout.to_s)
Libgvc.gvRenderFilename(@@gvc, ptr, format.to_s, filename);
Libgvc.gvFreeLayout(@@gvc, ptr)
nil
end | ruby | def save(filename, format = 'png', layout = 'dot')
Libgvc.gvLayout(@@gvc, ptr, layout.to_s)
Libgvc.gvRenderFilename(@@gvc, ptr, format.to_s, filename);
Libgvc.gvFreeLayout(@@gvc, ptr)
nil
end | [
"def",
"save",
"(",
"filename",
",",
"format",
"=",
"'png'",
",",
"layout",
"=",
"'dot'",
")",
"Libgvc",
".",
"gvLayout",
"(",
"@@gvc",
",",
"ptr",
",",
"layout",
".",
"to_s",
")",
"Libgvc",
".",
"gvRenderFilename",
"(",
"@@gvc",
",",
"ptr",
",",
"format",
".",
"to_s",
",",
"filename",
")",
";",
"Libgvc",
".",
"gvFreeLayout",
"(",
"@@gvc",
",",
"ptr",
")",
"nil",
"end"
] | Renders the graph to an images and saves the result to a file
@param filename [String] the filename
@param format [String] the image format to use, e.g. 'svg', 'pdf' etc.
@param layout [String] the layout to use, e.g. 'dot' or 'neato' etc.
@return [nil] | [
"Renders",
"the",
"graph",
"to",
"an",
"images",
"and",
"saves",
"the",
"result",
"to",
"a",
"file"
] | 3a744032ee806d5ef78f94ff2dde290a2541029a | https://github.com/furunkel/gv/blob/3a744032ee806d5ef78f94ff2dde290a2541029a/lib/gv.rb#L282-L288 | train |
furunkel/gv | lib/gv.rb | GV.Graph.render | def render(format = 'png', layout = 'dot')
Libgvc.gvLayout(@@gvc, ptr, layout.to_s)
data_ptr = FFI::MemoryPointer.new(:pointer, 1)
len_ptr = FFI::MemoryPointer.new(:int, 1)
Libgvc.gvRenderData(@@gvc, ptr, format.to_s, data_ptr, len_ptr)
len = len_ptr.read_uint
data_ptr = data_ptr.read_pointer
data = data_ptr.read_string len
Libgvc.gvFreeRenderData(data_ptr)
Libgvc.gvFreeLayout(@@gvc, ptr)
data
end | ruby | def render(format = 'png', layout = 'dot')
Libgvc.gvLayout(@@gvc, ptr, layout.to_s)
data_ptr = FFI::MemoryPointer.new(:pointer, 1)
len_ptr = FFI::MemoryPointer.new(:int, 1)
Libgvc.gvRenderData(@@gvc, ptr, format.to_s, data_ptr, len_ptr)
len = len_ptr.read_uint
data_ptr = data_ptr.read_pointer
data = data_ptr.read_string len
Libgvc.gvFreeRenderData(data_ptr)
Libgvc.gvFreeLayout(@@gvc, ptr)
data
end | [
"def",
"render",
"(",
"format",
"=",
"'png'",
",",
"layout",
"=",
"'dot'",
")",
"Libgvc",
".",
"gvLayout",
"(",
"@@gvc",
",",
"ptr",
",",
"layout",
".",
"to_s",
")",
"data_ptr",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":pointer",
",",
"1",
")",
"len_ptr",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":int",
",",
"1",
")",
"Libgvc",
".",
"gvRenderData",
"(",
"@@gvc",
",",
"ptr",
",",
"format",
".",
"to_s",
",",
"data_ptr",
",",
"len_ptr",
")",
"len",
"=",
"len_ptr",
".",
"read_uint",
"data_ptr",
"=",
"data_ptr",
".",
"read_pointer",
"data",
"=",
"data_ptr",
".",
"read_string",
"len",
"Libgvc",
".",
"gvFreeRenderData",
"(",
"data_ptr",
")",
"Libgvc",
".",
"gvFreeLayout",
"(",
"@@gvc",
",",
"ptr",
")",
"data",
"end"
] | Renders the graph to an image and returns the result as a string
@param format [String] the image format to use, e.g. 'svg', 'pdf' etc.
@param layout [String] the layout to use, e.g. 'dot' or 'neato' etc.
@return [String] the rendered graph in the given format | [
"Renders",
"the",
"graph",
"to",
"an",
"image",
"and",
"returns",
"the",
"result",
"as",
"a",
"string"
] | 3a744032ee806d5ef78f94ff2dde290a2541029a | https://github.com/furunkel/gv/blob/3a744032ee806d5ef78f94ff2dde290a2541029a/lib/gv.rb#L294-L310 | train |
Kuniri/kuniri | lib/kuniri/language/abstract_container/structured_and_oo/variable_behaviour_helpers.rb | Languages.VariableBehaviourHelpers.setup_variable_behaviour | def setup_variable_behaviour
expression = MODULEBASE + type_of_language + VARIABLECLASS +
type_of_language
begin
clazz = Object.const_get(expression)
@variableBehaviour = clazz.new(who_am_i)
rescue NameError
Util::LoggerKuniri.error('Class name error')
end
end | ruby | def setup_variable_behaviour
expression = MODULEBASE + type_of_language + VARIABLECLASS +
type_of_language
begin
clazz = Object.const_get(expression)
@variableBehaviour = clazz.new(who_am_i)
rescue NameError
Util::LoggerKuniri.error('Class name error')
end
end | [
"def",
"setup_variable_behaviour",
"expression",
"=",
"MODULEBASE",
"+",
"type_of_language",
"+",
"VARIABLECLASS",
"+",
"type_of_language",
"begin",
"clazz",
"=",
"Object",
".",
"const_get",
"(",
"expression",
")",
"@variableBehaviour",
"=",
"clazz",
".",
"new",
"(",
"who_am_i",
")",
"rescue",
"NameError",
"Util",
"::",
"LoggerKuniri",
".",
"error",
"(",
"'Class name error'",
")",
"end",
"end"
] | Setup basic configurations for make attribute work correctly. It is
mandatory to call it with the correct parameters in the child class.
@param pVariableBehaviour Reference to a variable behaviour. | [
"Setup",
"basic",
"configurations",
"for",
"make",
"attribute",
"work",
"correctly",
".",
"It",
"is",
"mandatory",
"to",
"call",
"it",
"with",
"the",
"correct",
"parameters",
"in",
"the",
"child",
"class",
"."
] | 8b840ab307dc6bec48edd272c732b28c98f93f45 | https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/language/abstract_container/structured_and_oo/variable_behaviour_helpers.rb#L20-L29 | train |
Kuniri/kuniri | data/lang_syntax.rb | Languages.{LANG}.analyse_source | def analyse_source(pPath)
@name = File.basename(pPath, ".*")
@path = File.dirname(pPath)
analyse_first_step(pPath)
analyse_second_step
end | ruby | def analyse_source(pPath)
@name = File.basename(pPath, ".*")
@path = File.dirname(pPath)
analyse_first_step(pPath)
analyse_second_step
end | [
"def",
"analyse_source",
"(",
"pPath",
")",
"@name",
"=",
"File",
".",
"basename",
"(",
"pPath",
",",
"\".*\"",
")",
"@path",
"=",
"File",
".",
"dirname",
"(",
"pPath",
")",
"analyse_first_step",
"(",
"pPath",
")",
"analyse_second_step",
"end"
] | Analyse source code.
@param pPath Path of file to be analysed. | [
"Analyse",
"source",
"code",
"."
] | 8b840ab307dc6bec48edd272c732b28c98f93f45 | https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/data/lang_syntax.rb#L48-L53 | train |
Kuniri/kuniri | lib/kuniri/parser/parser.rb | Parser.Parser.start_parser | def start_parser
if (@filesPath.empty?)
raise Error::ConfigurationFileError,
"Source path not have #{@language} files."
end
@filesPath.each do |file|
language = @factory.get_language(@language)
fileElement = Languages::FileElementData.new(file)
source = File.open(file, 'rb')
language.analyse_source(fileElement, source)
@fileLanguage.push(language)
end
end | ruby | def start_parser
if (@filesPath.empty?)
raise Error::ConfigurationFileError,
"Source path not have #{@language} files."
end
@filesPath.each do |file|
language = @factory.get_language(@language)
fileElement = Languages::FileElementData.new(file)
source = File.open(file, 'rb')
language.analyse_source(fileElement, source)
@fileLanguage.push(language)
end
end | [
"def",
"start_parser",
"if",
"(",
"@filesPath",
".",
"empty?",
")",
"raise",
"Error",
"::",
"ConfigurationFileError",
",",
"\"Source path not have #{@language} files.\"",
"end",
"@filesPath",
".",
"each",
"do",
"|",
"file",
"|",
"language",
"=",
"@factory",
".",
"get_language",
"(",
"@language",
")",
"fileElement",
"=",
"Languages",
"::",
"FileElementData",
".",
"new",
"(",
"file",
")",
"source",
"=",
"File",
".",
"open",
"(",
"file",
",",
"'rb'",
")",
"language",
".",
"analyse_source",
"(",
"fileElement",
",",
"source",
")",
"@fileLanguage",
".",
"push",
"(",
"language",
")",
"end",
"end"
] | Start parse in the project. | [
"Start",
"parse",
"in",
"the",
"project",
"."
] | 8b840ab307dc6bec48edd272c732b28c98f93f45 | https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/parser/parser.rb#L45-L59 | train |
payneteasy/ruby-library-payneteasy-api | lib/paynet_easy/paynet_easy_api/callback/callback_factory.rb | PaynetEasy::PaynetEasyApi::Callback.CallbackFactory.callback | def callback(callback_type)
callback_class = "#{callback_type.camelize}Callback"
callback_file = "callback/#{callback_type}_callback"
begin
instantiate_callback callback_file, callback_class, callback_type
rescue LoadError => error
if @@allowed_payneteasy_callback_types.include? callback_type
instantiate_callback 'callback/paynet_easy_callback', 'PaynetEasyCallback', callback_type
else
raise error
end
end
end | ruby | def callback(callback_type)
callback_class = "#{callback_type.camelize}Callback"
callback_file = "callback/#{callback_type}_callback"
begin
instantiate_callback callback_file, callback_class, callback_type
rescue LoadError => error
if @@allowed_payneteasy_callback_types.include? callback_type
instantiate_callback 'callback/paynet_easy_callback', 'PaynetEasyCallback', callback_type
else
raise error
end
end
end | [
"def",
"callback",
"(",
"callback_type",
")",
"callback_class",
"=",
"\"#{callback_type.camelize}Callback\"",
"callback_file",
"=",
"\"callback/#{callback_type}_callback\"",
"begin",
"instantiate_callback",
"callback_file",
",",
"callback_class",
",",
"callback_type",
"rescue",
"LoadError",
"=>",
"error",
"if",
"@@allowed_payneteasy_callback_types",
".",
"include?",
"callback_type",
"instantiate_callback",
"'callback/paynet_easy_callback'",
",",
"'PaynetEasyCallback'",
",",
"callback_type",
"else",
"raise",
"error",
"end",
"end",
"end"
] | Get callback processor by callback type
@param callback_type [String] Callback type
@return [CallbackPrototype] Callback processor | [
"Get",
"callback",
"processor",
"by",
"callback",
"type"
] | 3200a447829b62e241fdc329f80fddb5f8d68cc0 | https://github.com/payneteasy/ruby-library-payneteasy-api/blob/3200a447829b62e241fdc329f80fddb5f8d68cc0/lib/paynet_easy/paynet_easy_api/callback/callback_factory.rb#L18-L31 | train |
payneteasy/ruby-library-payneteasy-api | lib/paynet_easy/paynet_easy_api/callback/callback_factory.rb | PaynetEasy::PaynetEasyApi::Callback.CallbackFactory.instantiate_callback | def instantiate_callback(callback_file, callback_class, callback_type)
require callback_file
PaynetEasy::PaynetEasyApi::Callback.const_get(callback_class).new(callback_type)
end | ruby | def instantiate_callback(callback_file, callback_class, callback_type)
require callback_file
PaynetEasy::PaynetEasyApi::Callback.const_get(callback_class).new(callback_type)
end | [
"def",
"instantiate_callback",
"(",
"callback_file",
",",
"callback_class",
",",
"callback_type",
")",
"require",
"callback_file",
"PaynetEasy",
"::",
"PaynetEasyApi",
"::",
"Callback",
".",
"const_get",
"(",
"callback_class",
")",
".",
"new",
"(",
"callback_type",
")",
"end"
] | Load callback class file and return new callback object
@param callback_file [String] Callback class file
@param callback_class [String] Callback class
@param callback_type [String] Callback type
@return [CallbackPrototype] Callback object | [
"Load",
"callback",
"class",
"file",
"and",
"return",
"new",
"callback",
"object"
] | 3200a447829b62e241fdc329f80fddb5f8d68cc0 | https://github.com/payneteasy/ruby-library-payneteasy-api/blob/3200a447829b62e241fdc329f80fddb5f8d68cc0/lib/paynet_easy/paynet_easy_api/callback/callback_factory.rb#L42-L45 | train |
wvanbergen/sql_tree | lib/sql_tree/node.rb | SQLTree::Node.Base.equal_children? | def equal_children?(other)
self.class.children.all? { |child| send(child) == other.send(child) }
end | ruby | def equal_children?(other)
self.class.children.all? { |child| send(child) == other.send(child) }
end | [
"def",
"equal_children?",
"(",
"other",
")",
"self",
".",
"class",
".",
"children",
".",
"all?",
"{",
"|",
"child",
"|",
"send",
"(",
"child",
")",
"==",
"other",
".",
"send",
"(",
"child",
")",
"}",
"end"
] | Compares this node with another node, returns true if the nodes are equal.
Returns true if all children of the current object and the other object are equal. | [
"Compares",
"this",
"node",
"with",
"another",
"node",
"returns",
"true",
"if",
"the",
"nodes",
"are",
"equal",
".",
"Returns",
"true",
"if",
"all",
"children",
"of",
"the",
"current",
"object",
"and",
"the",
"other",
"object",
"are",
"equal",
"."
] | b45566c4c52962def5bfd376622a19697dd49969 | https://github.com/wvanbergen/sql_tree/blob/b45566c4c52962def5bfd376622a19697dd49969/lib/sql_tree/node.rb#L58-L60 | train |
wvanbergen/sql_tree | lib/sql_tree/node.rb | SQLTree::Node.Base.equal_leafs? | def equal_leafs?(other)
self.class.leafs.all? { |leaf| send(leaf) == other.send(leaf) }
end | ruby | def equal_leafs?(other)
self.class.leafs.all? { |leaf| send(leaf) == other.send(leaf) }
end | [
"def",
"equal_leafs?",
"(",
"other",
")",
"self",
".",
"class",
".",
"leafs",
".",
"all?",
"{",
"|",
"leaf",
"|",
"send",
"(",
"leaf",
")",
"==",
"other",
".",
"send",
"(",
"leaf",
")",
"}",
"end"
] | Returns true if all leaf values of the current object and the other object are equal. | [
"Returns",
"true",
"if",
"all",
"leaf",
"values",
"of",
"the",
"current",
"object",
"and",
"the",
"other",
"object",
"are",
"equal",
"."
] | b45566c4c52962def5bfd376622a19697dd49969 | https://github.com/wvanbergen/sql_tree/blob/b45566c4c52962def5bfd376622a19697dd49969/lib/sql_tree/node.rb#L63-L65 | train |
hulihanapplications/fletcher | spec/support/benchmark.rb | RSpec.Benchmark.benchmark | def benchmark(times = 1, &block)
elapsed = (1..times).collect do
GC.start
::Benchmark.realtime(&block) * times
end
Result.new(elapsed)
end | ruby | def benchmark(times = 1, &block)
elapsed = (1..times).collect do
GC.start
::Benchmark.realtime(&block) * times
end
Result.new(elapsed)
end | [
"def",
"benchmark",
"(",
"times",
"=",
"1",
",",
"&",
"block",
")",
"elapsed",
"=",
"(",
"1",
"..",
"times",
")",
".",
"collect",
"do",
"GC",
".",
"start",
"::",
"Benchmark",
".",
"realtime",
"(",
"&",
"block",
")",
"*",
"times",
"end",
"Result",
".",
"new",
"(",
"elapsed",
")",
"end"
] | Run a given block and calculate the average execution time.
The block will be executed 1 times by default.
benchmark { do something }
benchmark(100) { do something } | [
"Run",
"a",
"given",
"block",
"and",
"calculate",
"the",
"average",
"execution",
"time",
".",
"The",
"block",
"will",
"be",
"executed",
"1",
"times",
"by",
"default",
"."
] | 8843bfb908007da654268e13b7973219570cde54 | https://github.com/hulihanapplications/fletcher/blob/8843bfb908007da654268e13b7973219570cde54/spec/support/benchmark.rb#L27-L34 | train |
darbylabs/magma | lib/magma/renderer.rb | Magma.Renderer.format | def format(options)
options.map do |key, value|
[{
format: :f,
size: :s,
length: :hls_time,
}[key] || key, value].map(&:to_s).join('=')
end
end | ruby | def format(options)
options.map do |key, value|
[{
format: :f,
size: :s,
length: :hls_time,
}[key] || key, value].map(&:to_s).join('=')
end
end | [
"def",
"format",
"(",
"options",
")",
"options",
".",
"map",
"do",
"|",
"key",
",",
"value",
"|",
"[",
"{",
"format",
":",
":f",
",",
"size",
":",
":s",
",",
"length",
":",
":hls_time",
",",
"}",
"[",
"key",
"]",
"||",
"key",
",",
"value",
"]",
".",
"map",
"(",
"&",
":to_s",
")",
".",
"join",
"(",
"'='",
")",
"end",
"end"
] | Formats keys to melt arguments | [
"Formats",
"keys",
"to",
"melt",
"arguments"
] | 62da478396fb479786f109128b6f65dd85b7c04c | https://github.com/darbylabs/magma/blob/62da478396fb479786f109128b6f65dd85b7c04c/lib/magma/renderer.rb#L37-L45 | train |
darbylabs/magma | lib/magma/renderer.rb | Magma.Renderer.melt_args | def melt_args(options)
[
options[:infile],
"-consumer avformat:#{outfile}",
].concat(pipe(options, %i[
symbolize_keys
add_defaults
select
transform
table
format
]))
end | ruby | def melt_args(options)
[
options[:infile],
"-consumer avformat:#{outfile}",
].concat(pipe(options, %i[
symbolize_keys
add_defaults
select
transform
table
format
]))
end | [
"def",
"melt_args",
"(",
"options",
")",
"[",
"options",
"[",
":infile",
"]",
",",
"\"-consumer avformat:#{outfile}\"",
",",
"]",
".",
"concat",
"(",
"pipe",
"(",
"options",
",",
"%i[",
"symbolize_keys",
"add_defaults",
"select",
"transform",
"table",
"format",
"]",
")",
")",
"end"
] | Constructs melt arguments from options hash | [
"Constructs",
"melt",
"arguments",
"from",
"options",
"hash"
] | 62da478396fb479786f109128b6f65dd85b7c04c | https://github.com/darbylabs/magma/blob/62da478396fb479786f109128b6f65dd85b7c04c/lib/magma/renderer.rb#L54-L66 | train |
darbylabs/magma | lib/magma/renderer.rb | Magma.Renderer.render! | def render!
cmd = melt melt_args(options.merge(outfile: outfile)).join(' ')
puts "Run: #{cmd}"
puts
run(cmd) do |_stdin, _stdout, stderr|
stderr.each("\r") do |line|
STDOUT.write "\r#{line}"
end
end
end | ruby | def render!
cmd = melt melt_args(options.merge(outfile: outfile)).join(' ')
puts "Run: #{cmd}"
puts
run(cmd) do |_stdin, _stdout, stderr|
stderr.each("\r") do |line|
STDOUT.write "\r#{line}"
end
end
end | [
"def",
"render!",
"cmd",
"=",
"melt",
"melt_args",
"(",
"options",
".",
"merge",
"(",
"outfile",
":",
"outfile",
")",
")",
".",
"join",
"(",
"' '",
")",
"puts",
"\"Run: #{cmd}\"",
"puts",
"run",
"(",
"cmd",
")",
"do",
"|",
"_stdin",
",",
"_stdout",
",",
"stderr",
"|",
"stderr",
".",
"each",
"(",
"\"\\r\"",
")",
"do",
"|",
"line",
"|",
"STDOUT",
".",
"write",
"\"\\r#{line}\"",
"end",
"end",
"end"
] | Renders the project | [
"Renders",
"the",
"project"
] | 62da478396fb479786f109128b6f65dd85b7c04c | https://github.com/darbylabs/magma/blob/62da478396fb479786f109128b6f65dd85b7c04c/lib/magma/renderer.rb#L69-L79 | train |
darbylabs/magma | lib/magma/renderer.rb | Magma.Renderer.select | def select(options)
# Clone original
options = options.clone
# Handle related options
options.delete(:real_time) unless options.delete(:enable_real_time)
# Reject
options.select do |key, value|
!value.nil? && %i[
format
hls_list_size
real_time
length
preset
size
start_number
vcodec
].include?(key)
end
end | ruby | def select(options)
# Clone original
options = options.clone
# Handle related options
options.delete(:real_time) unless options.delete(:enable_real_time)
# Reject
options.select do |key, value|
!value.nil? && %i[
format
hls_list_size
real_time
length
preset
size
start_number
vcodec
].include?(key)
end
end | [
"def",
"select",
"(",
"options",
")",
"options",
"=",
"options",
".",
"clone",
"options",
".",
"delete",
"(",
":real_time",
")",
"unless",
"options",
".",
"delete",
"(",
":enable_real_time",
")",
"options",
".",
"select",
"do",
"|",
"key",
",",
"value",
"|",
"!",
"value",
".",
"nil?",
"&&",
"%i[",
"format",
"hls_list_size",
"real_time",
"length",
"preset",
"size",
"start_number",
"vcodec",
"]",
".",
"include?",
"(",
"key",
")",
"end",
"end"
] | Selects certain options | [
"Selects",
"certain",
"options"
] | 62da478396fb479786f109128b6f65dd85b7c04c | https://github.com/darbylabs/magma/blob/62da478396fb479786f109128b6f65dd85b7c04c/lib/magma/renderer.rb#L82-L102 | train |
darbylabs/magma | lib/magma/renderer.rb | Magma.Renderer.table | def table(options)
lpadding = options.keys.max_by(&:length).length + 2
rpadding = options.values.max_by { |v| v.to_s.length }.to_s.length
puts 'PROPERTY'.ljust(lpadding) + 'VALUE'
puts '=' * (lpadding + rpadding)
options.keys.sort.each do |key|
puts key.to_s.ljust(lpadding) + options[key].to_s
end
puts
options
end | ruby | def table(options)
lpadding = options.keys.max_by(&:length).length + 2
rpadding = options.values.max_by { |v| v.to_s.length }.to_s.length
puts 'PROPERTY'.ljust(lpadding) + 'VALUE'
puts '=' * (lpadding + rpadding)
options.keys.sort.each do |key|
puts key.to_s.ljust(lpadding) + options[key].to_s
end
puts
options
end | [
"def",
"table",
"(",
"options",
")",
"lpadding",
"=",
"options",
".",
"keys",
".",
"max_by",
"(",
"&",
":length",
")",
".",
"length",
"+",
"2",
"rpadding",
"=",
"options",
".",
"values",
".",
"max_by",
"{",
"|",
"v",
"|",
"v",
".",
"to_s",
".",
"length",
"}",
".",
"to_s",
".",
"length",
"puts",
"'PROPERTY'",
".",
"ljust",
"(",
"lpadding",
")",
"+",
"'VALUE'",
"puts",
"'='",
"*",
"(",
"lpadding",
"+",
"rpadding",
")",
"options",
".",
"keys",
".",
"sort",
".",
"each",
"do",
"|",
"key",
"|",
"puts",
"key",
".",
"to_s",
".",
"ljust",
"(",
"lpadding",
")",
"+",
"options",
"[",
"key",
"]",
".",
"to_s",
"end",
"puts",
"options",
"end"
] | Prints a table and passes through the options hash | [
"Prints",
"a",
"table",
"and",
"passes",
"through",
"the",
"options",
"hash"
] | 62da478396fb479786f109128b6f65dd85b7c04c | https://github.com/darbylabs/magma/blob/62da478396fb479786f109128b6f65dd85b7c04c/lib/magma/renderer.rb#L105-L115 | train |
darbylabs/magma | lib/magma/renderer.rb | Magma.Renderer.transform | def transform(options)
options.map do |key, value|
[key, ({
real_time: ->(x) { "-#{x}" },
}[key] || proc { |x| x }).call(value)]
end.to_h
end | ruby | def transform(options)
options.map do |key, value|
[key, ({
real_time: ->(x) { "-#{x}" },
}[key] || proc { |x| x }).call(value)]
end.to_h
end | [
"def",
"transform",
"(",
"options",
")",
"options",
".",
"map",
"do",
"|",
"key",
",",
"value",
"|",
"[",
"key",
",",
"(",
"{",
"real_time",
":",
"->",
"(",
"x",
")",
"{",
"\"-#{x}\"",
"}",
",",
"}",
"[",
"key",
"]",
"||",
"proc",
"{",
"|",
"x",
"|",
"x",
"}",
")",
".",
"call",
"(",
"value",
")",
"]",
"end",
".",
"to_h",
"end"
] | Transforms certain options values | [
"Transforms",
"certain",
"options",
"values"
] | 62da478396fb479786f109128b6f65dd85b7c04c | https://github.com/darbylabs/magma/blob/62da478396fb479786f109128b6f65dd85b7c04c/lib/magma/renderer.rb#L118-L124 | train |
ronyv89/skydrive | lib/skydrive/collection.rb | Skydrive.Collection.items | def items
@items = []
@data.each do |object_data|
if object_data["type"]
@items << "Skydrive::#{object_data["type"].capitalize}".constantize.new(client, object_data)
elsif object_data["id"].match /^comment\..+/
@items << Skydrive::Comment.new(client, object_data)
end
end
@items
end | ruby | def items
@items = []
@data.each do |object_data|
if object_data["type"]
@items << "Skydrive::#{object_data["type"].capitalize}".constantize.new(client, object_data)
elsif object_data["id"].match /^comment\..+/
@items << Skydrive::Comment.new(client, object_data)
end
end
@items
end | [
"def",
"items",
"@items",
"=",
"[",
"]",
"@data",
".",
"each",
"do",
"|",
"object_data",
"|",
"if",
"object_data",
"[",
"\"type\"",
"]",
"@items",
"<<",
"\"Skydrive::#{object_data[\"type\"].capitalize}\"",
".",
"constantize",
".",
"new",
"(",
"client",
",",
"object_data",
")",
"elsif",
"object_data",
"[",
"\"id\"",
"]",
".",
"match",
"/",
"\\.",
"/",
"@items",
"<<",
"Skydrive",
"::",
"Comment",
".",
"new",
"(",
"client",
",",
"object_data",
")",
"end",
"end",
"@items",
"end"
] | Array of items in the collection
@return [Array] | [
"Array",
"of",
"items",
"in",
"the",
"collection"
] | 6cf7b692f64c6f00a81bc7ca6fffca3020244072 | https://github.com/ronyv89/skydrive/blob/6cf7b692f64c6f00a81bc7ca6fffca3020244072/lib/skydrive/collection.rb#L19-L29 | train |
bdurand/json_record | lib/json_record/attribute_methods.rb | JsonRecord.AttributeMethods.read_attribute | def read_attribute (field, context)
if field.multivalued?
arr = json_attributes[field.name]
unless arr
arr = EmbeddedDocumentArray.new(field.type, context)
json_attributes[field.name] = arr
end
return arr
else
val = json_attributes[field.name]
if val.nil? and !field.default.nil?
val = field.default.dup rescue field.default
json_attributes[field.name] = val
end
return val
end
end | ruby | def read_attribute (field, context)
if field.multivalued?
arr = json_attributes[field.name]
unless arr
arr = EmbeddedDocumentArray.new(field.type, context)
json_attributes[field.name] = arr
end
return arr
else
val = json_attributes[field.name]
if val.nil? and !field.default.nil?
val = field.default.dup rescue field.default
json_attributes[field.name] = val
end
return val
end
end | [
"def",
"read_attribute",
"(",
"field",
",",
"context",
")",
"if",
"field",
".",
"multivalued?",
"arr",
"=",
"json_attributes",
"[",
"field",
".",
"name",
"]",
"unless",
"arr",
"arr",
"=",
"EmbeddedDocumentArray",
".",
"new",
"(",
"field",
".",
"type",
",",
"context",
")",
"json_attributes",
"[",
"field",
".",
"name",
"]",
"=",
"arr",
"end",
"return",
"arr",
"else",
"val",
"=",
"json_attributes",
"[",
"field",
".",
"name",
"]",
"if",
"val",
".",
"nil?",
"and",
"!",
"field",
".",
"default",
".",
"nil?",
"val",
"=",
"field",
".",
"default",
".",
"dup",
"rescue",
"field",
".",
"default",
"json_attributes",
"[",
"field",
".",
"name",
"]",
"=",
"val",
"end",
"return",
"val",
"end",
"end"
] | Read a field. The field param must be a FieldDefinition and the context should be the record
which is being read from. | [
"Read",
"a",
"field",
".",
"The",
"field",
"param",
"must",
"be",
"a",
"FieldDefinition",
"and",
"the",
"context",
"should",
"be",
"the",
"record",
"which",
"is",
"being",
"read",
"from",
"."
] | 463f4719d9618f6d2406c0aab6028e0156f7c775 | https://github.com/bdurand/json_record/blob/463f4719d9618f6d2406c0aab6028e0156f7c775/lib/json_record/attribute_methods.rb#L6-L22 | train |
bdurand/json_record | lib/json_record/attribute_methods.rb | JsonRecord.AttributeMethods.write_attribute | def write_attribute (field, val, context)
if field.multivalued?
val = val.values if val.is_a?(Hash)
json_attributes[field.name] = EmbeddedDocumentArray.new(field.type, context, val)
else
old_value = read_attribute(field, context)
converted_value = field.convert(val)
converted_value.parent = context if converted_value.is_a?(EmbeddedDocument)
unless old_value == converted_value
unless field.type.include?(EmbeddedDocument) or Thread.current[:do_not_track_json_field_changes]
changes = changed_attributes
if changes.include?(field.name)
changes.delete(field.name) if converted_value == changes[field.name]
else
old_value = (old_value.clone rescue old_value) unless old_value.nil? || old_value.is_a?(Numeric) || old_value.is_a?(Symbol) || old_value.is_a?(TrueClass) || old_value.is_a?(FalseClass)
changes[field.name] = old_value
end
end
unless converted_value.nil?
json_attributes[field.name] = converted_value
else
json_attributes.delete(field.name)
end
end
context.json_attributes_before_type_cast[field.name] = val
end
return val
end | ruby | def write_attribute (field, val, context)
if field.multivalued?
val = val.values if val.is_a?(Hash)
json_attributes[field.name] = EmbeddedDocumentArray.new(field.type, context, val)
else
old_value = read_attribute(field, context)
converted_value = field.convert(val)
converted_value.parent = context if converted_value.is_a?(EmbeddedDocument)
unless old_value == converted_value
unless field.type.include?(EmbeddedDocument) or Thread.current[:do_not_track_json_field_changes]
changes = changed_attributes
if changes.include?(field.name)
changes.delete(field.name) if converted_value == changes[field.name]
else
old_value = (old_value.clone rescue old_value) unless old_value.nil? || old_value.is_a?(Numeric) || old_value.is_a?(Symbol) || old_value.is_a?(TrueClass) || old_value.is_a?(FalseClass)
changes[field.name] = old_value
end
end
unless converted_value.nil?
json_attributes[field.name] = converted_value
else
json_attributes.delete(field.name)
end
end
context.json_attributes_before_type_cast[field.name] = val
end
return val
end | [
"def",
"write_attribute",
"(",
"field",
",",
"val",
",",
"context",
")",
"if",
"field",
".",
"multivalued?",
"val",
"=",
"val",
".",
"values",
"if",
"val",
".",
"is_a?",
"(",
"Hash",
")",
"json_attributes",
"[",
"field",
".",
"name",
"]",
"=",
"EmbeddedDocumentArray",
".",
"new",
"(",
"field",
".",
"type",
",",
"context",
",",
"val",
")",
"else",
"old_value",
"=",
"read_attribute",
"(",
"field",
",",
"context",
")",
"converted_value",
"=",
"field",
".",
"convert",
"(",
"val",
")",
"converted_value",
".",
"parent",
"=",
"context",
"if",
"converted_value",
".",
"is_a?",
"(",
"EmbeddedDocument",
")",
"unless",
"old_value",
"==",
"converted_value",
"unless",
"field",
".",
"type",
".",
"include?",
"(",
"EmbeddedDocument",
")",
"or",
"Thread",
".",
"current",
"[",
":do_not_track_json_field_changes",
"]",
"changes",
"=",
"changed_attributes",
"if",
"changes",
".",
"include?",
"(",
"field",
".",
"name",
")",
"changes",
".",
"delete",
"(",
"field",
".",
"name",
")",
"if",
"converted_value",
"==",
"changes",
"[",
"field",
".",
"name",
"]",
"else",
"old_value",
"=",
"(",
"old_value",
".",
"clone",
"rescue",
"old_value",
")",
"unless",
"old_value",
".",
"nil?",
"||",
"old_value",
".",
"is_a?",
"(",
"Numeric",
")",
"||",
"old_value",
".",
"is_a?",
"(",
"Symbol",
")",
"||",
"old_value",
".",
"is_a?",
"(",
"TrueClass",
")",
"||",
"old_value",
".",
"is_a?",
"(",
"FalseClass",
")",
"changes",
"[",
"field",
".",
"name",
"]",
"=",
"old_value",
"end",
"end",
"unless",
"converted_value",
".",
"nil?",
"json_attributes",
"[",
"field",
".",
"name",
"]",
"=",
"converted_value",
"else",
"json_attributes",
".",
"delete",
"(",
"field",
".",
"name",
")",
"end",
"end",
"context",
".",
"json_attributes_before_type_cast",
"[",
"field",
".",
"name",
"]",
"=",
"val",
"end",
"return",
"val",
"end"
] | Write a field. The field param must be a FieldDefinition and the context should be the record
which is being read from. | [
"Write",
"a",
"field",
".",
"The",
"field",
"param",
"must",
"be",
"a",
"FieldDefinition",
"and",
"the",
"context",
"should",
"be",
"the",
"record",
"which",
"is",
"being",
"read",
"from",
"."
] | 463f4719d9618f6d2406c0aab6028e0156f7c775 | https://github.com/bdurand/json_record/blob/463f4719d9618f6d2406c0aab6028e0156f7c775/lib/json_record/attribute_methods.rb#L26-L53 | train |
jwoertink/tourets | lib/tourets/property.rb | TouRETS.Property.method_missing | def method_missing(method_name, *args, &block)
mapped_key = key_map[method_name.to_sym]
if attributes.has_key?(mapped_key)
attributes[mapped_key]
else
super
end
end | ruby | def method_missing(method_name, *args, &block)
mapped_key = key_map[method_name.to_sym]
if attributes.has_key?(mapped_key)
attributes[mapped_key]
else
super
end
end | [
"def",
"method_missing",
"(",
"method_name",
",",
"*",
"args",
",",
"&",
"block",
")",
"mapped_key",
"=",
"key_map",
"[",
"method_name",
".",
"to_sym",
"]",
"if",
"attributes",
".",
"has_key?",
"(",
"mapped_key",
")",
"attributes",
"[",
"mapped_key",
"]",
"else",
"super",
"end",
"end"
] | Look for one of the mapped keys, and return the value or throw method missing error. | [
"Look",
"for",
"one",
"of",
"the",
"mapped",
"keys",
"and",
"return",
"the",
"value",
"or",
"throw",
"method",
"missing",
"error",
"."
] | 1cf5b5b061702846d38a261ad256f1641d2553c1 | https://github.com/jwoertink/tourets/blob/1cf5b5b061702846d38a261ad256f1641d2553c1/lib/tourets/property.rb#L68-L75 | train |
Kuniri/kuniri | lib/kuniri/language/container_data/structured_and_oo/file_element_data.rb | Languages.FileElementData.add_global_variable | def add_global_variable(*pVariable)
pVariable.flatten.each do |element|
next unless element.is_a?(Languages::VariableGlobalData)
@global_variables.push(element)
end
end | ruby | def add_global_variable(*pVariable)
pVariable.flatten.each do |element|
next unless element.is_a?(Languages::VariableGlobalData)
@global_variables.push(element)
end
end | [
"def",
"add_global_variable",
"(",
"*",
"pVariable",
")",
"pVariable",
".",
"flatten",
".",
"each",
"do",
"|",
"element",
"|",
"next",
"unless",
"element",
".",
"is_a?",
"(",
"Languages",
"::",
"VariableGlobalData",
")",
"@global_variables",
".",
"push",
"(",
"element",
")",
"end",
"end"
] | Add global variable inside file.
@param pVariable A single VariableGlobalData object or list to be added. | [
"Add",
"global",
"variable",
"inside",
"file",
"."
] | 8b840ab307dc6bec48edd272c732b28c98f93f45 | https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/language/container_data/structured_and_oo/file_element_data.rb#L48-L53 | train |
fuminori-ido/edgarj | app/models/edgarj/user_group.rb | Edgarj.UserGroup.permitted? | def permitted?(model_name, requested_flags = 0)
return false if self.kind != Kind::ROLE
return true if admin?
p = self.model_permissions.find_by_model(model_name)
if requested_flags == 0
p
else
p && p.permitted?(requested_flags)
end
end | ruby | def permitted?(model_name, requested_flags = 0)
return false if self.kind != Kind::ROLE
return true if admin?
p = self.model_permissions.find_by_model(model_name)
if requested_flags == 0
p
else
p && p.permitted?(requested_flags)
end
end | [
"def",
"permitted?",
"(",
"model_name",
",",
"requested_flags",
"=",
"0",
")",
"return",
"false",
"if",
"self",
".",
"kind",
"!=",
"Kind",
"::",
"ROLE",
"return",
"true",
"if",
"admin?",
"p",
"=",
"self",
".",
"model_permissions",
".",
"find_by_model",
"(",
"model_name",
")",
"if",
"requested_flags",
"==",
"0",
"p",
"else",
"p",
"&&",
"p",
".",
"permitted?",
"(",
"requested_flags",
")",
"end",
"end"
] | return true if the role has enough permission on the controller.
If user role is 'admin' then all operations are permitted.
Always return false if the user-group is not ROLE.
if requested_flags is omitted, just checks existence of
model_permissions and doesn't check CRUD level. | [
"return",
"true",
"if",
"the",
"role",
"has",
"enough",
"permission",
"on",
"the",
"controller",
"."
] | 1648ab180f1f4adaeea03d54b645f58f3702a2bf | https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/models/edgarj/user_group.rb#L41-L51 | train |
loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.Auth.auth | def auth
# entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/auth"
# payload
payload = {
app: {
name: @client.app_info[:name],
version: @client.app_info[:version],
vendor: @client.app_info[:vendor],
id: @client.app_info[:id]
},
permissions: @client.app_info[:permissions]
}
# api call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json'})
req.body = payload.to_json
res = http.request(req)
# return's parser
if res.code == "200"
response = JSON.parse(res.body)
# save it in conf.json
conf = response.dup
File.open(@client.app_info[:conf_path], "w") { |f| f << JSON.pretty_generate(conf) }
else
# puts "ERROR #{res.code}: #{res.message}"
response = nil
end
# return
response
end | ruby | def auth
# entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/auth"
# payload
payload = {
app: {
name: @client.app_info[:name],
version: @client.app_info[:version],
vendor: @client.app_info[:vendor],
id: @client.app_info[:id]
},
permissions: @client.app_info[:permissions]
}
# api call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json'})
req.body = payload.to_json
res = http.request(req)
# return's parser
if res.code == "200"
response = JSON.parse(res.body)
# save it in conf.json
conf = response.dup
File.open(@client.app_info[:conf_path], "w") { |f| f << JSON.pretty_generate(conf) }
else
# puts "ERROR #{res.code}: #{res.message}"
response = nil
end
# return
response
end | [
"def",
"auth",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/auth\"",
"payload",
"=",
"{",
"app",
":",
"{",
"name",
":",
"@client",
".",
"app_info",
"[",
":name",
"]",
",",
"version",
":",
"@client",
".",
"app_info",
"[",
":version",
"]",
",",
"vendor",
":",
"@client",
".",
"app_info",
"[",
":vendor",
"]",
",",
"id",
":",
"@client",
".",
"app_info",
"[",
":id",
"]",
"}",
",",
"permissions",
":",
"@client",
".",
"app_info",
"[",
":permissions",
"]",
"}",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"req",
".",
"body",
"=",
"payload",
".",
"to_json",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"if",
"res",
".",
"code",
"==",
"\"200\"",
"response",
"=",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"conf",
"=",
"response",
".",
"dup",
"File",
".",
"open",
"(",
"@client",
".",
"app_info",
"[",
":conf_path",
"]",
",",
"\"w\"",
")",
"{",
"|",
"f",
"|",
"f",
"<<",
"JSON",
".",
"pretty_generate",
"(",
"conf",
")",
"}",
"else",
"response",
"=",
"nil",
"end",
"response",
"end"
] | Any application that wants to access API endpoints that require authorised
access must receive an authorisation token from SAFE Launcher.
Reading public data using the DNS API does not require an authorisation
token. All other API endpoints require authorised access.
The application will initiate the authorisation request with information
about the application itself and the required permissions. SAFE Launcher
will then display a prompt to the user with the application information
along with the requested permissions. Once the user authorises the
request, the application will receive an authorisation token. If the user
denies the request, the application will receive an unauthorised error
response.
Usage: my_client.auth.auth(["SAFE_DRIVE_ACCESS"])
Fail: nil
Success: {token: "1222", "permissions": []}
Reference: https://maidsafe.readme.io/docs/auth | [
"Any",
"application",
"that",
"wants",
"to",
"access",
"API",
"endpoints",
"that",
"require",
"authorised",
"access",
"must",
"receive",
"an",
"authorisation",
"token",
"from",
"SAFE",
"Launcher",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L105-L141 | train |
loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.Auth.is_token_valid | def is_token_valid
# entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/auth"
# api call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Get.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_token()}"
})
res = http.request(req)
res.code == "200"
end | ruby | def is_token_valid
# entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/auth"
# api call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Get.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_token()}"
})
res = http.request(req)
res.code == "200"
end | [
"def",
"is_token_valid",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/auth\"",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_token()}\"",
"}",
")",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res",
".",
"code",
"==",
"\"200\"",
"end"
] | Check whether the authorisation token obtained from SAFE Launcher is still
valid.
Usage: my_client.auth.is_token_valid()
Fail: false
Success: true
Reference: https://maidsafe.readme.io/docs/is-token-valid | [
"Check",
"whether",
"the",
"authorisation",
"token",
"obtained",
"from",
"SAFE",
"Launcher",
"is",
"still",
"valid",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L154-L166 | train |
loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.Auth.revoke_token | def revoke_token
# entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/auth"
# api call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Delete.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}"
})
res = http.request(req)
res.code == "200"
end | ruby | def revoke_token
# entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/auth"
# api call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Delete.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}"
})
res = http.request(req)
res.code == "200"
end | [
"def",
"revoke_token",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/auth\"",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Delete",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
"}",
")",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res",
".",
"code",
"==",
"\"200\"",
"end"
] | Revoke the authorisation token obtained from SAFE Launcher.
Usage: my_client.auth.revoke_token()
Fail: false
Success: true
Reference: https://maidsafe.readme.io/docs/revoke-token | [
"Revoke",
"the",
"authorisation",
"token",
"obtained",
"from",
"SAFE",
"Launcher",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L178-L190 | train |
loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.NFS.create_directory | def create_directory(dir_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
options[:is_private] = true if ! options.has_key?(:is_private)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/directory/#{options[:root_path]}/#{SafeNet.escape(dir_path)}"
# Payload
payload = {
isPrivate: options[:is_private],
}
# Optional
payload["metadata"] = Base64.strict_encode64(options[:meta]) if options.has_key?(:meta)
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
'Content-Type' => 'application/json'
})
req.body = payload.to_json
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | ruby | def create_directory(dir_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
options[:is_private] = true if ! options.has_key?(:is_private)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/directory/#{options[:root_path]}/#{SafeNet.escape(dir_path)}"
# Payload
payload = {
isPrivate: options[:is_private],
}
# Optional
payload["metadata"] = Base64.strict_encode64(options[:meta]) if options.has_key?(:meta)
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
'Content-Type' => 'application/json'
})
req.body = payload.to_json
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | [
"def",
"create_directory",
"(",
"dir_path",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":root_path",
"]",
"=",
"'app'",
"if",
"!",
"options",
".",
"has_key?",
"(",
":root_path",
")",
"options",
"[",
":is_private",
"]",
"=",
"true",
"if",
"!",
"options",
".",
"has_key?",
"(",
":is_private",
")",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/directory/#{options[:root_path]}/#{SafeNet.escape(dir_path)}\"",
"payload",
"=",
"{",
"isPrivate",
":",
"options",
"[",
":is_private",
"]",
",",
"}",
"payload",
"[",
"\"metadata\"",
"]",
"=",
"Base64",
".",
"strict_encode64",
"(",
"options",
"[",
":meta",
"]",
")",
"if",
"options",
".",
"has_key?",
"(",
":meta",
")",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"req",
".",
"body",
"=",
"payload",
".",
"to_json",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res",
".",
"code",
"==",
"\"200\"",
"?",
"true",
":",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Create a public or private directory either in the application's root
directory or in SAFE Drive.
Only authorised requests can create a directory.
Usage: my_client.nfs.create_directory("/photos")
Adv.Usage: my_client.nfs.create_directory("/photos", meta: "some meta", root_path: 'drive', is_private: true)
Fail: {"errorCode"=>-505, "description"=>"NfsError::FileAlreadyExistsWithSameName"}
Success: true
Reference: https://maidsafe.readme.io/docs/nfs-create-directory | [
"Create",
"a",
"public",
"or",
"private",
"directory",
"either",
"in",
"the",
"application",
"s",
"root",
"directory",
"or",
"in",
"SAFE",
"Drive",
".",
"Only",
"authorised",
"requests",
"can",
"create",
"a",
"directory",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L211-L237 | train |
loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.NFS.get_directory | def get_directory(dir_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/directory/#{options[:root_path]}/#{SafeNet.escape(dir_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Get.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
})
res = http.request(req)
JSON.parse(res.body)
end | ruby | def get_directory(dir_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/directory/#{options[:root_path]}/#{SafeNet.escape(dir_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Get.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
})
res = http.request(req)
JSON.parse(res.body)
end | [
"def",
"get_directory",
"(",
"dir_path",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":root_path",
"]",
"=",
"'app'",
"if",
"!",
"options",
".",
"has_key?",
"(",
":root_path",
")",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/directory/#{options[:root_path]}/#{SafeNet.escape(dir_path)}\"",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"}",
")",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Fetch a directory.
Only authorised requests can invoke this API.
Usage: my_client.nfs.get_directory("/photos", root_path: 'drive')
Fail: {"errorCode"=>-1502, "description"=>"FfiError::PathNotFound"}
Success: {"info"=> {"name"=> "my_dir", ...}, ...}
Reference: https://maidsafe.readme.io/docs/nfs-get-directory | [
"Fetch",
"a",
"directory",
".",
"Only",
"authorised",
"requests",
"can",
"invoke",
"this",
"API",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L261-L276 | train |
loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.NFS.create_file | def create_file(file_path, contents, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
contents ||= ""
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
headers = {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
}
headers["Metadata"] = Base64.strict_encode64(options[:meta]) if options.has_key?(:meta)
headers["Content-Type"] = options[:content_type] || 'text/plain'
headers["Content-Length"] = contents.size.to_s
req = Net::HTTP::Post.new(uri.path, headers)
req.body = contents
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | ruby | def create_file(file_path, contents, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
contents ||= ""
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
headers = {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
}
headers["Metadata"] = Base64.strict_encode64(options[:meta]) if options.has_key?(:meta)
headers["Content-Type"] = options[:content_type] || 'text/plain'
headers["Content-Length"] = contents.size.to_s
req = Net::HTTP::Post.new(uri.path, headers)
req.body = contents
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | [
"def",
"create_file",
"(",
"file_path",
",",
"contents",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":root_path",
"]",
"=",
"'app'",
"if",
"!",
"options",
".",
"has_key?",
"(",
":root_path",
")",
"contents",
"||=",
"\"\"",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}\"",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"headers",
"=",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"}",
"headers",
"[",
"\"Metadata\"",
"]",
"=",
"Base64",
".",
"strict_encode64",
"(",
"options",
"[",
":meta",
"]",
")",
"if",
"options",
".",
"has_key?",
"(",
":meta",
")",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"options",
"[",
":content_type",
"]",
"||",
"'text/plain'",
"headers",
"[",
"\"Content-Length\"",
"]",
"=",
"contents",
".",
"size",
".",
"to_s",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"path",
",",
"headers",
")",
"req",
".",
"body",
"=",
"contents",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res",
".",
"code",
"==",
"\"200\"",
"?",
"true",
":",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Create a file.
Only authorised requests can invoke the API.
Usage: my_client.nfs.create_file("/docs/hello.txt", "Hello World!")
Adv.Usage: my_client.nfs.create_file("/docs/hello.txt", meta: "some meta", root_path: "app", content_type: "text/plain")
Fail: {"errorCode"=>-505, "description"=>"NfsError::FileAlreadyExistsWithSameName"}
Success: true
Reference: https://maidsafe.readme.io/docs/nfsfile | [
"Create",
"a",
"file",
".",
"Only",
"authorised",
"requests",
"can",
"invoke",
"the",
"API",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L360-L381 | train |
loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.NFS.get_file_meta | def get_file_meta(file_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
headers = {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
}
req = Net::HTTP::Head.new(uri.path, headers)
res = http.request(req)
res_headers = {}
res.response.each_header {|k,v| res_headers[k] = v}
res_headers["metadata"] = Base64.strict_decode64(res_headers["metadata"]) if res_headers.has_key?("metadata")
res.code == "200" ? {"headers" => res_headers, "body" => res.body} : JSON.parse(res.body)
end | ruby | def get_file_meta(file_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
headers = {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
}
req = Net::HTTP::Head.new(uri.path, headers)
res = http.request(req)
res_headers = {}
res.response.each_header {|k,v| res_headers[k] = v}
res_headers["metadata"] = Base64.strict_decode64(res_headers["metadata"]) if res_headers.has_key?("metadata")
res.code == "200" ? {"headers" => res_headers, "body" => res.body} : JSON.parse(res.body)
end | [
"def",
"get_file_meta",
"(",
"file_path",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":root_path",
"]",
"=",
"'app'",
"if",
"!",
"options",
".",
"has_key?",
"(",
":root_path",
")",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}\"",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"headers",
"=",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"}",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Head",
".",
"new",
"(",
"uri",
".",
"path",
",",
"headers",
")",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res_headers",
"=",
"{",
"}",
"res",
".",
"response",
".",
"each_header",
"{",
"|",
"k",
",",
"v",
"|",
"res_headers",
"[",
"k",
"]",
"=",
"v",
"}",
"res_headers",
"[",
"\"metadata\"",
"]",
"=",
"Base64",
".",
"strict_decode64",
"(",
"res_headers",
"[",
"\"metadata\"",
"]",
")",
"if",
"res_headers",
".",
"has_key?",
"(",
"\"metadata\"",
")",
"res",
".",
"code",
"==",
"\"200\"",
"?",
"{",
"\"headers\"",
"=>",
"res_headers",
",",
"\"body\"",
"=>",
"res",
".",
"body",
"}",
":",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Fetch the metadata of a file.
Only authorised requests can invoke the API.
Usage: my_client.nfs.get_file_meta("/docs/hello.txt")
Adv.Usage: my_client.nfs.get_file_meta("/docs/hello.txt", root_path: "app")
Fail: {"errorCode"=>-505, "description"=>"NfsError::FileAlreadyExistsWithSameName"}
Success:
Reference: https://maidsafe.readme.io/docs/nfs-get-file-metadata | [
"Fetch",
"the",
"metadata",
"of",
"a",
"file",
".",
"Only",
"authorised",
"requests",
"can",
"invoke",
"the",
"API",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L395-L414 | train |
loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.NFS.get_file | def get_file(file_path, options = {})
# Default values
options[:offset] = 0 if ! options.has_key?(:offset)
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}?"
# Query params
query = []
query << "offset=#{options[:offset]}"
query << "length=#{options[:length]}" if options.has_key?(:length) # length is optional
url = "#{url}#{query.join('&')}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
headers = {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
}
headers["Range"] = options[:range] if options.has_key?(:range)
req = Net::HTTP::Get.new(uri.path, headers)
res = http.request(req)
res_headers = {}
res.response.each_header {|k,v| res_headers[k] = v}
res.code == "200" ? {"headers" => res_headers, "body" => res.body} : JSON.parse(res.body)
end | ruby | def get_file(file_path, options = {})
# Default values
options[:offset] = 0 if ! options.has_key?(:offset)
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}?"
# Query params
query = []
query << "offset=#{options[:offset]}"
query << "length=#{options[:length]}" if options.has_key?(:length) # length is optional
url = "#{url}#{query.join('&')}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
headers = {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
}
headers["Range"] = options[:range] if options.has_key?(:range)
req = Net::HTTP::Get.new(uri.path, headers)
res = http.request(req)
res_headers = {}
res.response.each_header {|k,v| res_headers[k] = v}
res.code == "200" ? {"headers" => res_headers, "body" => res.body} : JSON.parse(res.body)
end | [
"def",
"get_file",
"(",
"file_path",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":offset",
"]",
"=",
"0",
"if",
"!",
"options",
".",
"has_key?",
"(",
":offset",
")",
"options",
"[",
":root_path",
"]",
"=",
"'app'",
"if",
"!",
"options",
".",
"has_key?",
"(",
":root_path",
")",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}?\"",
"query",
"=",
"[",
"]",
"query",
"<<",
"\"offset=#{options[:offset]}\"",
"query",
"<<",
"\"length=#{options[:length]}\"",
"if",
"options",
".",
"has_key?",
"(",
":length",
")",
"url",
"=",
"\"#{url}#{query.join('&')}\"",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"headers",
"=",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"}",
"headers",
"[",
"\"Range\"",
"]",
"=",
"options",
"[",
":range",
"]",
"if",
"options",
".",
"has_key?",
"(",
":range",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"uri",
".",
"path",
",",
"headers",
")",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res_headers",
"=",
"{",
"}",
"res",
".",
"response",
".",
"each_header",
"{",
"|",
"k",
",",
"v",
"|",
"res_headers",
"[",
"k",
"]",
"=",
"v",
"}",
"res",
".",
"code",
"==",
"\"200\"",
"?",
"{",
"\"headers\"",
"=>",
"res_headers",
",",
"\"body\"",
"=>",
"res",
".",
"body",
"}",
":",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Read a file.
The file can be streamed in chunks and also fetched as partial content
based on the range header specified in the request.
Only authorised requests can invoke the API.
Usage: my_client.nfs.get_file("/docs/hello.txt")
Adv.Usage: my_client.nfs.get_file("/docs/hello.txt", range: "bytes 0-1000", root_path: "app")
Fail: {"errorCode"=>-1503, "description"=>"FfiError::InvalidPath"}
Success: {"headers"=>{"x-powered-by"=>"Express", "content-range"=>"bytes 0-4/4", "accept-ranges"=>"bytes", "content-length"=>"4", "created-on"=>"2016-08-14T12:51:18.924Z", "last-modified"=>"2016-08-14T12:51:18.935Z", "content-type"=>"text/plain", "date"=>"Sun, 14 Aug 2016 13:30:07 GMT", "connection"=>"close"}, "body"=>"Test"}
Reference: https://maidsafe.readme.io/docs/nfs-get-file | [
"Read",
"a",
"file",
".",
"The",
"file",
"can",
"be",
"streamed",
"in",
"chunks",
"and",
"also",
"fetched",
"as",
"partial",
"content",
"based",
"on",
"the",
"range",
"header",
"specified",
"in",
"the",
"request",
".",
"Only",
"authorised",
"requests",
"can",
"invoke",
"the",
"API",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L430-L456 | train |
loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.NFS.move_file | def move_file(src_root_path, src_path, dst_root_path, dst_path, action = 'move')
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/movefile"
# Payload
payload = {}
payload["srcRootPath"] = src_root_path # 'app' or 'drive'
payload["srcPath"] = src_path
payload["destRootPath"] = dst_root_path # 'app' or 'drive'
payload["destPath"] = dst_path
payload["action"] = action
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
'Content-Type' => 'application/json'
})
req.body = payload.to_json
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | ruby | def move_file(src_root_path, src_path, dst_root_path, dst_path, action = 'move')
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/movefile"
# Payload
payload = {}
payload["srcRootPath"] = src_root_path # 'app' or 'drive'
payload["srcPath"] = src_path
payload["destRootPath"] = dst_root_path # 'app' or 'drive'
payload["destPath"] = dst_path
payload["action"] = action
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
'Content-Type' => 'application/json'
})
req.body = payload.to_json
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | [
"def",
"move_file",
"(",
"src_root_path",
",",
"src_path",
",",
"dst_root_path",
",",
"dst_path",
",",
"action",
"=",
"'move'",
")",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/movefile\"",
"payload",
"=",
"{",
"}",
"payload",
"[",
"\"srcRootPath\"",
"]",
"=",
"src_root_path",
"payload",
"[",
"\"srcPath\"",
"]",
"=",
"src_path",
"payload",
"[",
"\"destRootPath\"",
"]",
"=",
"dst_root_path",
"payload",
"[",
"\"destPath\"",
"]",
"=",
"dst_path",
"payload",
"[",
"\"action\"",
"]",
"=",
"action",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"req",
".",
"body",
"=",
"payload",
".",
"to_json",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res",
".",
"code",
"==",
"\"200\"",
"?",
"true",
":",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Move or copy a file | [
"Move",
"or",
"copy",
"a",
"file"
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L502-L524 | train |
loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.NFS.delete_file | def delete_file(file_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Delete.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
})
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | ruby | def delete_file(file_path, options = {})
# Default values
options[:root_path] = 'app' if ! options.has_key?(:root_path)
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}"
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Delete.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
})
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | [
"def",
"delete_file",
"(",
"file_path",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":root_path",
"]",
"=",
"'app'",
"if",
"!",
"options",
".",
"has_key?",
"(",
":root_path",
")",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}\"",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Delete",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"}",
")",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res",
".",
"code",
"==",
"\"200\"",
"?",
"true",
":",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Delete a file.
Only authorised requests can invoke the API.
Usage: my_client.nfs.delete_file("/docs/hello.txt")
Adv.Usage: my_client.nfs.delete_file("/docs/hello.txt", root_path: "app")
Fail: {"errorCode"=>-1503, "description"=>"FfiError::InvalidPath"}
Success: true
Reference: https://maidsafe.readme.io/docs/nfs-delete-file | [
"Delete",
"a",
"file",
".",
"Only",
"authorised",
"requests",
"can",
"invoke",
"the",
"API",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L537-L552 | train |
loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.DNS.register_service | def register_service(long_name, service_name, service_home_dir_path, options = {})
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/dns"
# Payload
payload = {
longName: long_name,
serviceName: service_name,
rootPath: 'app',
serviceHomeDirPath: service_home_dir_path,
}
# Optional
payload["metadata"] = options[:meta] if options.has_key?(:meta)
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
'Content-Type' => 'application/json'
})
req.body = payload.to_json
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | ruby | def register_service(long_name, service_name, service_home_dir_path, options = {})
# Entry point
url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/dns"
# Payload
payload = {
longName: long_name,
serviceName: service_name,
rootPath: 'app',
serviceHomeDirPath: service_home_dir_path,
}
# Optional
payload["metadata"] = options[:meta] if options.has_key?(:meta)
# API call
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {
'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}",
'Content-Type' => 'application/json'
})
req.body = payload.to_json
res = http.request(req)
res.code == "200" ? true : JSON.parse(res.body)
end | [
"def",
"register_service",
"(",
"long_name",
",",
"service_name",
",",
"service_home_dir_path",
",",
"options",
"=",
"{",
"}",
")",
"url",
"=",
"\"#{@client.app_info[:launcher_server]}#{API_VERSION}/dns\"",
"payload",
"=",
"{",
"longName",
":",
"long_name",
",",
"serviceName",
":",
"service_name",
",",
"rootPath",
":",
"'app'",
",",
"serviceHomeDirPath",
":",
"service_home_dir_path",
",",
"}",
"payload",
"[",
"\"metadata\"",
"]",
"=",
"options",
"[",
":meta",
"]",
"if",
"options",
".",
"has_key?",
"(",
":meta",
")",
"uri",
"=",
"URI",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"path",
",",
"{",
"'Authorization'",
"=>",
"\"Bearer #{@client.key_helper.get_valid_token()}\"",
",",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"req",
".",
"body",
"=",
"payload",
".",
"to_json",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"res",
".",
"code",
"==",
"\"200\"",
"?",
"true",
":",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Register a long name and a service.
Only authorised requests can invoke the API.
Usage: my_client.dns.register_service("my-domain", "www", "/sources")
Fail: {"errorCode"=>-1503, "description"=>"FfiError::InvalidPath"}
Success: true
Reference: https://maidsafe.readme.io/docs/dns-register-service | [
"Register",
"a",
"long",
"name",
"and",
"a",
"service",
".",
"Only",
"authorised",
"requests",
"can",
"invoke",
"the",
"API",
"."
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L597-L622 | train |
loureirorg/ruby-safenet | lib/safenet.rb | SafeNet.SD.set | def set(name, contents = '', type = 500)
sd = @client.sd.update(name, contents)
if sd.is_a?(Hash) && (sd["errorCode"] == -22) # doesn't exist
sd = @client.sd.create(name, contents)
end
sd
end | ruby | def set(name, contents = '', type = 500)
sd = @client.sd.update(name, contents)
if sd.is_a?(Hash) && (sd["errorCode"] == -22) # doesn't exist
sd = @client.sd.create(name, contents)
end
sd
end | [
"def",
"set",
"(",
"name",
",",
"contents",
"=",
"''",
",",
"type",
"=",
"500",
")",
"sd",
"=",
"@client",
".",
"sd",
".",
"update",
"(",
"name",
",",
"contents",
")",
"if",
"sd",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"(",
"sd",
"[",
"\"errorCode\"",
"]",
"==",
"-",
"22",
")",
"sd",
"=",
"@client",
".",
"sd",
".",
"create",
"(",
"name",
",",
"contents",
")",
"end",
"sd",
"end"
] | create or update | [
"create",
"or",
"update"
] | fe4c1a01f2a096ca978daae711928475c2183570 | https://github.com/loureirorg/ruby-safenet/blob/fe4c1a01f2a096ca978daae711928475c2183570/lib/safenet.rb#L1049-L1055 | train |
nathanstitt/erb_latex | lib/erb_latex/template.rb | ErbLatex.Template.to_file | def to_file( file = suggested_filename )
execute do | contents |
if file.is_a?(String)
FileUtils.mv contents, file
else
file.write contents.read
file.rewind
end
end
file
end | ruby | def to_file( file = suggested_filename )
execute do | contents |
if file.is_a?(String)
FileUtils.mv contents, file
else
file.write contents.read
file.rewind
end
end
file
end | [
"def",
"to_file",
"(",
"file",
"=",
"suggested_filename",
")",
"execute",
"do",
"|",
"contents",
"|",
"if",
"file",
".",
"is_a?",
"(",
"String",
")",
"FileUtils",
".",
"mv",
"contents",
",",
"file",
"else",
"file",
".",
"write",
"contents",
".",
"read",
"file",
".",
"rewind",
"end",
"end",
"file",
"end"
] | Save the PDF to the file
@param file [String,IO] if file is a String, the PDF is moved to the path indicated (most efficient).
Otherwise, file is considered an instance of IO, and write is called on it with the PDF contents
@return [String,IO] the file | [
"Save",
"the",
"PDF",
"to",
"the",
"file"
] | ea74677264b48b72913d5eae9eaac60f4151de8c | https://github.com/nathanstitt/erb_latex/blob/ea74677264b48b72913d5eae9eaac60f4151de8c/lib/erb_latex/template.rb#L68-L78 | train |
nathanstitt/erb_latex | lib/erb_latex/template.rb | ErbLatex.Template.execute | def execute
latex = compile_latex
Dir.mktmpdir do | dir |
@pass_count = 0
@log = ''
success = false
while log_suggests_rerunning? && @pass_count < 5
@pass_count += 1
success = execute_xelatex(latex,dir)
end
pdf_file = Pathname.new(dir).join( "output.pdf" )
if success && pdf_file.exist?
yield pdf_file
else
errors = @log.scan(/\*\!\s(.*?)\n\s*\n/m).map{|e| e.first.gsub(/\n/,'') }.join("; ")
STDERR.puts @log, errors if ErbLatex.config.verbose_logs
raise LatexError.new( errors.empty? ? "xelatex compile error" : errors, @log )
end
end
end | ruby | def execute
latex = compile_latex
Dir.mktmpdir do | dir |
@pass_count = 0
@log = ''
success = false
while log_suggests_rerunning? && @pass_count < 5
@pass_count += 1
success = execute_xelatex(latex,dir)
end
pdf_file = Pathname.new(dir).join( "output.pdf" )
if success && pdf_file.exist?
yield pdf_file
else
errors = @log.scan(/\*\!\s(.*?)\n\s*\n/m).map{|e| e.first.gsub(/\n/,'') }.join("; ")
STDERR.puts @log, errors if ErbLatex.config.verbose_logs
raise LatexError.new( errors.empty? ? "xelatex compile error" : errors, @log )
end
end
end | [
"def",
"execute",
"latex",
"=",
"compile_latex",
"Dir",
".",
"mktmpdir",
"do",
"|",
"dir",
"|",
"@pass_count",
"=",
"0",
"@log",
"=",
"''",
"success",
"=",
"false",
"while",
"log_suggests_rerunning?",
"&&",
"@pass_count",
"<",
"5",
"@pass_count",
"+=",
"1",
"success",
"=",
"execute_xelatex",
"(",
"latex",
",",
"dir",
")",
"end",
"pdf_file",
"=",
"Pathname",
".",
"new",
"(",
"dir",
")",
".",
"join",
"(",
"\"output.pdf\"",
")",
"if",
"success",
"&&",
"pdf_file",
".",
"exist?",
"yield",
"pdf_file",
"else",
"errors",
"=",
"@log",
".",
"scan",
"(",
"/",
"\\*",
"\\!",
"\\s",
"\\n",
"\\s",
"\\n",
"/m",
")",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"first",
".",
"gsub",
"(",
"/",
"\\n",
"/",
",",
"''",
")",
"}",
".",
"join",
"(",
"\"; \"",
")",
"STDERR",
".",
"puts",
"@log",
",",
"errors",
"if",
"ErbLatex",
".",
"config",
".",
"verbose_logs",
"raise",
"LatexError",
".",
"new",
"(",
"errors",
".",
"empty?",
"?",
"\"xelatex compile error\"",
":",
"errors",
",",
"@log",
")",
"end",
"end",
"end"
] | Compile the Latex template into a PDF file
@yield [Pathname] complete path to the PDF file
@raise [LatexError] if the xelatex process does not complete successfully | [
"Compile",
"the",
"Latex",
"template",
"into",
"a",
"PDF",
"file"
] | ea74677264b48b72913d5eae9eaac60f4151de8c | https://github.com/nathanstitt/erb_latex/blob/ea74677264b48b72913d5eae9eaac60f4151de8c/lib/erb_latex/template.rb#L88-L107 | train |
nathanstitt/erb_latex | lib/erb_latex/template.rb | ErbLatex.Template.compile_latex | def compile_latex
begin
context = @context.new( @partials_path || @view.dirname, @data )
content = ErbLatex::File.evaluate(@view, context.getBinding)
if layout
ErbLatex::File.evaluate(layout_file, context.getBinding{ content })
else
content
end
rescue LocalJumpError=>e
raise LatexError.new( "ERB compile raised #{e.class} on #{@view}", e.backtrace )
end
end | ruby | def compile_latex
begin
context = @context.new( @partials_path || @view.dirname, @data )
content = ErbLatex::File.evaluate(@view, context.getBinding)
if layout
ErbLatex::File.evaluate(layout_file, context.getBinding{ content })
else
content
end
rescue LocalJumpError=>e
raise LatexError.new( "ERB compile raised #{e.class} on #{@view}", e.backtrace )
end
end | [
"def",
"compile_latex",
"begin",
"context",
"=",
"@context",
".",
"new",
"(",
"@partials_path",
"||",
"@view",
".",
"dirname",
",",
"@data",
")",
"content",
"=",
"ErbLatex",
"::",
"File",
".",
"evaluate",
"(",
"@view",
",",
"context",
".",
"getBinding",
")",
"if",
"layout",
"ErbLatex",
"::",
"File",
".",
"evaluate",
"(",
"layout_file",
",",
"context",
".",
"getBinding",
"{",
"content",
"}",
")",
"else",
"content",
"end",
"rescue",
"LocalJumpError",
"=>",
"e",
"raise",
"LatexError",
".",
"new",
"(",
"\"ERB compile raised #{e.class} on #{@view}\"",
",",
"e",
".",
"backtrace",
")",
"end",
"end"
] | Runs the ERB pre-process on the latex file
@return [String] latex with ERB substitutions performed
@raise [LatexError] if the xelatex process does not complete successfully | [
"Runs",
"the",
"ERB",
"pre",
"-",
"process",
"on",
"the",
"latex",
"file"
] | ea74677264b48b72913d5eae9eaac60f4151de8c | https://github.com/nathanstitt/erb_latex/blob/ea74677264b48b72913d5eae9eaac60f4151de8c/lib/erb_latex/template.rb#L117-L129 | train |
nathanstitt/erb_latex | lib/erb_latex/template.rb | ErbLatex.Template.execute_xelatex | def execute_xelatex( latex, dir )
success = false
@log = ''
if @packages_path
ENV['TEXINPUTS'] = "#{@packages_path}:"
end
Open3.popen2e( ErbLatex.config.xelatex_path,
"--no-shell-escape", "-shell-restricted",
"-jobname=output", "-output-directory=#{dir}",
) do |stdin, output, wait_thr|
stdin.write latex
stdin.close
@log = output.read.strip
success = ( 0 == wait_thr.value )
end
success
end | ruby | def execute_xelatex( latex, dir )
success = false
@log = ''
if @packages_path
ENV['TEXINPUTS'] = "#{@packages_path}:"
end
Open3.popen2e( ErbLatex.config.xelatex_path,
"--no-shell-escape", "-shell-restricted",
"-jobname=output", "-output-directory=#{dir}",
) do |stdin, output, wait_thr|
stdin.write latex
stdin.close
@log = output.read.strip
success = ( 0 == wait_thr.value )
end
success
end | [
"def",
"execute_xelatex",
"(",
"latex",
",",
"dir",
")",
"success",
"=",
"false",
"@log",
"=",
"''",
"if",
"@packages_path",
"ENV",
"[",
"'TEXINPUTS'",
"]",
"=",
"\"#{@packages_path}:\"",
"end",
"Open3",
".",
"popen2e",
"(",
"ErbLatex",
".",
"config",
".",
"xelatex_path",
",",
"\"--no-shell-escape\"",
",",
"\"-shell-restricted\"",
",",
"\"-jobname=output\"",
",",
"\"-output-directory=#{dir}\"",
",",
")",
"do",
"|",
"stdin",
",",
"output",
",",
"wait_thr",
"|",
"stdin",
".",
"write",
"latex",
"stdin",
".",
"close",
"@log",
"=",
"output",
".",
"read",
".",
"strip",
"success",
"=",
"(",
"0",
"==",
"wait_thr",
".",
"value",
")",
"end",
"success",
"end"
] | Execute xelatex on the file.
@param latex [String] contents of the template after running ERB on it
@param dir [String] path to the temporary working directory | [
"Execute",
"xelatex",
"on",
"the",
"file",
"."
] | ea74677264b48b72913d5eae9eaac60f4151de8c | https://github.com/nathanstitt/erb_latex/blob/ea74677264b48b72913d5eae9eaac60f4151de8c/lib/erb_latex/template.rb#L141-L158 | train |
wvanbergen/sql_tree | lib/sql_tree/node/update_query.rb | SQLTree::Node.UpdateQuery.to_sql | def to_sql(options = {})
sql = "UPDATE #{table.to_sql(options)} SET "
sql << updates.map { |u| u.to_sql(options) }.join(', ')
sql << " WHERE " << where.to_sql(options) if self.where
sql
end | ruby | def to_sql(options = {})
sql = "UPDATE #{table.to_sql(options)} SET "
sql << updates.map { |u| u.to_sql(options) }.join(', ')
sql << " WHERE " << where.to_sql(options) if self.where
sql
end | [
"def",
"to_sql",
"(",
"options",
"=",
"{",
"}",
")",
"sql",
"=",
"\"UPDATE #{table.to_sql(options)} SET \"",
"sql",
"<<",
"updates",
".",
"map",
"{",
"|",
"u",
"|",
"u",
".",
"to_sql",
"(",
"options",
")",
"}",
".",
"join",
"(",
"', '",
")",
"sql",
"<<",
"\" WHERE \"",
"<<",
"where",
".",
"to_sql",
"(",
"options",
")",
"if",
"self",
".",
"where",
"sql",
"end"
] | Generates the SQL UPDATE query.
@return [String] The SQL update query | [
"Generates",
"the",
"SQL",
"UPDATE",
"query",
"."
] | b45566c4c52962def5bfd376622a19697dd49969 | https://github.com/wvanbergen/sql_tree/blob/b45566c4c52962def5bfd376622a19697dd49969/lib/sql_tree/node/update_query.rb#L25-L30 | train |
tpope/ldaptic | lib/ldaptic/entry.rb | Ldaptic.Entry.attributes | def attributes
(@original_attributes||{}).merge(@attributes).keys.inject({}) do |hash, key|
hash[key] = read_attribute(key)
hash
end
end | ruby | def attributes
(@original_attributes||{}).merge(@attributes).keys.inject({}) do |hash, key|
hash[key] = read_attribute(key)
hash
end
end | [
"def",
"attributes",
"(",
"@original_attributes",
"||",
"{",
"}",
")",
".",
"merge",
"(",
"@attributes",
")",
".",
"keys",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"hash",
",",
"key",
"|",
"hash",
"[",
"key",
"]",
"=",
"read_attribute",
"(",
"key",
")",
"hash",
"end",
"end"
] | Returns a hash of attributes. | [
"Returns",
"a",
"hash",
"of",
"attributes",
"."
] | 159a39464e9f5a05c0145db2b21cb256ef859612 | https://github.com/tpope/ldaptic/blob/159a39464e9f5a05c0145db2b21cb256ef859612/lib/ldaptic/entry.rb#L284-L289 | train |
tpope/ldaptic | lib/ldaptic/entry.rb | Ldaptic.Entry.modify_attribute | def modify_attribute(action, key, *values)
key = Ldaptic.encode(key)
values.flatten!.map! {|v| Ldaptic.encode(v)}
@original_attributes[key] ||= []
virgin = @original_attributes[key].dup
original = Ldaptic::AttributeSet.new(self, key, @original_attributes[key])
original.__send__(action, values)
begin
namespace.modify(dn, [[action, key, values]])
rescue
@original_attributes[key] = virgin
raise $!
end
if @attributes[key]
read_attribute(key).__send__(action, values)
end
self
end | ruby | def modify_attribute(action, key, *values)
key = Ldaptic.encode(key)
values.flatten!.map! {|v| Ldaptic.encode(v)}
@original_attributes[key] ||= []
virgin = @original_attributes[key].dup
original = Ldaptic::AttributeSet.new(self, key, @original_attributes[key])
original.__send__(action, values)
begin
namespace.modify(dn, [[action, key, values]])
rescue
@original_attributes[key] = virgin
raise $!
end
if @attributes[key]
read_attribute(key).__send__(action, values)
end
self
end | [
"def",
"modify_attribute",
"(",
"action",
",",
"key",
",",
"*",
"values",
")",
"key",
"=",
"Ldaptic",
".",
"encode",
"(",
"key",
")",
"values",
".",
"flatten!",
".",
"map!",
"{",
"|",
"v",
"|",
"Ldaptic",
".",
"encode",
"(",
"v",
")",
"}",
"@original_attributes",
"[",
"key",
"]",
"||=",
"[",
"]",
"virgin",
"=",
"@original_attributes",
"[",
"key",
"]",
".",
"dup",
"original",
"=",
"Ldaptic",
"::",
"AttributeSet",
".",
"new",
"(",
"self",
",",
"key",
",",
"@original_attributes",
"[",
"key",
"]",
")",
"original",
".",
"__send__",
"(",
"action",
",",
"values",
")",
"begin",
"namespace",
".",
"modify",
"(",
"dn",
",",
"[",
"[",
"action",
",",
"key",
",",
"values",
"]",
"]",
")",
"rescue",
"@original_attributes",
"[",
"key",
"]",
"=",
"virgin",
"raise",
"$!",
"end",
"if",
"@attributes",
"[",
"key",
"]",
"read_attribute",
"(",
"key",
")",
".",
"__send__",
"(",
"action",
",",
"values",
")",
"end",
"self",
"end"
] | Note the values are not typecast and thus must be strings. | [
"Note",
"the",
"values",
"are",
"not",
"typecast",
"and",
"thus",
"must",
"be",
"strings",
"."
] | 159a39464e9f5a05c0145db2b21cb256ef859612 | https://github.com/tpope/ldaptic/blob/159a39464e9f5a05c0145db2b21cb256ef859612/lib/ldaptic/entry.rb#L316-L333 | train |
tpope/ldaptic | lib/ldaptic/entry.rb | Ldaptic.Entry.method_missing | def method_missing(method, *args, &block)
attribute = Ldaptic.encode(method)
if attribute[-1] == ?=
attribute.chop!
if may_must(attribute)
return write_attribute(attribute, *args, &block)
end
elsif attribute[-1] == ??
attribute.chop!
if may_must(attribute)
if args.empty?
return !read_attribute(attribute).empty?
else
return args.flatten.any? {|arg| compare(attribute, arg)}
end
end
elsif attribute =~ /\A(.*)-before-type-cast\z/ && may_must($1)
return read_attribute($1, *args, &block)
elsif may_must(attribute)
return read_attribute(attribute, *args, &block).one
end
super(method, *args, &block)
end | ruby | def method_missing(method, *args, &block)
attribute = Ldaptic.encode(method)
if attribute[-1] == ?=
attribute.chop!
if may_must(attribute)
return write_attribute(attribute, *args, &block)
end
elsif attribute[-1] == ??
attribute.chop!
if may_must(attribute)
if args.empty?
return !read_attribute(attribute).empty?
else
return args.flatten.any? {|arg| compare(attribute, arg)}
end
end
elsif attribute =~ /\A(.*)-before-type-cast\z/ && may_must($1)
return read_attribute($1, *args, &block)
elsif may_must(attribute)
return read_attribute(attribute, *args, &block).one
end
super(method, *args, &block)
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"attribute",
"=",
"Ldaptic",
".",
"encode",
"(",
"method",
")",
"if",
"attribute",
"[",
"-",
"1",
"]",
"==",
"?=",
"attribute",
".",
"chop!",
"if",
"may_must",
"(",
"attribute",
")",
"return",
"write_attribute",
"(",
"attribute",
",",
"*",
"args",
",",
"&",
"block",
")",
"end",
"elsif",
"attribute",
"[",
"-",
"1",
"]",
"==",
"??",
"attribute",
".",
"chop!",
"if",
"may_must",
"(",
"attribute",
")",
"if",
"args",
".",
"empty?",
"return",
"!",
"read_attribute",
"(",
"attribute",
")",
".",
"empty?",
"else",
"return",
"args",
".",
"flatten",
".",
"any?",
"{",
"|",
"arg",
"|",
"compare",
"(",
"attribute",
",",
"arg",
")",
"}",
"end",
"end",
"elsif",
"attribute",
"=~",
"/",
"\\A",
"\\z",
"/",
"&&",
"may_must",
"(",
"$1",
")",
"return",
"read_attribute",
"(",
"$1",
",",
"*",
"args",
",",
"&",
"block",
")",
"elsif",
"may_must",
"(",
"attribute",
")",
"return",
"read_attribute",
"(",
"attribute",
",",
"*",
"args",
",",
"&",
"block",
")",
".",
"one",
"end",
"super",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"end"
] | Delegates to +read_attribute+ or +write_attribute+. Pops an element out
of its set if the attribute is marked SINGLE-VALUE. | [
"Delegates",
"to",
"+",
"read_attribute",
"+",
"or",
"+",
"write_attribute",
"+",
".",
"Pops",
"an",
"element",
"out",
"of",
"its",
"set",
"if",
"the",
"attribute",
"is",
"marked",
"SINGLE",
"-",
"VALUE",
"."
] | 159a39464e9f5a05c0145db2b21cb256ef859612 | https://github.com/tpope/ldaptic/blob/159a39464e9f5a05c0145db2b21cb256ef859612/lib/ldaptic/entry.rb#L413-L435 | train |
tpope/ldaptic | lib/ldaptic/entry.rb | Ldaptic.Entry.reload | def reload
new = search(:scope => :base, :limit => true)
@original_attributes = new.instance_variable_get(:@original_attributes)
@attributes = new.instance_variable_get(:@attributes)
@dn = Ldaptic::DN(new.dn, self)
@children = {}
self
end | ruby | def reload
new = search(:scope => :base, :limit => true)
@original_attributes = new.instance_variable_get(:@original_attributes)
@attributes = new.instance_variable_get(:@attributes)
@dn = Ldaptic::DN(new.dn, self)
@children = {}
self
end | [
"def",
"reload",
"new",
"=",
"search",
"(",
":scope",
"=>",
":base",
",",
":limit",
"=>",
"true",
")",
"@original_attributes",
"=",
"new",
".",
"instance_variable_get",
"(",
":@original_attributes",
")",
"@attributes",
"=",
"new",
".",
"instance_variable_get",
"(",
":@attributes",
")",
"@dn",
"=",
"Ldaptic",
"::",
"DN",
"(",
"new",
".",
"dn",
",",
"self",
")",
"@children",
"=",
"{",
"}",
"self",
"end"
] | Refetches the attributes from the server. | [
"Refetches",
"the",
"attributes",
"from",
"the",
"server",
"."
] | 159a39464e9f5a05c0145db2b21cb256ef859612 | https://github.com/tpope/ldaptic/blob/159a39464e9f5a05c0145db2b21cb256ef859612/lib/ldaptic/entry.rb#L550-L557 | train |
MattRyder/tableau | lib/tableau/timetableparser.rb | Tableau.TimetableParser.sort_classes | def sort_classes(timetable, classes)
classes.each do |c|
if !(cmodule = timetable.module_for_code(c.code))
cmodule = Tableau::Module.new(c.code)
timetable.push_module(cmodule)
end
cmodule.add_class(c)
end
end | ruby | def sort_classes(timetable, classes)
classes.each do |c|
if !(cmodule = timetable.module_for_code(c.code))
cmodule = Tableau::Module.new(c.code)
timetable.push_module(cmodule)
end
cmodule.add_class(c)
end
end | [
"def",
"sort_classes",
"(",
"timetable",
",",
"classes",
")",
"classes",
".",
"each",
"do",
"|",
"c",
"|",
"if",
"!",
"(",
"cmodule",
"=",
"timetable",
".",
"module_for_code",
"(",
"c",
".",
"code",
")",
")",
"cmodule",
"=",
"Tableau",
"::",
"Module",
".",
"new",
"(",
"c",
".",
"code",
")",
"timetable",
".",
"push_module",
"(",
"cmodule",
")",
"end",
"cmodule",
".",
"add_class",
"(",
"c",
")",
"end",
"end"
] | Sort all the parsed classes into modules | [
"Sort",
"all",
"the",
"parsed",
"classes",
"into",
"modules"
] | a313fa88bf165ca66cb564c14abd3e526d6c1494 | https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/timetableparser.rb#L42-L51 | train |
siuying/itunes-auto-ingestion | lib/itunes_ingestion/fetcher.rb | ITunesIngestion.Fetcher.fetch | def fetch(options={})
params = {
:USERNAME => @username, :PASSWORD => @password, :VNDNUMBER => @vadnumber
}
params[:TYPEOFREPORT] = options[:type_of_report] || REPORT_TYPE_SALES
params[:DATETYPE] = options[:date_type] || DATE_TYPE_DAILY
params[:REPORTTYPE] = options[:report_type] || REPORT_SUMMARY
params[:REPORTDATE] = options[:report_date] || (Time.now-60*60*24).strftime("%Y%m%d")
response = RestClient.post BASE_URL, params
if response.headers[:"errormsg"]
raise ITunesConnectError.new response.headers[:"errormsg"]
elsif response.headers[:"filename"]
Zlib::GzipReader.new(StringIO.new(response.body)).read
else
raise "no data returned from itunes: #{response.body}"
end
end | ruby | def fetch(options={})
params = {
:USERNAME => @username, :PASSWORD => @password, :VNDNUMBER => @vadnumber
}
params[:TYPEOFREPORT] = options[:type_of_report] || REPORT_TYPE_SALES
params[:DATETYPE] = options[:date_type] || DATE_TYPE_DAILY
params[:REPORTTYPE] = options[:report_type] || REPORT_SUMMARY
params[:REPORTDATE] = options[:report_date] || (Time.now-60*60*24).strftime("%Y%m%d")
response = RestClient.post BASE_URL, params
if response.headers[:"errormsg"]
raise ITunesConnectError.new response.headers[:"errormsg"]
elsif response.headers[:"filename"]
Zlib::GzipReader.new(StringIO.new(response.body)).read
else
raise "no data returned from itunes: #{response.body}"
end
end | [
"def",
"fetch",
"(",
"options",
"=",
"{",
"}",
")",
"params",
"=",
"{",
":USERNAME",
"=>",
"@username",
",",
":PASSWORD",
"=>",
"@password",
",",
":VNDNUMBER",
"=>",
"@vadnumber",
"}",
"params",
"[",
":TYPEOFREPORT",
"]",
"=",
"options",
"[",
":type_of_report",
"]",
"||",
"REPORT_TYPE_SALES",
"params",
"[",
":DATETYPE",
"]",
"=",
"options",
"[",
":date_type",
"]",
"||",
"DATE_TYPE_DAILY",
"params",
"[",
":REPORTTYPE",
"]",
"=",
"options",
"[",
":report_type",
"]",
"||",
"REPORT_SUMMARY",
"params",
"[",
":REPORTDATE",
"]",
"=",
"options",
"[",
":report_date",
"]",
"||",
"(",
"Time",
".",
"now",
"-",
"60",
"*",
"60",
"*",
"24",
")",
".",
"strftime",
"(",
"\"%Y%m%d\"",
")",
"response",
"=",
"RestClient",
".",
"post",
"BASE_URL",
",",
"params",
"if",
"response",
".",
"headers",
"[",
":\"",
"\"",
"]",
"raise",
"ITunesConnectError",
".",
"new",
"response",
".",
"headers",
"[",
":\"",
"\"",
"]",
"elsif",
"response",
".",
"headers",
"[",
":\"",
"\"",
"]",
"Zlib",
"::",
"GzipReader",
".",
"new",
"(",
"StringIO",
".",
"new",
"(",
"response",
".",
"body",
")",
")",
".",
"read",
"else",
"raise",
"\"no data returned from itunes: #{response.body}\"",
"end",
"end"
] | Create new instance of Fetcher
username - username
password - password
vadnumber - vadnumber
Fetch and unzip report from itunes connect
options - Hash of options:
- :type_of_report can only be REPORT_TYPE_SALES at the moment
- :date_type either DATE_TYPE_DAILY or DATE_TYPE_WEEKLY, default DATE_TYPE_DAILY
- :report_type either REPORT_OPT_IN or REPORT_SUMMARY, default REPORT_SUMMARY
- :report_date date in YYYYMMDD
Returns text file downloaded and unzipped from iTunes | [
"Create",
"new",
"instance",
"of",
"Fetcher"
] | 2bfd5cb4a12b68a352a0b0191f831845c65b84e2 | https://github.com/siuying/itunes-auto-ingestion/blob/2bfd5cb4a12b68a352a0b0191f831845c65b84e2/lib/itunes_ingestion/fetcher.rb#L35-L52 | train |
nathanstitt/erb_latex | lib/erb_latex/context.rb | ErbLatex.Context.partial | def partial( template, data={} )
context = self.class.new( @directory, data )
ErbLatex::File.evaluate(Pathname.new(template), context.getBinding, @directory)
end | ruby | def partial( template, data={} )
context = self.class.new( @directory, data )
ErbLatex::File.evaluate(Pathname.new(template), context.getBinding, @directory)
end | [
"def",
"partial",
"(",
"template",
",",
"data",
"=",
"{",
"}",
")",
"context",
"=",
"self",
".",
"class",
".",
"new",
"(",
"@directory",
",",
"data",
")",
"ErbLatex",
"::",
"File",
".",
"evaluate",
"(",
"Pathname",
".",
"new",
"(",
"template",
")",
",",
"context",
".",
"getBinding",
",",
"@directory",
")",
"end"
] | create new Context
@param directory [String] directory to use as a base for finding partials
@param data [Hash]
include another latex file into the current template | [
"create",
"new",
"Context"
] | ea74677264b48b72913d5eae9eaac60f4151de8c | https://github.com/nathanstitt/erb_latex/blob/ea74677264b48b72913d5eae9eaac60f4151de8c/lib/erb_latex/context.rb#L32-L35 | train |
Kuniri/kuniri | lib/kuniri/language/container_data/structured_and_oo/class_data.rb | Languages.ClassData.add_attribute | def add_attribute(pAttribute)
pAttribute.each do |attributeElement|
next unless attributeElement.is_a?(Languages::AttributeData)
@attributes.push(attributeElement)
end
end | ruby | def add_attribute(pAttribute)
pAttribute.each do |attributeElement|
next unless attributeElement.is_a?(Languages::AttributeData)
@attributes.push(attributeElement)
end
end | [
"def",
"add_attribute",
"(",
"pAttribute",
")",
"pAttribute",
".",
"each",
"do",
"|",
"attributeElement",
"|",
"next",
"unless",
"attributeElement",
".",
"is_a?",
"(",
"Languages",
"::",
"AttributeData",
")",
"@attributes",
".",
"push",
"(",
"attributeElement",
")",
"end",
"end"
] | Add attribute to class data, notice the possibility of call this
method more than one time.
@param pAttribute Attribute to be added inside class. This attribute
is a list of AttributeData. | [
"Add",
"attribute",
"to",
"class",
"data",
"notice",
"the",
"possibility",
"of",
"call",
"this",
"method",
"more",
"than",
"one",
"time",
"."
] | 8b840ab307dc6bec48edd272c732b28c98f93f45 | https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/language/container_data/structured_and_oo/class_data.rb#L37-L42 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.bundles_set | def bundles_set(bundle_or_name, tags = [])
params = prepare_bundles_set_params(bundle_or_name, tags)
response = request(API_PATH_BUNDLES_SET, params)
parse_and_eval_execution_response(response.body)
end | ruby | def bundles_set(bundle_or_name, tags = [])
params = prepare_bundles_set_params(bundle_or_name, tags)
response = request(API_PATH_BUNDLES_SET, params)
parse_and_eval_execution_response(response.body)
end | [
"def",
"bundles_set",
"(",
"bundle_or_name",
",",
"tags",
"=",
"[",
"]",
")",
"params",
"=",
"prepare_bundles_set_params",
"(",
"bundle_or_name",
",",
"tags",
")",
"response",
"=",
"request",
"(",
"API_PATH_BUNDLES_SET",
",",
"params",
")",
"parse_and_eval_execution_response",
"(",
"response",
".",
"body",
")",
"end"
] | Assignes a set of tags to a single bundle,
wipes away previous settings for bundle.
# create from a bundle
d.bundles_set(WWW::Delicious::Bundle.new('MyBundle'), %w(foo bar))
# create from a string
d.bundles_set('MyBundle', %w(foo bar))
Raises:: WWW::Delicious::Error
Raises:: WWW::Delicious::HTTPError
Raises:: WWW::Delicious::ResponseError | [
"Assignes",
"a",
"set",
"of",
"tags",
"to",
"a",
"single",
"bundle",
"wipes",
"away",
"previous",
"settings",
"for",
"bundle",
"."
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L296-L300 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.tags_rename | def tags_rename(from_name_or_tag, to_name_or_tag)
params = prepare_tags_rename_params(from_name_or_tag, to_name_or_tag)
response = request(API_PATH_TAGS_RENAME, params)
parse_and_eval_execution_response(response.body)
end | ruby | def tags_rename(from_name_or_tag, to_name_or_tag)
params = prepare_tags_rename_params(from_name_or_tag, to_name_or_tag)
response = request(API_PATH_TAGS_RENAME, params)
parse_and_eval_execution_response(response.body)
end | [
"def",
"tags_rename",
"(",
"from_name_or_tag",
",",
"to_name_or_tag",
")",
"params",
"=",
"prepare_tags_rename_params",
"(",
"from_name_or_tag",
",",
"to_name_or_tag",
")",
"response",
"=",
"request",
"(",
"API_PATH_TAGS_RENAME",
",",
"params",
")",
"parse_and_eval_execution_response",
"(",
"response",
".",
"body",
")",
"end"
] | Renames an existing tag with a new tag name.
# rename from a tag
d.bundles_set(WWW::Delicious::Tag.new('old'), WWW::Delicious::Tag.new('new'))
# rename from a string
d.bundles_set('old', 'new')
Raises:: WWW::Delicious::Error
Raises:: WWW::Delicious::HTTPError
Raises:: WWW::Delicious::ResponseError | [
"Renames",
"an",
"existing",
"tag",
"with",
"a",
"new",
"tag",
"name",
"."
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L358-L362 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.posts_recent | def posts_recent(options = {})
params = prepare_posts_params(options.clone, [:count, :tag])
response = request(API_PATH_POSTS_RECENT, params)
parse_post_collection(response.body)
end | ruby | def posts_recent(options = {})
params = prepare_posts_params(options.clone, [:count, :tag])
response = request(API_PATH_POSTS_RECENT, params)
parse_post_collection(response.body)
end | [
"def",
"posts_recent",
"(",
"options",
"=",
"{",
"}",
")",
"params",
"=",
"prepare_posts_params",
"(",
"options",
".",
"clone",
",",
"[",
":count",
",",
":tag",
"]",
")",
"response",
"=",
"request",
"(",
"API_PATH_POSTS_RECENT",
",",
"params",
")",
"parse_post_collection",
"(",
"response",
".",
"body",
")",
"end"
] | Returns a list of the most recent posts, filtered by argument.
# get the most recent posts
d.posts_recent()
# get the 10 most recent posts
d.posts_recent(:count => 10)
=== Options
<tt>:tag</tt>:: a tag to filter by. It can be either a <tt>WWW::Delicious::Tag</tt> or a +String+.
<tt>:count</tt>:: number of items to retrieve. (default: 15, maximum: 100). | [
"Returns",
"a",
"list",
"of",
"the",
"most",
"recent",
"posts",
"filtered",
"by",
"argument",
"."
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L412-L416 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.posts_all | def posts_all(options = {})
params = prepare_posts_params(options.clone, [:tag])
response = request(API_PATH_POSTS_ALL, params)
parse_post_collection(response.body)
end | ruby | def posts_all(options = {})
params = prepare_posts_params(options.clone, [:tag])
response = request(API_PATH_POSTS_ALL, params)
parse_post_collection(response.body)
end | [
"def",
"posts_all",
"(",
"options",
"=",
"{",
"}",
")",
"params",
"=",
"prepare_posts_params",
"(",
"options",
".",
"clone",
",",
"[",
":tag",
"]",
")",
"response",
"=",
"request",
"(",
"API_PATH_POSTS_ALL",
",",
"params",
")",
"parse_post_collection",
"(",
"response",
".",
"body",
")",
"end"
] | Returns a list of all posts, filtered by argument.
# get all (this is a very expensive query)
d.posts_all
# get all posts matching ruby
d.posts_all(:tag => WWW::Delicious::Tag.new('ruby'))
=== Options
<tt>:tag</tt>:: a tag to filter by. It can be either a <tt>WWW::Delicious::Tag</tt> or a +String+. | [
"Returns",
"a",
"list",
"of",
"all",
"posts",
"filtered",
"by",
"argument",
"."
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L431-L435 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.posts_dates | def posts_dates(options = {})
params = prepare_posts_params(options.clone, [:tag])
response = request(API_PATH_POSTS_DATES, params)
parse_posts_dates_response(response.body)
end | ruby | def posts_dates(options = {})
params = prepare_posts_params(options.clone, [:tag])
response = request(API_PATH_POSTS_DATES, params)
parse_posts_dates_response(response.body)
end | [
"def",
"posts_dates",
"(",
"options",
"=",
"{",
"}",
")",
"params",
"=",
"prepare_posts_params",
"(",
"options",
".",
"clone",
",",
"[",
":tag",
"]",
")",
"response",
"=",
"request",
"(",
"API_PATH_POSTS_DATES",
",",
"params",
")",
"parse_posts_dates_response",
"(",
"response",
".",
"body",
")",
"end"
] | Returns a list of dates with the number of posts at each date.
# get number of posts per date
d.posts_dates
# => { '2008-05-05' => 12, '2008-05-06' => 3, ... }
# get number posts per date tagged as ruby
d.posts_dates(:tag => WWW::Delicious::Tag.new('ruby'))
# => { '2008-05-05' => 10, '2008-05-06' => 3, ... }
=== Options
<tt>:tag</tt>:: a tag to filter by. It can be either a <tt>WWW::Delicious::Tag</tt> or a +String+. | [
"Returns",
"a",
"list",
"of",
"dates",
"with",
"the",
"number",
"of",
"posts",
"at",
"each",
"date",
"."
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L452-L456 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.posts_delete | def posts_delete(url)
params = prepare_posts_params({ :url => url }, [:url])
response = request(API_PATH_POSTS_DELETE, params)
parse_and_eval_execution_response(response.body)
end | ruby | def posts_delete(url)
params = prepare_posts_params({ :url => url }, [:url])
response = request(API_PATH_POSTS_DELETE, params)
parse_and_eval_execution_response(response.body)
end | [
"def",
"posts_delete",
"(",
"url",
")",
"params",
"=",
"prepare_posts_params",
"(",
"{",
":url",
"=>",
"url",
"}",
",",
"[",
":url",
"]",
")",
"response",
"=",
"request",
"(",
"API_PATH_POSTS_DELETE",
",",
"params",
")",
"parse_and_eval_execution_response",
"(",
"response",
".",
"body",
")",
"end"
] | Deletes the post matching given +url+ from del.icio.us.
+url+ can be either an URI instance or a string representation of a valid URL.
This method doesn't care whether a post with given +url+ exists.
If not, the execution will silently return without rising any error.
# delete a post from URI
d.post_delete(URI.parse('http://www.foobar.com/'))
# delete a post from a string
d.post_delete('http://www.foobar.com/') | [
"Deletes",
"the",
"post",
"matching",
"given",
"+",
"url",
"+",
"from",
"del",
".",
"icio",
".",
"us",
".",
"+",
"url",
"+",
"can",
"be",
"either",
"an",
"URI",
"instance",
"or",
"a",
"string",
"representation",
"of",
"a",
"valid",
"URL",
"."
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L491-L495 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.init_http_client | def init_http_client(options)
http = Net::HTTP.new(@base_uri.host, 443)
http.use_ssl = true if @base_uri.scheme == "https"
http.verify_mode = OpenSSL::SSL::VERIFY_NONE # FIXME: not 100% supported
self.http_client = http
end | ruby | def init_http_client(options)
http = Net::HTTP.new(@base_uri.host, 443)
http.use_ssl = true if @base_uri.scheme == "https"
http.verify_mode = OpenSSL::SSL::VERIFY_NONE # FIXME: not 100% supported
self.http_client = http
end | [
"def",
"init_http_client",
"(",
"options",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"@base_uri",
".",
"host",
",",
"443",
")",
"http",
".",
"use_ssl",
"=",
"true",
"if",
"@base_uri",
".",
"scheme",
"==",
"\"https\"",
"http",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_NONE",
"self",
".",
"http_client",
"=",
"http",
"end"
] | Initializes the HTTP client.
It automatically enable +use_ssl+ flag according to +@base_uri+ scheme. | [
"Initializes",
"the",
"HTTP",
"client",
".",
"It",
"automatically",
"enable",
"+",
"use_ssl",
"+",
"flag",
"according",
"to",
"+"
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L502-L507 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.http_build_query | def http_build_query(params = {})
params.collect do |k,v|
"#{URI.encode(k.to_s)}=#{URI.encode(v.to_s)}" unless v.nil?
end.compact.join('&')
end | ruby | def http_build_query(params = {})
params.collect do |k,v|
"#{URI.encode(k.to_s)}=#{URI.encode(v.to_s)}" unless v.nil?
end.compact.join('&')
end | [
"def",
"http_build_query",
"(",
"params",
"=",
"{",
"}",
")",
"params",
".",
"collect",
"do",
"|",
"k",
",",
"v",
"|",
"\"#{URI.encode(k.to_s)}=#{URI.encode(v.to_s)}\"",
"unless",
"v",
".",
"nil?",
"end",
".",
"compact",
".",
"join",
"(",
"'&'",
")",
"end"
] | Composes an HTTP query string from an hash of +options+.
The result is URI encoded.
http_build_query(:foo => 'baa', :bar => 'boo')
# => foo=baa&bar=boo | [
"Composes",
"an",
"HTTP",
"query",
"string",
"from",
"an",
"hash",
"of",
"+",
"options",
"+",
".",
"The",
"result",
"is",
"URI",
"encoded",
"."
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L540-L544 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.request | def request(path, params = {})
raise Error, 'Invalid HTTP Client' unless http_client
wait_before_new_request
uri = @base_uri.merge(path)
uri.query = http_build_query(params) unless params.empty?
begin
@last_request = Time.now # see #wait_before_new_request
@last_request_uri = uri # useful for debug
response = make_request(uri)
rescue => e # catch EOFError, SocketError and more
raise HTTPError, e.message
end
case response
when Net::HTTPSuccess
response
when Net::HTTPUnauthorized # 401
raise HTTPError, 'Invalid username or password'
when Net::HTTPServiceUnavailable # 503
raise HTTPError, 'You have been throttled.' +
'Please ensure you are waiting at least one second before each request.'
else
raise HTTPError, "HTTP #{response.code}: #{response.message}"
end
end | ruby | def request(path, params = {})
raise Error, 'Invalid HTTP Client' unless http_client
wait_before_new_request
uri = @base_uri.merge(path)
uri.query = http_build_query(params) unless params.empty?
begin
@last_request = Time.now # see #wait_before_new_request
@last_request_uri = uri # useful for debug
response = make_request(uri)
rescue => e # catch EOFError, SocketError and more
raise HTTPError, e.message
end
case response
when Net::HTTPSuccess
response
when Net::HTTPUnauthorized # 401
raise HTTPError, 'Invalid username or password'
when Net::HTTPServiceUnavailable # 503
raise HTTPError, 'You have been throttled.' +
'Please ensure you are waiting at least one second before each request.'
else
raise HTTPError, "HTTP #{response.code}: #{response.message}"
end
end | [
"def",
"request",
"(",
"path",
",",
"params",
"=",
"{",
"}",
")",
"raise",
"Error",
",",
"'Invalid HTTP Client'",
"unless",
"http_client",
"wait_before_new_request",
"uri",
"=",
"@base_uri",
".",
"merge",
"(",
"path",
")",
"uri",
".",
"query",
"=",
"http_build_query",
"(",
"params",
")",
"unless",
"params",
".",
"empty?",
"begin",
"@last_request",
"=",
"Time",
".",
"now",
"@last_request_uri",
"=",
"uri",
"response",
"=",
"make_request",
"(",
"uri",
")",
"rescue",
"=>",
"e",
"raise",
"HTTPError",
",",
"e",
".",
"message",
"end",
"case",
"response",
"when",
"Net",
"::",
"HTTPSuccess",
"response",
"when",
"Net",
"::",
"HTTPUnauthorized",
"raise",
"HTTPError",
",",
"'Invalid username or password'",
"when",
"Net",
"::",
"HTTPServiceUnavailable",
"raise",
"HTTPError",
",",
"'You have been throttled.'",
"+",
"'Please ensure you are waiting at least one second before each request.'",
"else",
"raise",
"HTTPError",
",",
"\"HTTP #{response.code}: #{response.message}\"",
"end",
"end"
] | Sends an HTTP GET request to +path+ and appends given +params+.
This method is 100% compliant with Delicious API reference.
It waits at least 1 second between each HTTP request and
provides an identifiable user agent by default,
or the custom user agent set by +user_agent+ option
when this instance has been created.
request('/v1/api/path', :foo => 1, :bar => 2)
# => sends a GET request to /v1/api/path?foo=1&bar=2 | [
"Sends",
"an",
"HTTP",
"GET",
"request",
"to",
"+",
"path",
"+",
"and",
"appends",
"given",
"+",
"params",
"+",
"."
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L558-L584 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.make_request | def make_request(uri)
http_client.start do |http|
req = Net::HTTP::Get.new(uri.request_uri, @headers)
req.basic_auth(@username, @password)
http.request(req)
end
end | ruby | def make_request(uri)
http_client.start do |http|
req = Net::HTTP::Get.new(uri.request_uri, @headers)
req.basic_auth(@username, @password)
http.request(req)
end
end | [
"def",
"make_request",
"(",
"uri",
")",
"http_client",
".",
"start",
"do",
"|",
"http",
"|",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"uri",
".",
"request_uri",
",",
"@headers",
")",
"req",
".",
"basic_auth",
"(",
"@username",
",",
"@password",
")",
"http",
".",
"request",
"(",
"req",
")",
"end",
"end"
] | Makes the real HTTP request to given +uri+ and returns the +response+.
This method exists basically to simplify unit testing with mocha. | [
"Makes",
"the",
"real",
"HTTP",
"request",
"to",
"given",
"+",
"uri",
"+",
"and",
"returns",
"the",
"+",
"response",
"+",
".",
"This",
"method",
"exists",
"basically",
"to",
"simplify",
"unit",
"testing",
"with",
"mocha",
"."
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L588-L594 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.parse_update_response | def parse_update_response(body)
dom = parse_and_validate_response(body, :root_name => 'update')
dom.root.if_attribute_value(:time) { |v| Time.parse(v) }
end | ruby | def parse_update_response(body)
dom = parse_and_validate_response(body, :root_name => 'update')
dom.root.if_attribute_value(:time) { |v| Time.parse(v) }
end | [
"def",
"parse_update_response",
"(",
"body",
")",
"dom",
"=",
"parse_and_validate_response",
"(",
"body",
",",
":root_name",
"=>",
"'update'",
")",
"dom",
".",
"root",
".",
"if_attribute_value",
"(",
":time",
")",
"{",
"|",
"v",
"|",
"Time",
".",
"parse",
"(",
"v",
")",
"}",
"end"
] | Parses the response of an Update request
and returns the update Timestamp. | [
"Parses",
"the",
"response",
"of",
"an",
"Update",
"request",
"and",
"returns",
"the",
"update",
"Timestamp",
"."
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L652-L655 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.prepare_tags_rename_params | def prepare_tags_rename_params(from_name_or_tag, to_name_or_tag)
from, to = [from_name_or_tag, to_name_or_tag].collect do |v|
prepare_param_tag(v)
end
{ :old => from, :new => to }
end | ruby | def prepare_tags_rename_params(from_name_or_tag, to_name_or_tag)
from, to = [from_name_or_tag, to_name_or_tag].collect do |v|
prepare_param_tag(v)
end
{ :old => from, :new => to }
end | [
"def",
"prepare_tags_rename_params",
"(",
"from_name_or_tag",
",",
"to_name_or_tag",
")",
"from",
",",
"to",
"=",
"[",
"from_name_or_tag",
",",
"to_name_or_tag",
"]",
".",
"collect",
"do",
"|",
"v",
"|",
"prepare_param_tag",
"(",
"v",
")",
"end",
"{",
":old",
"=>",
"from",
",",
":new",
"=>",
"to",
"}",
"end"
] | Prepares the params for a `tags_rename` call
and returns a Hash with the params ready for the HTTP request.
Raises:: WWW::Delicious::Error | [
"Prepares",
"the",
"params",
"for",
"a",
"tags_rename",
"call",
"and",
"returns",
"a",
"Hash",
"with",
"the",
"params",
"ready",
"for",
"the",
"HTTP",
"request",
"."
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L723-L728 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.prepare_param_post | def prepare_param_post(post_or_values, &block)
post = case post_or_values
when WWW::Delicious::Post
post_or_values
when Hash
Post.new(post_or_values)
else
raise ArgumentError, 'Expected `args` to be `WWW::Delicious::Post` or `Hash`'
end
yield(post) if block_given?
# TODO: validate post with post.validate!
raise ArgumentError, 'Both `url` and `title` are required' unless post.api_valid?
post
end | ruby | def prepare_param_post(post_or_values, &block)
post = case post_or_values
when WWW::Delicious::Post
post_or_values
when Hash
Post.new(post_or_values)
else
raise ArgumentError, 'Expected `args` to be `WWW::Delicious::Post` or `Hash`'
end
yield(post) if block_given?
# TODO: validate post with post.validate!
raise ArgumentError, 'Both `url` and `title` are required' unless post.api_valid?
post
end | [
"def",
"prepare_param_post",
"(",
"post_or_values",
",",
"&",
"block",
")",
"post",
"=",
"case",
"post_or_values",
"when",
"WWW",
"::",
"Delicious",
"::",
"Post",
"post_or_values",
"when",
"Hash",
"Post",
".",
"new",
"(",
"post_or_values",
")",
"else",
"raise",
"ArgumentError",
",",
"'Expected `args` to be `WWW::Delicious::Post` or `Hash`'",
"end",
"yield",
"(",
"post",
")",
"if",
"block_given?",
"raise",
"ArgumentError",
",",
"'Both `url` and `title` are required'",
"unless",
"post",
".",
"api_valid?",
"post",
"end"
] | Prepares the +post+ param for an API request.
Creates and returns a <tt>WWW::Delicious::Post</tt> instance from <tt>post_or_values</tt>.
<tt>post_or_values</tt> can be either an Hash with post attributes
or a <tt>WWW::Delicious::Post</tt> instance. | [
"Prepares",
"the",
"+",
"post",
"+",
"param",
"for",
"an",
"API",
"request",
"."
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L764-L778 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.prepare_param_bundle | def prepare_param_bundle(name_or_bundle, tags = [], &block) # :yields: bundle
bundle = case name_or_bundle
when WWW::Delicious::Bundle
name_or_bundle
else
Bundle.new(:name => name_or_bundle, :tags => tags)
end
yield(bundle) if block_given?
# TODO: validate bundle with bundle.validate!
bundle
end | ruby | def prepare_param_bundle(name_or_bundle, tags = [], &block) # :yields: bundle
bundle = case name_or_bundle
when WWW::Delicious::Bundle
name_or_bundle
else
Bundle.new(:name => name_or_bundle, :tags => tags)
end
yield(bundle) if block_given?
# TODO: validate bundle with bundle.validate!
bundle
end | [
"def",
"prepare_param_bundle",
"(",
"name_or_bundle",
",",
"tags",
"=",
"[",
"]",
",",
"&",
"block",
")",
"bundle",
"=",
"case",
"name_or_bundle",
"when",
"WWW",
"::",
"Delicious",
"::",
"Bundle",
"name_or_bundle",
"else",
"Bundle",
".",
"new",
"(",
":name",
"=>",
"name_or_bundle",
",",
":tags",
"=>",
"tags",
")",
"end",
"yield",
"(",
"bundle",
")",
"if",
"block_given?",
"bundle",
"end"
] | Prepares the +bundle+ param for an API request.
Creates and returns a <tt>WWW::Delicious::Bundle</tt> instance from <tt>name_or_bundle</tt>.
<tt>name_or_bundle</tt> can be either a string holding bundle name
or a <tt>WWW::Delicious::Bundle</tt> instance. | [
"Prepares",
"the",
"+",
"bundle",
"+",
"param",
"for",
"an",
"API",
"request",
"."
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L787-L798 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.prepare_param_tag | def prepare_param_tag(name_or_tag, &block) # :yields: tag
tag = case name_or_tag
when WWW::Delicious::Tag
name_or_tag
else
Tag.new(:name => name_or_tag.to_s)
end
yield(tag) if block_given?
# TODO: validate tag with tag.validate!
raise "Invalid `tag` value supplied" unless tag.api_valid?
tag
end | ruby | def prepare_param_tag(name_or_tag, &block) # :yields: tag
tag = case name_or_tag
when WWW::Delicious::Tag
name_or_tag
else
Tag.new(:name => name_or_tag.to_s)
end
yield(tag) if block_given?
# TODO: validate tag with tag.validate!
raise "Invalid `tag` value supplied" unless tag.api_valid?
tag
end | [
"def",
"prepare_param_tag",
"(",
"name_or_tag",
",",
"&",
"block",
")",
"tag",
"=",
"case",
"name_or_tag",
"when",
"WWW",
"::",
"Delicious",
"::",
"Tag",
"name_or_tag",
"else",
"Tag",
".",
"new",
"(",
":name",
"=>",
"name_or_tag",
".",
"to_s",
")",
"end",
"yield",
"(",
"tag",
")",
"if",
"block_given?",
"raise",
"\"Invalid `tag` value supplied\"",
"unless",
"tag",
".",
"api_valid?",
"tag",
"end"
] | Prepares the +tag+ param for an API request.
Creates and returns a <tt>WWW::Delicious::Tag</tt> instance from <tt>name_or_tag</tt>.
<tt>name_or_tag</tt> can be either a string holding tag name
or a <tt>WWW::Delicious::Tag</tt> instance. | [
"Prepares",
"the",
"+",
"tag",
"+",
"param",
"for",
"an",
"API",
"request",
"."
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L807-L819 | train |
weppos/www-delicious | lib/www/delicious.rb | WWW.Delicious.compare_params | def compare_params(params, valid_params)
raise ArgumentError, "Expected `params` to be a kind of `Hash`" unless params.kind_of?(Hash)
raise ArgumentError, "Expected `valid_params` to be a kind of `Array`" unless valid_params.kind_of?(Array)
# compute options difference
difference = params.keys - valid_params
raise Error, "Invalid params: `#{difference.join('`, `')}`" unless difference.empty?
end | ruby | def compare_params(params, valid_params)
raise ArgumentError, "Expected `params` to be a kind of `Hash`" unless params.kind_of?(Hash)
raise ArgumentError, "Expected `valid_params` to be a kind of `Array`" unless valid_params.kind_of?(Array)
# compute options difference
difference = params.keys - valid_params
raise Error, "Invalid params: `#{difference.join('`, `')}`" unless difference.empty?
end | [
"def",
"compare_params",
"(",
"params",
",",
"valid_params",
")",
"raise",
"ArgumentError",
",",
"\"Expected `params` to be a kind of `Hash`\"",
"unless",
"params",
".",
"kind_of?",
"(",
"Hash",
")",
"raise",
"ArgumentError",
",",
"\"Expected `valid_params` to be a kind of `Array`\"",
"unless",
"valid_params",
".",
"kind_of?",
"(",
"Array",
")",
"difference",
"=",
"params",
".",
"keys",
"-",
"valid_params",
"raise",
"Error",
",",
"\"Invalid params: `#{difference.join('`, `')}`\"",
"unless",
"difference",
".",
"empty?",
"end"
] | Checks whether user given +params+ are valid against a defined collection of +valid_params+.
=== Examples
params = {:foo => 1, :bar => 2}
compare_params(params, [:foo, :bar])
# => valid
compare_params(params, [:foo, :bar, :baz])
# => raises
compare_params(params, [:foo])
# => raises
Raises:: WWW::Delicious::Error | [
"Checks",
"whether",
"user",
"given",
"+",
"params",
"+",
"are",
"valid",
"against",
"a",
"defined",
"collection",
"of",
"+",
"valid_params",
"+",
"."
] | 68006915fdca50af7868e12b0fa93f62b01e0f9f | https://github.com/weppos/www-delicious/blob/68006915fdca50af7868e12b0fa93f62b01e0f9f/lib/www/delicious.rb#L839-L846 | train |
pengwynn/groupon | lib/groupon/client.rb | Groupon.Client.deals | def deals(query={})
division = query.delete(:division)
query.merge! :client_id => @api_key
path = division ? "/#{division}" : ""
path += "/deals.json"
self.class.get(path, :query => query).deals
end | ruby | def deals(query={})
division = query.delete(:division)
query.merge! :client_id => @api_key
path = division ? "/#{division}" : ""
path += "/deals.json"
self.class.get(path, :query => query).deals
end | [
"def",
"deals",
"(",
"query",
"=",
"{",
"}",
")",
"division",
"=",
"query",
".",
"delete",
"(",
":division",
")",
"query",
".",
"merge!",
":client_id",
"=>",
"@api_key",
"path",
"=",
"division",
"?",
"\"/#{division}\"",
":",
"\"\"",
"path",
"+=",
"\"/deals.json\"",
"self",
".",
"class",
".",
"get",
"(",
"path",
",",
":query",
"=>",
"query",
")",
".",
"deals",
"end"
] | Returns a list of deals.
The API returns an ordered list of deals currently running for a given Division.
Priority is based on position within the response (top deals are higher in priority).
@see http://sites.google.com/site/grouponapi/divisions-api Groupon API docs
@option options [String] :lat (Latitudinal coordinates based on IP of API request) Latitude of geolocation to find deals
@option options [String] :lng (Longtitudinal coordinates based on IP of API request) Longitude of geolocation to find deals
@return [Array<Hashie::Mash>] an array of deals | [
"Returns",
"a",
"list",
"of",
"deals",
"."
] | 6f778cc71bf51a559c40038822d90cc7cacca0b7 | https://github.com/pengwynn/groupon/blob/6f778cc71bf51a559c40038822d90cc7cacca0b7/lib/groupon/client.rb#L40-L46 | train |
groupon/sycl | lib/sycl.rb | Sycl.Array.[]= | def []=(*args) # :nodoc:
raise ArgumentError => 'wrong number of arguments' unless args.size > 1
unless args[-1].is_a?(Sycl::Hash) || args[-1].is_a?(Sycl::Array)
args[-1] = Sycl::from_object(args[-1])
end
super
end | ruby | def []=(*args) # :nodoc:
raise ArgumentError => 'wrong number of arguments' unless args.size > 1
unless args[-1].is_a?(Sycl::Hash) || args[-1].is_a?(Sycl::Array)
args[-1] = Sycl::from_object(args[-1])
end
super
end | [
"def",
"[]=",
"(",
"*",
"args",
")",
"raise",
"ArgumentError",
"=>",
"'wrong number of arguments'",
"unless",
"args",
".",
"size",
">",
"1",
"unless",
"args",
"[",
"-",
"1",
"]",
".",
"is_a?",
"(",
"Sycl",
"::",
"Hash",
")",
"||",
"args",
"[",
"-",
"1",
"]",
".",
"is_a?",
"(",
"Sycl",
"::",
"Array",
")",
"args",
"[",
"-",
"1",
"]",
"=",
"Sycl",
"::",
"from_object",
"(",
"args",
"[",
"-",
"1",
"]",
")",
"end",
"super",
"end"
] | Make sure that if we write to this array, we promote any inputs
to their Sycl equivalents. This lets dot notation, styled YAML,
and other Sycl goodies continue. | [
"Make",
"sure",
"that",
"if",
"we",
"write",
"to",
"this",
"array",
"we",
"promote",
"any",
"inputs",
"to",
"their",
"Sycl",
"equivalents",
".",
"This",
"lets",
"dot",
"notation",
"styled",
"YAML",
"and",
"other",
"Sycl",
"goodies",
"continue",
"."
] | 1efa291503b212d69355c2fbf6c1f2588e15068d | https://github.com/groupon/sycl/blob/1efa291503b212d69355c2fbf6c1f2588e15068d/lib/sycl.rb#L179-L185 | train |
groupon/sycl | lib/sycl.rb | Sycl.Hash.[]= | def []=(k, v) # :nodoc:
unless v.is_a?(Sycl::Hash) || v.is_a?(Sycl::Array)
v = Sycl::from_object(v)
end
super
end | ruby | def []=(k, v) # :nodoc:
unless v.is_a?(Sycl::Hash) || v.is_a?(Sycl::Array)
v = Sycl::from_object(v)
end
super
end | [
"def",
"[]=",
"(",
"k",
",",
"v",
")",
"unless",
"v",
".",
"is_a?",
"(",
"Sycl",
"::",
"Hash",
")",
"||",
"v",
".",
"is_a?",
"(",
"Sycl",
"::",
"Array",
")",
"v",
"=",
"Sycl",
"::",
"from_object",
"(",
"v",
")",
"end",
"super",
"end"
] | Make sure that if we write to this hash, we promote any inputs
to their Sycl equivalents. This lets dot notation, styled YAML,
and other Sycl goodies continue. | [
"Make",
"sure",
"that",
"if",
"we",
"write",
"to",
"this",
"hash",
"we",
"promote",
"any",
"inputs",
"to",
"their",
"Sycl",
"equivalents",
".",
"This",
"lets",
"dot",
"notation",
"styled",
"YAML",
"and",
"other",
"Sycl",
"goodies",
"continue",
"."
] | 1efa291503b212d69355c2fbf6c1f2588e15068d | https://github.com/groupon/sycl/blob/1efa291503b212d69355c2fbf6c1f2588e15068d/lib/sycl.rb#L467-L472 | train |
vigetlabs/stat_board | lib/stat_board/graph_helper.rb | StatBoard.GraphHelper.first_day_of | def first_day_of(klass_name)
klass = klass_name.to_s.constantize
klass.order("created_at ASC").first.try(:created_at) || Time.now
end | ruby | def first_day_of(klass_name)
klass = klass_name.to_s.constantize
klass.order("created_at ASC").first.try(:created_at) || Time.now
end | [
"def",
"first_day_of",
"(",
"klass_name",
")",
"klass",
"=",
"klass_name",
".",
"to_s",
".",
"constantize",
"klass",
".",
"order",
"(",
"\"created_at ASC\"",
")",
".",
"first",
".",
"try",
"(",
":created_at",
")",
"||",
"Time",
".",
"now",
"end"
] | returns the earliest `created_at` of a given class
returns `Time.now` if none is available | [
"returns",
"the",
"earliest",
"created_at",
"of",
"a",
"given",
"class",
"returns",
"Time",
".",
"now",
"if",
"none",
"is",
"available"
] | c3486280cc86d48de88f8ddb1a506a855650f7fe | https://github.com/vigetlabs/stat_board/blob/c3486280cc86d48de88f8ddb1a506a855650f7fe/lib/stat_board/graph_helper.rb#L53-L56 | train |
darbylabs/magma | lib/magma/utils.rb | Magma.Utils.read_file_or_stdin | def read_file_or_stdin(filename = nil)
filename.nil? ? !STDIN.tty? && STDIN.read : File.read(filename)
end | ruby | def read_file_or_stdin(filename = nil)
filename.nil? ? !STDIN.tty? && STDIN.read : File.read(filename)
end | [
"def",
"read_file_or_stdin",
"(",
"filename",
"=",
"nil",
")",
"filename",
".",
"nil?",
"?",
"!",
"STDIN",
".",
"tty?",
"&&",
"STDIN",
".",
"read",
":",
"File",
".",
"read",
"(",
"filename",
")",
"end"
] | Reads a file or from STDIN if piped | [
"Reads",
"a",
"file",
"or",
"from",
"STDIN",
"if",
"piped"
] | 62da478396fb479786f109128b6f65dd85b7c04c | https://github.com/darbylabs/magma/blob/62da478396fb479786f109128b6f65dd85b7c04c/lib/magma/utils.rb#L6-L8 | train |
darbylabs/magma | lib/magma/utils.rb | Magma.Utils.run | def run(*args, &block)
return Open3.popen3(*args, &block) if block_given?
Open3.popen3(*args)
end | ruby | def run(*args, &block)
return Open3.popen3(*args, &block) if block_given?
Open3.popen3(*args)
end | [
"def",
"run",
"(",
"*",
"args",
",",
"&",
"block",
")",
"return",
"Open3",
".",
"popen3",
"(",
"*",
"args",
",",
"&",
"block",
")",
"if",
"block_given?",
"Open3",
".",
"popen3",
"(",
"*",
"args",
")",
"end"
] | Delegates to Open3 | [
"Delegates",
"to",
"Open3"
] | 62da478396fb479786f109128b6f65dd85b7c04c | https://github.com/darbylabs/magma/blob/62da478396fb479786f109128b6f65dd85b7c04c/lib/magma/utils.rb#L34-L37 | train |
darbylabs/magma | lib/magma/utils.rb | Magma.Utils.symbolize_keys | def symbolize_keys(hash)
hash.each_with_object({}) { |(k, v), memo| memo[k.to_sym] = v }
end | ruby | def symbolize_keys(hash)
hash.each_with_object({}) { |(k, v), memo| memo[k.to_sym] = v }
end | [
"def",
"symbolize_keys",
"(",
"hash",
")",
"hash",
".",
"each_with_object",
"(",
"{",
"}",
")",
"{",
"|",
"(",
"k",
",",
"v",
")",
",",
"memo",
"|",
"memo",
"[",
"k",
".",
"to_sym",
"]",
"=",
"v",
"}",
"end"
] | Symbolizes a hash's keys | [
"Symbolizes",
"a",
"hash",
"s",
"keys"
] | 62da478396fb479786f109128b6f65dd85b7c04c | https://github.com/darbylabs/magma/blob/62da478396fb479786f109128b6f65dd85b7c04c/lib/magma/utils.rb#L40-L42 | train |
rschultheis/tcfg | lib/tcfg/tcfg_helper.rb | TCFG.Helper.tcfg_get | def tcfg_get(key)
t_tcfg = tcfg
unless t_tcfg.key? key
raise NoSuchConfigurationKeyError, "No configuration defined for '#{key}'"
end
t_tcfg[key]
end | ruby | def tcfg_get(key)
t_tcfg = tcfg
unless t_tcfg.key? key
raise NoSuchConfigurationKeyError, "No configuration defined for '#{key}'"
end
t_tcfg[key]
end | [
"def",
"tcfg_get",
"(",
"key",
")",
"t_tcfg",
"=",
"tcfg",
"unless",
"t_tcfg",
".",
"key?",
"key",
"raise",
"NoSuchConfigurationKeyError",
",",
"\"No configuration defined for '#{key}'\"",
"end",
"t_tcfg",
"[",
"key",
"]",
"end"
] | return a single piece of configuration by key
@param key [String] the configuration to return
@return [String, Integer, FixNum, Array, Hash] the value of the configuration from the resolved configuration | [
"return",
"a",
"single",
"piece",
"of",
"configuration",
"by",
"key"
] | 7016ee3a70404d468e20efc39b7ee8d37f288b19 | https://github.com/rschultheis/tcfg/blob/7016ee3a70404d468e20efc39b7ee8d37f288b19/lib/tcfg/tcfg_helper.rb#L121-L127 | train |
Kuniri/kuniri | lib/kuniri/language/language_factory.rb | Languages.LanguageFactory.get_language | def get_language(pType)
pType.downcase!
return Languages::RubySyntax.new if pType == 'ruby'
# if pType == "python"
# raise Error::LanguageError
# end
# if pType == "vhdl"
# raise Error::LanguageError
# end
# if pType == "c"
# raise Error::LanguageError
# end
# if pType == "cplusplus"
# raise Error::LanguageError
# end
# if pType == "java"
# raise Error::LanguageError
# end
# if pType == "assemblyarm"
# raise Error::LanguageError
# end
# if pType == "php"
# raise Error::LanguageError
raise Error::LanguageError
end | ruby | def get_language(pType)
pType.downcase!
return Languages::RubySyntax.new if pType == 'ruby'
# if pType == "python"
# raise Error::LanguageError
# end
# if pType == "vhdl"
# raise Error::LanguageError
# end
# if pType == "c"
# raise Error::LanguageError
# end
# if pType == "cplusplus"
# raise Error::LanguageError
# end
# if pType == "java"
# raise Error::LanguageError
# end
# if pType == "assemblyarm"
# raise Error::LanguageError
# end
# if pType == "php"
# raise Error::LanguageError
raise Error::LanguageError
end | [
"def",
"get_language",
"(",
"pType",
")",
"pType",
".",
"downcase!",
"return",
"Languages",
"::",
"RubySyntax",
".",
"new",
"if",
"pType",
"==",
"'ruby'",
"raise",
"Error",
"::",
"LanguageError",
"end"
] | Handling the class creation.
@param pType [String] Type of object
@return Return an object of language. | [
"Handling",
"the",
"class",
"creation",
"."
] | 8b840ab307dc6bec48edd272c732b28c98f93f45 | https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/language/language_factory.rb#L19-L44 | train |
bdurand/json_record | lib/json_record/embedded_document_array.rb | JsonRecord.EmbeddedDocumentArray.concat | def concat (objects)
objects = objects.collect do |obj|
obj = @klass.new(obj) if obj.is_a?(Hash)
raise ArgumentError.new("#{obj.inspect} is not a #{@klass}") unless obj.is_a?(@klass)
obj.parent = @parent
obj
end
super(objects)
end | ruby | def concat (objects)
objects = objects.collect do |obj|
obj = @klass.new(obj) if obj.is_a?(Hash)
raise ArgumentError.new("#{obj.inspect} is not a #{@klass}") unless obj.is_a?(@klass)
obj.parent = @parent
obj
end
super(objects)
end | [
"def",
"concat",
"(",
"objects",
")",
"objects",
"=",
"objects",
".",
"collect",
"do",
"|",
"obj",
"|",
"obj",
"=",
"@klass",
".",
"new",
"(",
"obj",
")",
"if",
"obj",
".",
"is_a?",
"(",
"Hash",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"#{obj.inspect} is not a #{@klass}\"",
")",
"unless",
"obj",
".",
"is_a?",
"(",
"@klass",
")",
"obj",
".",
"parent",
"=",
"@parent",
"obj",
"end",
"super",
"(",
"objects",
")",
"end"
] | Concatenate an array of objects to the array. The objects must either be an EmbeddedDocument of the
correct class, or a Hash. | [
"Concatenate",
"an",
"array",
"of",
"objects",
"to",
"the",
"array",
".",
"The",
"objects",
"must",
"either",
"be",
"an",
"EmbeddedDocument",
"of",
"the",
"correct",
"class",
"or",
"a",
"Hash",
"."
] | 463f4719d9618f6d2406c0aab6028e0156f7c775 | https://github.com/bdurand/json_record/blob/463f4719d9618f6d2406c0aab6028e0156f7c775/lib/json_record/embedded_document_array.rb#L34-L42 | train |
bdurand/json_record | lib/json_record/embedded_document_array.rb | JsonRecord.EmbeddedDocumentArray.build | def build (obj)
obj = @klass.new(obj) if obj.is_a?(Hash)
raise ArgumentError.new("#{obj.inspect} is not a #{@klass}") unless obj.is_a?(@klass)
obj.parent = @parent
self << obj
obj
end | ruby | def build (obj)
obj = @klass.new(obj) if obj.is_a?(Hash)
raise ArgumentError.new("#{obj.inspect} is not a #{@klass}") unless obj.is_a?(@klass)
obj.parent = @parent
self << obj
obj
end | [
"def",
"build",
"(",
"obj",
")",
"obj",
"=",
"@klass",
".",
"new",
"(",
"obj",
")",
"if",
"obj",
".",
"is_a?",
"(",
"Hash",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"#{obj.inspect} is not a #{@klass}\"",
")",
"unless",
"obj",
".",
"is_a?",
"(",
"@klass",
")",
"obj",
".",
"parent",
"=",
"@parent",
"self",
"<<",
"obj",
"obj",
"end"
] | Similar add an EmbeddedDocument to the array and return the object. If the object passed
in is a Hash, it will be used to make a new EmbeddedDocument. | [
"Similar",
"add",
"an",
"EmbeddedDocument",
"to",
"the",
"array",
"and",
"return",
"the",
"object",
".",
"If",
"the",
"object",
"passed",
"in",
"is",
"a",
"Hash",
"it",
"will",
"be",
"used",
"to",
"make",
"a",
"new",
"EmbeddedDocument",
"."
] | 463f4719d9618f6d2406c0aab6028e0156f7c775 | https://github.com/bdurand/json_record/blob/463f4719d9618f6d2406c0aab6028e0156f7c775/lib/json_record/embedded_document_array.rb#L46-L52 | train |
ronyv89/skydrive | lib/skydrive/client.rb | Skydrive.Client.put | def put url, body=nil, options={}
response = filtered_response(self.class.put(url, { :body => body, :query => options, headers: { 'content-type' => ''} }))
end | ruby | def put url, body=nil, options={}
response = filtered_response(self.class.put(url, { :body => body, :query => options, headers: { 'content-type' => ''} }))
end | [
"def",
"put",
"url",
",",
"body",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
"response",
"=",
"filtered_response",
"(",
"self",
".",
"class",
".",
"put",
"(",
"url",
",",
"{",
":body",
"=>",
"body",
",",
":query",
"=>",
"options",
",",
"headers",
":",
"{",
"'content-type'",
"=>",
"''",
"}",
"}",
")",
")",
"end"
] | Do a put request
@param [String] url the url to put
@param [Hash] options Additonal options to be passed | [
"Do",
"a",
"put",
"request"
] | 6cf7b692f64c6f00a81bc7ca6fffca3020244072 | https://github.com/ronyv89/skydrive/blob/6cf7b692f64c6f00a81bc7ca6fffca3020244072/lib/skydrive/client.rb#L44-L46 | train |
ronyv89/skydrive | lib/skydrive/client.rb | Skydrive.Client.filtered_response | def filtered_response response
raise Skydrive::Error.new({"code" => "no_response_received", "message" => "Request didn't make through or response not received"}) unless response
if response.success?
filtered_response = response.parsed_response
if response.response.code =~ /(201|200)/
raise Skydrive::Error.new(filtered_response["error"]) if filtered_response["error"]
if filtered_response["data"]
return Skydrive::Collection.new(self, filtered_response["data"])
elsif filtered_response["id"] && (filtered_response["id"].match /^comment\..+/)
return Skydrive::Comment.new(self, filtered_response)
elsif filtered_response["id"] && (filtered_response["id"].match /^file\..+/)
return Skydrive::File.new(self, filtered_response)
elsif filtered_response["type"]
return "Skydrive::#{filtered_response["type"].capitalize}".constantize.new(self, filtered_response)
else
return filtered_response
end
else
return true
end
else
raise Skydrive::Error.new("code" => "http_error_#{response.response.code}", "message" => response.response.message)
end
end | ruby | def filtered_response response
raise Skydrive::Error.new({"code" => "no_response_received", "message" => "Request didn't make through or response not received"}) unless response
if response.success?
filtered_response = response.parsed_response
if response.response.code =~ /(201|200)/
raise Skydrive::Error.new(filtered_response["error"]) if filtered_response["error"]
if filtered_response["data"]
return Skydrive::Collection.new(self, filtered_response["data"])
elsif filtered_response["id"] && (filtered_response["id"].match /^comment\..+/)
return Skydrive::Comment.new(self, filtered_response)
elsif filtered_response["id"] && (filtered_response["id"].match /^file\..+/)
return Skydrive::File.new(self, filtered_response)
elsif filtered_response["type"]
return "Skydrive::#{filtered_response["type"].capitalize}".constantize.new(self, filtered_response)
else
return filtered_response
end
else
return true
end
else
raise Skydrive::Error.new("code" => "http_error_#{response.response.code}", "message" => response.response.message)
end
end | [
"def",
"filtered_response",
"response",
"raise",
"Skydrive",
"::",
"Error",
".",
"new",
"(",
"{",
"\"code\"",
"=>",
"\"no_response_received\"",
",",
"\"message\"",
"=>",
"\"Request didn't make through or response not received\"",
"}",
")",
"unless",
"response",
"if",
"response",
".",
"success?",
"filtered_response",
"=",
"response",
".",
"parsed_response",
"if",
"response",
".",
"response",
".",
"code",
"=~",
"/",
"/",
"raise",
"Skydrive",
"::",
"Error",
".",
"new",
"(",
"filtered_response",
"[",
"\"error\"",
"]",
")",
"if",
"filtered_response",
"[",
"\"error\"",
"]",
"if",
"filtered_response",
"[",
"\"data\"",
"]",
"return",
"Skydrive",
"::",
"Collection",
".",
"new",
"(",
"self",
",",
"filtered_response",
"[",
"\"data\"",
"]",
")",
"elsif",
"filtered_response",
"[",
"\"id\"",
"]",
"&&",
"(",
"filtered_response",
"[",
"\"id\"",
"]",
".",
"match",
"/",
"\\.",
"/",
")",
"return",
"Skydrive",
"::",
"Comment",
".",
"new",
"(",
"self",
",",
"filtered_response",
")",
"elsif",
"filtered_response",
"[",
"\"id\"",
"]",
"&&",
"(",
"filtered_response",
"[",
"\"id\"",
"]",
".",
"match",
"/",
"\\.",
"/",
")",
"return",
"Skydrive",
"::",
"File",
".",
"new",
"(",
"self",
",",
"filtered_response",
")",
"elsif",
"filtered_response",
"[",
"\"type\"",
"]",
"return",
"\"Skydrive::#{filtered_response[\"type\"].capitalize}\"",
".",
"constantize",
".",
"new",
"(",
"self",
",",
"filtered_response",
")",
"else",
"return",
"filtered_response",
"end",
"else",
"return",
"true",
"end",
"else",
"raise",
"Skydrive",
"::",
"Error",
".",
"new",
"(",
"\"code\"",
"=>",
"\"http_error_#{response.response.code}\"",
",",
"\"message\"",
"=>",
"response",
".",
"response",
".",
"message",
")",
"end",
"end"
] | Filter the response after checking for any errors | [
"Filter",
"the",
"response",
"after",
"checking",
"for",
"any",
"errors"
] | 6cf7b692f64c6f00a81bc7ca6fffca3020244072 | https://github.com/ronyv89/skydrive/blob/6cf7b692f64c6f00a81bc7ca6fffca3020244072/lib/skydrive/client.rb#L73-L96 | train |
Kuniri/kuniri | lib/kuniri/parser/output_factory.rb | Parser.OutputFactory.get_output | def get_output(pType)
pType.downcase!
return XMLOutputFormat.new if pType == 'xml'
raise Error::ParserError if pType == 'yml'
end | ruby | def get_output(pType)
pType.downcase!
return XMLOutputFormat.new if pType == 'xml'
raise Error::ParserError if pType == 'yml'
end | [
"def",
"get_output",
"(",
"pType",
")",
"pType",
".",
"downcase!",
"return",
"XMLOutputFormat",
".",
"new",
"if",
"pType",
"==",
"'xml'",
"raise",
"Error",
"::",
"ParserError",
"if",
"pType",
"==",
"'yml'",
"end"
] | Handling the output tyoe.
@param pType [String] Type of object
@return Return an object of output. | [
"Handling",
"the",
"output",
"tyoe",
"."
] | 8b840ab307dc6bec48edd272c732b28c98f93f45 | https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/parser/output_factory.rb#L17-L22 | train |
oggy/redis_master_slave | lib/redis_master_slave/client.rb | RedisMasterSlave.Client.method_missing | def method_missing(name, *args, &block) # :nodoc:
if writable_master.respond_to?(name)
Client.send(:send_to_master, name)
send(name, *args, &block)
else
super
end
end | ruby | def method_missing(name, *args, &block) # :nodoc:
if writable_master.respond_to?(name)
Client.send(:send_to_master, name)
send(name, *args, &block)
else
super
end
end | [
"def",
"method_missing",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"writable_master",
".",
"respond_to?",
"(",
"name",
")",
"Client",
".",
"send",
"(",
":send_to_master",
",",
"name",
")",
"send",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"else",
"super",
"end",
"end"
] | Send everything else to master. | [
"Send",
"everything",
"else",
"to",
"master",
"."
] | 29a0aeb62e5f4466e40be58d99de9420b54f3758 | https://github.com/oggy/redis_master_slave/blob/29a0aeb62e5f4466e40be58d99de9420b54f3758/lib/redis_master_slave/client.rb#L121-L128 | train |
payneteasy/ruby-library-payneteasy-api | lib/paynet_easy/paynet_easy_api/callback/callback_prototype.rb | PaynetEasy::PaynetEasyApi::Callback.CallbackPrototype.process_callback | def process_callback(payment_transaction, callback_response)
begin
validate_callback payment_transaction, callback_response
rescue Exception => error
payment_transaction.add_error error
payment_transaction.status = PaymentTransaction::STATUS_ERROR
raise error
end
update_payment_transaction payment_transaction, callback_response
if callback_response.error?
raise callback_response.error
end
callback_response
end | ruby | def process_callback(payment_transaction, callback_response)
begin
validate_callback payment_transaction, callback_response
rescue Exception => error
payment_transaction.add_error error
payment_transaction.status = PaymentTransaction::STATUS_ERROR
raise error
end
update_payment_transaction payment_transaction, callback_response
if callback_response.error?
raise callback_response.error
end
callback_response
end | [
"def",
"process_callback",
"(",
"payment_transaction",
",",
"callback_response",
")",
"begin",
"validate_callback",
"payment_transaction",
",",
"callback_response",
"rescue",
"Exception",
"=>",
"error",
"payment_transaction",
".",
"add_error",
"error",
"payment_transaction",
".",
"status",
"=",
"PaymentTransaction",
"::",
"STATUS_ERROR",
"raise",
"error",
"end",
"update_payment_transaction",
"payment_transaction",
",",
"callback_response",
"if",
"callback_response",
".",
"error?",
"raise",
"callback_response",
".",
"error",
"end",
"callback_response",
"end"
] | Process API gateway Response and update Payment transaction
@param payment_transaction [PaymentTransaction] Payment transaction for update
@param callback_response [CallbackResponse] PaynetEasy callback
@return [CallbackResponse] PaynetEasy callback | [
"Process",
"API",
"gateway",
"Response",
"and",
"update",
"Payment",
"transaction"
] | 3200a447829b62e241fdc329f80fddb5f8d68cc0 | https://github.com/payneteasy/ruby-library-payneteasy-api/blob/3200a447829b62e241fdc329f80fddb5f8d68cc0/lib/paynet_easy/paynet_easy_api/callback/callback_prototype.rb#L56-L73 | train |
payneteasy/ruby-library-payneteasy-api | lib/paynet_easy/paynet_easy_api/callback/callback_prototype.rb | PaynetEasy::PaynetEasyApi::Callback.CallbackPrototype.validate_signature | def validate_signature(payment_transaction, callback_response)
expected_control_code = Digest::SHA1.hexdigest(
callback_response.status +
callback_response.payment_paynet_id.to_s +
callback_response.payment_client_id.to_s +
payment_transaction.query_config.signing_key
)
if expected_control_code != callback_response.control_code
raise ValidationError, "Actual control code '#{callback_response.control_code}' does " +
"not equal expected '#{expected_control_code}'"
end
end | ruby | def validate_signature(payment_transaction, callback_response)
expected_control_code = Digest::SHA1.hexdigest(
callback_response.status +
callback_response.payment_paynet_id.to_s +
callback_response.payment_client_id.to_s +
payment_transaction.query_config.signing_key
)
if expected_control_code != callback_response.control_code
raise ValidationError, "Actual control code '#{callback_response.control_code}' does " +
"not equal expected '#{expected_control_code}'"
end
end | [
"def",
"validate_signature",
"(",
"payment_transaction",
",",
"callback_response",
")",
"expected_control_code",
"=",
"Digest",
"::",
"SHA1",
".",
"hexdigest",
"(",
"callback_response",
".",
"status",
"+",
"callback_response",
".",
"payment_paynet_id",
".",
"to_s",
"+",
"callback_response",
".",
"payment_client_id",
".",
"to_s",
"+",
"payment_transaction",
".",
"query_config",
".",
"signing_key",
")",
"if",
"expected_control_code",
"!=",
"callback_response",
".",
"control_code",
"raise",
"ValidationError",
",",
"\"Actual control code '#{callback_response.control_code}' does \"",
"+",
"\"not equal expected '#{expected_control_code}'\"",
"end",
"end"
] | Validate callback response control code
@param payment_transaction [PaymentTransaction] Payment transaction for control code checking
@param callback_response [CallbackResponse] Callback for control code checking | [
"Validate",
"callback",
"response",
"control",
"code"
] | 3200a447829b62e241fdc329f80fddb5f8d68cc0 | https://github.com/payneteasy/ruby-library-payneteasy-api/blob/3200a447829b62e241fdc329f80fddb5f8d68cc0/lib/paynet_easy/paynet_easy_api/callback/callback_prototype.rb#L134-L146 | train |
payneteasy/ruby-library-payneteasy-api | lib/paynet_easy/paynet_easy_api/callback/callback_prototype.rb | PaynetEasy::PaynetEasyApi::Callback.CallbackPrototype.update_payment_transaction | def update_payment_transaction(payment_transaction, callback_response)
payment_transaction.status = callback_response.status
payment_transaction.payment.paynet_id = callback_response.payment_paynet_id
if callback_response.error? || callback_response.declined?
payment_transaction.add_error callback_response.error
end
end | ruby | def update_payment_transaction(payment_transaction, callback_response)
payment_transaction.status = callback_response.status
payment_transaction.payment.paynet_id = callback_response.payment_paynet_id
if callback_response.error? || callback_response.declined?
payment_transaction.add_error callback_response.error
end
end | [
"def",
"update_payment_transaction",
"(",
"payment_transaction",
",",
"callback_response",
")",
"payment_transaction",
".",
"status",
"=",
"callback_response",
".",
"status",
"payment_transaction",
".",
"payment",
".",
"paynet_id",
"=",
"callback_response",
".",
"payment_paynet_id",
"if",
"callback_response",
".",
"error?",
"||",
"callback_response",
".",
"declined?",
"payment_transaction",
".",
"add_error",
"callback_response",
".",
"error",
"end",
"end"
] | Updates Payment transaction by Callback data
@param payment_transaction [PaymentTransaction] Payment transaction for updating
@param callback_response [CallbackResponse] Callback for payment transaction updating | [
"Updates",
"Payment",
"transaction",
"by",
"Callback",
"data"
] | 3200a447829b62e241fdc329f80fddb5f8d68cc0 | https://github.com/payneteasy/ruby-library-payneteasy-api/blob/3200a447829b62e241fdc329f80fddb5f8d68cc0/lib/paynet_easy/paynet_easy_api/callback/callback_prototype.rb#L152-L159 | train |
petebrowne/massimo | lib/massimo/ui.rb | Massimo.UI.report_errors | def report_errors
begin
yield
true
rescue Exception => error
say 'massimo had a problem', :red
indent do
say error.message, :magenta
say error.backtrace.first, :magenta
end
growl "#{error.message}\n#{error.backtrace.first}", 'massimo problem'
false
end
end | ruby | def report_errors
begin
yield
true
rescue Exception => error
say 'massimo had a problem', :red
indent do
say error.message, :magenta
say error.backtrace.first, :magenta
end
growl "#{error.message}\n#{error.backtrace.first}", 'massimo problem'
false
end
end | [
"def",
"report_errors",
"begin",
"yield",
"true",
"rescue",
"Exception",
"=>",
"error",
"say",
"'massimo had a problem'",
",",
":red",
"indent",
"do",
"say",
"error",
".",
"message",
",",
":magenta",
"say",
"error",
".",
"backtrace",
".",
"first",
",",
":magenta",
"end",
"growl",
"\"#{error.message}\\n#{error.backtrace.first}\"",
",",
"'massimo problem'",
"false",
"end",
"end"
] | Run the given block and cleanly report any errors | [
"Run",
"the",
"given",
"block",
"and",
"cleanly",
"report",
"any",
"errors"
] | c450edc531ad358f011da0a47e5d0bc9a038d911 | https://github.com/petebrowne/massimo/blob/c450edc531ad358f011da0a47e5d0bc9a038d911/lib/massimo/ui.rb#L35-L48 | train |
mamantoha/freshdesk_api_client_rb | lib/freshdesk_api/client.rb | FreshdeskAPI.Client.method_missing | def method_missing(method, *args)
method = method.to_s
method_class = method_as_class(method)
options = args.last.is_a?(Hash) ? args.pop : {}
FreshdeskAPI::Collection.new(self, method_class, options)
end | ruby | def method_missing(method, *args)
method = method.to_s
method_class = method_as_class(method)
options = args.last.is_a?(Hash) ? args.pop : {}
FreshdeskAPI::Collection.new(self, method_class, options)
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
")",
"method",
"=",
"method",
".",
"to_s",
"method_class",
"=",
"method_as_class",
"(",
"method",
")",
"options",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"FreshdeskAPI",
"::",
"Collection",
".",
"new",
"(",
"self",
",",
"method_class",
",",
"options",
")",
"end"
] | Handles resources such as 'tickets'.
@return [Collection] Collection instance for resource | [
"Handles",
"resources",
"such",
"as",
"tickets",
"."
] | 74367fe0dd31bd269197b3f419412ef600031e62 | https://github.com/mamantoha/freshdesk_api_client_rb/blob/74367fe0dd31bd269197b3f419412ef600031e62/lib/freshdesk_api/client.rb#L28-L34 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.