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
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.deleteDuplicateRecords
def deleteDuplicateRecords( fnames, fids = nil, options = nil, dbid = @dbid ) num_deleted = 0 if options and not options.is_a?( Hash ) raise "deleteDuplicateRecords: 'options' parameter must be a Hash" else options = {} options[ "keeplastrecord" ] = true options[ "ignoreCase" ] = true end findDuplicateRecordIDs( fnames, fids, dbid, options[ "ignoreCase" ] ) { |dupeValues, recordIDs| if options[ "keeplastrecord" ] recordIDs[0..(recordIDs.length-2)].each{ |rid| num_deleted += 1 if deleteRecord( dbid, rid ) } elsif options[ "keepfirstrecord" ] recordIDs[1..(recordIDs.length-1)].each{ |rid| num_deleted += 1 if deleteRecord( dbid, rid ) } end } num_deleted end
ruby
def deleteDuplicateRecords( fnames, fids = nil, options = nil, dbid = @dbid ) num_deleted = 0 if options and not options.is_a?( Hash ) raise "deleteDuplicateRecords: 'options' parameter must be a Hash" else options = {} options[ "keeplastrecord" ] = true options[ "ignoreCase" ] = true end findDuplicateRecordIDs( fnames, fids, dbid, options[ "ignoreCase" ] ) { |dupeValues, recordIDs| if options[ "keeplastrecord" ] recordIDs[0..(recordIDs.length-2)].each{ |rid| num_deleted += 1 if deleteRecord( dbid, rid ) } elsif options[ "keepfirstrecord" ] recordIDs[1..(recordIDs.length-1)].each{ |rid| num_deleted += 1 if deleteRecord( dbid, rid ) } end } num_deleted end
[ "def", "deleteDuplicateRecords", "(", "fnames", ",", "fids", "=", "nil", ",", "options", "=", "nil", ",", "dbid", "=", "@dbid", ")", "num_deleted", "=", "0", "if", "options", "and", "not", "options", ".", "is_a?", "(", "Hash", ")", "raise", "\"deleteDuplicateRecords: 'options' parameter must be a Hash\"", "else", "options", "=", "{", "}", "options", "[", "\"keeplastrecord\"", "]", "=", "true", "options", "[", "\"ignoreCase\"", "]", "=", "true", "end", "findDuplicateRecordIDs", "(", "fnames", ",", "fids", ",", "dbid", ",", "options", "[", "\"ignoreCase\"", "]", ")", "{", "|", "dupeValues", ",", "recordIDs", "|", "if", "options", "[", "\"keeplastrecord\"", "]", "recordIDs", "[", "0", "..", "(", "recordIDs", ".", "length", "-", "2", ")", "]", ".", "each", "{", "|", "rid", "|", "num_deleted", "+=", "1", "if", "deleteRecord", "(", "dbid", ",", "rid", ")", "}", "elsif", "options", "[", "\"keepfirstrecord\"", "]", "recordIDs", "[", "1", "..", "(", "recordIDs", ".", "length", "-", "1", ")", "]", ".", "each", "{", "|", "rid", "|", "num_deleted", "+=", "1", "if", "deleteRecord", "(", "dbid", ",", "rid", ")", "}", "end", "}", "num_deleted", "end" ]
Finds records with the same values in a specified list of fields and deletes all but the first or last duplicate record. The field list may be a list of field IDs or a list of field names. The 'options' parameter can be used to keep the oldest record instead of the newest record, and to control whether to ignore the case of field values when deciding which records are duplicates. Returns the number of records deleted.
[ "Finds", "records", "with", "the", "same", "values", "in", "a", "specified", "list", "of", "fields", "and", "deletes", "all", "but", "the", "first", "or", "last", "duplicate", "record", ".", "The", "field", "list", "may", "be", "a", "list", "of", "field", "IDs", "or", "a", "list", "of", "field", "names", ".", "The", "options", "parameter", "can", "be", "used", "to", "keep", "the", "oldest", "record", "instead", "of", "the", "newest", "record", "and", "to", "control", "whether", "to", "ignore", "the", "case", "of", "field", "values", "when", "deciding", "which", "records", "are", "duplicates", ".", "Returns", "the", "number", "of", "records", "deleted", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L4257-L4274
train
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.copyRecord
def copyRecord( rid, numCopies = 1, dbid = @dbid ) clearFieldValuePairList getRecordInfo( dbid, rid ) { |field| if field and field.elements[ "value" ] and field.elements[ "value" ].has_text? if field.elements[ "fid" ].text.to_i > 5 #skip built-in fields addFieldValuePair( field.elements[ "name" ].text, nil, nil, field.elements[ "value" ].text ) end end } newRecordIDs = [] if @fvlist and @fvlist.length > 0 numCopies.times { addRecord( dbid, @fvlist ) newRecordIDs << @rid if @rid and @update_id } end if block_given? newRecordIDs.each{ |newRecordID| yield newRecordID } else newRecordIDs end end
ruby
def copyRecord( rid, numCopies = 1, dbid = @dbid ) clearFieldValuePairList getRecordInfo( dbid, rid ) { |field| if field and field.elements[ "value" ] and field.elements[ "value" ].has_text? if field.elements[ "fid" ].text.to_i > 5 #skip built-in fields addFieldValuePair( field.elements[ "name" ].text, nil, nil, field.elements[ "value" ].text ) end end } newRecordIDs = [] if @fvlist and @fvlist.length > 0 numCopies.times { addRecord( dbid, @fvlist ) newRecordIDs << @rid if @rid and @update_id } end if block_given? newRecordIDs.each{ |newRecordID| yield newRecordID } else newRecordIDs end end
[ "def", "copyRecord", "(", "rid", ",", "numCopies", "=", "1", ",", "dbid", "=", "@dbid", ")", "clearFieldValuePairList", "getRecordInfo", "(", "dbid", ",", "rid", ")", "{", "|", "field", "|", "if", "field", "and", "field", ".", "elements", "[", "\"value\"", "]", "and", "field", ".", "elements", "[", "\"value\"", "]", ".", "has_text?", "if", "field", ".", "elements", "[", "\"fid\"", "]", ".", "text", ".", "to_i", ">", "5", "addFieldValuePair", "(", "field", ".", "elements", "[", "\"name\"", "]", ".", "text", ",", "nil", ",", "nil", ",", "field", ".", "elements", "[", "\"value\"", "]", ".", "text", ")", "end", "end", "}", "newRecordIDs", "=", "[", "]", "if", "@fvlist", "and", "@fvlist", ".", "length", ">", "0", "numCopies", ".", "times", "{", "addRecord", "(", "dbid", ",", "@fvlist", ")", "newRecordIDs", "<<", "@rid", "if", "@rid", "and", "@update_id", "}", "end", "if", "block_given?", "newRecordIDs", ".", "each", "{", "|", "newRecordID", "|", "yield", "newRecordID", "}", "else", "newRecordIDs", "end", "end" ]
Make one or more copies of a record.
[ "Make", "one", "or", "more", "copies", "of", "a", "record", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L4277-L4298
train
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client._importFromExcel
def _importFromExcel(excelFilename,lastColumn = 'j',lastDataRow = 0,worksheetNumber = 1,fieldNameRow = 1,firstDataRow = 2,firstColumn = 'a') importFromExcel( @dbid, excelFilename, lastColumn, lastDataRow, worksheetNumber, fieldNameRow, firstDataRow, firstColumn ) end
ruby
def _importFromExcel(excelFilename,lastColumn = 'j',lastDataRow = 0,worksheetNumber = 1,fieldNameRow = 1,firstDataRow = 2,firstColumn = 'a') importFromExcel( @dbid, excelFilename, lastColumn, lastDataRow, worksheetNumber, fieldNameRow, firstDataRow, firstColumn ) end
[ "def", "_importFromExcel", "(", "excelFilename", ",", "lastColumn", "=", "'j'", ",", "lastDataRow", "=", "0", ",", "worksheetNumber", "=", "1", ",", "fieldNameRow", "=", "1", ",", "firstDataRow", "=", "2", ",", "firstColumn", "=", "'a'", ")", "importFromExcel", "(", "@dbid", ",", "excelFilename", ",", "lastColumn", ",", "lastDataRow", ",", "worksheetNumber", ",", "fieldNameRow", ",", "firstDataRow", ",", "firstColumn", ")", "end" ]
Import data directly from an Excel file into the active table.
[ "Import", "data", "directly", "from", "an", "Excel", "file", "into", "the", "active", "table", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L4380-L4382
train
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.importCSVFile
def importCSVFile( filename, dbid = @dbid, targetFieldNames = nil, validateLines = true ) importSVFile( filename, ",", dbid, targetFieldNames, validateLines ) end
ruby
def importCSVFile( filename, dbid = @dbid, targetFieldNames = nil, validateLines = true ) importSVFile( filename, ",", dbid, targetFieldNames, validateLines ) end
[ "def", "importCSVFile", "(", "filename", ",", "dbid", "=", "@dbid", ",", "targetFieldNames", "=", "nil", ",", "validateLines", "=", "true", ")", "importSVFile", "(", "filename", ",", "\",\"", ",", "dbid", ",", "targetFieldNames", ",", "validateLines", ")", "end" ]
Add records from lines in a CSV file. If dbid is not specified, the active table will be used. values in subsequent lines. The file must not contain commas inside field names or values.
[ "Add", "records", "from", "lines", "in", "a", "CSV", "file", ".", "If", "dbid", "is", "not", "specified", "the", "active", "table", "will", "be", "used", ".", "values", "in", "subsequent", "lines", ".", "The", "file", "must", "not", "contain", "commas", "inside", "field", "names", "or", "values", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L4387-L4389
train
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.importTSVFile
def importTSVFile( filename, dbid = @dbid, targetFieldNames = nil, validateLines = true ) importSVFile( filename, "\t", dbid, targetFieldNames, validateLines ) end
ruby
def importTSVFile( filename, dbid = @dbid, targetFieldNames = nil, validateLines = true ) importSVFile( filename, "\t", dbid, targetFieldNames, validateLines ) end
[ "def", "importTSVFile", "(", "filename", ",", "dbid", "=", "@dbid", ",", "targetFieldNames", "=", "nil", ",", "validateLines", "=", "true", ")", "importSVFile", "(", "filename", ",", "\"\\t\"", ",", "dbid", ",", "targetFieldNames", ",", "validateLines", ")", "end" ]
Import records from a text file in Tab-Separated-Values format.
[ "Import", "records", "from", "a", "text", "file", "in", "Tab", "-", "Separated", "-", "Values", "format", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L4392-L4394
train
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.makeSVFile
def makeSVFile( filename, fieldSeparator = ",", dbid = @dbid, query = nil, qid = nil, qname = nil ) File.open( filename, "w" ) { |file| if dbid doQuery( dbid, query, qid, qname ) end if @records and @fields # ------------- write field names on first line ---------------- output = "" fieldNamesBlock = proc { |element| if element.is_a?(REXML::Element) and element.name == "label" and element.has_text? output << "#{element.text}#{fieldSeparator}" end } processChildElements( @fields, true, fieldNamesBlock ) output << "\n" output.sub!( "#{fieldSeparator}\n", "\n" ) file.write( output ) # ------------- write records ---------------- output = "" valuesBlock = proc { |element| if element.is_a?(REXML::Element) if element.name == "record" if output.length > 1 output << "\n" output.sub!( "#{fieldSeparator}\n", "\n" ) file.write( output ) end output = "" elsif element.name == "f" if element.has_text? text = element.text text.gsub!("<BR/>","\n") text = "\"#{text}\"" if text.include?( fieldSeparator ) output << "#{text}#{fieldSeparator}" else output << "#{fieldSeparator}" end end end } processChildElements( @records, false, valuesBlock ) if output.length > 1 output << "\n" output.sub!( "#{fieldSeparator}\n", "\n" ) file.write( output ) output = "" end end } end
ruby
def makeSVFile( filename, fieldSeparator = ",", dbid = @dbid, query = nil, qid = nil, qname = nil ) File.open( filename, "w" ) { |file| if dbid doQuery( dbid, query, qid, qname ) end if @records and @fields # ------------- write field names on first line ---------------- output = "" fieldNamesBlock = proc { |element| if element.is_a?(REXML::Element) and element.name == "label" and element.has_text? output << "#{element.text}#{fieldSeparator}" end } processChildElements( @fields, true, fieldNamesBlock ) output << "\n" output.sub!( "#{fieldSeparator}\n", "\n" ) file.write( output ) # ------------- write records ---------------- output = "" valuesBlock = proc { |element| if element.is_a?(REXML::Element) if element.name == "record" if output.length > 1 output << "\n" output.sub!( "#{fieldSeparator}\n", "\n" ) file.write( output ) end output = "" elsif element.name == "f" if element.has_text? text = element.text text.gsub!("<BR/>","\n") text = "\"#{text}\"" if text.include?( fieldSeparator ) output << "#{text}#{fieldSeparator}" else output << "#{fieldSeparator}" end end end } processChildElements( @records, false, valuesBlock ) if output.length > 1 output << "\n" output.sub!( "#{fieldSeparator}\n", "\n" ) file.write( output ) output = "" end end } end
[ "def", "makeSVFile", "(", "filename", ",", "fieldSeparator", "=", "\",\"", ",", "dbid", "=", "@dbid", ",", "query", "=", "nil", ",", "qid", "=", "nil", ",", "qname", "=", "nil", ")", "File", ".", "open", "(", "filename", ",", "\"w\"", ")", "{", "|", "file", "|", "if", "dbid", "doQuery", "(", "dbid", ",", "query", ",", "qid", ",", "qname", ")", "end", "if", "@records", "and", "@fields", "output", "=", "\"\"", "fieldNamesBlock", "=", "proc", "{", "|", "element", "|", "if", "element", ".", "is_a?", "(", "REXML", "::", "Element", ")", "and", "element", ".", "name", "==", "\"label\"", "and", "element", ".", "has_text?", "output", "<<", "\"#{element.text}#{fieldSeparator}\"", "end", "}", "processChildElements", "(", "@fields", ",", "true", ",", "fieldNamesBlock", ")", "output", "<<", "\"\\n\"", "output", ".", "sub!", "(", "\"#{fieldSeparator}\\n\"", ",", "\"\\n\"", ")", "file", ".", "write", "(", "output", ")", "output", "=", "\"\"", "valuesBlock", "=", "proc", "{", "|", "element", "|", "if", "element", ".", "is_a?", "(", "REXML", "::", "Element", ")", "if", "element", ".", "name", "==", "\"record\"", "if", "output", ".", "length", ">", "1", "output", "<<", "\"\\n\"", "output", ".", "sub!", "(", "\"#{fieldSeparator}\\n\"", ",", "\"\\n\"", ")", "file", ".", "write", "(", "output", ")", "end", "output", "=", "\"\"", "elsif", "element", ".", "name", "==", "\"f\"", "if", "element", ".", "has_text?", "text", "=", "element", ".", "text", "text", ".", "gsub!", "(", "\"<BR/>\"", ",", "\"\\n\"", ")", "text", "=", "\"\\\"#{text}\\\"\"", "if", "text", ".", "include?", "(", "fieldSeparator", ")", "output", "<<", "\"#{text}#{fieldSeparator}\"", "else", "output", "<<", "\"#{fieldSeparator}\"", "end", "end", "end", "}", "processChildElements", "(", "@records", ",", "false", ",", "valuesBlock", ")", "if", "output", ".", "length", ">", "1", "output", "<<", "\"\\n\"", "output", ".", "sub!", "(", "\"#{fieldSeparator}\\n\"", ",", "\"\\n\"", ")", "file", ".", "write", "(", "output", ")", "output", "=", "\"\"", "end", "end", "}", "end" ]
Make a CSV file using the results of a query. Specify a different separator in the second paramater. Fields containing the separator will be double-quoted. e.g. makeSVFile( "contacts.txt", "\t", nil ) e.g. makeSVFile( "contacts.txt", ",", "dhnju5y7", nil, nil, "List Changes" )
[ "Make", "a", "CSV", "file", "using", "the", "results", "of", "a", "query", ".", "Specify", "a", "different", "separator", "in", "the", "second", "paramater", ".", "Fields", "containing", "the", "separator", "will", "be", "double", "-", "quoted", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L4489-L4544
train
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.makeCSVFileForReport
def makeCSVFileForReport(filename,dbid=@dbid,query=nil,qid=nil,qname=nil) csv = getCSVForReport(dbid,query,qid,qname) File.open(filename,"w"){|f|f.write(csv || "")} end
ruby
def makeCSVFileForReport(filename,dbid=@dbid,query=nil,qid=nil,qname=nil) csv = getCSVForReport(dbid,query,qid,qname) File.open(filename,"w"){|f|f.write(csv || "")} end
[ "def", "makeCSVFileForReport", "(", "filename", ",", "dbid", "=", "@dbid", ",", "query", "=", "nil", ",", "qid", "=", "nil", ",", "qname", "=", "nil", ")", "csv", "=", "getCSVForReport", "(", "dbid", ",", "query", ",", "qid", ",", "qname", ")", "File", ".", "open", "(", "filename", ",", "\"w\"", ")", "{", "|", "f", "|", "f", ".", "write", "(", "csv", "||", "\"\"", ")", "}", "end" ]
Create a CSV file using the records for a Report.
[ "Create", "a", "CSV", "file", "using", "the", "records", "for", "a", "Report", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L4547-L4550
train
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.getCSVForReport
def getCSVForReport(dbid,query=nil,qid=nil,qname=nil) genResultsTable(dbid,query,nil,nil,nil,nil,"csv",qid,qname) end
ruby
def getCSVForReport(dbid,query=nil,qid=nil,qname=nil) genResultsTable(dbid,query,nil,nil,nil,nil,"csv",qid,qname) end
[ "def", "getCSVForReport", "(", "dbid", ",", "query", "=", "nil", ",", "qid", "=", "nil", ",", "qname", "=", "nil", ")", "genResultsTable", "(", "dbid", ",", "query", ",", "nil", ",", "nil", ",", "nil", ",", "nil", ",", "\"csv\"", ",", "qid", ",", "qname", ")", "end" ]
Get the CSV data for a Report.
[ "Get", "the", "CSV", "data", "for", "a", "Report", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L4553-L4555
train
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.doSQLUpdate
def doSQLUpdate(sqlString) sql = sqlString.dup dbname = "" state = nil fieldName = "" fieldValue = "" sqlQuery = "SELECT 3 FROM " clearFieldValuePairList sql.split(' ').each{ |token| case token when "UPDATE" state = "getTable" unless state == "getFilter" next when "SET" state = "getFieldName" unless state == "getFilter" next when "=" sqlQuery << " = " if state == "getFilter" state = "getFieldValue" unless state == "getFilter" next when "WHERE" sqlQuery << " WHERE " state = "getFilter" next end if state == "getTable" dbname = token.dup sqlQuery << dbname elsif state == "getFieldName" fieldName = token.gsub('[','').gsub(']','') elsif state == "getFieldValue" test = token if test[-1,1] == "'" or test[-2,2] == "'," fieldValue << token if fieldValue[-2,2] == "'," state = "getFieldName" fieldValue.gsub!("',","") end fieldValue.gsub!("'","") if fieldName.length > 0 addFieldValuePair(fieldName,nil,nil,fieldValue) fieldName = "" fieldValue = "" end else fieldValue << "#{token} " end elsif state == "getFilter" sqlQuery << token end } rows = doSQLQuery(sqlQuery,:Array) if rows and @dbid and @fvlist idFieldName = lookupFieldNameFromID("3") rows.each{ |row| recordID = row[idFieldName] editRecord(@dbid,recordID,@fvlist) if recordID } end end
ruby
def doSQLUpdate(sqlString) sql = sqlString.dup dbname = "" state = nil fieldName = "" fieldValue = "" sqlQuery = "SELECT 3 FROM " clearFieldValuePairList sql.split(' ').each{ |token| case token when "UPDATE" state = "getTable" unless state == "getFilter" next when "SET" state = "getFieldName" unless state == "getFilter" next when "=" sqlQuery << " = " if state == "getFilter" state = "getFieldValue" unless state == "getFilter" next when "WHERE" sqlQuery << " WHERE " state = "getFilter" next end if state == "getTable" dbname = token.dup sqlQuery << dbname elsif state == "getFieldName" fieldName = token.gsub('[','').gsub(']','') elsif state == "getFieldValue" test = token if test[-1,1] == "'" or test[-2,2] == "'," fieldValue << token if fieldValue[-2,2] == "'," state = "getFieldName" fieldValue.gsub!("',","") end fieldValue.gsub!("'","") if fieldName.length > 0 addFieldValuePair(fieldName,nil,nil,fieldValue) fieldName = "" fieldValue = "" end else fieldValue << "#{token} " end elsif state == "getFilter" sqlQuery << token end } rows = doSQLQuery(sqlQuery,:Array) if rows and @dbid and @fvlist idFieldName = lookupFieldNameFromID("3") rows.each{ |row| recordID = row[idFieldName] editRecord(@dbid,recordID,@fvlist) if recordID } end end
[ "def", "doSQLUpdate", "(", "sqlString", ")", "sql", "=", "sqlString", ".", "dup", "dbname", "=", "\"\"", "state", "=", "nil", "fieldName", "=", "\"\"", "fieldValue", "=", "\"\"", "sqlQuery", "=", "\"SELECT 3 FROM \"", "clearFieldValuePairList", "sql", ".", "split", "(", "' '", ")", ".", "each", "{", "|", "token", "|", "case", "token", "when", "\"UPDATE\"", "state", "=", "\"getTable\"", "unless", "state", "==", "\"getFilter\"", "next", "when", "\"SET\"", "state", "=", "\"getFieldName\"", "unless", "state", "==", "\"getFilter\"", "next", "when", "\"=\"", "sqlQuery", "<<", "\" = \"", "if", "state", "==", "\"getFilter\"", "state", "=", "\"getFieldValue\"", "unless", "state", "==", "\"getFilter\"", "next", "when", "\"WHERE\"", "sqlQuery", "<<", "\" WHERE \"", "state", "=", "\"getFilter\"", "next", "end", "if", "state", "==", "\"getTable\"", "dbname", "=", "token", ".", "dup", "sqlQuery", "<<", "dbname", "elsif", "state", "==", "\"getFieldName\"", "fieldName", "=", "token", ".", "gsub", "(", "'['", ",", "''", ")", ".", "gsub", "(", "']'", ",", "''", ")", "elsif", "state", "==", "\"getFieldValue\"", "test", "=", "token", "if", "test", "[", "-", "1", ",", "1", "]", "==", "\"'\"", "or", "test", "[", "-", "2", ",", "2", "]", "==", "\"',\"", "fieldValue", "<<", "token", "if", "fieldValue", "[", "-", "2", ",", "2", "]", "==", "\"',\"", "state", "=", "\"getFieldName\"", "fieldValue", ".", "gsub!", "(", "\"',\"", ",", "\"\"", ")", "end", "fieldValue", ".", "gsub!", "(", "\"'\"", ",", "\"\"", ")", "if", "fieldName", ".", "length", ">", "0", "addFieldValuePair", "(", "fieldName", ",", "nil", ",", "nil", ",", "fieldValue", ")", "fieldName", "=", "\"\"", "fieldValue", "=", "\"\"", "end", "else", "fieldValue", "<<", "\"#{token} \"", "end", "elsif", "state", "==", "\"getFilter\"", "sqlQuery", "<<", "token", "end", "}", "rows", "=", "doSQLQuery", "(", "sqlQuery", ",", ":Array", ")", "if", "rows", "and", "@dbid", "and", "@fvlist", "idFieldName", "=", "lookupFieldNameFromID", "(", "\"3\"", ")", "rows", ".", "each", "{", "|", "row", "|", "recordID", "=", "row", "[", "idFieldName", "]", "editRecord", "(", "@dbid", ",", "recordID", ",", "@fvlist", ")", "if", "recordID", "}", "end", "end" ]
Translate a simple SQL UPDATE statement to a QuickBase editRecord call. Note: This method is here primarily for Rails integration. Note: This assumes, like SQL, that your column (i.e. field) names do not contain spaces. Note: This assumes that Record ID# is the key field in your table.
[ "Translate", "a", "simple", "SQL", "UPDATE", "statement", "to", "a", "QuickBase", "editRecord", "call", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L4828-L4892
train
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.doSQLInsert
def doSQLInsert(sqlString) sql = sqlString.dup dbname = "" state = nil fieldName = "" fieldValue = "" fieldNames = [] fieldValues = [] index = 0 clearFieldValuePairList sql.gsub!("("," ") sql.gsub!(")"," ") sql.split(' ').each{ |token| case token when "INSERT", "INTO" state = "getTable" next when "VALUES" state = "getFieldValue" next end if state == "getTable" dbname = token.strip state = "getFieldName" elsif state == "getFieldName" fieldName = token.dup fieldName.gsub!("],","") fieldName.gsub!('[','') fieldName.gsub!(']','') fieldName.gsub!(',','') fieldNames << fieldName elsif state == "getFieldValue" test = token.dup if test[-1,1] == "'" or test[-2,2] == "'," fieldValue << token.dup if fieldValue[-2,2] == "'," fieldValue.gsub!("',",'') end fieldValue.gsub!('\'','') if fieldValue.length > 0 and fieldNames[index] addFieldValuePair(fieldNames[index],nil,nil,fieldValue) fieldName = "" fieldValue = "" end index += 1 elsif token == "," addFieldValuePair(fieldNames[index],nil,nil,"") fieldName = "" fieldValue = "" index += 1 else fieldValue << "#{token.dup} " end end } if dbname and @dbid.nil? dbid = findDBByname( dbname ) else dbid = lookupChdbid( dbname ) end dbid ||= @dbid recordid = nil if dbid recordid,updateid = addRecord(dbid,@fvlist) end recordid end
ruby
def doSQLInsert(sqlString) sql = sqlString.dup dbname = "" state = nil fieldName = "" fieldValue = "" fieldNames = [] fieldValues = [] index = 0 clearFieldValuePairList sql.gsub!("("," ") sql.gsub!(")"," ") sql.split(' ').each{ |token| case token when "INSERT", "INTO" state = "getTable" next when "VALUES" state = "getFieldValue" next end if state == "getTable" dbname = token.strip state = "getFieldName" elsif state == "getFieldName" fieldName = token.dup fieldName.gsub!("],","") fieldName.gsub!('[','') fieldName.gsub!(']','') fieldName.gsub!(',','') fieldNames << fieldName elsif state == "getFieldValue" test = token.dup if test[-1,1] == "'" or test[-2,2] == "'," fieldValue << token.dup if fieldValue[-2,2] == "'," fieldValue.gsub!("',",'') end fieldValue.gsub!('\'','') if fieldValue.length > 0 and fieldNames[index] addFieldValuePair(fieldNames[index],nil,nil,fieldValue) fieldName = "" fieldValue = "" end index += 1 elsif token == "," addFieldValuePair(fieldNames[index],nil,nil,"") fieldName = "" fieldValue = "" index += 1 else fieldValue << "#{token.dup} " end end } if dbname and @dbid.nil? dbid = findDBByname( dbname ) else dbid = lookupChdbid( dbname ) end dbid ||= @dbid recordid = nil if dbid recordid,updateid = addRecord(dbid,@fvlist) end recordid end
[ "def", "doSQLInsert", "(", "sqlString", ")", "sql", "=", "sqlString", ".", "dup", "dbname", "=", "\"\"", "state", "=", "nil", "fieldName", "=", "\"\"", "fieldValue", "=", "\"\"", "fieldNames", "=", "[", "]", "fieldValues", "=", "[", "]", "index", "=", "0", "clearFieldValuePairList", "sql", ".", "gsub!", "(", "\"(\"", ",", "\" \"", ")", "sql", ".", "gsub!", "(", "\")\"", ",", "\" \"", ")", "sql", ".", "split", "(", "' '", ")", ".", "each", "{", "|", "token", "|", "case", "token", "when", "\"INSERT\"", ",", "\"INTO\"", "state", "=", "\"getTable\"", "next", "when", "\"VALUES\"", "state", "=", "\"getFieldValue\"", "next", "end", "if", "state", "==", "\"getTable\"", "dbname", "=", "token", ".", "strip", "state", "=", "\"getFieldName\"", "elsif", "state", "==", "\"getFieldName\"", "fieldName", "=", "token", ".", "dup", "fieldName", ".", "gsub!", "(", "\"],\"", ",", "\"\"", ")", "fieldName", ".", "gsub!", "(", "'['", ",", "''", ")", "fieldName", ".", "gsub!", "(", "']'", ",", "''", ")", "fieldName", ".", "gsub!", "(", "','", ",", "''", ")", "fieldNames", "<<", "fieldName", "elsif", "state", "==", "\"getFieldValue\"", "test", "=", "token", ".", "dup", "if", "test", "[", "-", "1", ",", "1", "]", "==", "\"'\"", "or", "test", "[", "-", "2", ",", "2", "]", "==", "\"',\"", "fieldValue", "<<", "token", ".", "dup", "if", "fieldValue", "[", "-", "2", ",", "2", "]", "==", "\"',\"", "fieldValue", ".", "gsub!", "(", "\"',\"", ",", "''", ")", "end", "fieldValue", ".", "gsub!", "(", "'\\''", ",", "''", ")", "if", "fieldValue", ".", "length", ">", "0", "and", "fieldNames", "[", "index", "]", "addFieldValuePair", "(", "fieldNames", "[", "index", "]", ",", "nil", ",", "nil", ",", "fieldValue", ")", "fieldName", "=", "\"\"", "fieldValue", "=", "\"\"", "end", "index", "+=", "1", "elsif", "token", "==", "\",\"", "addFieldValuePair", "(", "fieldNames", "[", "index", "]", ",", "nil", ",", "nil", ",", "\"\"", ")", "fieldName", "=", "\"\"", "fieldValue", "=", "\"\"", "index", "+=", "1", "else", "fieldValue", "<<", "\"#{token.dup} \"", "end", "end", "}", "if", "dbname", "and", "@dbid", ".", "nil?", "dbid", "=", "findDBByname", "(", "dbname", ")", "else", "dbid", "=", "lookupChdbid", "(", "dbname", ")", "end", "dbid", "||=", "@dbid", "recordid", "=", "nil", "if", "dbid", "recordid", ",", "updateid", "=", "addRecord", "(", "dbid", ",", "@fvlist", ")", "end", "recordid", "end" ]
Translate a simple SQL INSERT statement to a QuickBase addRecord call. Note: This method is here primarily for Rails integration. Note: This assumes, like SQL, that your column (i.e. field) names do not contain spaces.
[ "Translate", "a", "simple", "SQL", "INSERT", "statement", "to", "a", "QuickBase", "addRecord", "call", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L4898-L4971
train
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.eachField
def eachField( record = @record ) if record and block_given? record.each{ |field| if field.is_a?( REXML::Element) and field.name == "f" and field.attributes["id"] @field = field yield field end } end nil end
ruby
def eachField( record = @record ) if record and block_given? record.each{ |field| if field.is_a?( REXML::Element) and field.name == "f" and field.attributes["id"] @field = field yield field end } end nil end
[ "def", "eachField", "(", "record", "=", "@record", ")", "if", "record", "and", "block_given?", "record", ".", "each", "{", "|", "field", "|", "if", "field", ".", "is_a?", "(", "REXML", "::", "Element", ")", "and", "field", ".", "name", "==", "\"f\"", "and", "field", ".", "attributes", "[", "\"id\"", "]", "@field", "=", "field", "yield", "field", "end", "}", "end", "nil", "end" ]
Iterate record XML and yield only 'f' elements.
[ "Iterate", "record", "XML", "and", "yield", "only", "f", "elements", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L4987-L4997
train
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.alias_methods
def alias_methods aliased_methods = [] public_methods.each{|old_method| if old_method.match(/[A-Z]+/) new_method = old_method.gsub(/[A-Z]+/){|uc| "_#{uc.downcase}"} aliased_methods << new_method instance_eval( "alias #{new_method} #{old_method}") end } aliased_methods end
ruby
def alias_methods aliased_methods = [] public_methods.each{|old_method| if old_method.match(/[A-Z]+/) new_method = old_method.gsub(/[A-Z]+/){|uc| "_#{uc.downcase}"} aliased_methods << new_method instance_eval( "alias #{new_method} #{old_method}") end } aliased_methods end
[ "def", "alias_methods", "aliased_methods", "=", "[", "]", "public_methods", ".", "each", "{", "|", "old_method", "|", "if", "old_method", ".", "match", "(", "/", "/", ")", "new_method", "=", "old_method", ".", "gsub", "(", "/", "/", ")", "{", "|", "uc", "|", "\"_#{uc.downcase}\"", "}", "aliased_methods", "<<", "new_method", "instance_eval", "(", "\"alias #{new_method} #{old_method}\"", ")", "end", "}", "aliased_methods", "end" ]
Add method aliases that follow the ruby method naming convention. E.g. sendRequest will be aliased as send_request.
[ "Add", "method", "aliases", "that", "follow", "the", "ruby", "method", "naming", "convention", ".", "E", ".", "g", ".", "sendRequest", "will", "be", "aliased", "as", "send_request", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L5007-L5017
train
sethvargo/community-zero
lib/community_zero/objects/cookbook.rb
CommunityZero.Cookbook.to_hash
def to_hash methods = instance_variables.map { |i| i.to_s.gsub('@', '') } Hash[*methods.map { |m| [m, send(m.to_sym)] }.flatten] end
ruby
def to_hash methods = instance_variables.map { |i| i.to_s.gsub('@', '') } Hash[*methods.map { |m| [m, send(m.to_sym)] }.flatten] end
[ "def", "to_hash", "methods", "=", "instance_variables", ".", "map", "{", "|", "i", "|", "i", ".", "to_s", ".", "gsub", "(", "'@'", ",", "''", ")", "}", "Hash", "[", "*", "methods", ".", "map", "{", "|", "m", "|", "[", "m", ",", "send", "(", "m", ".", "to_sym", ")", "]", "}", ".", "flatten", "]", "end" ]
Create a new cookbook from the given hash. @param [Hash] hash the hash from which to create the cookbook Dump this cookbook to a hash. @return [Hash] the hash representation of this cookbook
[ "Create", "a", "new", "cookbook", "from", "the", "given", "hash", "." ]
08a22c47c865deb6a5f931cb4d9f747a2b9d3459
https://github.com/sethvargo/community-zero/blob/08a22c47c865deb6a5f931cb4d9f747a2b9d3459/lib/community_zero/objects/cookbook.rb#L36-L39
train
scrapper/perobs
lib/perobs/Array.rb
PEROBS.Array._referenced_object_ids
def _referenced_object_ids @data.each.select do |v| v && v.respond_to?(:is_poxreference?) end.map { |o| o.id } end
ruby
def _referenced_object_ids @data.each.select do |v| v && v.respond_to?(:is_poxreference?) end.map { |o| o.id } end
[ "def", "_referenced_object_ids", "@data", ".", "each", ".", "select", "do", "|", "v", "|", "v", "&&", "v", ".", "respond_to?", "(", ":is_poxreference?", ")", "end", ".", "map", "{", "|", "o", "|", "o", ".", "id", "}", "end" ]
Return a list of all object IDs of all persistend objects that this Array is referencing. @return [Array of Integer] IDs of referenced objects
[ "Return", "a", "list", "of", "all", "object", "IDs", "of", "all", "persistend", "objects", "that", "this", "Array", "is", "referencing", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Array.rb#L145-L149
train
pupeno/assert_difference
lib/assert_difference/expectation.rb
AssertDifference.Expectation.generate_expected_value
def generate_expected_value if expected_difference.is_a? Range (before_value + expected_difference.first)..(before_value + expected_difference.end) else before_value + expected_difference end end
ruby
def generate_expected_value if expected_difference.is_a? Range (before_value + expected_difference.first)..(before_value + expected_difference.end) else before_value + expected_difference end end
[ "def", "generate_expected_value", "if", "expected_difference", ".", "is_a?", "Range", "(", "before_value", "+", "expected_difference", ".", "first", ")", "..", "(", "before_value", "+", "expected_difference", ".", "end", ")", "else", "before_value", "+", "expected_difference", "end", "end" ]
Generate the expected value. @return [Integer, Range] Generate the expected value.
[ "Generate", "the", "expected", "value", "." ]
56490e7157dd975caed8080abd910a559e3bd785
https://github.com/pupeno/assert_difference/blob/56490e7157dd975caed8080abd910a559e3bd785/lib/assert_difference/expectation.rb#L77-L83
train
PublicHealthEngland/ndr_support
lib/ndr_support/obfuscator.rb
NdrSupport.Obfuscator.obfuscate
def obfuscate(name, seed = nil) rnd = Random.new(seed || @seed) vowels = %w(A E I O U) consonants = ('A'..'Z').to_a - vowels digits = ('0'..'9').to_a dict = Hash[(vowels + consonants + digits).zip(vowels.shuffle(random: rnd) + consonants.shuffle(random: rnd) + digits.shuffle(random: rnd))] name.upcase.split(//).map { |s| dict[s] || s }.join end
ruby
def obfuscate(name, seed = nil) rnd = Random.new(seed || @seed) vowels = %w(A E I O U) consonants = ('A'..'Z').to_a - vowels digits = ('0'..'9').to_a dict = Hash[(vowels + consonants + digits).zip(vowels.shuffle(random: rnd) + consonants.shuffle(random: rnd) + digits.shuffle(random: rnd))] name.upcase.split(//).map { |s| dict[s] || s }.join end
[ "def", "obfuscate", "(", "name", ",", "seed", "=", "nil", ")", "rnd", "=", "Random", ".", "new", "(", "seed", "||", "@seed", ")", "vowels", "=", "%w(", "A", "E", "I", "O", "U", ")", "consonants", "=", "(", "'A'", "..", "'Z'", ")", ".", "to_a", "-", "vowels", "digits", "=", "(", "'0'", "..", "'9'", ")", ".", "to_a", "dict", "=", "Hash", "[", "(", "vowels", "+", "consonants", "+", "digits", ")", ".", "zip", "(", "vowels", ".", "shuffle", "(", "random", ":", "rnd", ")", "+", "consonants", ".", "shuffle", "(", "random", ":", "rnd", ")", "+", "digits", ".", "shuffle", "(", "random", ":", "rnd", ")", ")", "]", "name", ".", "upcase", ".", "split", "(", "/", "/", ")", ".", "map", "{", "|", "s", "|", "dict", "[", "s", "]", "||", "s", "}", ".", "join", "end" ]
Obfuscate a name or address, either with the given seed, or default seed
[ "Obfuscate", "a", "name", "or", "address", "either", "with", "the", "given", "seed", "or", "default", "seed" ]
6daf98ca972e79de1c8457eb720f058b03ead21c
https://github.com/PublicHealthEngland/ndr_support/blob/6daf98ca972e79de1c8457eb720f058b03ead21c/lib/ndr_support/obfuscator.rb#L13-L22
train
sethvargo/community-zero
lib/community_zero/server.rb
CommunityZero.Server.start_background
def start_background(wait = 5) @server = WEBrick::HTTPServer.new( :BindAddress => @options[:host], :Port => @options[:port], :AccessLog => [], :Logger => WEBrick::Log.new(StringIO.new, 7) ) @server.mount('/', Rack::Handler::WEBrick, app) @thread = Thread.new { @server.start } @thread.abort_on_exception = true @thread end
ruby
def start_background(wait = 5) @server = WEBrick::HTTPServer.new( :BindAddress => @options[:host], :Port => @options[:port], :AccessLog => [], :Logger => WEBrick::Log.new(StringIO.new, 7) ) @server.mount('/', Rack::Handler::WEBrick, app) @thread = Thread.new { @server.start } @thread.abort_on_exception = true @thread end
[ "def", "start_background", "(", "wait", "=", "5", ")", "@server", "=", "WEBrick", "::", "HTTPServer", ".", "new", "(", ":BindAddress", "=>", "@options", "[", ":host", "]", ",", ":Port", "=>", "@options", "[", ":port", "]", ",", ":AccessLog", "=>", "[", "]", ",", ":Logger", "=>", "WEBrick", "::", "Log", ".", "new", "(", "StringIO", ".", "new", ",", "7", ")", ")", "@server", ".", "mount", "(", "'/'", ",", "Rack", "::", "Handler", "::", "WEBrick", ",", "app", ")", "@thread", "=", "Thread", ".", "new", "{", "@server", ".", "start", "}", "@thread", ".", "abort_on_exception", "=", "true", "@thread", "end" ]
Start a Community Zero server in a forked process. This method returns the PID to the forked process. @param [Fixnum] wait the number of seconds to wait for the server to start @return [Thread] the thread the background process is running in
[ "Start", "a", "Community", "Zero", "server", "in", "a", "forked", "process", ".", "This", "method", "returns", "the", "PID", "to", "the", "forked", "process", "." ]
08a22c47c865deb6a5f931cb4d9f747a2b9d3459
https://github.com/sethvargo/community-zero/blob/08a22c47c865deb6a5f931cb4d9f747a2b9d3459/lib/community_zero/server.rb#L121-L133
train
sethvargo/community-zero
lib/community_zero/server.rb
CommunityZero.Server.running?
def running? if @server.nil? || @server.status != :Running return false end uri = URI.join(url, 'cookbooks') headers = { 'Accept' => 'application/json' } Timeout.timeout(0.1) { !open(uri, headers).nil? } rescue SocketError, Errno::ECONNREFUSED, Timeout::Error false end
ruby
def running? if @server.nil? || @server.status != :Running return false end uri = URI.join(url, 'cookbooks') headers = { 'Accept' => 'application/json' } Timeout.timeout(0.1) { !open(uri, headers).nil? } rescue SocketError, Errno::ECONNREFUSED, Timeout::Error false end
[ "def", "running?", "if", "@server", ".", "nil?", "||", "@server", ".", "status", "!=", ":Running", "return", "false", "end", "uri", "=", "URI", ".", "join", "(", "url", ",", "'cookbooks'", ")", "headers", "=", "{", "'Accept'", "=>", "'application/json'", "}", "Timeout", ".", "timeout", "(", "0.1", ")", "{", "!", "open", "(", "uri", ",", "headers", ")", ".", "nil?", "}", "rescue", "SocketError", ",", "Errno", "::", "ECONNREFUSED", ",", "Timeout", "::", "Error", "false", "end" ]
Boolean method to determine if the server is currently ready to accept requests. This method will attempt to make an HTTP request against the server. If this method returns true, you are safe to make a request. @return [Boolean] true if the server is accepting requests, false otherwise
[ "Boolean", "method", "to", "determine", "if", "the", "server", "is", "currently", "ready", "to", "accept", "requests", ".", "This", "method", "will", "attempt", "to", "make", "an", "HTTP", "request", "against", "the", "server", ".", "If", "this", "method", "returns", "true", "you", "are", "safe", "to", "make", "a", "request", "." ]
08a22c47c865deb6a5f931cb4d9f747a2b9d3459
https://github.com/sethvargo/community-zero/blob/08a22c47c865deb6a5f931cb4d9f747a2b9d3459/lib/community_zero/server.rb#L143-L154
train
sethvargo/community-zero
lib/community_zero/server.rb
CommunityZero.Server.stop
def stop(wait = 5) Timeout.timeout(wait) do @server.shutdown @thread.join(wait) if @thread end rescue Timeout::Error if @thread $stderr.puts("Community Zero did not stop within #{wait} seconds! Killing...") @thread.kill end ensure @server = nil @thread = nil end
ruby
def stop(wait = 5) Timeout.timeout(wait) do @server.shutdown @thread.join(wait) if @thread end rescue Timeout::Error if @thread $stderr.puts("Community Zero did not stop within #{wait} seconds! Killing...") @thread.kill end ensure @server = nil @thread = nil end
[ "def", "stop", "(", "wait", "=", "5", ")", "Timeout", ".", "timeout", "(", "wait", ")", "do", "@server", ".", "shutdown", "@thread", ".", "join", "(", "wait", ")", "if", "@thread", "end", "rescue", "Timeout", "::", "Error", "if", "@thread", "$stderr", ".", "puts", "(", "\"Community Zero did not stop within #{wait} seconds! Killing...\"", ")", "@thread", ".", "kill", "end", "ensure", "@server", "=", "nil", "@thread", "=", "nil", "end" ]
Gracefully stop the Community Zero server. @param [Fixnum] wait the number of seconds to wait before raising force-terminating the server
[ "Gracefully", "stop", "the", "Community", "Zero", "server", "." ]
08a22c47c865deb6a5f931cb4d9f747a2b9d3459
https://github.com/sethvargo/community-zero/blob/08a22c47c865deb6a5f931cb4d9f747a2b9d3459/lib/community_zero/server.rb#L163-L176
train
sethvargo/community-zero
lib/community_zero/server.rb
CommunityZero.Server.app
def app lambda do |env| request = Request.new(env) response = router.call(request) response[-1] = Array(response[-1]) response end end
ruby
def app lambda do |env| request = Request.new(env) response = router.call(request) response[-1] = Array(response[-1]) response end end
[ "def", "app", "lambda", "do", "|", "env", "|", "request", "=", "Request", ".", "new", "(", "env", ")", "response", "=", "router", ".", "call", "(", "request", ")", "response", "[", "-", "1", "]", "=", "Array", "(", "response", "[", "-", "1", "]", ")", "response", "end", "end" ]
The actual application the server will respond to. @return [RackApp]
[ "The", "actual", "application", "the", "server", "will", "respond", "to", "." ]
08a22c47c865deb6a5f931cb4d9f747a2b9d3459
https://github.com/sethvargo/community-zero/blob/08a22c47c865deb6a5f931cb4d9f747a2b9d3459/lib/community_zero/server.rb#L199-L207
train
sethvargo/community-zero
lib/community_zero/endpoints/cookbooks_endpoint.rb
CommunityZero.CookbooksEndpoint.create_cookbook
def create_cookbook(metadata, overrides = {}) cookbook = Cookbook.new({ :name => metadata.name, :category => nil, :maintainer => metadata.maintainer, :description => metadata.description, :version => metadata.version }.merge(overrides)) store.add(cookbook) cookbook end
ruby
def create_cookbook(metadata, overrides = {}) cookbook = Cookbook.new({ :name => metadata.name, :category => nil, :maintainer => metadata.maintainer, :description => metadata.description, :version => metadata.version }.merge(overrides)) store.add(cookbook) cookbook end
[ "def", "create_cookbook", "(", "metadata", ",", "overrides", "=", "{", "}", ")", "cookbook", "=", "Cookbook", ".", "new", "(", "{", ":name", "=>", "metadata", ".", "name", ",", ":category", "=>", "nil", ",", ":maintainer", "=>", "metadata", ".", "maintainer", ",", ":description", "=>", "metadata", ".", "description", ",", ":version", "=>", "metadata", ".", "version", "}", ".", "merge", "(", "overrides", ")", ")", "store", ".", "add", "(", "cookbook", ")", "cookbook", "end" ]
Create the cookbook from the metadata. @param [CommunityZero::Metadata] metadata the metadata to create the cookbook from
[ "Create", "the", "cookbook", "from", "the", "metadata", "." ]
08a22c47c865deb6a5f931cb4d9f747a2b9d3459
https://github.com/sethvargo/community-zero/blob/08a22c47c865deb6a5f931cb4d9f747a2b9d3459/lib/community_zero/endpoints/cookbooks_endpoint.rb#L71-L83
train
sethvargo/community-zero
lib/community_zero/endpoints/cookbooks_endpoint.rb
CommunityZero.CookbooksEndpoint.find_metadata
def find_metadata(tarball) gzip = Zlib::GzipReader.new(tarball[:tempfile]) tar = Gem::Package::TarReader.new(gzip) tar.each do |entry| if entry.full_name =~ /metadata\.json$/ return Metadata.from_json(entry.read) elsif entry.full_name =~ /metadata\.rb$/ return Metadata.from_ruby(entry.read) end end ensure tar.close end
ruby
def find_metadata(tarball) gzip = Zlib::GzipReader.new(tarball[:tempfile]) tar = Gem::Package::TarReader.new(gzip) tar.each do |entry| if entry.full_name =~ /metadata\.json$/ return Metadata.from_json(entry.read) elsif entry.full_name =~ /metadata\.rb$/ return Metadata.from_ruby(entry.read) end end ensure tar.close end
[ "def", "find_metadata", "(", "tarball", ")", "gzip", "=", "Zlib", "::", "GzipReader", ".", "new", "(", "tarball", "[", ":tempfile", "]", ")", "tar", "=", "Gem", "::", "Package", "::", "TarReader", ".", "new", "(", "gzip", ")", "tar", ".", "each", "do", "|", "entry", "|", "if", "entry", ".", "full_name", "=~", "/", "\\.", "/", "return", "Metadata", ".", "from_json", "(", "entry", ".", "read", ")", "elsif", "entry", ".", "full_name", "=~", "/", "\\.", "/", "return", "Metadata", ".", "from_ruby", "(", "entry", ".", "read", ")", "end", "end", "ensure", "tar", ".", "close", "end" ]
Parse the metadata from the tarball. @param [Tempfile] tarball the temporarily uploaded file @return [Metadata]
[ "Parse", "the", "metadata", "from", "the", "tarball", "." ]
08a22c47c865deb6a5f931cb4d9f747a2b9d3459
https://github.com/sethvargo/community-zero/blob/08a22c47c865deb6a5f931cb4d9f747a2b9d3459/lib/community_zero/endpoints/cookbooks_endpoint.rb#L91-L104
train
holtrop/ruby-gnucash
lib/gnucash/account.rb
Gnucash.Account.finalize
def finalize @transactions.sort! { |a, b| a.date <=> b.date } balance = Value.new(0) @balances = @transactions.map do |act_txn| balance += act_txn.value { date: act_txn.date, value: balance, } end end
ruby
def finalize @transactions.sort! { |a, b| a.date <=> b.date } balance = Value.new(0) @balances = @transactions.map do |act_txn| balance += act_txn.value { date: act_txn.date, value: balance, } end end
[ "def", "finalize", "@transactions", ".", "sort!", "{", "|", "a", ",", "b", "|", "a", ".", "date", "<=>", "b", ".", "date", "}", "balance", "=", "Value", ".", "new", "(", "0", ")", "@balances", "=", "@transactions", ".", "map", "do", "|", "act_txn", "|", "balance", "+=", "act_txn", ".", "value", "{", "date", ":", "act_txn", ".", "date", ",", "value", ":", "balance", ",", "}", "end", "end" ]
Internal method used to complete initialization of the Account after all transactions have been associated with it. @return [void]
[ "Internal", "method", "used", "to", "complete", "initialization", "of", "the", "Account", "after", "all", "transactions", "have", "been", "associated", "with", "it", "." ]
a233cc4da0f36b13bc3f7a17264adb82c8a12c6b
https://github.com/holtrop/ruby-gnucash/blob/a233cc4da0f36b13bc3f7a17264adb82c8a12c6b/lib/gnucash/account.rb#L78-L88
train
snowplow/iglu-ruby-client
lib/iglu-client/resolver.rb
Iglu.Resolver.lookup_schema
def lookup_schema(schema_key) lookup_time = Time.now.getutc if schema_key.is_a?(String) schema_key = SchemaKey.parse_key(schema_key) end failures = [] cache_result = @cache[schema_key] if not cache_result.nil? if not @cacheTtl.nil? store_time = cache_result[1] time_diff = (lookup_time - store_time).round if time_diff >= @cacheTtl @cache.delete(schema_key) cache_result = nil else return cache_result[0] end else return cache_result[0] end end if cache_result.nil? # Fetch from every registry for registry in prioritize_repos(schema_key, @registries) do begin lookup_result = registry.lookup_schema(schema_key) rescue StandardError => e failures.push(Registries::LookupFailure.new(registry.config.name, e)) else if lookup_result.nil? failures.push(Registries::NotFound.new(registry.config.name)) else break end end end if lookup_result.nil? raise Registries::ResolverError.new(failures, schema_key) else store_time = Time.now.getutc @cache[schema_key] = [lookup_result, store_time] lookup_result end end end
ruby
def lookup_schema(schema_key) lookup_time = Time.now.getutc if schema_key.is_a?(String) schema_key = SchemaKey.parse_key(schema_key) end failures = [] cache_result = @cache[schema_key] if not cache_result.nil? if not @cacheTtl.nil? store_time = cache_result[1] time_diff = (lookup_time - store_time).round if time_diff >= @cacheTtl @cache.delete(schema_key) cache_result = nil else return cache_result[0] end else return cache_result[0] end end if cache_result.nil? # Fetch from every registry for registry in prioritize_repos(schema_key, @registries) do begin lookup_result = registry.lookup_schema(schema_key) rescue StandardError => e failures.push(Registries::LookupFailure.new(registry.config.name, e)) else if lookup_result.nil? failures.push(Registries::NotFound.new(registry.config.name)) else break end end end if lookup_result.nil? raise Registries::ResolverError.new(failures, schema_key) else store_time = Time.now.getutc @cache[schema_key] = [lookup_result, store_time] lookup_result end end end
[ "def", "lookup_schema", "(", "schema_key", ")", "lookup_time", "=", "Time", ".", "now", ".", "getutc", "if", "schema_key", ".", "is_a?", "(", "String", ")", "schema_key", "=", "SchemaKey", ".", "parse_key", "(", "schema_key", ")", "end", "failures", "=", "[", "]", "cache_result", "=", "@cache", "[", "schema_key", "]", "if", "not", "cache_result", ".", "nil?", "if", "not", "@cacheTtl", ".", "nil?", "store_time", "=", "cache_result", "[", "1", "]", "time_diff", "=", "(", "lookup_time", "-", "store_time", ")", ".", "round", "if", "time_diff", ">=", "@cacheTtl", "@cache", ".", "delete", "(", "schema_key", ")", "cache_result", "=", "nil", "else", "return", "cache_result", "[", "0", "]", "end", "else", "return", "cache_result", "[", "0", "]", "end", "end", "if", "cache_result", ".", "nil?", "for", "registry", "in", "prioritize_repos", "(", "schema_key", ",", "@registries", ")", "do", "begin", "lookup_result", "=", "registry", ".", "lookup_schema", "(", "schema_key", ")", "rescue", "StandardError", "=>", "e", "failures", ".", "push", "(", "Registries", "::", "LookupFailure", ".", "new", "(", "registry", ".", "config", ".", "name", ",", "e", ")", ")", "else", "if", "lookup_result", ".", "nil?", "failures", ".", "push", "(", "Registries", "::", "NotFound", ".", "new", "(", "registry", ".", "config", ".", "name", ")", ")", "else", "break", "end", "end", "end", "if", "lookup_result", ".", "nil?", "raise", "Registries", "::", "ResolverError", ".", "new", "(", "failures", ",", "schema_key", ")", "else", "store_time", "=", "Time", ".", "now", ".", "getutc", "@cache", "[", "schema_key", "]", "=", "[", "lookup_result", ",", "store_time", "]", "lookup_result", "end", "end", "end" ]
Lookup schema in cache or try to fetch
[ "Lookup", "schema", "in", "cache", "or", "try", "to", "fetch" ]
6d41668dc3e5615e3358a952e193812b5c4b3d6b
https://github.com/snowplow/iglu-ruby-client/blob/6d41668dc3e5615e3358a952e193812b5c4b3d6b/lib/iglu-client/resolver.rb#L28-L74
train
snowplow/iglu-ruby-client
lib/iglu-client/resolver.rb
Iglu.Resolver.validate
def validate(json) schema_key = Resolver.get_schema_key json data = Resolver.get_data json schema = lookup_schema schema_key JSON::Validator.validate!(schema, data) end
ruby
def validate(json) schema_key = Resolver.get_schema_key json data = Resolver.get_data json schema = lookup_schema schema_key JSON::Validator.validate!(schema, data) end
[ "def", "validate", "(", "json", ")", "schema_key", "=", "Resolver", ".", "get_schema_key", "json", "data", "=", "Resolver", ".", "get_data", "json", "schema", "=", "lookup_schema", "schema_key", "JSON", "::", "Validator", ".", "validate!", "(", "schema", ",", "data", ")", "end" ]
Return true or throw exception
[ "Return", "true", "or", "throw", "exception" ]
6d41668dc3e5615e3358a952e193812b5c4b3d6b
https://github.com/snowplow/iglu-ruby-client/blob/6d41668dc3e5615e3358a952e193812b5c4b3d6b/lib/iglu-client/resolver.rb#L119-L124
train
code-and-effect/effective_pages
app/models/effective/menu_item.rb
Effective.MenuItem.visible_for?
def visible_for?(user) can_view_page = ( if dropdown? true elsif menuable.kind_of?(Effective::Page) menuable.roles_permit?(user) else true end ) can_view_menu_item = ( if roles_mask == nil true elsif roles_mask == -1 # Am I logged out? user.blank? elsif roles_mask == 0 # Am I logged in? user.present? else roles_permit?(user) end ) can_view_page && can_view_menu_item end
ruby
def visible_for?(user) can_view_page = ( if dropdown? true elsif menuable.kind_of?(Effective::Page) menuable.roles_permit?(user) else true end ) can_view_menu_item = ( if roles_mask == nil true elsif roles_mask == -1 # Am I logged out? user.blank? elsif roles_mask == 0 # Am I logged in? user.present? else roles_permit?(user) end ) can_view_page && can_view_menu_item end
[ "def", "visible_for?", "(", "user", ")", "can_view_page", "=", "(", "if", "dropdown?", "true", "elsif", "menuable", ".", "kind_of?", "(", "Effective", "::", "Page", ")", "menuable", ".", "roles_permit?", "(", "user", ")", "else", "true", "end", ")", "can_view_menu_item", "=", "(", "if", "roles_mask", "==", "nil", "true", "elsif", "roles_mask", "==", "-", "1", "user", ".", "blank?", "elsif", "roles_mask", "==", "0", "user", ".", "present?", "else", "roles_permit?", "(", "user", ")", "end", ")", "can_view_page", "&&", "can_view_menu_item", "end" ]
For now it's just logged in or not? This will work with effective_roles one day...
[ "For", "now", "it", "s", "just", "logged", "in", "or", "not?", "This", "will", "work", "with", "effective_roles", "one", "day", "..." ]
ff00e2d76055985ab65f570747bc9a5f2748f817
https://github.com/code-and-effect/effective_pages/blob/ff00e2d76055985ab65f570747bc9a5f2748f817/app/models/effective/menu_item.rb#L51-L75
train
scrapper/perobs
lib/perobs/Store.rb
PEROBS.Store.copy
def copy(dir, options = {}) # Make sure all objects are persisted. sync # Create a new store with the specified directory and options. new_db = Store.new(dir, options) # Clear the cache. new_db.sync # Copy all objects of the existing store to the new store. i = 0 each do |ref_obj| obj = ref_obj._referenced_object obj._transfer(new_db) obj._sync i += 1 end PEROBS.log.debug "Copied #{i} objects into new database at #{dir}" # Flush the new store and close it. new_db.exit true end
ruby
def copy(dir, options = {}) # Make sure all objects are persisted. sync # Create a new store with the specified directory and options. new_db = Store.new(dir, options) # Clear the cache. new_db.sync # Copy all objects of the existing store to the new store. i = 0 each do |ref_obj| obj = ref_obj._referenced_object obj._transfer(new_db) obj._sync i += 1 end PEROBS.log.debug "Copied #{i} objects into new database at #{dir}" # Flush the new store and close it. new_db.exit true end
[ "def", "copy", "(", "dir", ",", "options", "=", "{", "}", ")", "sync", "new_db", "=", "Store", ".", "new", "(", "dir", ",", "options", ")", "new_db", ".", "sync", "i", "=", "0", "each", "do", "|", "ref_obj", "|", "obj", "=", "ref_obj", ".", "_referenced_object", "obj", ".", "_transfer", "(", "new_db", ")", "obj", ".", "_sync", "i", "+=", "1", "end", "PEROBS", ".", "log", ".", "debug", "\"Copied #{i} objects into new database at #{dir}\"", "new_db", ".", "exit", "true", "end" ]
Create a new Store. @param data_base [String] the name of the database @param options [Hash] various options to affect the operation of the database. Currently the following options are supported: :engine : The class that provides the back-end storage engine. By default FlatFileDB is used. A user can provide it's own storage engine that must conform to the same API exposed by FlatFileDB. :cache_bits : the number of bits used for cache indexing. The cache will hold 2 to the power of bits number of objects. We have separate caches for reading and writing. The default value is 16. It probably makes little sense to use much larger numbers than that. :serializer : select the format used to serialize the data. There are 3 different options: :marshal : Native Ruby serializer. Fastest option that can handle most Ruby data types. Big disadvantate is the stability of the format. Data written with one Ruby version may not be readable with another version. :json : About half as fast as marshal, but the format is rock solid and portable between languages. It only supports basic Ruby data types like String, Integer, Float, Array, Hash. This is the default option. :yaml : Can also handle most Ruby data types and is portable between Ruby versions (1.9 and later). Unfortunately, it is 10x slower than marshal. :progressmeter : reference to a ProgressMeter object that receives progress information during longer running tasks. It defaults to ProgressMeter which only logs into the log. Use ConsoleProgressMeter or a derived class for more fancy progress reporting. Copy the store content into a new Store. The arguments are identical to Store.new(). @param options [Hash] various options to affect the operation of the
[ "Create", "a", "new", "Store", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Store.rb#L183-L204
train
scrapper/perobs
lib/perobs/Store.rb
PEROBS.Store.exit
def exit if @cache && @cache.in_transaction? @cache.abort_transaction @cache.flush @db.close if @db PEROBS.log.fatal "You cannot call exit() during a transaction: #{Kernel.caller}" end @cache.flush if @cache @db.close if @db @db = @class_map = @in_memory_objects = @stats = @cache = @root_objects = nil end
ruby
def exit if @cache && @cache.in_transaction? @cache.abort_transaction @cache.flush @db.close if @db PEROBS.log.fatal "You cannot call exit() during a transaction: #{Kernel.caller}" end @cache.flush if @cache @db.close if @db @db = @class_map = @in_memory_objects = @stats = @cache = @root_objects = nil end
[ "def", "exit", "if", "@cache", "&&", "@cache", ".", "in_transaction?", "@cache", ".", "abort_transaction", "@cache", ".", "flush", "@db", ".", "close", "if", "@db", "PEROBS", ".", "log", ".", "fatal", "\"You cannot call exit() during a transaction: #{Kernel.caller}\"", "end", "@cache", ".", "flush", "if", "@cache", "@db", ".", "close", "if", "@db", "@db", "=", "@class_map", "=", "@in_memory_objects", "=", "@stats", "=", "@cache", "=", "@root_objects", "=", "nil", "end" ]
Close the store and ensure that all in-memory objects are written out to the storage backend. The Store object is no longer usable after this method was called.
[ "Close", "the", "store", "and", "ensure", "that", "all", "in", "-", "memory", "objects", "are", "written", "out", "to", "the", "storage", "backend", ".", "The", "Store", "object", "is", "no", "longer", "usable", "after", "this", "method", "was", "called", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Store.rb#L210-L221
train
scrapper/perobs
lib/perobs/Store.rb
PEROBS.Store.new
def new(klass, *args) unless klass.is_a?(BasicObject) PEROBS.log.fatal "#{klass} is not a BasicObject derivative" end obj = _construct_po(klass, _new_id, *args) # Mark the new object as modified so it gets pushed into the database. @cache.cache_write(obj) # Return a POXReference proxy for the newly created object. obj.myself end
ruby
def new(klass, *args) unless klass.is_a?(BasicObject) PEROBS.log.fatal "#{klass} is not a BasicObject derivative" end obj = _construct_po(klass, _new_id, *args) # Mark the new object as modified so it gets pushed into the database. @cache.cache_write(obj) # Return a POXReference proxy for the newly created object. obj.myself end
[ "def", "new", "(", "klass", ",", "*", "args", ")", "unless", "klass", ".", "is_a?", "(", "BasicObject", ")", "PEROBS", ".", "log", ".", "fatal", "\"#{klass} is not a BasicObject derivative\"", "end", "obj", "=", "_construct_po", "(", "klass", ",", "_new_id", ",", "*", "args", ")", "@cache", ".", "cache_write", "(", "obj", ")", "obj", ".", "myself", "end" ]
You need to call this method to create new PEROBS objects that belong to this Store. @param klass [Class] The class of the object you want to create. This must be a derivative of ObjectBase. @param args Optional list of other arguments that are passed to the constructor of the specified class. @return [POXReference] A reference to the newly created object.
[ "You", "need", "to", "call", "this", "method", "to", "create", "new", "PEROBS", "objects", "that", "belong", "to", "this", "Store", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Store.rb#L231-L241
train
scrapper/perobs
lib/perobs/Store.rb
PEROBS.Store._construct_po
def _construct_po(klass, id, *args) klass.new(Handle.new(self, id), *args) end
ruby
def _construct_po(klass, id, *args) klass.new(Handle.new(self, id), *args) end
[ "def", "_construct_po", "(", "klass", ",", "id", ",", "*", "args", ")", "klass", ".", "new", "(", "Handle", ".", "new", "(", "self", ",", "id", ")", ",", "*", "args", ")", "end" ]
For library internal use only! This method will create a new PEROBS object. @param klass [BasicObject] Class of the object to create @param id [Integer] Requested object ID @param args [Array] Arguments to pass to the object constructor. @return [BasicObject] Newly constructed PEROBS object
[ "For", "library", "internal", "use", "only!", "This", "method", "will", "create", "a", "new", "PEROBS", "object", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Store.rb#L249-L251
train
scrapper/perobs
lib/perobs/Store.rb
PEROBS.Store.sync
def sync if @cache.in_transaction? @cache.abort_transaction @cache.flush PEROBS.log.fatal "You cannot call sync() during a transaction: \n" + Kernel.caller.join("\n") end @cache.flush end
ruby
def sync if @cache.in_transaction? @cache.abort_transaction @cache.flush PEROBS.log.fatal "You cannot call sync() during a transaction: \n" + Kernel.caller.join("\n") end @cache.flush end
[ "def", "sync", "if", "@cache", ".", "in_transaction?", "@cache", ".", "abort_transaction", "@cache", ".", "flush", "PEROBS", ".", "log", ".", "fatal", "\"You cannot call sync() during a transaction: \\n\"", "+", "Kernel", ".", "caller", ".", "join", "(", "\"\\n\"", ")", "end", "@cache", ".", "flush", "end" ]
Flush out all modified objects to disk and shrink the in-memory list if needed.
[ "Flush", "out", "all", "modified", "objects", "to", "disk", "and", "shrink", "the", "in", "-", "memory", "list", "if", "needed", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Store.rb#L313-L321
train
scrapper/perobs
lib/perobs/Store.rb
PEROBS.Store.object_by_id
def object_by_id(id) if (ruby_object_id = @in_memory_objects[id]) # We have the object in memory so we can just return it. begin object = ObjectSpace._id2ref(ruby_object_id) # Let's make sure the object is really the object we are looking # for. The GC might have recycled it already and the Ruby object ID # could now be used for another object. if object.is_a?(ObjectBase) && object._id == id return object end rescue RangeError => e # Due to a race condition the object can still be in the # @in_memory_objects list but has been collected already by the Ruby # GC. In that case we need to load it again. In this case the # _collect() call will happen much later, potentially after we have # registered a new object with the same ID. @in_memory_objects.delete(id) end end if (obj = @cache.object_by_id(id)) PEROBS.log.fatal "Object #{id} with Ruby #{obj.object_id} is in cache but not in_memory" end # We don't have the object in memory. Let's find it in the storage. if @db.include?(id) # Great, object found. Read it into memory and return it. obj = ObjectBase::read(self, id) # Add the object to the in-memory storage list. @cache.cache_read(obj) return obj end # The requested object does not exist. Return nil. nil end
ruby
def object_by_id(id) if (ruby_object_id = @in_memory_objects[id]) # We have the object in memory so we can just return it. begin object = ObjectSpace._id2ref(ruby_object_id) # Let's make sure the object is really the object we are looking # for. The GC might have recycled it already and the Ruby object ID # could now be used for another object. if object.is_a?(ObjectBase) && object._id == id return object end rescue RangeError => e # Due to a race condition the object can still be in the # @in_memory_objects list but has been collected already by the Ruby # GC. In that case we need to load it again. In this case the # _collect() call will happen much later, potentially after we have # registered a new object with the same ID. @in_memory_objects.delete(id) end end if (obj = @cache.object_by_id(id)) PEROBS.log.fatal "Object #{id} with Ruby #{obj.object_id} is in cache but not in_memory" end # We don't have the object in memory. Let's find it in the storage. if @db.include?(id) # Great, object found. Read it into memory and return it. obj = ObjectBase::read(self, id) # Add the object to the in-memory storage list. @cache.cache_read(obj) return obj end # The requested object does not exist. Return nil. nil end
[ "def", "object_by_id", "(", "id", ")", "if", "(", "ruby_object_id", "=", "@in_memory_objects", "[", "id", "]", ")", "begin", "object", "=", "ObjectSpace", ".", "_id2ref", "(", "ruby_object_id", ")", "if", "object", ".", "is_a?", "(", "ObjectBase", ")", "&&", "object", ".", "_id", "==", "id", "return", "object", "end", "rescue", "RangeError", "=>", "e", "@in_memory_objects", ".", "delete", "(", "id", ")", "end", "end", "if", "(", "obj", "=", "@cache", ".", "object_by_id", "(", "id", ")", ")", "PEROBS", ".", "log", ".", "fatal", "\"Object #{id} with Ruby #{obj.object_id} is in cache but not in_memory\"", "end", "if", "@db", ".", "include?", "(", "id", ")", "obj", "=", "ObjectBase", "::", "read", "(", "self", ",", "id", ")", "@cache", ".", "cache_read", "(", "obj", ")", "return", "obj", "end", "nil", "end" ]
Return the object with the provided ID. This method is not part of the public API and should never be called by outside users. It's purely intended for internal use.
[ "Return", "the", "object", "with", "the", "provided", "ID", ".", "This", "method", "is", "not", "part", "of", "the", "public", "API", "and", "should", "never", "be", "called", "by", "outside", "users", ".", "It", "s", "purely", "intended", "for", "internal", "use", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Store.rb#L347-L384
train
scrapper/perobs
lib/perobs/Store.rb
PEROBS.Store.check
def check(repair = false) stats = { :errors => 0, :object_cnt => 0 } # All objects must have in-db version. sync # Run basic consistency checks first. stats[:errors] += @db.check_db(repair) # We will use the mark to mark all objects that we have checked already. # Before we start, we need to clear all marks. @db.clear_marks @progressmeter.start("Checking object link structure", @db.item_counter) do @root_objects.each do |name, id| check_object(id, repair, stats) end end # Delete all broken root objects. if repair @root_objects.delete_if do |name, id| unless @db.check(id, repair) PEROBS.log.error "Discarding broken root object '#{name}' " + "with ID #{id}" stats[:errors] += 1 end end end if stats[:errors] > 0 if repair PEROBS.log.error "#{stats[:errors]} errors found in " + "#{stats[:object_cnt]} objects" else PEROBS.log.fatal "#{stats[:errors]} errors found in " + "#{stats[:object_cnt]} objects" end else PEROBS.log.debug "No errors found" end # Ensure that any fixes are written into the DB. sync if repair stats[:errors] end
ruby
def check(repair = false) stats = { :errors => 0, :object_cnt => 0 } # All objects must have in-db version. sync # Run basic consistency checks first. stats[:errors] += @db.check_db(repair) # We will use the mark to mark all objects that we have checked already. # Before we start, we need to clear all marks. @db.clear_marks @progressmeter.start("Checking object link structure", @db.item_counter) do @root_objects.each do |name, id| check_object(id, repair, stats) end end # Delete all broken root objects. if repair @root_objects.delete_if do |name, id| unless @db.check(id, repair) PEROBS.log.error "Discarding broken root object '#{name}' " + "with ID #{id}" stats[:errors] += 1 end end end if stats[:errors] > 0 if repair PEROBS.log.error "#{stats[:errors]} errors found in " + "#{stats[:object_cnt]} objects" else PEROBS.log.fatal "#{stats[:errors]} errors found in " + "#{stats[:object_cnt]} objects" end else PEROBS.log.debug "No errors found" end # Ensure that any fixes are written into the DB. sync if repair stats[:errors] end
[ "def", "check", "(", "repair", "=", "false", ")", "stats", "=", "{", ":errors", "=>", "0", ",", ":object_cnt", "=>", "0", "}", "sync", "stats", "[", ":errors", "]", "+=", "@db", ".", "check_db", "(", "repair", ")", "@db", ".", "clear_marks", "@progressmeter", ".", "start", "(", "\"Checking object link structure\"", ",", "@db", ".", "item_counter", ")", "do", "@root_objects", ".", "each", "do", "|", "name", ",", "id", "|", "check_object", "(", "id", ",", "repair", ",", "stats", ")", "end", "end", "if", "repair", "@root_objects", ".", "delete_if", "do", "|", "name", ",", "id", "|", "unless", "@db", ".", "check", "(", "id", ",", "repair", ")", "PEROBS", ".", "log", ".", "error", "\"Discarding broken root object '#{name}' \"", "+", "\"with ID #{id}\"", "stats", "[", ":errors", "]", "+=", "1", "end", "end", "end", "if", "stats", "[", ":errors", "]", ">", "0", "if", "repair", "PEROBS", ".", "log", ".", "error", "\"#{stats[:errors]} errors found in \"", "+", "\"#{stats[:object_cnt]} objects\"", "else", "PEROBS", ".", "log", ".", "fatal", "\"#{stats[:errors]} errors found in \"", "+", "\"#{stats[:object_cnt]} objects\"", "end", "else", "PEROBS", ".", "log", ".", "debug", "\"No errors found\"", "end", "sync", "if", "repair", "stats", "[", ":errors", "]", "end" ]
This method can be used to check the database and optionally repair it. The repair is a pure structural repair. It cannot ensure that the stored data is still correct. E. g. if a reference to a non-existing or unreadable object is found, the reference will simply be deleted. @param repair [TrueClass/FalseClass] true if a repair attempt should be made. @return [Integer] The number of references to bad objects found.
[ "This", "method", "can", "be", "used", "to", "check", "the", "database", "and", "optionally", "repair", "it", ".", "The", "repair", "is", "a", "pure", "structural", "repair", ".", "It", "cannot", "ensure", "that", "the", "stored", "data", "is", "still", "correct", ".", "E", ".", "g", ".", "if", "a", "reference", "to", "a", "non", "-", "existing", "or", "unreadable", "object", "is", "found", "the", "reference", "will", "simply", "be", "deleted", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Store.rb#L393-L439
train
scrapper/perobs
lib/perobs/Store.rb
PEROBS.Store.each
def each @db.clear_marks # Start with the object 0 and the indexes of the root objects. Push them # onto the work stack. stack = [ 0 ] + @root_objects.values while !stack.empty? # Get an object index from the stack. id = stack.pop next if @db.is_marked?(id) unless (obj = object_by_id(id)) PEROBS.log.fatal "Database is corrupted. Object with ID #{id} " + "not found." end # Mark the object so it will never be pushed to the stack again. @db.mark(id) yield(obj.myself) if block_given? # Push the IDs of all unmarked referenced objects onto the stack obj._referenced_object_ids.each do |r_id| stack << r_id unless @db.is_marked?(r_id) end end end
ruby
def each @db.clear_marks # Start with the object 0 and the indexes of the root objects. Push them # onto the work stack. stack = [ 0 ] + @root_objects.values while !stack.empty? # Get an object index from the stack. id = stack.pop next if @db.is_marked?(id) unless (obj = object_by_id(id)) PEROBS.log.fatal "Database is corrupted. Object with ID #{id} " + "not found." end # Mark the object so it will never be pushed to the stack again. @db.mark(id) yield(obj.myself) if block_given? # Push the IDs of all unmarked referenced objects onto the stack obj._referenced_object_ids.each do |r_id| stack << r_id unless @db.is_marked?(r_id) end end end
[ "def", "each", "@db", ".", "clear_marks", "stack", "=", "[", "0", "]", "+", "@root_objects", ".", "values", "while", "!", "stack", ".", "empty?", "id", "=", "stack", ".", "pop", "next", "if", "@db", ".", "is_marked?", "(", "id", ")", "unless", "(", "obj", "=", "object_by_id", "(", "id", ")", ")", "PEROBS", ".", "log", ".", "fatal", "\"Database is corrupted. Object with ID #{id} \"", "+", "\"not found.\"", "end", "@db", ".", "mark", "(", "id", ")", "yield", "(", "obj", ".", "myself", ")", "if", "block_given?", "obj", ".", "_referenced_object_ids", ".", "each", "do", "|", "r_id", "|", "stack", "<<", "r_id", "unless", "@db", ".", "is_marked?", "(", "r_id", ")", "end", "end", "end" ]
Calls the given block once for each object, passing that object as a parameter.
[ "Calls", "the", "given", "block", "once", "for", "each", "object", "passing", "that", "object", "as", "a", "parameter", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Store.rb#L460-L482
train
scrapper/perobs
lib/perobs/Store.rb
PEROBS.Store.mark
def mark classes = Set.new marked_objects = 0 @progressmeter.start("Marking linked objects", @db.item_counter) do each do |obj| classes.add(obj.class) @progressmeter.update(marked_objects += 1) end end @class_map.keep(classes.map { |c| c.to_s }) # The root_objects object is included in the count, but we only want to # count user objects here. PEROBS.log.debug "#{marked_objects - 1} of #{@db.item_counter} " + "objects marked" @stats.marked_objects = marked_objects - 1 end
ruby
def mark classes = Set.new marked_objects = 0 @progressmeter.start("Marking linked objects", @db.item_counter) do each do |obj| classes.add(obj.class) @progressmeter.update(marked_objects += 1) end end @class_map.keep(classes.map { |c| c.to_s }) # The root_objects object is included in the count, but we only want to # count user objects here. PEROBS.log.debug "#{marked_objects - 1} of #{@db.item_counter} " + "objects marked" @stats.marked_objects = marked_objects - 1 end
[ "def", "mark", "classes", "=", "Set", ".", "new", "marked_objects", "=", "0", "@progressmeter", ".", "start", "(", "\"Marking linked objects\"", ",", "@db", ".", "item_counter", ")", "do", "each", "do", "|", "obj", "|", "classes", ".", "add", "(", "obj", ".", "class", ")", "@progressmeter", ".", "update", "(", "marked_objects", "+=", "1", ")", "end", "end", "@class_map", ".", "keep", "(", "classes", ".", "map", "{", "|", "c", "|", "c", ".", "to_s", "}", ")", "PEROBS", ".", "log", ".", "debug", "\"#{marked_objects - 1} of #{@db.item_counter} \"", "+", "\"objects marked\"", "@stats", ".", "marked_objects", "=", "marked_objects", "-", "1", "end" ]
Mark phase of a mark-and-sweep garbage collector. It will mark all objects that are reachable from the root objects.
[ "Mark", "phase", "of", "a", "mark", "-", "and", "-", "sweep", "garbage", "collector", ".", "It", "will", "mark", "all", "objects", "that", "are", "reachable", "from", "the", "root", "objects", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Store.rb#L538-L554
train
scrapper/perobs
lib/perobs/Store.rb
PEROBS.Store.check_object
def check_object(start_id, repair, stats) @db.mark(start_id) # The todo list holds a touple for each object that still needs to be # checked. The first item is the referring object and the second is the # ID of the object to check. todo_list = [ [ nil, start_id ] ] while !todo_list.empty? # Get the next PEROBS object to check ref_obj, id = todo_list.pop begin obj = object_by_id(id) rescue PEROBS::FatalError obj = nil end if obj # The object exists and is OK. Mark is as checked. @db.mark(id) # Now look at all other objects referenced by this object. obj._referenced_object_ids.each do |refd_id| # Push them onto the todo list unless they have been marked # already. todo_list << [ obj, refd_id ] unless @db.is_marked?(refd_id, true) end else # Remove references to bad objects. if ref_obj if repair PEROBS.log.error "Removing reference to " + "#{obj ? 'broken' : 'non-existing'} object #{id} from:\n" + ref_obj.inspect ref_obj._delete_reference_to_id(id) else PEROBS.log.error "The following object references a " + "#{obj ? 'broken' : 'non-existing'} object #{id}:\n" + ref_obj.inspect end end stats[:errors] += 1 end @progressmeter.update(stats[:object_cnt] += 1) end end
ruby
def check_object(start_id, repair, stats) @db.mark(start_id) # The todo list holds a touple for each object that still needs to be # checked. The first item is the referring object and the second is the # ID of the object to check. todo_list = [ [ nil, start_id ] ] while !todo_list.empty? # Get the next PEROBS object to check ref_obj, id = todo_list.pop begin obj = object_by_id(id) rescue PEROBS::FatalError obj = nil end if obj # The object exists and is OK. Mark is as checked. @db.mark(id) # Now look at all other objects referenced by this object. obj._referenced_object_ids.each do |refd_id| # Push them onto the todo list unless they have been marked # already. todo_list << [ obj, refd_id ] unless @db.is_marked?(refd_id, true) end else # Remove references to bad objects. if ref_obj if repair PEROBS.log.error "Removing reference to " + "#{obj ? 'broken' : 'non-existing'} object #{id} from:\n" + ref_obj.inspect ref_obj._delete_reference_to_id(id) else PEROBS.log.error "The following object references a " + "#{obj ? 'broken' : 'non-existing'} object #{id}:\n" + ref_obj.inspect end end stats[:errors] += 1 end @progressmeter.update(stats[:object_cnt] += 1) end end
[ "def", "check_object", "(", "start_id", ",", "repair", ",", "stats", ")", "@db", ".", "mark", "(", "start_id", ")", "todo_list", "=", "[", "[", "nil", ",", "start_id", "]", "]", "while", "!", "todo_list", ".", "empty?", "ref_obj", ",", "id", "=", "todo_list", ".", "pop", "begin", "obj", "=", "object_by_id", "(", "id", ")", "rescue", "PEROBS", "::", "FatalError", "obj", "=", "nil", "end", "if", "obj", "@db", ".", "mark", "(", "id", ")", "obj", ".", "_referenced_object_ids", ".", "each", "do", "|", "refd_id", "|", "todo_list", "<<", "[", "obj", ",", "refd_id", "]", "unless", "@db", ".", "is_marked?", "(", "refd_id", ",", "true", ")", "end", "else", "if", "ref_obj", "if", "repair", "PEROBS", ".", "log", ".", "error", "\"Removing reference to \"", "+", "\"#{obj ? 'broken' : 'non-existing'} object #{id} from:\\n\"", "+", "ref_obj", ".", "inspect", "ref_obj", ".", "_delete_reference_to_id", "(", "id", ")", "else", "PEROBS", ".", "log", ".", "error", "\"The following object references a \"", "+", "\"#{obj ? 'broken' : 'non-existing'} object #{id}:\\n\"", "+", "ref_obj", ".", "inspect", "end", "end", "stats", "[", ":errors", "]", "+=", "1", "end", "@progressmeter", ".", "update", "(", "stats", "[", ":object_cnt", "]", "+=", "1", ")", "end", "end" ]
Check the object with the given start_id and all other objects that are somehow reachable from the start object. @param start_id [Integer] ID of the top-level object to start with @param repair [Boolean] Delete refernces to broken objects if true @return [Integer] The number of references to bad objects.
[ "Check", "the", "object", "with", "the", "given", "start_id", "and", "all", "other", "objects", "that", "are", "somehow", "reachable", "from", "the", "start", "object", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Store.rb#L571-L616
train
scrapper/perobs
lib/perobs/Object.rb
PEROBS.Object._referenced_object_ids
def _referenced_object_ids ids = [] _all_attributes.each do |attr| value = instance_variable_get(('@' + attr.to_s).to_sym) ids << value.id if value && value.respond_to?(:is_poxreference?) end ids end
ruby
def _referenced_object_ids ids = [] _all_attributes.each do |attr| value = instance_variable_get(('@' + attr.to_s).to_sym) ids << value.id if value && value.respond_to?(:is_poxreference?) end ids end
[ "def", "_referenced_object_ids", "ids", "=", "[", "]", "_all_attributes", ".", "each", "do", "|", "attr", "|", "value", "=", "instance_variable_get", "(", "(", "'@'", "+", "attr", ".", "to_s", ")", ".", "to_sym", ")", "ids", "<<", "value", ".", "id", "if", "value", "&&", "value", ".", "respond_to?", "(", ":is_poxreference?", ")", "end", "ids", "end" ]
Return a list of all object IDs that the attributes of this instance are referencing. @return [Array of Integer] IDs of referenced objects
[ "Return", "a", "list", "of", "all", "object", "IDs", "that", "the", "attributes", "of", "this", "instance", "are", "referencing", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Object.rb#L149-L156
train
scrapper/perobs
lib/perobs/Object.rb
PEROBS.Object._delete_reference_to_id
def _delete_reference_to_id(id) _all_attributes.each do |attr| ivar = ('@' + attr.to_s).to_sym value = instance_variable_get(ivar) if value && value.respond_to?(:is_poxreference?) && value.id == id instance_variable_set(ivar, nil) end end mark_as_modified end
ruby
def _delete_reference_to_id(id) _all_attributes.each do |attr| ivar = ('@' + attr.to_s).to_sym value = instance_variable_get(ivar) if value && value.respond_to?(:is_poxreference?) && value.id == id instance_variable_set(ivar, nil) end end mark_as_modified end
[ "def", "_delete_reference_to_id", "(", "id", ")", "_all_attributes", ".", "each", "do", "|", "attr", "|", "ivar", "=", "(", "'@'", "+", "attr", ".", "to_s", ")", ".", "to_sym", "value", "=", "instance_variable_get", "(", "ivar", ")", "if", "value", "&&", "value", ".", "respond_to?", "(", ":is_poxreference?", ")", "&&", "value", ".", "id", "==", "id", "instance_variable_set", "(", "ivar", ",", "nil", ")", "end", "end", "mark_as_modified", "end" ]
This method should only be used during store repair operations. It will delete all references to the given object ID. @param id [Integer] targeted object ID
[ "This", "method", "should", "only", "be", "used", "during", "store", "repair", "operations", ".", "It", "will", "delete", "all", "references", "to", "the", "given", "object", "ID", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Object.rb#L161-L170
train
scrapper/perobs
lib/perobs/Object.rb
PEROBS.Object.inspect
def inspect "<#{self.class}:#{@_id}>\n{\n" + _all_attributes.map do |attr| ivar = ('@' + attr.to_s).to_sym if (value = instance_variable_get(ivar)).respond_to?(:is_poxreference?) " #{attr} => <PEROBS::ObjectBase:#{value._id}>" else " #{attr} => #{value.inspect}" end end.join(",\n") + "\n}\n" end
ruby
def inspect "<#{self.class}:#{@_id}>\n{\n" + _all_attributes.map do |attr| ivar = ('@' + attr.to_s).to_sym if (value = instance_variable_get(ivar)).respond_to?(:is_poxreference?) " #{attr} => <PEROBS::ObjectBase:#{value._id}>" else " #{attr} => #{value.inspect}" end end.join(",\n") + "\n}\n" end
[ "def", "inspect", "\"<#{self.class}:#{@_id}>\\n{\\n\"", "+", "_all_attributes", ".", "map", "do", "|", "attr", "|", "ivar", "=", "(", "'@'", "+", "attr", ".", "to_s", ")", ".", "to_sym", "if", "(", "value", "=", "instance_variable_get", "(", "ivar", ")", ")", ".", "respond_to?", "(", ":is_poxreference?", ")", "\" #{attr} => <PEROBS::ObjectBase:#{value._id}>\"", "else", "\" #{attr} => #{value.inspect}\"", "end", "end", ".", "join", "(", "\",\\n\"", ")", "+", "\"\\n}\\n\"", "end" ]
Textual dump for debugging purposes @return [String]
[ "Textual", "dump", "for", "debugging", "purposes" ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Object.rb#L186-L197
train
scrapper/perobs
lib/perobs/Object.rb
PEROBS.Object._serialize
def _serialize attributes = {} _all_attributes.each do |attr| ivar = ('@' + attr.to_s).to_sym value = instance_variable_get(ivar) attributes[attr.to_s] = value.respond_to?(:is_poxreference?) ? POReference.new(value.id) : value end attributes end
ruby
def _serialize attributes = {} _all_attributes.each do |attr| ivar = ('@' + attr.to_s).to_sym value = instance_variable_get(ivar) attributes[attr.to_s] = value.respond_to?(:is_poxreference?) ? POReference.new(value.id) : value end attributes end
[ "def", "_serialize", "attributes", "=", "{", "}", "_all_attributes", ".", "each", "do", "|", "attr", "|", "ivar", "=", "(", "'@'", "+", "attr", ".", "to_s", ")", ".", "to_sym", "value", "=", "instance_variable_get", "(", "ivar", ")", "attributes", "[", "attr", ".", "to_s", "]", "=", "value", ".", "respond_to?", "(", ":is_poxreference?", ")", "?", "POReference", ".", "new", "(", "value", ".", "id", ")", ":", "value", "end", "attributes", "end" ]
Return a single data structure that holds all persistent data for this class.
[ "Return", "a", "single", "data", "structure", "that", "holds", "all", "persistent", "data", "for", "this", "class", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Object.rb#L203-L212
train
danielpclark/PolyBelongsTo
lib/poly_belongs_to/singleton_set.rb
PolyBelongsTo.SingletonSet.add?
def add?(record) result = @set.add?( formatted_name( record ) ) return result if result flag(record) result end
ruby
def add?(record) result = @set.add?( formatted_name( record ) ) return result if result flag(record) result end
[ "def", "add?", "(", "record", ")", "result", "=", "@set", ".", "add?", "(", "formatted_name", "(", "record", ")", ")", "return", "result", "if", "result", "flag", "(", "record", ")", "result", "end" ]
Add record to set. Flag if covered already. @param record [Object] ActiveRecord object instance @return [Object, nil] Object if added safely, nil otherwise
[ "Add", "record", "to", "set", ".", "Flag", "if", "covered", "already", "." ]
38d51d37f9148613519d6b6d56bdf4d0884f0e86
https://github.com/danielpclark/PolyBelongsTo/blob/38d51d37f9148613519d6b6d56bdf4d0884f0e86/lib/poly_belongs_to/singleton_set.rb#L24-L29
train
danielpclark/PolyBelongsTo
lib/poly_belongs_to/singleton_set.rb
PolyBelongsTo.SingletonSet.method_missing
def method_missing(mthd, *args, &block) new_recs = args.reduce([]) {|a, i| a.push(formatted_name(i)) if i.class.ancestors.include?(ActiveRecord::Base); a} result = @set.send(mthd, *(args.map do |arg| arg.class.ancestors.include?(ActiveRecord::Base) ? formatted_name(arg) : arg end ), &block ) @set.to_a.select {|i| new_recs.include? i }.each {|f| @flagged << f} result end
ruby
def method_missing(mthd, *args, &block) new_recs = args.reduce([]) {|a, i| a.push(formatted_name(i)) if i.class.ancestors.include?(ActiveRecord::Base); a} result = @set.send(mthd, *(args.map do |arg| arg.class.ancestors.include?(ActiveRecord::Base) ? formatted_name(arg) : arg end ), &block ) @set.to_a.select {|i| new_recs.include? i }.each {|f| @flagged << f} result end
[ "def", "method_missing", "(", "mthd", ",", "*", "args", ",", "&", "block", ")", "new_recs", "=", "args", ".", "reduce", "(", "[", "]", ")", "{", "|", "a", ",", "i", "|", "a", ".", "push", "(", "formatted_name", "(", "i", ")", ")", "if", "i", ".", "class", ".", "ancestors", ".", "include?", "(", "ActiveRecord", "::", "Base", ")", ";", "a", "}", "result", "=", "@set", ".", "send", "(", "mthd", ",", "*", "(", "args", ".", "map", "do", "|", "arg", "|", "arg", ".", "class", ".", "ancestors", ".", "include?", "(", "ActiveRecord", "::", "Base", ")", "?", "formatted_name", "(", "arg", ")", ":", "arg", "end", ")", ",", "&", "block", ")", "@set", ".", "to_a", ".", "select", "{", "|", "i", "|", "new_recs", ".", "include?", "i", "}", ".", "each", "{", "|", "f", "|", "@flagged", "<<", "f", "}", "result", "end" ]
method_missing will transform any record argument into a formatted string and pass the method and arguments on to the internal Set. Also will flag any existing records covered.
[ "method_missing", "will", "transform", "any", "record", "argument", "into", "a", "formatted", "string", "and", "pass", "the", "method", "and", "arguments", "on", "to", "the", "internal", "Set", ".", "Also", "will", "flag", "any", "existing", "records", "covered", "." ]
38d51d37f9148613519d6b6d56bdf4d0884f0e86
https://github.com/danielpclark/PolyBelongsTo/blob/38d51d37f9148613519d6b6d56bdf4d0884f0e86/lib/poly_belongs_to/singleton_set.rb#L56-L67
train
Absolight/epp-client
lib/epp-client/xml.rb
EPPClient.XML.get_result
def get_result(args) xml = case args when Hash args.delete(:xml) else xml = args args = {} xml end args[:range] ||= 1000..1999 if !(mq = xml.xpath('epp:epp/epp:response/epp:msgQ', EPPClient::SCHEMAS_URL)).empty? @msgQ_count = mq.attribute('count').value.to_i @msgQ_id = mq.attribute('id').value puts "DEBUG: MSGQ : count=#{@msgQ_count}, id=#{@msgQ_id}\n" if debug else @msgQ_count = 0 @msgQ_id = nil end unless (trID = xml.xpath('epp:epp/epp:response/epp:trID', EPPClient::SCHEMAS_URL)).empty? @trID = get_trid(trID) end res = xml.xpath('epp:epp/epp:response/epp:result', EPPClient::SCHEMAS_URL) code = res.attribute('code').value.to_i raise EPPClient::EPPErrorResponse.new(:xml => xml, :code => code, :message => res.xpath('epp:msg', EPPClient::SCHEMAS_URL).text) unless args[:range].include?(code) return true unless args.key?(:callback) case cb = args[:callback] when Symbol return send(cb, xml.xpath('epp:epp/epp:response', EPPClient::SCHEMAS_URL)) else raise ArgumentError, 'Invalid callback type' end end
ruby
def get_result(args) xml = case args when Hash args.delete(:xml) else xml = args args = {} xml end args[:range] ||= 1000..1999 if !(mq = xml.xpath('epp:epp/epp:response/epp:msgQ', EPPClient::SCHEMAS_URL)).empty? @msgQ_count = mq.attribute('count').value.to_i @msgQ_id = mq.attribute('id').value puts "DEBUG: MSGQ : count=#{@msgQ_count}, id=#{@msgQ_id}\n" if debug else @msgQ_count = 0 @msgQ_id = nil end unless (trID = xml.xpath('epp:epp/epp:response/epp:trID', EPPClient::SCHEMAS_URL)).empty? @trID = get_trid(trID) end res = xml.xpath('epp:epp/epp:response/epp:result', EPPClient::SCHEMAS_URL) code = res.attribute('code').value.to_i raise EPPClient::EPPErrorResponse.new(:xml => xml, :code => code, :message => res.xpath('epp:msg', EPPClient::SCHEMAS_URL).text) unless args[:range].include?(code) return true unless args.key?(:callback) case cb = args[:callback] when Symbol return send(cb, xml.xpath('epp:epp/epp:response', EPPClient::SCHEMAS_URL)) else raise ArgumentError, 'Invalid callback type' end end
[ "def", "get_result", "(", "args", ")", "xml", "=", "case", "args", "when", "Hash", "args", ".", "delete", "(", ":xml", ")", "else", "xml", "=", "args", "args", "=", "{", "}", "xml", "end", "args", "[", ":range", "]", "||=", "1000", "..", "1999", "if", "!", "(", "mq", "=", "xml", ".", "xpath", "(", "'epp:epp/epp:response/epp:msgQ'", ",", "EPPClient", "::", "SCHEMAS_URL", ")", ")", ".", "empty?", "@msgQ_count", "=", "mq", ".", "attribute", "(", "'count'", ")", ".", "value", ".", "to_i", "@msgQ_id", "=", "mq", ".", "attribute", "(", "'id'", ")", ".", "value", "puts", "\"DEBUG: MSGQ : count=#{@msgQ_count}, id=#{@msgQ_id}\\n\"", "if", "debug", "else", "@msgQ_count", "=", "0", "@msgQ_id", "=", "nil", "end", "unless", "(", "trID", "=", "xml", ".", "xpath", "(", "'epp:epp/epp:response/epp:trID'", ",", "EPPClient", "::", "SCHEMAS_URL", ")", ")", ".", "empty?", "@trID", "=", "get_trid", "(", "trID", ")", "end", "res", "=", "xml", ".", "xpath", "(", "'epp:epp/epp:response/epp:result'", ",", "EPPClient", "::", "SCHEMAS_URL", ")", "code", "=", "res", ".", "attribute", "(", "'code'", ")", ".", "value", ".", "to_i", "raise", "EPPClient", "::", "EPPErrorResponse", ".", "new", "(", ":xml", "=>", "xml", ",", ":code", "=>", "code", ",", ":message", "=>", "res", ".", "xpath", "(", "'epp:msg'", ",", "EPPClient", "::", "SCHEMAS_URL", ")", ".", "text", ")", "unless", "args", "[", ":range", "]", ".", "include?", "(", "code", ")", "return", "true", "unless", "args", ".", "key?", "(", ":callback", ")", "case", "cb", "=", "args", "[", ":callback", "]", "when", "Symbol", "return", "send", "(", "cb", ",", "xml", ".", "xpath", "(", "'epp:epp/epp:response'", ",", "EPPClient", "::", "SCHEMAS_URL", ")", ")", "else", "raise", "ArgumentError", ",", "'Invalid callback type'", "end", "end" ]
Takes a xml response and checks that the result is in the right range of results, that is, between 1000 and 1999, which are results meaning all went well. In case all went well, it either calls the callback if given, or returns true. In case there was a problem, an EPPErrorResponse exception is raised.
[ "Takes", "a", "xml", "response", "and", "checks", "that", "the", "result", "is", "in", "the", "right", "range", "of", "results", "that", "is", "between", "1000", "and", "1999", "which", "are", "results", "meaning", "all", "went", "well", "." ]
c0025daee5e7087f60b654595a8e7d92e966c54e
https://github.com/Absolight/epp-client/blob/c0025daee5e7087f60b654595a8e7d92e966c54e/lib/epp-client/xml.rb#L50-L88
train
Absolight/epp-client
lib/epp-client/xml.rb
EPPClient.XML.command
def command(*args, &_block) builder do |xml| xml.command do if block_given? yield xml else command = args.shift command.call(xml) args.each do |ext| xml.extension do ext.call(xml) end end end xml.clTRID(clTRID) end end end
ruby
def command(*args, &_block) builder do |xml| xml.command do if block_given? yield xml else command = args.shift command.call(xml) args.each do |ext| xml.extension do ext.call(xml) end end end xml.clTRID(clTRID) end end end
[ "def", "command", "(", "*", "args", ",", "&", "_block", ")", "builder", "do", "|", "xml", "|", "xml", ".", "command", "do", "if", "block_given?", "yield", "xml", "else", "command", "=", "args", ".", "shift", "command", ".", "call", "(", "xml", ")", "args", ".", "each", "do", "|", "ext", "|", "xml", ".", "extension", "do", "ext", ".", "call", "(", "xml", ")", "end", "end", "end", "xml", ".", "clTRID", "(", "clTRID", ")", "end", "end", "end" ]
Creates the xml for the command. You can either pass a block to it, in that case, it's the command body, or a series of procs, the first one being the commands, the other ones being the extensions. command do |xml| xml.logout end or command(lambda do |xml| xml.logout end, lambda do |xml| xml.extension end)
[ "Creates", "the", "xml", "for", "the", "command", "." ]
c0025daee5e7087f60b654595a8e7d92e966c54e
https://github.com/Absolight/epp-client/blob/c0025daee5e7087f60b654595a8e7d92e966c54e/lib/epp-client/xml.rb#L114-L131
train
regru/reg_api2-ruby
lib/reg_api2/action.rb
RegApi2.Action.create_http
def create_http http = Net::HTTP.new( API_URI.host, API_URI.port ) http.use_ssl = true apply_ca_cert_path(http) apply_pem(http) http end
ruby
def create_http http = Net::HTTP.new( API_URI.host, API_URI.port ) http.use_ssl = true apply_ca_cert_path(http) apply_pem(http) http end
[ "def", "create_http", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "API_URI", ".", "host", ",", "API_URI", ".", "port", ")", "http", ".", "use_ssl", "=", "true", "apply_ca_cert_path", "(", "http", ")", "apply_pem", "(", "http", ")", "http", "end" ]
Creates HTTPS handler. @return [Net::HTTP] HTTPS handler. @see #http
[ "Creates", "HTTPS", "handler", "." ]
82fadffc9da6534761003b8a33edb77ab617df70
https://github.com/regru/reg_api2-ruby/blob/82fadffc9da6534761003b8a33edb77ab617df70/lib/reg_api2/action.rb#L48-L57
train
regru/reg_api2-ruby
lib/reg_api2/action.rb
RegApi2.Action.get_form_data
def get_form_data(defopts, opts) # HACK: REG.API doesn't know about utf-8. io_encoding = 'utf8' if !io_encoding || io_encoding == DEFAULT_IO_ENCODING opts = opts.to_hash if opts.respond_to?(:to_hash) req_contract = RegApi2::RequestContract.new(defopts) opts = req_contract.validate(opts) form = { 'username' => username || DEFAULT_USERNAME, 'password' => password || DEFAULT_PASSWORD, 'io_encoding' => io_encoding, 'lang' => lang || DEFAULT_LANG, 'output_format' => 'json', 'input_format' => 'json', 'show_input_params' => 0, 'input_data' => Yajl::Encoder.encode(opts) } form end
ruby
def get_form_data(defopts, opts) # HACK: REG.API doesn't know about utf-8. io_encoding = 'utf8' if !io_encoding || io_encoding == DEFAULT_IO_ENCODING opts = opts.to_hash if opts.respond_to?(:to_hash) req_contract = RegApi2::RequestContract.new(defopts) opts = req_contract.validate(opts) form = { 'username' => username || DEFAULT_USERNAME, 'password' => password || DEFAULT_PASSWORD, 'io_encoding' => io_encoding, 'lang' => lang || DEFAULT_LANG, 'output_format' => 'json', 'input_format' => 'json', 'show_input_params' => 0, 'input_data' => Yajl::Encoder.encode(opts) } form end
[ "def", "get_form_data", "(", "defopts", ",", "opts", ")", "io_encoding", "=", "'utf8'", "if", "!", "io_encoding", "||", "io_encoding", "==", "DEFAULT_IO_ENCODING", "opts", "=", "opts", ".", "to_hash", "if", "opts", ".", "respond_to?", "(", ":to_hash", ")", "req_contract", "=", "RegApi2", "::", "RequestContract", ".", "new", "(", "defopts", ")", "opts", "=", "req_contract", ".", "validate", "(", "opts", ")", "form", "=", "{", "'username'", "=>", "username", "||", "DEFAULT_USERNAME", ",", "'password'", "=>", "password", "||", "DEFAULT_PASSWORD", ",", "'io_encoding'", "=>", "io_encoding", ",", "'lang'", "=>", "lang", "||", "DEFAULT_LANG", ",", "'output_format'", "=>", "'json'", ",", "'input_format'", "=>", "'json'", ",", "'show_input_params'", "=>", "0", ",", "'input_data'", "=>", "Yajl", "::", "Encoder", ".", "encode", "(", "opts", ")", "}", "form", "end" ]
Gets form data for POST request @param [Hash] defopts @param [Hash] opts @return [Hash] Form data to be sent. @raise [ContractError]
[ "Gets", "form", "data", "for", "POST", "request" ]
82fadffc9da6534761003b8a33edb77ab617df70
https://github.com/regru/reg_api2-ruby/blob/82fadffc9da6534761003b8a33edb77ab617df70/lib/reg_api2/action.rb#L83-L102
train
radar/summer
lib/summer.rb
Summer.Connection.startup!
def startup! @started = true try(:did_start_up) if config['nickserv_password'] privmsg("identify #{config['nickserv_password']}", "nickserv") # Wait 10 seconds for nickserv to get back to us. Thread.new do sleep(10) finalize_startup end else finalize_startup end end
ruby
def startup! @started = true try(:did_start_up) if config['nickserv_password'] privmsg("identify #{config['nickserv_password']}", "nickserv") # Wait 10 seconds for nickserv to get back to us. Thread.new do sleep(10) finalize_startup end else finalize_startup end end
[ "def", "startup!", "@started", "=", "true", "try", "(", ":did_start_up", ")", "if", "config", "[", "'nickserv_password'", "]", "privmsg", "(", "\"identify #{config['nickserv_password']}\"", ",", "\"nickserv\"", ")", "Thread", ".", "new", "do", "sleep", "(", "10", ")", "finalize_startup", "end", "else", "finalize_startup", "end", "end" ]
Will join channels specified in configuration.
[ "Will", "join", "channels", "specified", "in", "configuration", "." ]
7c08c6a8b2e986030db3718ca71daf2ca8dd668d
https://github.com/radar/summer/blob/7c08c6a8b2e986030db3718ca71daf2ca8dd668d/lib/summer.rb#L69-L83
train
radar/summer
lib/summer.rb
Summer.Connection.parse
def parse(message) puts "<< #{message.to_s.strip}" words = message.split(" ") sender = words[0] raw = words[1] channel = words[2] # Handling pings if /^PING (.*?)\s$/.match(message) response("PONG #{$1}") # Handling raws elsif /\d+/.match(raw) send("handle_#{raw}", message) if raws_to_handle.include?(raw) # Privmsgs elsif raw == "PRIVMSG" message = words[3..-1].clean # Parse commands if /^!(\w+)\s*(.*)/.match(message) && respond_to?("#{$1}_command") try("#{$1}_command", parse_sender(sender), channel, $2) # Plain and boring message else sender = parse_sender(sender) method, channel = channel == me ? [:private_message, sender[:nick]] : [:channel_message, channel] try(method, sender, channel, message) end # Joins elsif raw == "JOIN" try(:join_event, parse_sender(sender), channel) elsif raw == "PART" try(:part_event, parse_sender(sender), channel, words[3..-1].clean) elsif raw == "QUIT" try(:quit_event, parse_sender(sender), words[2..-1].clean) elsif raw == "KICK" try(:kick_event, parse_sender(sender), channel, words[3], words[4..-1].clean) join(channel) if words[3] == me && config[:auto_rejoin] elsif raw == "MODE" try(:mode_event, parse_sender(sender), channel, words[3], words[4..-1].clean) end end
ruby
def parse(message) puts "<< #{message.to_s.strip}" words = message.split(" ") sender = words[0] raw = words[1] channel = words[2] # Handling pings if /^PING (.*?)\s$/.match(message) response("PONG #{$1}") # Handling raws elsif /\d+/.match(raw) send("handle_#{raw}", message) if raws_to_handle.include?(raw) # Privmsgs elsif raw == "PRIVMSG" message = words[3..-1].clean # Parse commands if /^!(\w+)\s*(.*)/.match(message) && respond_to?("#{$1}_command") try("#{$1}_command", parse_sender(sender), channel, $2) # Plain and boring message else sender = parse_sender(sender) method, channel = channel == me ? [:private_message, sender[:nick]] : [:channel_message, channel] try(method, sender, channel, message) end # Joins elsif raw == "JOIN" try(:join_event, parse_sender(sender), channel) elsif raw == "PART" try(:part_event, parse_sender(sender), channel, words[3..-1].clean) elsif raw == "QUIT" try(:quit_event, parse_sender(sender), words[2..-1].clean) elsif raw == "KICK" try(:kick_event, parse_sender(sender), channel, words[3], words[4..-1].clean) join(channel) if words[3] == me && config[:auto_rejoin] elsif raw == "MODE" try(:mode_event, parse_sender(sender), channel, words[3], words[4..-1].clean) end end
[ "def", "parse", "(", "message", ")", "puts", "\"<< #{message.to_s.strip}\"", "words", "=", "message", ".", "split", "(", "\" \"", ")", "sender", "=", "words", "[", "0", "]", "raw", "=", "words", "[", "1", "]", "channel", "=", "words", "[", "2", "]", "if", "/", "\\s", "/", ".", "match", "(", "message", ")", "response", "(", "\"PONG #{$1}\"", ")", "elsif", "/", "\\d", "/", ".", "match", "(", "raw", ")", "send", "(", "\"handle_#{raw}\"", ",", "message", ")", "if", "raws_to_handle", ".", "include?", "(", "raw", ")", "elsif", "raw", "==", "\"PRIVMSG\"", "message", "=", "words", "[", "3", "..", "-", "1", "]", ".", "clean", "if", "/", "\\w", "\\s", "/", ".", "match", "(", "message", ")", "&&", "respond_to?", "(", "\"#{$1}_command\"", ")", "try", "(", "\"#{$1}_command\"", ",", "parse_sender", "(", "sender", ")", ",", "channel", ",", "$2", ")", "else", "sender", "=", "parse_sender", "(", "sender", ")", "method", ",", "channel", "=", "channel", "==", "me", "?", "[", ":private_message", ",", "sender", "[", ":nick", "]", "]", ":", "[", ":channel_message", ",", "channel", "]", "try", "(", "method", ",", "sender", ",", "channel", ",", "message", ")", "end", "elsif", "raw", "==", "\"JOIN\"", "try", "(", ":join_event", ",", "parse_sender", "(", "sender", ")", ",", "channel", ")", "elsif", "raw", "==", "\"PART\"", "try", "(", ":part_event", ",", "parse_sender", "(", "sender", ")", ",", "channel", ",", "words", "[", "3", "..", "-", "1", "]", ".", "clean", ")", "elsif", "raw", "==", "\"QUIT\"", "try", "(", ":quit_event", ",", "parse_sender", "(", "sender", ")", ",", "words", "[", "2", "..", "-", "1", "]", ".", "clean", ")", "elsif", "raw", "==", "\"KICK\"", "try", "(", ":kick_event", ",", "parse_sender", "(", "sender", ")", ",", "channel", ",", "words", "[", "3", "]", ",", "words", "[", "4", "..", "-", "1", "]", ".", "clean", ")", "join", "(", "channel", ")", "if", "words", "[", "3", "]", "==", "me", "&&", "config", "[", ":auto_rejoin", "]", "elsif", "raw", "==", "\"MODE\"", "try", "(", ":mode_event", ",", "parse_sender", "(", "sender", ")", ",", "channel", ",", "words", "[", "3", "]", ",", "words", "[", "4", "..", "-", "1", "]", ".", "clean", ")", "end", "end" ]
What did they say?
[ "What", "did", "they", "say?" ]
7c08c6a8b2e986030db3718ca71daf2ca8dd668d
https://github.com/radar/summer/blob/7c08c6a8b2e986030db3718ca71daf2ca8dd668d/lib/summer.rb#L107-L145
train
apeiros/swissmatch-location
lib/swissmatch/zipcodes.rb
SwissMatch.ZipCodes.[]
def [](key, add_on=nil) case key when /\A(\d{4})(\d\d)\z/ by_code_and_add_on($1.to_i, $2.to_i) when 100_000..999_999 by_code_and_add_on(*key.divmod(100)) when 0..9999, /\A\d{4}\z/ case add_on when nil by_code(key.to_i) when 0..99, /\A\d+\z/ by_code_and_add_on(key.to_i, add_on.to_i) when String by_code_and_name(key.to_i, add_on) else raise ArgumentError, "Expected a String, an Integer between 0 and 99, or a String containing an integer between 0 and 99, " \ "but got #{key.class}: #{key.inspect}" end when String by_name(key) else raise ArgumentError, "Expected a String, an Integer between 1000 and 9999, or an " \ "Integer between 100_000 and 999_999, but got #{key.class}:" \ "#{key.inspect}" end end
ruby
def [](key, add_on=nil) case key when /\A(\d{4})(\d\d)\z/ by_code_and_add_on($1.to_i, $2.to_i) when 100_000..999_999 by_code_and_add_on(*key.divmod(100)) when 0..9999, /\A\d{4}\z/ case add_on when nil by_code(key.to_i) when 0..99, /\A\d+\z/ by_code_and_add_on(key.to_i, add_on.to_i) when String by_code_and_name(key.to_i, add_on) else raise ArgumentError, "Expected a String, an Integer between 0 and 99, or a String containing an integer between 0 and 99, " \ "but got #{key.class}: #{key.inspect}" end when String by_name(key) else raise ArgumentError, "Expected a String, an Integer between 1000 and 9999, or an " \ "Integer between 100_000 and 999_999, but got #{key.class}:" \ "#{key.inspect}" end end
[ "def", "[]", "(", "key", ",", "add_on", "=", "nil", ")", "case", "key", "when", "/", "\\A", "\\d", "\\d", "\\d", "\\z", "/", "by_code_and_add_on", "(", "$1", ".", "to_i", ",", "$2", ".", "to_i", ")", "when", "100_000", "..", "999_999", "by_code_and_add_on", "(", "*", "key", ".", "divmod", "(", "100", ")", ")", "when", "0", "..", "9999", ",", "/", "\\A", "\\d", "\\z", "/", "case", "add_on", "when", "nil", "by_code", "(", "key", ".", "to_i", ")", "when", "0", "..", "99", ",", "/", "\\A", "\\d", "\\z", "/", "by_code_and_add_on", "(", "key", ".", "to_i", ",", "add_on", ".", "to_i", ")", "when", "String", "by_code_and_name", "(", "key", ".", "to_i", ",", "add_on", ")", "else", "raise", "ArgumentError", ",", "\"Expected a String, an Integer between 0 and 99, or a String containing an integer between 0 and 99, \"", "\"but got #{key.class}: #{key.inspect}\"", "end", "when", "String", "by_name", "(", "key", ")", "else", "raise", "ArgumentError", ",", "\"Expected a String, an Integer between 1000 and 9999, or an \"", "\"Integer between 100_000 and 999_999, but got #{key.class}:\"", "\"#{key.inspect}\"", "end", "end" ]
A convenience method to get one or many zip codes by code, code and add-on, code and city or just city. There are various allowed styles to pass those values. All numeric values can be passed either as Integer or String. You can pass the code and add-on as six-digit number, or you can pass the code as four digit number plus either the add-on or name as second parameter. Or you can pass the code alone, or the name alone. @example All usage styles zip_codes[805200] # zip code 8052, add-on 0 zip_codes["805200"] # zip code 8052, add-on 0 zip_codes[8052, 0] # zip code 8052, add-on 0 zip_codes["8052", 0] # zip code 8052, add-on 0 zip_codes[8052, "0"] # zip code 8052, add-on 0 zip_codes["8052", 0] # zip code 8052, add-on 0 zip_codes[8052, "Zürich"] # zip code 8052, add-on 0 zip_codes["8052", "Zürich"] # zip code 8052, add-on 0 zip_codes[8052] # all zip codes with code 8052 zip_codes["8052"] # all zip codes with code 8052 zip_codes["Zürich"] # all zip codes with name "Zürich" @see #by_code_and_add_on Get a zip code by code and add-on directly @see #by_code_and_name Get a zip code by code and name directly @see #by_name Get a collection of zip codes by name directly @see #by_ordering_number Get a zip code by its ONRP directly (#[] can't do that) @param [String, Integer] key Either the zip code, zip code and add-on @return [SwissMatch::ZipCode, SwissMatch::ZipCodes] Either a SwissMatch::ZipCodes collection of zip codes or a single SwissMatch::ZipCode, depending on the argument you pass.
[ "A", "convenience", "method", "to", "get", "one", "or", "many", "zip", "codes", "by", "code", "code", "and", "add", "-", "on", "code", "and", "city", "or", "just", "city", ".", "There", "are", "various", "allowed", "styles", "to", "pass", "those", "values", ".", "All", "numeric", "values", "can", "be", "passed", "either", "as", "Integer", "or", "String", ".", "You", "can", "pass", "the", "code", "and", "add", "-", "on", "as", "six", "-", "digit", "number", "or", "you", "can", "pass", "the", "code", "as", "four", "digit", "number", "plus", "either", "the", "add", "-", "on", "or", "name", "as", "second", "parameter", ".", "Or", "you", "can", "pass", "the", "code", "alone", "or", "the", "name", "alone", "." ]
9d360149f29a3e876a55338833e5e6fe89e3622f
https://github.com/apeiros/swissmatch-location/blob/9d360149f29a3e876a55338833e5e6fe89e3622f/lib/swissmatch/zipcodes.rb#L67-L94
train
pboling/csv_pirate
lib/csv_pirate/the_capn.rb
CsvPirate.TheCapn.poop_deck
def poop_deck(brig) if BRIGANTINE_OPTIONS.include?(brig) && !self.flies.empty? self.old_csv_dump(brig) elsif brig.is_a?(String) "#{self.analemma}#{brig}" else "#{self.analemma}#{self.swabbie}#{self.aft}" end end
ruby
def poop_deck(brig) if BRIGANTINE_OPTIONS.include?(brig) && !self.flies.empty? self.old_csv_dump(brig) elsif brig.is_a?(String) "#{self.analemma}#{brig}" else "#{self.analemma}#{self.swabbie}#{self.aft}" end end
[ "def", "poop_deck", "(", "brig", ")", "if", "BRIGANTINE_OPTIONS", ".", "include?", "(", "brig", ")", "&&", "!", "self", ".", "flies", ".", "empty?", "self", ".", "old_csv_dump", "(", "brig", ")", "elsif", "brig", ".", "is_a?", "(", "String", ")", "\"#{self.analemma}#{brig}\"", "else", "\"#{self.analemma}#{self.swabbie}#{self.aft}\"", "end", "end" ]
complete file path
[ "complete", "file", "path" ]
3fb0bde9a49b3894bde45d2668fc258eebd61049
https://github.com/pboling/csv_pirate/blob/3fb0bde9a49b3894bde45d2668fc258eebd61049/lib/csv_pirate/the_capn.rb#L277-L285
train
pboling/csv_pirate
lib/csv_pirate/the_capn.rb
CsvPirate.TheCapn.unfurl
def unfurl wibbly = self.waggoner == '' ? '' : Regexp.escape(self.waggoner) timey = self.sand_glass == '' ? '' : '\.\d+' wimey = self.gibbet == '' ? '' : Regexp.escape(self.gibbet) Regexp.new("#{wibbly}#{timey}#{wimey}") end
ruby
def unfurl wibbly = self.waggoner == '' ? '' : Regexp.escape(self.waggoner) timey = self.sand_glass == '' ? '' : '\.\d+' wimey = self.gibbet == '' ? '' : Regexp.escape(self.gibbet) Regexp.new("#{wibbly}#{timey}#{wimey}") end
[ "def", "unfurl", "wibbly", "=", "self", ".", "waggoner", "==", "''", "?", "''", ":", "Regexp", ".", "escape", "(", "self", ".", "waggoner", ")", "timey", "=", "self", ".", "sand_glass", "==", "''", "?", "''", ":", "'\\.\\d+'", "wimey", "=", "self", ".", "gibbet", "==", "''", "?", "''", ":", "Regexp", ".", "escape", "(", "self", ".", "gibbet", ")", "Regexp", ".", "new", "(", "\"#{wibbly}#{timey}#{wimey}\"", ")", "end" ]
Regex for matching dumped CSVs
[ "Regex", "for", "matching", "dumped", "CSVs" ]
3fb0bde9a49b3894bde45d2668fc258eebd61049
https://github.com/pboling/csv_pirate/blob/3fb0bde9a49b3894bde45d2668fc258eebd61049/lib/csv_pirate/the_capn.rb#L432-L437
train
pboling/csv_pirate
lib/csv_pirate/the_capn.rb
CsvPirate.TheCapn.binnacle
def binnacle(join_value, humanize = true) self.booty.map do |compass| string = compass.is_a?(Hash) ? self.run_through(compass, join_value) : compass.is_a?(String) ? compass : compass.is_a?(Symbol) ? compass.to_s : compass.to_s humanize ? string.to_s.gsub(/_id$/, "").gsub(/_/, " ").capitalize : string end end
ruby
def binnacle(join_value, humanize = true) self.booty.map do |compass| string = compass.is_a?(Hash) ? self.run_through(compass, join_value) : compass.is_a?(String) ? compass : compass.is_a?(Symbol) ? compass.to_s : compass.to_s humanize ? string.to_s.gsub(/_id$/, "").gsub(/_/, " ").capitalize : string end end
[ "def", "binnacle", "(", "join_value", ",", "humanize", "=", "true", ")", "self", ".", "booty", ".", "map", "do", "|", "compass", "|", "string", "=", "compass", ".", "is_a?", "(", "Hash", ")", "?", "self", ".", "run_through", "(", "compass", ",", "join_value", ")", ":", "compass", ".", "is_a?", "(", "String", ")", "?", "compass", ":", "compass", ".", "is_a?", "(", "Symbol", ")", "?", "compass", ".", "to_s", ":", "compass", ".", "to_s", "humanize", "?", "string", ".", "to_s", ".", "gsub", "(", "/", "/", ",", "\"\"", ")", ".", "gsub", "(", "/", "/", ",", "\" \"", ")", ".", "capitalize", ":", "string", "end", "end" ]
returns an array of strings for CSV header based on booty
[ "returns", "an", "array", "of", "strings", "for", "CSV", "header", "based", "on", "booty" ]
3fb0bde9a49b3894bde45d2668fc258eebd61049
https://github.com/pboling/csv_pirate/blob/3fb0bde9a49b3894bde45d2668fc258eebd61049/lib/csv_pirate/the_capn.rb#L457-L468
train
pboling/csv_pirate
lib/csv_pirate/the_capn.rb
CsvPirate.TheCapn.boatswain
def boatswain return self.swabbie unless self.swabbie.nil? highval = 0 self.axe.each do |flotsam| counter = self.filibuster(flotsam) highval = ((highval <=> counter) == 1) ? highval : counter end ".#{highval + 1}" end
ruby
def boatswain return self.swabbie unless self.swabbie.nil? highval = 0 self.axe.each do |flotsam| counter = self.filibuster(flotsam) highval = ((highval <=> counter) == 1) ? highval : counter end ".#{highval + 1}" end
[ "def", "boatswain", "return", "self", ".", "swabbie", "unless", "self", ".", "swabbie", ".", "nil?", "highval", "=", "0", "self", ".", "axe", ".", "each", "do", "|", "flotsam", "|", "counter", "=", "self", ".", "filibuster", "(", "flotsam", ")", "highval", "=", "(", "(", "highval", "<=>", "counter", ")", "==", "1", ")", "?", "highval", ":", "counter", "end", "\".#{highval + 1}\"", "end" ]
File increment for next CSV to dump
[ "File", "increment", "for", "next", "CSV", "to", "dump" ]
3fb0bde9a49b3894bde45d2668fc258eebd61049
https://github.com/pboling/csv_pirate/blob/3fb0bde9a49b3894bde45d2668fc258eebd61049/lib/csv_pirate/the_capn.rb#L517-L525
train
scrapper/perobs
lib/perobs/FlatFileBlobHeader.rb
PEROBS.FlatFileBlobHeader.write
def write begin buf = [ @flags, @length, @id, @crc].pack(FORMAT) crc = Zlib.crc32(buf, 0) @file.seek(@addr) @file.write(buf + [ crc ].pack('L')) rescue IOError => e PEROBS.log.fatal "Cannot write blob header into flat file DB: " + e.message end end
ruby
def write begin buf = [ @flags, @length, @id, @crc].pack(FORMAT) crc = Zlib.crc32(buf, 0) @file.seek(@addr) @file.write(buf + [ crc ].pack('L')) rescue IOError => e PEROBS.log.fatal "Cannot write blob header into flat file DB: " + e.message end end
[ "def", "write", "begin", "buf", "=", "[", "@flags", ",", "@length", ",", "@id", ",", "@crc", "]", ".", "pack", "(", "FORMAT", ")", "crc", "=", "Zlib", ".", "crc32", "(", "buf", ",", "0", ")", "@file", ".", "seek", "(", "@addr", ")", "@file", ".", "write", "(", "buf", "+", "[", "crc", "]", ".", "pack", "(", "'L'", ")", ")", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot write blob header into flat file DB: \"", "+", "e", ".", "message", "end", "end" ]
Write the header to a given File.
[ "Write", "the", "header", "to", "a", "given", "File", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/FlatFileBlobHeader.rb#L182-L192
train
jeffnyman/tapestry
lib/tapestry/extensions/dom_observer.rb
Watir.Element.dom_updated?
def dom_updated?(delay: 1.1) element_call do begin driver.manage.timeouts.script_timeout = delay + 1 driver.execute_async_script(DOM_OBSERVER, wd, delay) rescue Selenium::WebDriver::Error::StaleElementReferenceError # This situation can occur when the DOM changes between two calls to # some element or aspect of the page. In this case, we are expecting # the DOM to be different so what's being handled here are those hard # to anticipate race conditions when "weird things happen" and DOM # updating plus script execution get interleaved. retry rescue Selenium::WebDriver::Error::JavascriptError => e # This situation can occur if the script execution has started before # a new page is fully loaded. The specific error being checked for # here is one that occurs when a new page is loaded as that page is # trying to execute a JavaScript function. retry if e.message.include?( 'document unloaded while waiting for result' ) raise ensure # Note that this setting here means any user-defined timeout would # effectively be overwritten. driver.manage.timeouts.script_timeout = 1 end end end
ruby
def dom_updated?(delay: 1.1) element_call do begin driver.manage.timeouts.script_timeout = delay + 1 driver.execute_async_script(DOM_OBSERVER, wd, delay) rescue Selenium::WebDriver::Error::StaleElementReferenceError # This situation can occur when the DOM changes between two calls to # some element or aspect of the page. In this case, we are expecting # the DOM to be different so what's being handled here are those hard # to anticipate race conditions when "weird things happen" and DOM # updating plus script execution get interleaved. retry rescue Selenium::WebDriver::Error::JavascriptError => e # This situation can occur if the script execution has started before # a new page is fully loaded. The specific error being checked for # here is one that occurs when a new page is loaded as that page is # trying to execute a JavaScript function. retry if e.message.include?( 'document unloaded while waiting for result' ) raise ensure # Note that this setting here means any user-defined timeout would # effectively be overwritten. driver.manage.timeouts.script_timeout = 1 end end end
[ "def", "dom_updated?", "(", "delay", ":", "1.1", ")", "element_call", "do", "begin", "driver", ".", "manage", ".", "timeouts", ".", "script_timeout", "=", "delay", "+", "1", "driver", ".", "execute_async_script", "(", "DOM_OBSERVER", ",", "wd", ",", "delay", ")", "rescue", "Selenium", "::", "WebDriver", "::", "Error", "::", "StaleElementReferenceError", "retry", "rescue", "Selenium", "::", "WebDriver", "::", "Error", "::", "JavascriptError", "=>", "e", "retry", "if", "e", ".", "message", ".", "include?", "(", "'document unloaded while waiting for result'", ")", "raise", "ensure", "driver", ".", "manage", ".", "timeouts", ".", "script_timeout", "=", "1", "end", "end", "end" ]
This method makes a call to `execute_async_script` which means that the DOM observer script must explicitly signal that it is finished by invoking a callback. In this case, the callback is nothing more than a delay. The delay is being used to allow the DOM to be updated before script actions continue. The method returns true if the DOM has been changed within the element context, while false means that the DOM has not yet finished changing. Note the wording: "has not finished changing." It's known that the DOM is changing because the observer has recognized that. So the question this method is helping to answer is "has it finished?" Consider the following element definition: p :page_list, id: 'navlist' You could then do this: page_list.dom_updated? That would return true if the DOM content for page_list has finished updating. If the DOM was in the process of being updated, this would return false. You could also do this: page_list.wait_until(&:dom_updated?).click This will use Watir's wait until functionality to wait for the DOM to be updated within the context of the element. Note that the "&:" is that the object that `dom_updated?` is being called on (in this case `page_list`) substitutes the ampersand. You can also structure it like this: page_list.wait_until do |element| element.dom_updated? end The default delay of waiting for the DOM to start updating is 1.1 second. However, you can pass a delay value when you call the method to set your own value, which can be useful for particular sensitivities in the application you are testing.
[ "This", "method", "makes", "a", "call", "to", "execute_async_script", "which", "means", "that", "the", "DOM", "observer", "script", "must", "explicitly", "signal", "that", "it", "is", "finished", "by", "invoking", "a", "callback", ".", "In", "this", "case", "the", "callback", "is", "nothing", "more", "than", "a", "delay", ".", "The", "delay", "is", "being", "used", "to", "allow", "the", "DOM", "to", "be", "updated", "before", "script", "actions", "continue", "." ]
da28652dd6de71e415cd2c01afd89f641938a05b
https://github.com/jeffnyman/tapestry/blob/da28652dd6de71e415cd2c01afd89f641938a05b/lib/tapestry/extensions/dom_observer.rb#L46-L73
train
scrapper/perobs
lib/perobs/DataBase.rb
PEROBS.DataBase.serialize
def serialize(obj) begin case @serializer when :marshal Marshal.dump(obj) when :json obj.to_json when :yaml YAML.dump(obj) end rescue => e PEROBS.log.fatal "Cannot serialize object as #{@serializer}: " + e.message end end
ruby
def serialize(obj) begin case @serializer when :marshal Marshal.dump(obj) when :json obj.to_json when :yaml YAML.dump(obj) end rescue => e PEROBS.log.fatal "Cannot serialize object as #{@serializer}: " + e.message end end
[ "def", "serialize", "(", "obj", ")", "begin", "case", "@serializer", "when", ":marshal", "Marshal", ".", "dump", "(", "obj", ")", "when", ":json", "obj", ".", "to_json", "when", ":yaml", "YAML", ".", "dump", "(", "obj", ")", "end", "rescue", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot serialize object as #{@serializer}: \"", "+", "e", ".", "message", "end", "end" ]
Serialize the given object using the object serializer. @param obj [ObjectBase] Object to serialize @return [String] Serialized version
[ "Serialize", "the", "given", "object", "using", "the", "object", "serializer", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/DataBase.rb#L64-L78
train
scrapper/perobs
lib/perobs/DataBase.rb
PEROBS.DataBase.deserialize
def deserialize(raw) begin case @serializer when :marshal Marshal.load(raw) when :json JSON.parse(raw, :create_additions => true) when :yaml YAML.load(raw) end rescue => e PEROBS.log.fatal "Cannot de-serialize object with #{@serializer} " + "parser: " + e.message end end
ruby
def deserialize(raw) begin case @serializer when :marshal Marshal.load(raw) when :json JSON.parse(raw, :create_additions => true) when :yaml YAML.load(raw) end rescue => e PEROBS.log.fatal "Cannot de-serialize object with #{@serializer} " + "parser: " + e.message end end
[ "def", "deserialize", "(", "raw", ")", "begin", "case", "@serializer", "when", ":marshal", "Marshal", ".", "load", "(", "raw", ")", "when", ":json", "JSON", ".", "parse", "(", "raw", ",", ":create_additions", "=>", "true", ")", "when", ":yaml", "YAML", ".", "load", "(", "raw", ")", "end", "rescue", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot de-serialize object with #{@serializer} \"", "+", "\"parser: \"", "+", "e", ".", "message", "end", "end" ]
De-serialize the given String into a Ruby object. @param raw [String] @return [Hash] Deserialized version
[ "De", "-", "serialize", "the", "given", "String", "into", "a", "Ruby", "object", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/DataBase.rb#L83-L97
train
scrapper/perobs
lib/perobs/DataBase.rb
PEROBS.DataBase.check_option
def check_option(name) value = instance_variable_get('@' + name) if @config.include?(name) # The database already existed and has a setting for this config # option. If it does not match the instance variable, adjust the # instance variable accordingly. unless @config[name] == value instance_variable_set('@' + name, @config[name]) end else # There is no such config option yet. Create it with the value of the # corresponding instance variable. @config[name] = value end end
ruby
def check_option(name) value = instance_variable_get('@' + name) if @config.include?(name) # The database already existed and has a setting for this config # option. If it does not match the instance variable, adjust the # instance variable accordingly. unless @config[name] == value instance_variable_set('@' + name, @config[name]) end else # There is no such config option yet. Create it with the value of the # corresponding instance variable. @config[name] = value end end
[ "def", "check_option", "(", "name", ")", "value", "=", "instance_variable_get", "(", "'@'", "+", "name", ")", "if", "@config", ".", "include?", "(", "name", ")", "unless", "@config", "[", "name", "]", "==", "value", "instance_variable_set", "(", "'@'", "+", "name", ",", "@config", "[", "name", "]", ")", "end", "else", "@config", "[", "name", "]", "=", "value", "end", "end" ]
Check a config option and adjust it if needed. @param name [String] Name of the config option.
[ "Check", "a", "config", "option", "and", "adjust", "it", "if", "needed", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/DataBase.rb#L101-L116
train
scrapper/perobs
lib/perobs/DataBase.rb
PEROBS.DataBase.ensure_dir_exists
def ensure_dir_exists(dir) unless Dir.exist?(dir) begin Dir.mkdir(dir) rescue IOError => e PEROBS.log.fatal "Cannote create DB directory '#{dir}': #{e.message}" end end end
ruby
def ensure_dir_exists(dir) unless Dir.exist?(dir) begin Dir.mkdir(dir) rescue IOError => e PEROBS.log.fatal "Cannote create DB directory '#{dir}': #{e.message}" end end end
[ "def", "ensure_dir_exists", "(", "dir", ")", "unless", "Dir", ".", "exist?", "(", "dir", ")", "begin", "Dir", ".", "mkdir", "(", "dir", ")", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannote create DB directory '#{dir}': #{e.message}\"", "end", "end", "end" ]
Ensure that we have a directory to store the DB items.
[ "Ensure", "that", "we", "have", "a", "directory", "to", "store", "the", "DB", "items", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/DataBase.rb#L121-L129
train
xinminlabs/synvert-core
lib/synvert/core/rewriter/gem_spec.rb
Synvert::Core.Rewriter::GemSpec.match?
def match? gemfile_lock_path = File.join(Configuration.instance.get(:path), 'Gemfile.lock') if File.exists? gemfile_lock_path parser = Bundler::LockfileParser.new(File.read(gemfile_lock_path)) if spec = parser.specs.find { |spec| spec.name == @name } Gem::Version.new(spec.version).send(OPERATORS[@operator], @version) else false end else raise GemfileLockNotFound.new 'Gemfile.lock does not exist' end end
ruby
def match? gemfile_lock_path = File.join(Configuration.instance.get(:path), 'Gemfile.lock') if File.exists? gemfile_lock_path parser = Bundler::LockfileParser.new(File.read(gemfile_lock_path)) if spec = parser.specs.find { |spec| spec.name == @name } Gem::Version.new(spec.version).send(OPERATORS[@operator], @version) else false end else raise GemfileLockNotFound.new 'Gemfile.lock does not exist' end end
[ "def", "match?", "gemfile_lock_path", "=", "File", ".", "join", "(", "Configuration", ".", "instance", ".", "get", "(", ":path", ")", ",", "'Gemfile.lock'", ")", "if", "File", ".", "exists?", "gemfile_lock_path", "parser", "=", "Bundler", "::", "LockfileParser", ".", "new", "(", "File", ".", "read", "(", "gemfile_lock_path", ")", ")", "if", "spec", "=", "parser", ".", "specs", ".", "find", "{", "|", "spec", "|", "spec", ".", "name", "==", "@name", "}", "Gem", "::", "Version", ".", "new", "(", "spec", ".", "version", ")", ".", "send", "(", "OPERATORS", "[", "@operator", "]", ",", "@version", ")", "else", "false", "end", "else", "raise", "GemfileLockNotFound", ".", "new", "'Gemfile.lock does not exist'", "end", "end" ]
Initialize a gem_spec. @param name [String] gem name @param comparator [Hash] comparator to gem version, e.g. {eq: '2.0.0'}, comparator key can be eq, lt, gt, lte, gte or ne. Check if the specified gem version in Gemfile.lock matches gem_spec comparator. @return [Boolean] true if matches, otherwise false. @raise [Synvert::Core::GemfileLockNotFound] raise if Gemfile.lock does not exist.
[ "Initialize", "a", "gem_spec", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/rewriter/gem_spec.rb#L28-L40
train
sethvargo/community-zero
lib/community_zero/endpoints/cookbook_versions_version_endpoint.rb
CommunityZero.CookbookVersionsVersionEndpoint.response_hash_for
def response_hash_for(cookbook) { 'cookbook' => url_for(cookbook), 'average_rating' => cookbook.average_rating, 'version' => cookbook.version, 'license' => cookbook.license, 'file' => "http://s3.amazonaws.com/#{cookbook.name}.tgz", 'tarball_file_size' => cookbook.name.split('').map(&:ord).inject(&:+) * 25, # don't even 'created_at' => cookbook.created_at, 'updated_at' => cookbook.upadated_at, } end
ruby
def response_hash_for(cookbook) { 'cookbook' => url_for(cookbook), 'average_rating' => cookbook.average_rating, 'version' => cookbook.version, 'license' => cookbook.license, 'file' => "http://s3.amazonaws.com/#{cookbook.name}.tgz", 'tarball_file_size' => cookbook.name.split('').map(&:ord).inject(&:+) * 25, # don't even 'created_at' => cookbook.created_at, 'updated_at' => cookbook.upadated_at, } end
[ "def", "response_hash_for", "(", "cookbook", ")", "{", "'cookbook'", "=>", "url_for", "(", "cookbook", ")", ",", "'average_rating'", "=>", "cookbook", ".", "average_rating", ",", "'version'", "=>", "cookbook", ".", "version", ",", "'license'", "=>", "cookbook", ".", "license", ",", "'file'", "=>", "\"http://s3.amazonaws.com/#{cookbook.name}.tgz\"", ",", "'tarball_file_size'", "=>", "cookbook", ".", "name", ".", "split", "(", "''", ")", ".", "map", "(", "&", ":ord", ")", ".", "inject", "(", "&", ":+", ")", "*", "25", ",", "'created_at'", "=>", "cookbook", ".", "created_at", ",", "'updated_at'", "=>", "cookbook", ".", "upadated_at", ",", "}", "end" ]
The response hash for this cookbook. @param [CommunityZero::Cookbook] cookbook the cookbook to generate a hash for
[ "The", "response", "hash", "for", "this", "cookbook", "." ]
08a22c47c865deb6a5f931cb4d9f747a2b9d3459
https://github.com/sethvargo/community-zero/blob/08a22c47c865deb6a5f931cb4d9f747a2b9d3459/lib/community_zero/endpoints/cookbook_versions_version_endpoint.rb#L45-L56
train
notonthehighstreet/chicago
lib/chicago/query.rb
Chicago.Query.order
def order(*ordering) @order = ordering.map do |c| if c.kind_of?(String) {:column => c, :ascending => true} else c.symbolize_keys! end end self end
ruby
def order(*ordering) @order = ordering.map do |c| if c.kind_of?(String) {:column => c, :ascending => true} else c.symbolize_keys! end end self end
[ "def", "order", "(", "*", "ordering", ")", "@order", "=", "ordering", ".", "map", "do", "|", "c", "|", "if", "c", ".", "kind_of?", "(", "String", ")", "{", ":column", "=>", "c", ",", ":ascending", "=>", "true", "}", "else", "c", ".", "symbolize_keys!", "end", "end", "self", "end" ]
Order the results by the specified columns. @param ordering an array of hashes, of the form {:column => "name", :ascending => true} @api public
[ "Order", "the", "results", "by", "the", "specified", "columns", "." ]
428e94f8089d2f36fdcff2e27ea2af572b816def
https://github.com/notonthehighstreet/chicago/blob/428e94f8089d2f36fdcff2e27ea2af572b816def/lib/chicago/query.rb#L79-L88
train
scrapper/perobs
lib/perobs/StackFile.rb
PEROBS.StackFile.close
def close begin @f.flush @f.flock(File::LOCK_UN) @f.close rescue IOError => e PEROBS.log.fatal "Cannot close stack file #{@file_name}: #{e.message}" end end
ruby
def close begin @f.flush @f.flock(File::LOCK_UN) @f.close rescue IOError => e PEROBS.log.fatal "Cannot close stack file #{@file_name}: #{e.message}" end end
[ "def", "close", "begin", "@f", ".", "flush", "@f", ".", "flock", "(", "File", "::", "LOCK_UN", ")", "@f", ".", "close", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot close stack file #{@file_name}: #{e.message}\"", "end", "end" ]
Close the stack file. This method must be called before the program is terminated to avoid data loss.
[ "Close", "the", "stack", "file", ".", "This", "method", "must", "be", "called", "before", "the", "program", "is", "terminated", "to", "avoid", "data", "loss", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/StackFile.rb#L64-L72
train
scrapper/perobs
lib/perobs/StackFile.rb
PEROBS.StackFile.push
def push(bytes) if bytes.length != @entry_bytes PEROBS.log.fatal "All stack entries must be #{@entry_bytes} " + "long. This entry is #{bytes.length} bytes long." end begin @f.seek(0, IO::SEEK_END) @f.write(bytes) rescue => e PEROBS.log.fatal "Cannot push to stack file #{@file_name}: #{e.message}" end end
ruby
def push(bytes) if bytes.length != @entry_bytes PEROBS.log.fatal "All stack entries must be #{@entry_bytes} " + "long. This entry is #{bytes.length} bytes long." end begin @f.seek(0, IO::SEEK_END) @f.write(bytes) rescue => e PEROBS.log.fatal "Cannot push to stack file #{@file_name}: #{e.message}" end end
[ "def", "push", "(", "bytes", ")", "if", "bytes", ".", "length", "!=", "@entry_bytes", "PEROBS", ".", "log", ".", "fatal", "\"All stack entries must be #{@entry_bytes} \"", "+", "\"long. This entry is #{bytes.length} bytes long.\"", "end", "begin", "@f", ".", "seek", "(", "0", ",", "IO", "::", "SEEK_END", ")", "@f", ".", "write", "(", "bytes", ")", "rescue", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot push to stack file #{@file_name}: #{e.message}\"", "end", "end" ]
Push the given bytes onto the stack file. @param bytes [String] Bytes to write.
[ "Push", "the", "given", "bytes", "onto", "the", "stack", "file", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/StackFile.rb#L85-L96
train
scrapper/perobs
lib/perobs/StackFile.rb
PEROBS.StackFile.pop
def pop begin return nil if @f.size == 0 @f.seek(-@entry_bytes, IO::SEEK_END) bytes = @f.read(@entry_bytes) @f.truncate(@f.size - @entry_bytes) @f.flush rescue => e PEROBS.log.fatal "Cannot pop from stack file #{@file_name}: " + e.message end bytes end
ruby
def pop begin return nil if @f.size == 0 @f.seek(-@entry_bytes, IO::SEEK_END) bytes = @f.read(@entry_bytes) @f.truncate(@f.size - @entry_bytes) @f.flush rescue => e PEROBS.log.fatal "Cannot pop from stack file #{@file_name}: " + e.message end bytes end
[ "def", "pop", "begin", "return", "nil", "if", "@f", ".", "size", "==", "0", "@f", ".", "seek", "(", "-", "@entry_bytes", ",", "IO", "::", "SEEK_END", ")", "bytes", "=", "@f", ".", "read", "(", "@entry_bytes", ")", "@f", ".", "truncate", "(", "@f", ".", "size", "-", "@entry_bytes", ")", "@f", ".", "flush", "rescue", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot pop from stack file #{@file_name}: \"", "+", "e", ".", "message", "end", "bytes", "end" ]
Pop the last entry from the stack file. @return [String or nil] Popped entry or nil if stack is already empty.
[ "Pop", "the", "last", "entry", "from", "the", "stack", "file", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/StackFile.rb#L100-L114
train
tagoh/ruby-bugzilla
lib/bugzilla/bug.rb
Bugzilla.Bug.get_comments
def get_comments(bugs) params = {} if bugs.kind_of?(Array) then params['ids'] = bugs elsif bugs.kind_of?(Integer) || bugs.kind_of?(String) then params['ids'] = [bugs] else raise ArgumentError, sprintf("Unknown type of arguments: %s", bugs.class) end result = comments(params) # not supporting comment_ids. so drop "comments". result['bugs'] end
ruby
def get_comments(bugs) params = {} if bugs.kind_of?(Array) then params['ids'] = bugs elsif bugs.kind_of?(Integer) || bugs.kind_of?(String) then params['ids'] = [bugs] else raise ArgumentError, sprintf("Unknown type of arguments: %s", bugs.class) end result = comments(params) # not supporting comment_ids. so drop "comments". result['bugs'] end
[ "def", "get_comments", "(", "bugs", ")", "params", "=", "{", "}", "if", "bugs", ".", "kind_of?", "(", "Array", ")", "then", "params", "[", "'ids'", "]", "=", "bugs", "elsif", "bugs", ".", "kind_of?", "(", "Integer", ")", "||", "bugs", ".", "kind_of?", "(", "String", ")", "then", "params", "[", "'ids'", "]", "=", "[", "bugs", "]", "else", "raise", "ArgumentError", ",", "sprintf", "(", "\"Unknown type of arguments: %s\"", ",", "bugs", ".", "class", ")", "end", "result", "=", "comments", "(", "params", ")", "result", "[", "'bugs'", "]", "end" ]
def get_bugs =begin rdoc ==== Bugzilla::Bug#get_comments(bugs) =end
[ "def", "get_bugs", "=", "begin", "rdoc" ]
5aabec1b045473bcd6e6ac7427b68adb3e3b4886
https://github.com/tagoh/ruby-bugzilla/blob/5aabec1b045473bcd6e6ac7427b68adb3e3b4886/lib/bugzilla/bug.rb#L107-L123
train
jeffnyman/tapestry
lib/tapestry/ready.rb
Tapestry.Ready.when_ready
def when_ready(simple_check = false, &_block) already_marked_ready = ready unless simple_check no_ready_check_possible unless block_given? end self.ready = ready? not_ready_validation(ready_error || 'NO REASON PROVIDED') unless ready yield self if block_given? ensure self.ready = already_marked_ready end
ruby
def when_ready(simple_check = false, &_block) already_marked_ready = ready unless simple_check no_ready_check_possible unless block_given? end self.ready = ready? not_ready_validation(ready_error || 'NO REASON PROVIDED') unless ready yield self if block_given? ensure self.ready = already_marked_ready end
[ "def", "when_ready", "(", "simple_check", "=", "false", ",", "&", "_block", ")", "already_marked_ready", "=", "ready", "unless", "simple_check", "no_ready_check_possible", "unless", "block_given?", "end", "self", ".", "ready", "=", "ready?", "not_ready_validation", "(", "ready_error", "||", "'NO REASON PROVIDED'", ")", "unless", "ready", "yield", "self", "if", "block_given?", "ensure", "self", ".", "ready", "=", "already_marked_ready", "end" ]
The `when_ready` method is called on an instance of an interface. This executes the provided validation block after the page has been loaded. The Ready object instance is yielded into the block. Calls to the `ready?` method use a poor-man's cache approach. The idea here being that when a page has confirmed that it is ready, meaning that no ready validations have failed, that information is stored so that any subsequent calls to `ready?` do not query the ready validations again.
[ "The", "when_ready", "method", "is", "called", "on", "an", "instance", "of", "an", "interface", ".", "This", "executes", "the", "provided", "validation", "block", "after", "the", "page", "has", "been", "loaded", ".", "The", "Ready", "object", "instance", "is", "yielded", "into", "the", "block", "." ]
da28652dd6de71e415cd2c01afd89f641938a05b
https://github.com/jeffnyman/tapestry/blob/da28652dd6de71e415cd2c01afd89f641938a05b/lib/tapestry/ready.rb#L55-L68
train
jeffnyman/tapestry
lib/tapestry/ready.rb
Tapestry.Ready.ready_validations_pass?
def ready_validations_pass? self.class.ready_validations.all? do |validation| passed, message = instance_eval(&validation) self.ready_error = message if message && !passed passed end end
ruby
def ready_validations_pass? self.class.ready_validations.all? do |validation| passed, message = instance_eval(&validation) self.ready_error = message if message && !passed passed end end
[ "def", "ready_validations_pass?", "self", ".", "class", ".", "ready_validations", ".", "all?", "do", "|", "validation", "|", "passed", ",", "message", "=", "instance_eval", "(", "&", "validation", ")", "self", ".", "ready_error", "=", "message", "if", "message", "&&", "!", "passed", "passed", "end", "end" ]
This method checks if the ready validations that have been specified have passed. If any ready validation fails, no matter if others have succeeded, this method immediately returns false.
[ "This", "method", "checks", "if", "the", "ready", "validations", "that", "have", "been", "specified", "have", "passed", ".", "If", "any", "ready", "validation", "fails", "no", "matter", "if", "others", "have", "succeeded", "this", "method", "immediately", "returns", "false", "." ]
da28652dd6de71e415cd2c01afd89f641938a05b
https://github.com/jeffnyman/tapestry/blob/da28652dd6de71e415cd2c01afd89f641938a05b/lib/tapestry/ready.rb#L92-L98
train
xinminlabs/synvert-core
lib/synvert/core/rewriter/condition/unless_exist_condition.rb
Synvert::Core.Rewriter::UnlessExistCondition.match?
def match? match = false @instance.current_node.recursive_children do |child_node| match = match || (child_node && child_node.match?(@rules)) end !match end
ruby
def match? match = false @instance.current_node.recursive_children do |child_node| match = match || (child_node && child_node.match?(@rules)) end !match end
[ "def", "match?", "match", "=", "false", "@instance", ".", "current_node", ".", "recursive_children", "do", "|", "child_node", "|", "match", "=", "match", "||", "(", "child_node", "&&", "child_node", ".", "match?", "(", "@rules", ")", ")", "end", "!", "match", "end" ]
check if none of child node matches the rules.
[ "check", "if", "none", "of", "child", "node", "matches", "the", "rules", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/rewriter/condition/unless_exist_condition.rb#L7-L13
train
pupeno/random_unique_id
lib/random_unique_id.rb
RandomUniqueId.ClassMethods.add_rid_related_validations
def add_rid_related_validations(options) validates(options[:field], presence: true) validates(options[:field], uniqueness: true) if options[:random_generation_method] != :uuid # If we're generating UUIDs, don't check for uniqueness end
ruby
def add_rid_related_validations(options) validates(options[:field], presence: true) validates(options[:field], uniqueness: true) if options[:random_generation_method] != :uuid # If we're generating UUIDs, don't check for uniqueness end
[ "def", "add_rid_related_validations", "(", "options", ")", "validates", "(", "options", "[", ":field", "]", ",", "presence", ":", "true", ")", "validates", "(", "options", "[", ":field", "]", ",", "uniqueness", ":", "true", ")", "if", "options", "[", ":random_generation_method", "]", "!=", ":uuid", "end" ]
Add the rid related validations to the model. @param options [Hash] same as in RandomUniqueID.config
[ "Add", "the", "rid", "related", "validations", "to", "the", "model", "." ]
bab61f23a17a3f6ba9f7bc255805d4f9d34b8bfc
https://github.com/pupeno/random_unique_id/blob/bab61f23a17a3f6ba9f7bc255805d4f9d34b8bfc/lib/random_unique_id.rb#L118-L121
train
pupeno/random_unique_id
lib/random_unique_id.rb
RandomUniqueId.ClassMethods.define_rid_accessors
def define_rid_accessors(related_class, relationship_name) define_method("#{relationship_name}_rid") do self.send(relationship_name).try(random_unique_id_options[:field]) end define_method("#{relationship_name}_rid=") do |rid| record = related_class.find_by_rid(rid) self.send("#{relationship_name}=", record) record end end
ruby
def define_rid_accessors(related_class, relationship_name) define_method("#{relationship_name}_rid") do self.send(relationship_name).try(random_unique_id_options[:field]) end define_method("#{relationship_name}_rid=") do |rid| record = related_class.find_by_rid(rid) self.send("#{relationship_name}=", record) record end end
[ "def", "define_rid_accessors", "(", "related_class", ",", "relationship_name", ")", "define_method", "(", "\"#{relationship_name}_rid\"", ")", "do", "self", ".", "send", "(", "relationship_name", ")", ".", "try", "(", "random_unique_id_options", "[", ":field", "]", ")", "end", "define_method", "(", "\"#{relationship_name}_rid=\"", ")", "do", "|", "rid", "|", "record", "=", "related_class", ".", "find_by_rid", "(", "rid", ")", "self", ".", "send", "(", "\"#{relationship_name}=\"", ",", "record", ")", "record", "end", "end" ]
Defines the setter and getter for the RID of a relationship. @param related_class [Class] class in which the RID methods are going to be defined. @param relationship_name [String] name of the relationship for which the RID methods are going to be defined. @see RandomUniqueId::ClassMethods.belongs_to
[ "Defines", "the", "setter", "and", "getter", "for", "the", "RID", "of", "a", "relationship", "." ]
bab61f23a17a3f6ba9f7bc255805d4f9d34b8bfc
https://github.com/pupeno/random_unique_id/blob/bab61f23a17a3f6ba9f7bc255805d4f9d34b8bfc/lib/random_unique_id.rb#L128-L138
train
code-and-effect/effective_pages
app/models/effective/menu.rb
Effective.Menu.build
def build(&block) raise 'build must be called with a block' if !block_given? root = menu_items.build(title: 'Home', url: '/', lft: 1, rgt: 2) root.parent = true instance_exec(&block) # A call to dropdown or item root.rgt = menu_items.map(&:rgt).max self end
ruby
def build(&block) raise 'build must be called with a block' if !block_given? root = menu_items.build(title: 'Home', url: '/', lft: 1, rgt: 2) root.parent = true instance_exec(&block) # A call to dropdown or item root.rgt = menu_items.map(&:rgt).max self end
[ "def", "build", "(", "&", "block", ")", "raise", "'build must be called with a block'", "if", "!", "block_given?", "root", "=", "menu_items", ".", "build", "(", "title", ":", "'Home'", ",", "url", ":", "'/'", ",", "lft", ":", "1", ",", "rgt", ":", "2", ")", "root", ".", "parent", "=", "true", "instance_exec", "(", "&", "block", ")", "root", ".", "rgt", "=", "menu_items", ".", "map", "(", "&", ":rgt", ")", ".", "max", "self", "end" ]
This is the entry point to the DSL method for creating menu items
[ "This", "is", "the", "entry", "point", "to", "the", "DSL", "method", "for", "creating", "menu", "items" ]
ff00e2d76055985ab65f570747bc9a5f2748f817
https://github.com/code-and-effect/effective_pages/blob/ff00e2d76055985ab65f570747bc9a5f2748f817/app/models/effective/menu.rb#L58-L66
train
scrapper/perobs
lib/perobs/BTreeNode.rb
PEROBS.BTreeNode.search_key_index
def search_key_index(key) # Handle special case for empty keys list. return 0 if @keys.empty? # Keys are unique and always sorted. Use a binary search to find the # index that fits the given key. li = pi = 0 ui = @keys.size - 1 while li <= ui # The pivot element is always in the middle between the lower and upper # index. pi = li + (ui - li) / 2 if key < @keys[pi] # The pivot element is smaller than the key. Set the upper index to # the pivot index. ui = pi - 1 elsif key > @keys[pi] # The pivot element is larger than the key. Set the lower index to # the pivot index. li = pi + 1 else # We've found an exact match. For leaf nodes return the found index. # For branch nodes we have to add one to the index since the larger # child is the right one. return @is_leaf ? pi : pi + 1 end end # No exact match was found. For the insert operaton we need to return # the index of the first key that is larger than the given key. @keys[pi] < key ? pi + 1 : pi end
ruby
def search_key_index(key) # Handle special case for empty keys list. return 0 if @keys.empty? # Keys are unique and always sorted. Use a binary search to find the # index that fits the given key. li = pi = 0 ui = @keys.size - 1 while li <= ui # The pivot element is always in the middle between the lower and upper # index. pi = li + (ui - li) / 2 if key < @keys[pi] # The pivot element is smaller than the key. Set the upper index to # the pivot index. ui = pi - 1 elsif key > @keys[pi] # The pivot element is larger than the key. Set the lower index to # the pivot index. li = pi + 1 else # We've found an exact match. For leaf nodes return the found index. # For branch nodes we have to add one to the index since the larger # child is the right one. return @is_leaf ? pi : pi + 1 end end # No exact match was found. For the insert operaton we need to return # the index of the first key that is larger than the given key. @keys[pi] < key ? pi + 1 : pi end
[ "def", "search_key_index", "(", "key", ")", "return", "0", "if", "@keys", ".", "empty?", "li", "=", "pi", "=", "0", "ui", "=", "@keys", ".", "size", "-", "1", "while", "li", "<=", "ui", "pi", "=", "li", "+", "(", "ui", "-", "li", ")", "/", "2", "if", "key", "<", "@keys", "[", "pi", "]", "ui", "=", "pi", "-", "1", "elsif", "key", ">", "@keys", "[", "pi", "]", "li", "=", "pi", "+", "1", "else", "return", "@is_leaf", "?", "pi", ":", "pi", "+", "1", "end", "end", "@keys", "[", "pi", "]", "<", "key", "?", "pi", "+", "1", ":", "pi", "end" ]
Search the keys of the node that fits the given key. The result is either the index of an exact match or the index of the position where the given key would have to be inserted. @param key [Integer] key to search for @return [Integer] Index of the matching key or the insert position.
[ "Search", "the", "keys", "of", "the", "node", "that", "fits", "the", "given", "key", ".", "The", "result", "is", "either", "the", "index", "of", "an", "exact", "match", "or", "the", "index", "of", "the", "position", "where", "the", "given", "key", "would", "have", "to", "be", "inserted", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BTreeNode.rb#L563-L594
train
astro/ruby-sasl
lib/sasl/digest_md5.rb
SASL.DigestMD5.response_value
def response_value(nonce, nc, cnonce, qop, a2_prefix='AUTHENTICATE') a1_h = h("#{preferences.username}:#{preferences.realm}:#{preferences.password}") a1 = "#{a1_h}:#{nonce}:#{cnonce}" if preferences.authzid a1 += ":#{preferences.authzid}" end if qop && (qop.downcase == 'auth-int' || qop.downcase == 'auth-conf') a2 = "#{a2_prefix}:#{preferences.digest_uri}:00000000000000000000000000000000" else a2 = "#{a2_prefix}:#{preferences.digest_uri}" end hh("#{hh(a1)}:#{nonce}:#{nc}:#{cnonce}:#{qop}:#{hh(a2)}") end
ruby
def response_value(nonce, nc, cnonce, qop, a2_prefix='AUTHENTICATE') a1_h = h("#{preferences.username}:#{preferences.realm}:#{preferences.password}") a1 = "#{a1_h}:#{nonce}:#{cnonce}" if preferences.authzid a1 += ":#{preferences.authzid}" end if qop && (qop.downcase == 'auth-int' || qop.downcase == 'auth-conf') a2 = "#{a2_prefix}:#{preferences.digest_uri}:00000000000000000000000000000000" else a2 = "#{a2_prefix}:#{preferences.digest_uri}" end hh("#{hh(a1)}:#{nonce}:#{nc}:#{cnonce}:#{qop}:#{hh(a2)}") end
[ "def", "response_value", "(", "nonce", ",", "nc", ",", "cnonce", ",", "qop", ",", "a2_prefix", "=", "'AUTHENTICATE'", ")", "a1_h", "=", "h", "(", "\"#{preferences.username}:#{preferences.realm}:#{preferences.password}\"", ")", "a1", "=", "\"#{a1_h}:#{nonce}:#{cnonce}\"", "if", "preferences", ".", "authzid", "a1", "+=", "\":#{preferences.authzid}\"", "end", "if", "qop", "&&", "(", "qop", ".", "downcase", "==", "'auth-int'", "||", "qop", ".", "downcase", "==", "'auth-conf'", ")", "a2", "=", "\"#{a2_prefix}:#{preferences.digest_uri}:00000000000000000000000000000000\"", "else", "a2", "=", "\"#{a2_prefix}:#{preferences.digest_uri}\"", "end", "hh", "(", "\"#{hh(a1)}:#{nonce}:#{nc}:#{cnonce}:#{qop}:#{hh(a2)}\"", ")", "end" ]
Calculate the value for the response field
[ "Calculate", "the", "value", "for", "the", "response", "field" ]
e54d8950c9cfb6a51066fcbbe3ada9f0121aa7f4
https://github.com/astro/ruby-sasl/blob/e54d8950c9cfb6a51066fcbbe3ada9f0121aa7f4/lib/sasl/digest_md5.rb#L139-L151
train
regru/reg_api2-ruby
lib/reg_api2/request_contract.rb
RegApi2.RequestContract.to_hash
def to_hash arr return {} if arr.nil? return arr if arr.kind_of?(Hash) arr = [ arr.to_sym ] unless arr.kind_of?(Array) ret = {} arr.each { |key| ret[key.to_sym] = {} } ret end
ruby
def to_hash arr return {} if arr.nil? return arr if arr.kind_of?(Hash) arr = [ arr.to_sym ] unless arr.kind_of?(Array) ret = {} arr.each { |key| ret[key.to_sym] = {} } ret end
[ "def", "to_hash", "arr", "return", "{", "}", "if", "arr", ".", "nil?", "return", "arr", "if", "arr", ".", "kind_of?", "(", "Hash", ")", "arr", "=", "[", "arr", ".", "to_sym", "]", "unless", "arr", ".", "kind_of?", "(", "Array", ")", "ret", "=", "{", "}", "arr", ".", "each", "{", "|", "key", "|", "ret", "[", "key", ".", "to_sym", "]", "=", "{", "}", "}", "ret", "end" ]
Normalizes `required` and `optional` fields to the form of Hash with options. @param [NilClass,Hash,Array, etc.] arr Something to normalize.
[ "Normalizes", "required", "and", "optional", "fields", "to", "the", "form", "of", "Hash", "with", "options", "." ]
82fadffc9da6534761003b8a33edb77ab617df70
https://github.com/regru/reg_api2-ruby/blob/82fadffc9da6534761003b8a33edb77ab617df70/lib/reg_api2/request_contract.rb#L21-L28
train
regru/reg_api2-ruby
lib/reg_api2/request_contract.rb
RegApi2.RequestContract.fields_to_validate
def fields_to_validate required_fields = to_hash opts[:required] optional_fields = to_hash opts[:optional] required_fields.keys.each { |key| required_fields[key][:required] = true } optional_fields.merge(required_fields) end
ruby
def fields_to_validate required_fields = to_hash opts[:required] optional_fields = to_hash opts[:optional] required_fields.keys.each { |key| required_fields[key][:required] = true } optional_fields.merge(required_fields) end
[ "def", "fields_to_validate", "required_fields", "=", "to_hash", "opts", "[", ":required", "]", "optional_fields", "=", "to_hash", "opts", "[", ":optional", "]", "required_fields", ".", "keys", ".", "each", "{", "|", "key", "|", "required_fields", "[", "key", "]", "[", ":required", "]", "=", "true", "}", "optional_fields", ".", "merge", "(", "required_fields", ")", "end" ]
Gets fields to validate @return [Hash] Fields to validate.
[ "Gets", "fields", "to", "validate" ]
82fadffc9da6534761003b8a33edb77ab617df70
https://github.com/regru/reg_api2-ruby/blob/82fadffc9da6534761003b8a33edb77ab617df70/lib/reg_api2/request_contract.rb#L32-L37
train
regru/reg_api2-ruby
lib/reg_api2/request_contract.rb
RegApi2.RequestContract.validate_ipaddr
def validate_ipaddr key, value, opts if opts[:ipaddr] == true && value.kind_of?(String) value = IPAddr.new(value) end value.to_s end
ruby
def validate_ipaddr key, value, opts if opts[:ipaddr] == true && value.kind_of?(String) value = IPAddr.new(value) end value.to_s end
[ "def", "validate_ipaddr", "key", ",", "value", ",", "opts", "if", "opts", "[", ":ipaddr", "]", "==", "true", "&&", "value", ".", "kind_of?", "(", "String", ")", "value", "=", "IPAddr", ".", "new", "(", "value", ")", "end", "value", ".", "to_s", "end" ]
Validates specified `value` with `ipaddr` field. @param [Object] key Value to validate. @param [Object] value Value to validate. @param [Hash] opts opts with optional ipaddr field. @return [String] Updated `value`
[ "Validates", "specified", "value", "with", "ipaddr", "field", "." ]
82fadffc9da6534761003b8a33edb77ab617df70
https://github.com/regru/reg_api2-ruby/blob/82fadffc9da6534761003b8a33edb77ab617df70/lib/reg_api2/request_contract.rb#L73-L78
train
regru/reg_api2-ruby
lib/reg_api2/request_contract.rb
RegApi2.RequestContract.validate_presence_of_required_fields
def validate_presence_of_required_fields form, fields absent_fields = [] fields.each_pair do |key, opts| next unless opts[:required] if !form.has_key?(key) || form[key].nil? absent_fields << key end end unless absent_fields.empty? raise RegApi2::ContractError.new( "Required fields missed: #{absent_fields.join(', ')}", absent_fields ) end nil end
ruby
def validate_presence_of_required_fields form, fields absent_fields = [] fields.each_pair do |key, opts| next unless opts[:required] if !form.has_key?(key) || form[key].nil? absent_fields << key end end unless absent_fields.empty? raise RegApi2::ContractError.new( "Required fields missed: #{absent_fields.join(', ')}", absent_fields ) end nil end
[ "def", "validate_presence_of_required_fields", "form", ",", "fields", "absent_fields", "=", "[", "]", "fields", ".", "each_pair", "do", "|", "key", ",", "opts", "|", "next", "unless", "opts", "[", ":required", "]", "if", "!", "form", ".", "has_key?", "(", "key", ")", "||", "form", "[", "key", "]", ".", "nil?", "absent_fields", "<<", "key", "end", "end", "unless", "absent_fields", ".", "empty?", "raise", "RegApi2", "::", "ContractError", ".", "new", "(", "\"Required fields missed: #{absent_fields.join(', ')}\"", ",", "absent_fields", ")", "end", "nil", "end" ]
Validates specified `form` for presence of all required fields. @param [Hash] form Form to validate. @param [Hash] fields Fields to test. return void @raise ContractError
[ "Validates", "specified", "form", "for", "presence", "of", "all", "required", "fields", "." ]
82fadffc9da6534761003b8a33edb77ab617df70
https://github.com/regru/reg_api2-ruby/blob/82fadffc9da6534761003b8a33edb77ab617df70/lib/reg_api2/request_contract.rb#L85-L100
train
regru/reg_api2-ruby
lib/reg_api2/request_contract.rb
RegApi2.RequestContract.validate
def validate(form) fields = fields_to_validate return form if fields.empty? validate_presence_of_required_fields form, fields fields.each_pair do |key, opts| next if !form.has_key?(key) || form[key].nil? form[key] = validate_re key, form[key], opts form[key] = validate_iso_date key, form[key], opts form[key] = validate_ipaddr key, form[key], opts end form end
ruby
def validate(form) fields = fields_to_validate return form if fields.empty? validate_presence_of_required_fields form, fields fields.each_pair do |key, opts| next if !form.has_key?(key) || form[key].nil? form[key] = validate_re key, form[key], opts form[key] = validate_iso_date key, form[key], opts form[key] = validate_ipaddr key, form[key], opts end form end
[ "def", "validate", "(", "form", ")", "fields", "=", "fields_to_validate", "return", "form", "if", "fields", ".", "empty?", "validate_presence_of_required_fields", "form", ",", "fields", "fields", ".", "each_pair", "do", "|", "key", ",", "opts", "|", "next", "if", "!", "form", ".", "has_key?", "(", "key", ")", "||", "form", "[", "key", "]", ".", "nil?", "form", "[", "key", "]", "=", "validate_re", "key", ",", "form", "[", "key", "]", ",", "opts", "form", "[", "key", "]", "=", "validate_iso_date", "key", ",", "form", "[", "key", "]", ",", "opts", "form", "[", "key", "]", "=", "validate_ipaddr", "key", ",", "form", "[", "key", "]", ",", "opts", "end", "form", "end" ]
Validates specified `form` with `required` and `optional` fields. @param [Hash] form Form to validate. @return [Hash] Updated form. @raise ContractError
[ "Validates", "specified", "form", "with", "required", "and", "optional", "fields", "." ]
82fadffc9da6534761003b8a33edb77ab617df70
https://github.com/regru/reg_api2-ruby/blob/82fadffc9da6534761003b8a33edb77ab617df70/lib/reg_api2/request_contract.rb#L106-L121
train
scrapper/perobs
lib/perobs/BigTreeNode.rb
PEROBS.BigTreeNode.has_key?
def has_key?(key) node = self while node do # Find index of the entry that best fits the key. i = node.search_key_index(key) if node.is_leaf? # This is a leaf node. Check if there is an exact match for the # given key and return the corresponding value or nil. return node.keys[i] == key end # Descend into the right child node to continue the search. node = node.children[i] end PEROBS.log.fatal "Could not find proper node to get from while " + "looking for key #{key}" end
ruby
def has_key?(key) node = self while node do # Find index of the entry that best fits the key. i = node.search_key_index(key) if node.is_leaf? # This is a leaf node. Check if there is an exact match for the # given key and return the corresponding value or nil. return node.keys[i] == key end # Descend into the right child node to continue the search. node = node.children[i] end PEROBS.log.fatal "Could not find proper node to get from while " + "looking for key #{key}" end
[ "def", "has_key?", "(", "key", ")", "node", "=", "self", "while", "node", "do", "i", "=", "node", ".", "search_key_index", "(", "key", ")", "if", "node", ".", "is_leaf?", "return", "node", ".", "keys", "[", "i", "]", "==", "key", "end", "node", "=", "node", ".", "children", "[", "i", "]", "end", "PEROBS", ".", "log", ".", "fatal", "\"Could not find proper node to get from while \"", "+", "\"looking for key #{key}\"", "end" ]
Return if given key is stored in the node. @param key [Integer] key to search for @return [Boolean] True if key was found, false otherwise
[ "Return", "if", "given", "key", "is", "stored", "in", "the", "node", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigTreeNode.rb#L169-L187
train
scrapper/perobs
lib/perobs/BigTreeNode.rb
PEROBS.BigTreeNode.remove_element
def remove_element(index) # Delete the key at the specified index. unless (key = @keys.delete_at(index)) PEROBS.log.fatal "Could not remove element #{index} from BigTreeNode " + "@#{@_id}" end update_branch_key(key) if index == 0 # Delete the corresponding value. removed_value = @values.delete_at(index) if @keys.length < min_keys if @prev_sibling && @prev_sibling.parent == @parent borrow_from_previous_sibling(@prev_sibling) || @prev_sibling.merge_with_leaf_node(myself) elsif @next_sibling && @next_sibling.parent == @parent borrow_from_next_sibling(@next_sibling) || merge_with_leaf_node(@next_sibling) elsif @parent PEROBS.log.fatal "Cannot not find adjecent leaf siblings" end end # The merge has potentially invalidated this node. After this method has # been called this copy of the node should no longer be used. removed_value end
ruby
def remove_element(index) # Delete the key at the specified index. unless (key = @keys.delete_at(index)) PEROBS.log.fatal "Could not remove element #{index} from BigTreeNode " + "@#{@_id}" end update_branch_key(key) if index == 0 # Delete the corresponding value. removed_value = @values.delete_at(index) if @keys.length < min_keys if @prev_sibling && @prev_sibling.parent == @parent borrow_from_previous_sibling(@prev_sibling) || @prev_sibling.merge_with_leaf_node(myself) elsif @next_sibling && @next_sibling.parent == @parent borrow_from_next_sibling(@next_sibling) || merge_with_leaf_node(@next_sibling) elsif @parent PEROBS.log.fatal "Cannot not find adjecent leaf siblings" end end # The merge has potentially invalidated this node. After this method has # been called this copy of the node should no longer be used. removed_value end
[ "def", "remove_element", "(", "index", ")", "unless", "(", "key", "=", "@keys", ".", "delete_at", "(", "index", ")", ")", "PEROBS", ".", "log", ".", "fatal", "\"Could not remove element #{index} from BigTreeNode \"", "+", "\"@#{@_id}\"", "end", "update_branch_key", "(", "key", ")", "if", "index", "==", "0", "removed_value", "=", "@values", ".", "delete_at", "(", "index", ")", "if", "@keys", ".", "length", "<", "min_keys", "if", "@prev_sibling", "&&", "@prev_sibling", ".", "parent", "==", "@parent", "borrow_from_previous_sibling", "(", "@prev_sibling", ")", "||", "@prev_sibling", ".", "merge_with_leaf_node", "(", "myself", ")", "elsif", "@next_sibling", "&&", "@next_sibling", ".", "parent", "==", "@parent", "borrow_from_next_sibling", "(", "@next_sibling", ")", "||", "merge_with_leaf_node", "(", "@next_sibling", ")", "elsif", "@parent", "PEROBS", ".", "log", ".", "fatal", "\"Cannot not find adjecent leaf siblings\"", "end", "end", "removed_value", "end" ]
Remove the element from a leaf node at the given index. @param index [Integer] The index of the entry to be removed @return [Object] The removed value
[ "Remove", "the", "element", "from", "a", "leaf", "node", "at", "the", "given", "index", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigTreeNode.rb#L518-L543
train
scrapper/perobs
lib/perobs/BigTreeNode.rb
PEROBS.BigTreeNode.remove_child
def remove_child(node) unless (index = search_node_index(node)) PEROBS.log.fatal "Cannot remove child #{node._id} from node #{@_id}" end if index == 0 # Removing the first child is a bit more complicated as the # corresponding branch key is in a parent node. key = @keys.shift update_branch_key(key) else # For all other children we can just remove the corresponding key. @keys.delete_at(index - 1) end # Remove the child node link. child = @children.delete_at(index) # If we remove the first or last leaf node we must update the reference # in the BigTree object. @tree.first_leaf = child.next_sibling if child == @tree.first_leaf @tree.last_leaf = child.prev_sibling if child == @tree.last_leaf # Unlink the neighbouring siblings from the child child.prev_sibling.next_sibling = child.next_sibling if child.prev_sibling child.next_sibling.prev_sibling = child.prev_sibling if child.next_sibling if @keys.length < min_keys # The node has become too small. Try borrowing a node from an adjecent # sibling or merge with an adjecent node. if @prev_sibling && @prev_sibling.parent == @parent borrow_from_previous_sibling(@prev_sibling) || @prev_sibling.merge_with_branch_node(myself) elsif @next_sibling && @next_sibling.parent == @parent borrow_from_next_sibling(@next_sibling) || merge_with_branch_node(@next_sibling) end end if @parent.nil? && @children.length <= 1 # If the node just below the root only has one child it will become # the new root node. new_root = @children.first new_root.parent = nil @tree.root = new_root end end
ruby
def remove_child(node) unless (index = search_node_index(node)) PEROBS.log.fatal "Cannot remove child #{node._id} from node #{@_id}" end if index == 0 # Removing the first child is a bit more complicated as the # corresponding branch key is in a parent node. key = @keys.shift update_branch_key(key) else # For all other children we can just remove the corresponding key. @keys.delete_at(index - 1) end # Remove the child node link. child = @children.delete_at(index) # If we remove the first or last leaf node we must update the reference # in the BigTree object. @tree.first_leaf = child.next_sibling if child == @tree.first_leaf @tree.last_leaf = child.prev_sibling if child == @tree.last_leaf # Unlink the neighbouring siblings from the child child.prev_sibling.next_sibling = child.next_sibling if child.prev_sibling child.next_sibling.prev_sibling = child.prev_sibling if child.next_sibling if @keys.length < min_keys # The node has become too small. Try borrowing a node from an adjecent # sibling or merge with an adjecent node. if @prev_sibling && @prev_sibling.parent == @parent borrow_from_previous_sibling(@prev_sibling) || @prev_sibling.merge_with_branch_node(myself) elsif @next_sibling && @next_sibling.parent == @parent borrow_from_next_sibling(@next_sibling) || merge_with_branch_node(@next_sibling) end end if @parent.nil? && @children.length <= 1 # If the node just below the root only has one child it will become # the new root node. new_root = @children.first new_root.parent = nil @tree.root = new_root end end
[ "def", "remove_child", "(", "node", ")", "unless", "(", "index", "=", "search_node_index", "(", "node", ")", ")", "PEROBS", ".", "log", ".", "fatal", "\"Cannot remove child #{node._id} from node #{@_id}\"", "end", "if", "index", "==", "0", "key", "=", "@keys", ".", "shift", "update_branch_key", "(", "key", ")", "else", "@keys", ".", "delete_at", "(", "index", "-", "1", ")", "end", "child", "=", "@children", ".", "delete_at", "(", "index", ")", "@tree", ".", "first_leaf", "=", "child", ".", "next_sibling", "if", "child", "==", "@tree", ".", "first_leaf", "@tree", ".", "last_leaf", "=", "child", ".", "prev_sibling", "if", "child", "==", "@tree", ".", "last_leaf", "child", ".", "prev_sibling", ".", "next_sibling", "=", "child", ".", "next_sibling", "if", "child", ".", "prev_sibling", "child", ".", "next_sibling", ".", "prev_sibling", "=", "child", ".", "prev_sibling", "if", "child", ".", "next_sibling", "if", "@keys", ".", "length", "<", "min_keys", "if", "@prev_sibling", "&&", "@prev_sibling", ".", "parent", "==", "@parent", "borrow_from_previous_sibling", "(", "@prev_sibling", ")", "||", "@prev_sibling", ".", "merge_with_branch_node", "(", "myself", ")", "elsif", "@next_sibling", "&&", "@next_sibling", ".", "parent", "==", "@parent", "borrow_from_next_sibling", "(", "@next_sibling", ")", "||", "merge_with_branch_node", "(", "@next_sibling", ")", "end", "end", "if", "@parent", ".", "nil?", "&&", "@children", ".", "length", "<=", "1", "new_root", "=", "@children", ".", "first", "new_root", ".", "parent", "=", "nil", "@tree", ".", "root", "=", "new_root", "end", "end" ]
Remove the specified node from this branch node. @param node [BigTreeNode] The child to remove
[ "Remove", "the", "specified", "node", "from", "this", "branch", "node", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigTreeNode.rb#L547-L591
train
scrapper/perobs
lib/perobs/BigTreeNode.rb
PEROBS.BigTreeNode.statistics
def statistics(stats) traverse do |node, position, stack| if position == 0 if node.is_leaf? stats.leaf_nodes += 1 depth = stack.size + 1 if stats.min_depth.nil? || stats.min_depth < depth stats.min_depth = depth end if stats.max_depth.nil? || stats.max_depth > depth stats.max_depth = depth end else stats.branch_nodes += 1 end end end end
ruby
def statistics(stats) traverse do |node, position, stack| if position == 0 if node.is_leaf? stats.leaf_nodes += 1 depth = stack.size + 1 if stats.min_depth.nil? || stats.min_depth < depth stats.min_depth = depth end if stats.max_depth.nil? || stats.max_depth > depth stats.max_depth = depth end else stats.branch_nodes += 1 end end end end
[ "def", "statistics", "(", "stats", ")", "traverse", "do", "|", "node", ",", "position", ",", "stack", "|", "if", "position", "==", "0", "if", "node", ".", "is_leaf?", "stats", ".", "leaf_nodes", "+=", "1", "depth", "=", "stack", ".", "size", "+", "1", "if", "stats", ".", "min_depth", ".", "nil?", "||", "stats", ".", "min_depth", "<", "depth", "stats", ".", "min_depth", "=", "depth", "end", "if", "stats", ".", "max_depth", ".", "nil?", "||", "stats", ".", "max_depth", ">", "depth", "stats", ".", "max_depth", "=", "depth", "end", "else", "stats", ".", "branch_nodes", "+=", "1", "end", "end", "end", "end" ]
Gather some statistics about the node and all sub nodes. @param stats [Stats] Data structure that stores the gathered data
[ "Gather", "some", "statistics", "about", "the", "node", "and", "all", "sub", "nodes", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigTreeNode.rb#L702-L719
train
scrapper/perobs
lib/perobs/BTreeDB.rb
PEROBS.BTreeDB.include?
def include?(id) !(blob = find_blob(id)).nil? && !blob.find(id).nil? end
ruby
def include?(id) !(blob = find_blob(id)).nil? && !blob.find(id).nil? end
[ "def", "include?", "(", "id", ")", "!", "(", "blob", "=", "find_blob", "(", "id", ")", ")", ".", "nil?", "&&", "!", "blob", ".", "find", "(", "id", ")", ".", "nil?", "end" ]
Return true if the object with given ID exists @param id [Integer]
[ "Return", "true", "if", "the", "object", "with", "given", "ID", "exists" ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BTreeDB.rb#L107-L109
train
scrapper/perobs
lib/perobs/BTreeDB.rb
PEROBS.BTreeDB.get_object
def get_object(id) return nil unless (blob = find_blob(id)) && (obj = blob.read_object(id)) deserialize(obj) end
ruby
def get_object(id) return nil unless (blob = find_blob(id)) && (obj = blob.read_object(id)) deserialize(obj) end
[ "def", "get_object", "(", "id", ")", "return", "nil", "unless", "(", "blob", "=", "find_blob", "(", "id", ")", ")", "&&", "(", "obj", "=", "blob", ".", "read_object", "(", "id", ")", ")", "deserialize", "(", "obj", ")", "end" ]
Load the given object from the filesystem. @param id [Integer] object ID @return [Hash] Object as defined by PEROBS::ObjectBase or nil if ID does not exist
[ "Load", "the", "given", "object", "from", "the", "filesystem", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BTreeDB.rb#L149-L152
train
scrapper/perobs
lib/perobs/BTreeDB.rb
PEROBS.BTreeDB.is_marked?
def is_marked?(id, ignore_errors = false) (blob = find_blob(id)) && blob.is_marked?(id, ignore_errors) end
ruby
def is_marked?(id, ignore_errors = false) (blob = find_blob(id)) && blob.is_marked?(id, ignore_errors) end
[ "def", "is_marked?", "(", "id", ",", "ignore_errors", "=", "false", ")", "(", "blob", "=", "find_blob", "(", "id", ")", ")", "&&", "blob", ".", "is_marked?", "(", "id", ",", "ignore_errors", ")", "end" ]
Check if the object is marked. @param id [Integer] ID of the object to check @param ignore_errors [Boolean] If set to true no errors will be raised for non-existing objects.
[ "Check", "if", "the", "object", "is", "marked", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BTreeDB.rb#L178-L180
train
dalehamel/cloudshaper
lib/cloudshaper/command.rb
Cloudshaper.Command.env
def env vars = {} @stack.variables.each { |k, v| vars["TF_VAR_#{k}"] = v } SECRETS.each do |_provider, secrets| if secrets.is_a?(Hash) secrets.each do |k, v| vars[k.to_s] = v end end end vars end
ruby
def env vars = {} @stack.variables.each { |k, v| vars["TF_VAR_#{k}"] = v } SECRETS.each do |_provider, secrets| if secrets.is_a?(Hash) secrets.each do |k, v| vars[k.to_s] = v end end end vars end
[ "def", "env", "vars", "=", "{", "}", "@stack", ".", "variables", ".", "each", "{", "|", "k", ",", "v", "|", "vars", "[", "\"TF_VAR_#{k}\"", "]", "=", "v", "}", "SECRETS", ".", "each", "do", "|", "_provider", ",", "secrets", "|", "if", "secrets", ".", "is_a?", "(", "Hash", ")", "secrets", ".", "each", "do", "|", "k", ",", "v", "|", "vars", "[", "k", ".", "to_s", "]", "=", "v", "end", "end", "end", "vars", "end" ]
fixme - make these shell safe
[ "fixme", "-", "make", "these", "shell", "safe" ]
bcfeb18fd9853f782b7aa81ebe3f84d69e17e5b4
https://github.com/dalehamel/cloudshaper/blob/bcfeb18fd9853f782b7aa81ebe3f84d69e17e5b4/lib/cloudshaper/command.rb#L14-L25
train
sethvargo/community-zero
lib/community_zero/store.rb
CommunityZero.Store.search
def search(query) regex = Regexp.new(query, 'i') _cookbooks.collect do |_, v| v[v.keys.first] if regex.match(v[v.keys.first].name) end.compact end
ruby
def search(query) regex = Regexp.new(query, 'i') _cookbooks.collect do |_, v| v[v.keys.first] if regex.match(v[v.keys.first].name) end.compact end
[ "def", "search", "(", "query", ")", "regex", "=", "Regexp", ".", "new", "(", "query", ",", "'i'", ")", "_cookbooks", ".", "collect", "do", "|", "_", ",", "v", "|", "v", "[", "v", ".", "keys", ".", "first", "]", "if", "regex", ".", "match", "(", "v", "[", "v", ".", "keys", ".", "first", "]", ".", "name", ")", "end", ".", "compact", "end" ]
Query the installed cookbooks, returning those who's name matches the given query. @param [String] query the query parameter @return [Array<CommunityZero::Cookbook>] the list of cookbooks that match the given query
[ "Query", "the", "installed", "cookbooks", "returning", "those", "who", "s", "name", "matches", "the", "given", "query", "." ]
08a22c47c865deb6a5f931cb4d9f747a2b9d3459
https://github.com/sethvargo/community-zero/blob/08a22c47c865deb6a5f931cb4d9f747a2b9d3459/lib/community_zero/store.rb#L51-L56
train
sethvargo/community-zero
lib/community_zero/store.rb
CommunityZero.Store.add
def add(cookbook) cookbook = cookbook.dup cookbook.created_at = Time.now cookbook.updated_at = Time.now entry = _cookbooks[cookbook.name] ||= {} entry[cookbook.version] = cookbook end
ruby
def add(cookbook) cookbook = cookbook.dup cookbook.created_at = Time.now cookbook.updated_at = Time.now entry = _cookbooks[cookbook.name] ||= {} entry[cookbook.version] = cookbook end
[ "def", "add", "(", "cookbook", ")", "cookbook", "=", "cookbook", ".", "dup", "cookbook", ".", "created_at", "=", "Time", ".", "now", "cookbook", ".", "updated_at", "=", "Time", ".", "now", "entry", "=", "_cookbooks", "[", "cookbook", ".", "name", "]", "||=", "{", "}", "entry", "[", "cookbook", ".", "version", "]", "=", "cookbook", "end" ]
Add the given cookbook to the cookbook store. This method's implementation prohibits duplicate cookbooks from entering the store. @param [CommunityZero::Cookbook] cookbook the cookbook to add
[ "Add", "the", "given", "cookbook", "to", "the", "cookbook", "store", ".", "This", "method", "s", "implementation", "prohibits", "duplicate", "cookbooks", "from", "entering", "the", "store", "." ]
08a22c47c865deb6a5f931cb4d9f747a2b9d3459
https://github.com/sethvargo/community-zero/blob/08a22c47c865deb6a5f931cb4d9f747a2b9d3459/lib/community_zero/store.rb#L68-L75
train
sethvargo/community-zero
lib/community_zero/store.rb
CommunityZero.Store.remove
def remove(cookbook) return unless has_cookbook?(cookbook.name, cookbook.version) _cookbooks[cookbook.name].delete(cookbook.version) end
ruby
def remove(cookbook) return unless has_cookbook?(cookbook.name, cookbook.version) _cookbooks[cookbook.name].delete(cookbook.version) end
[ "def", "remove", "(", "cookbook", ")", "return", "unless", "has_cookbook?", "(", "cookbook", ".", "name", ",", "cookbook", ".", "version", ")", "_cookbooks", "[", "cookbook", ".", "name", "]", ".", "delete", "(", "cookbook", ".", "version", ")", "end" ]
Remove the cookbook from the store. @param [CommunityZero::Cookbook] cookbook the cookbook to remove
[ "Remove", "the", "cookbook", "from", "the", "store", "." ]
08a22c47c865deb6a5f931cb4d9f747a2b9d3459
https://github.com/sethvargo/community-zero/blob/08a22c47c865deb6a5f931cb4d9f747a2b9d3459/lib/community_zero/store.rb#L82-L85
train
sethvargo/community-zero
lib/community_zero/store.rb
CommunityZero.Store.find
def find(name, version = nil) possibles = _cookbooks[name] return nil if possibles.nil? version ||= possibles.keys.sort.last possibles[version] end
ruby
def find(name, version = nil) possibles = _cookbooks[name] return nil if possibles.nil? version ||= possibles.keys.sort.last possibles[version] end
[ "def", "find", "(", "name", ",", "version", "=", "nil", ")", "possibles", "=", "_cookbooks", "[", "name", "]", "return", "nil", "if", "possibles", ".", "nil?", "version", "||=", "possibles", ".", "keys", ".", "sort", ".", "last", "possibles", "[", "version", "]", "end" ]
Determine if the cookbook store contains a cookbook. If the version attribute is nil, this method will return the latest cookbook version by that name that exists. If the version is specified, this method will only return that specific version, or nil if that cookbook at that version exists. @param [String] name the name of the cookbook to find @param [String, nil] version the version of the cookbook to search @return [CommunityZero::Cookbook, nil] the cookbook in the store, or nil if one does not exist
[ "Determine", "if", "the", "cookbook", "store", "contains", "a", "cookbook", ".", "If", "the", "version", "attribute", "is", "nil", "this", "method", "will", "return", "the", "latest", "cookbook", "version", "by", "that", "name", "that", "exists", ".", "If", "the", "version", "is", "specified", "this", "method", "will", "only", "return", "that", "specific", "version", "or", "nil", "if", "that", "cookbook", "at", "that", "version", "exists", "." ]
08a22c47c865deb6a5f931cb4d9f747a2b9d3459
https://github.com/sethvargo/community-zero/blob/08a22c47c865deb6a5f931cb4d9f747a2b9d3459/lib/community_zero/store.rb#L107-L113
train
sethvargo/community-zero
lib/community_zero/store.rb
CommunityZero.Store.versions
def versions(name) name = name.respond_to?(:name) ? name.name : name (_cookbooks[name] && _cookbooks[name].keys.sort) || [] end
ruby
def versions(name) name = name.respond_to?(:name) ? name.name : name (_cookbooks[name] && _cookbooks[name].keys.sort) || [] end
[ "def", "versions", "(", "name", ")", "name", "=", "name", ".", "respond_to?", "(", ":name", ")", "?", "name", ".", "name", ":", "name", "(", "_cookbooks", "[", "name", "]", "&&", "_cookbooks", "[", "name", "]", ".", "keys", ".", "sort", ")", "||", "[", "]", "end" ]
Return a list of all versions for the given cookbook. @param [String, CommunityZero::Cookbook] name the cookbook or name of the cookbook to get versions for
[ "Return", "a", "list", "of", "all", "versions", "for", "the", "given", "cookbook", "." ]
08a22c47c865deb6a5f931cb4d9f747a2b9d3459
https://github.com/sethvargo/community-zero/blob/08a22c47c865deb6a5f931cb4d9f747a2b9d3459/lib/community_zero/store.rb#L119-L122
train
scrapper/perobs
lib/perobs/Hash.rb
PEROBS.Hash._referenced_object_ids
def _referenced_object_ids @data.each_value.select { |v| v && v.respond_to?(:is_poxreference?) }. map { |o| o.id } end
ruby
def _referenced_object_ids @data.each_value.select { |v| v && v.respond_to?(:is_poxreference?) }. map { |o| o.id } end
[ "def", "_referenced_object_ids", "@data", ".", "each_value", ".", "select", "{", "|", "v", "|", "v", "&&", "v", ".", "respond_to?", "(", ":is_poxreference?", ")", "}", ".", "map", "{", "|", "o", "|", "o", ".", "id", "}", "end" ]
Return a list of all object IDs of all persistend objects that this Hash is referencing. @return [Array of Integer] IDs of referenced objects
[ "Return", "a", "list", "of", "all", "object", "IDs", "of", "all", "persistend", "objects", "that", "this", "Hash", "is", "referencing", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Hash.rb#L141-L144
train
scrapper/perobs
lib/perobs/Hash.rb
PEROBS.Hash._delete_reference_to_id
def _delete_reference_to_id(id) @data.delete_if do |k, v| v && v.respond_to?(:is_poxreference?) && v.id == id end @store.cache.cache_write(self) end
ruby
def _delete_reference_to_id(id) @data.delete_if do |k, v| v && v.respond_to?(:is_poxreference?) && v.id == id end @store.cache.cache_write(self) end
[ "def", "_delete_reference_to_id", "(", "id", ")", "@data", ".", "delete_if", "do", "|", "k", ",", "v", "|", "v", "&&", "v", ".", "respond_to?", "(", ":is_poxreference?", ")", "&&", "v", ".", "id", "==", "id", "end", "@store", ".", "cache", ".", "cache_write", "(", "self", ")", "end" ]
This method should only be used during store repair operations. It will delete all referenced to the given object ID. @param id [Integer] targeted object ID
[ "This", "method", "should", "only", "be", "used", "during", "store", "repair", "operations", ".", "It", "will", "delete", "all", "referenced", "to", "the", "given", "object", "ID", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Hash.rb#L149-L154
train
scrapper/perobs
lib/perobs/IDListPageRecord.rb
PEROBS.IDListPageRecord.split
def split # Determine the new max_id for the old page. max_id = @min_id + (@max_id - @min_id) / 2 # Create a new page that stores the upper half of the ID range. Remove # all IDs from this page that now belong into the new page and transfer # them. new_page_record = IDListPageRecord.new(@page_file, max_id + 1, @max_id, page.delete(max_id)) # Adjust the max_id of the current page. @max_id = max_id new_page_record end
ruby
def split # Determine the new max_id for the old page. max_id = @min_id + (@max_id - @min_id) / 2 # Create a new page that stores the upper half of the ID range. Remove # all IDs from this page that now belong into the new page and transfer # them. new_page_record = IDListPageRecord.new(@page_file, max_id + 1, @max_id, page.delete(max_id)) # Adjust the max_id of the current page. @max_id = max_id new_page_record end
[ "def", "split", "max_id", "=", "@min_id", "+", "(", "@max_id", "-", "@min_id", ")", "/", "2", "new_page_record", "=", "IDListPageRecord", ".", "new", "(", "@page_file", ",", "max_id", "+", "1", ",", "@max_id", ",", "page", ".", "delete", "(", "max_id", ")", ")", "@max_id", "=", "max_id", "new_page_record", "end" ]
Split the current page. This split is done by splitting the ID range in half. This page will keep the first half, the newly created page will get the second half. This may not actually yield an empty page as all values could remain with one of the pages. In this case further splits need to be issued by the caller. @return [IDListPageRecord] A new IDListPageRecord object.
[ "Split", "the", "current", "page", ".", "This", "split", "is", "done", "by", "splitting", "the", "ID", "range", "in", "half", ".", "This", "page", "will", "keep", "the", "first", "half", "the", "newly", "created", "page", "will", "get", "the", "second", "half", ".", "This", "may", "not", "actually", "yield", "an", "empty", "page", "as", "all", "values", "could", "remain", "with", "one", "of", "the", "pages", ".", "In", "this", "case", "further", "splits", "need", "to", "be", "issued", "by", "the", "caller", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/IDListPageRecord.rb#L84-L96
train
notonthehighstreet/chicago
lib/chicago/schema/builders/shrunken_dimension_builder.rb
Chicago::Schema::Builders.ShrunkenDimensionBuilder.columns
def columns(*names) columns = @base.columns.select {|c| names.include?(c.name) } check_columns_subset_of_base_dimension names, columns @options[:columns] = columns end
ruby
def columns(*names) columns = @base.columns.select {|c| names.include?(c.name) } check_columns_subset_of_base_dimension names, columns @options[:columns] = columns end
[ "def", "columns", "(", "*", "names", ")", "columns", "=", "@base", ".", "columns", ".", "select", "{", "|", "c", "|", "names", ".", "include?", "(", "c", ".", "name", ")", "}", "check_columns_subset_of_base_dimension", "names", ",", "columns", "@options", "[", ":columns", "]", "=", "columns", "end" ]
Defines which columns of the base dimension are present in the shrunken dimension. Takes an array of the column names as symbols. The columns must be a subset of the base dimension's columns; additional names will raise a Chicago::MissingDefinitionError.
[ "Defines", "which", "columns", "of", "the", "base", "dimension", "are", "present", "in", "the", "shrunken", "dimension", "." ]
428e94f8089d2f36fdcff2e27ea2af572b816def
https://github.com/notonthehighstreet/chicago/blob/428e94f8089d2f36fdcff2e27ea2af572b816def/lib/chicago/schema/builders/shrunken_dimension_builder.rb#L29-L33
train
xinminlabs/synvert-core
lib/synvert/core/rewriter/action/insert_action.rb
Synvert::Core.Rewriter::InsertAction.insert_position
def insert_position(node) case node.type when :block node.children[1].children.empty? ? node.children[0].loc.expression.end_pos + 3 : node.children[1].loc.expression.end_pos when :class node.children[1] ? node.children[1].loc.expression.end_pos : node.children[0].loc.expression.end_pos else node.children.last.loc.expression.end_pos end end
ruby
def insert_position(node) case node.type when :block node.children[1].children.empty? ? node.children[0].loc.expression.end_pos + 3 : node.children[1].loc.expression.end_pos when :class node.children[1] ? node.children[1].loc.expression.end_pos : node.children[0].loc.expression.end_pos else node.children.last.loc.expression.end_pos end end
[ "def", "insert_position", "(", "node", ")", "case", "node", ".", "type", "when", ":block", "node", ".", "children", "[", "1", "]", ".", "children", ".", "empty?", "?", "node", ".", "children", "[", "0", "]", ".", "loc", ".", "expression", ".", "end_pos", "+", "3", ":", "node", ".", "children", "[", "1", "]", ".", "loc", ".", "expression", ".", "end_pos", "when", ":class", "node", ".", "children", "[", "1", "]", "?", "node", ".", "children", "[", "1", "]", ".", "loc", ".", "expression", ".", "end_pos", ":", "node", ".", "children", "[", "0", "]", ".", "loc", ".", "expression", ".", "end_pos", "else", "node", ".", "children", ".", "last", ".", "loc", ".", "expression", ".", "end_pos", "end", "end" ]
Insert position. @return [Integer] insert position.
[ "Insert", "position", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/rewriter/action/insert_action.rb#L25-L34
train
jeffnyman/tapestry
lib/tapestry/element.rb
Tapestry.Element.accessor_aspects
def accessor_aspects(element, *signature) identifier = signature.shift locator_args = {} qualifier_args = {} gather_aspects(identifier, element, locator_args, qualifier_args) [locator_args, qualifier_args] end
ruby
def accessor_aspects(element, *signature) identifier = signature.shift locator_args = {} qualifier_args = {} gather_aspects(identifier, element, locator_args, qualifier_args) [locator_args, qualifier_args] end
[ "def", "accessor_aspects", "(", "element", ",", "*", "signature", ")", "identifier", "=", "signature", ".", "shift", "locator_args", "=", "{", "}", "qualifier_args", "=", "{", "}", "gather_aspects", "(", "identifier", ",", "element", ",", "locator_args", ",", "qualifier_args", ")", "[", "locator_args", ",", "qualifier_args", "]", "end" ]
This method provides the means to get the aspects of an accessor signature. The "aspects" refer to the locator information and any qualifier information that was provided along with the locator. This is important because the qualifier is not used to locate an element but rather to put conditions on how the state of the element is checked as it is being looked for. Note that "qualifiers" here refers to Watir boolean methods.
[ "This", "method", "provides", "the", "means", "to", "get", "the", "aspects", "of", "an", "accessor", "signature", ".", "The", "aspects", "refer", "to", "the", "locator", "information", "and", "any", "qualifier", "information", "that", "was", "provided", "along", "with", "the", "locator", ".", "This", "is", "important", "because", "the", "qualifier", "is", "not", "used", "to", "locate", "an", "element", "but", "rather", "to", "put", "conditions", "on", "how", "the", "state", "of", "the", "element", "is", "checked", "as", "it", "is", "being", "looked", "for", "." ]
da28652dd6de71e415cd2c01afd89f641938a05b
https://github.com/jeffnyman/tapestry/blob/da28652dd6de71e415cd2c01afd89f641938a05b/lib/tapestry/element.rb#L78-L84
train
scrapper/perobs
lib/perobs/DynamoDB.rb
PEROBS.DynamoDB.delete_database
def delete_database dynamodb = Aws::DynamoDB::Client.new dynamodb.delete_table(:table_name => @table_name) dynamodb.wait_until(:table_not_exists, table_name: @table_name) end
ruby
def delete_database dynamodb = Aws::DynamoDB::Client.new dynamodb.delete_table(:table_name => @table_name) dynamodb.wait_until(:table_not_exists, table_name: @table_name) end
[ "def", "delete_database", "dynamodb", "=", "Aws", "::", "DynamoDB", "::", "Client", ".", "new", "dynamodb", ".", "delete_table", "(", ":table_name", "=>", "@table_name", ")", "dynamodb", ".", "wait_until", "(", ":table_not_exists", ",", "table_name", ":", "@table_name", ")", "end" ]
Create a new DynamoDB object. @param db_name [String] name of the DB directory @param options [Hash] options to customize the behavior. Currently only the following options are supported: :serializer : Can be :json and :yaml :aws_id : AWS credentials ID :aws_key : AWS credentials key :aws_region : AWS region to host the data Delete the entire database. The database is no longer usable after this method was called.
[ "Create", "a", "new", "DynamoDB", "object", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/DynamoDB.rb#L93-L97
train
scrapper/perobs
lib/perobs/DynamoDB.rb
PEROBS.DynamoDB.delete_unmarked_objects
def delete_unmarked_objects deleted_objects_count = 0 each_item do |id| unless dynamo_is_marked?(id) dynamo_delete_item(id) deleted_objects_count += 1 @item_counter -= 1 end end dynamo_put_item('item_counter', @item_counter.to_s) deleted_objects_count end
ruby
def delete_unmarked_objects deleted_objects_count = 0 each_item do |id| unless dynamo_is_marked?(id) dynamo_delete_item(id) deleted_objects_count += 1 @item_counter -= 1 end end dynamo_put_item('item_counter', @item_counter.to_s) deleted_objects_count end
[ "def", "delete_unmarked_objects", "deleted_objects_count", "=", "0", "each_item", "do", "|", "id", "|", "unless", "dynamo_is_marked?", "(", "id", ")", "dynamo_delete_item", "(", "id", ")", "deleted_objects_count", "+=", "1", "@item_counter", "-=", "1", "end", "end", "dynamo_put_item", "(", "'item_counter'", ",", "@item_counter", ".", "to_s", ")", "deleted_objects_count", "end" ]
Permanently delete all objects that have not been marked. Those are orphaned and are no longer referenced by any actively used object. @return [Integer] Count of the deleted objects.
[ "Permanently", "delete", "all", "objects", "that", "have", "not", "been", "marked", ".", "Those", "are", "orphaned", "and", "are", "no", "longer", "referenced", "by", "any", "actively", "used", "object", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/DynamoDB.rb#L161-L173
train