_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q4100
|
QuickBase.Client.getFieldIDs
|
train
|
def getFieldIDs(dbid = nil, exclude_built_in_fields = false )
fieldIDs = []
dbid ||= @dbid
getSchema(dbid)
if @fields
@fields.each_element_with_attribute( "id" ){|f|
next if exclude_built_in_fields and isBuiltInField?(f.attributes["id"])
fieldIDs << f.attributes[ "id" ].dup
}
end
fieldIDs
end
|
ruby
|
{
"resource": ""
}
|
q4101
|
QuickBase.Client.getFieldNames
|
train
|
def getFieldNames( dbid = nil, lowerOrUppercase = "", exclude_built_in_fields = false )
fieldNames = []
dbid ||= @dbid
getSchema(dbid)
if @fields
@fields.each_element_with_attribute( "id" ){ |f|
next if exclude_built_in_fields and isBuiltInField?(f.attributes["id"])
if f.name == "field"
if lowerOrUppercase == "lowercase"
fieldNames << f.elements[ "label" ].text.downcase
elsif lowerOrUppercase == "uppercase"
fieldNames << f.elements[ "label" ].text.upcase
else
fieldNames << f.elements[ "label" ].text.dup
end
end
}
end
fieldNames
end
|
ruby
|
{
"resource": ""
}
|
q4102
|
QuickBase.Client.getApplicationVariables
|
train
|
def getApplicationVariables(dbid=nil)
variablesHash = {}
dbid ||= @dbid
qbc.getSchema(dbid)
if @variables
@variables.each_element_with_attribute( "name" ){ |var|
if var.name == "var" and var.has_text?
variablesHash[var.attributes["name"]] = var.text
end
}
end
variablesHash
end
|
ruby
|
{
"resource": ""
}
|
q4103
|
QuickBase.Client.lookupChdbid
|
train
|
def lookupChdbid( tableName, dbid=nil )
getSchema(dbid) if dbid
unmodifiedTableName = tableName.dup
@chdbid = findElementByAttributeValue( @chdbids, "name", formatChdbidName( tableName ) )
if @chdbid
@dbid = @chdbid.text
return @dbid
end
if @chdbids
chdbidArray = findElementsByAttributeName( @chdbids, "name" )
chdbidArray.each{ |chdbid|
if chdbid.has_text?
dbid = chdbid.text
getSchema( dbid )
name = getResponseElement( "table/name" )
if name and name.has_text? and name.text.downcase == unmodifiedTableName.downcase
@chdbid = chdbid
@dbid = dbid
return @dbid
end
end
}
end
nil
end
|
ruby
|
{
"resource": ""
}
|
q4104
|
QuickBase.Client.getTableName
|
train
|
def getTableName(dbid)
tableName = nil
dbid ||= @dbid
if getSchema(dbid)
tableName = getResponseElement( "table/name" ).text
end
tableName
end
|
ruby
|
{
"resource": ""
}
|
q4105
|
QuickBase.Client.getTableNames
|
train
|
def getTableNames(dbid, lowercaseOrUpperCase = "")
tableNames = []
dbid ||= @dbid
getSchema(dbid)
if @chdbids
chdbidArray = findElementsByAttributeName( @chdbids, "name" )
chdbidArray.each{ |chdbid|
if chdbid.has_text?
dbid = chdbid.text
getSchema( dbid )
name = getResponseElement( "table/name" )
if name and name.has_text?
if lowercaseOrUpperCase == "lowercase"
tableNames << name.text.downcase
elsif lowercaseOrUpperCase == "uppercase"
tableNames << name.text.upcase
else
tableNames << name.text.dup
end
end
end
}
end
tableNames
end
|
ruby
|
{
"resource": ""
}
|
q4106
|
QuickBase.Client.getTableIDs
|
train
|
def getTableIDs(dbid)
tableIDs = []
dbid ||= @dbid
getSchema(dbid)
if @chdbids
chdbidArray = findElementsByAttributeName( @chdbids, "name" )
chdbidArray.each{ |chdbid|
if chdbid.has_text?
tableIDs << chdbid.text
end
}
end
tableIDs
end
|
ruby
|
{
"resource": ""
}
|
q4107
|
QuickBase.Client.getNumTables
|
train
|
def getNumTables(dbid)
numTables = 0
dbid ||= @dbid
if getSchema(dbid)
if @chdbids
chdbidArray = findElementsByAttributeName( @chdbids, "name" )
numTables = chdbidArray.length
end
end
numTables
end
|
ruby
|
{
"resource": ""
}
|
q4108
|
QuickBase.Client.getRealmForDbid
|
train
|
def getRealmForDbid(dbid)
@realm = nil
if USING_HTTPCLIENT
begin
httpclient = HTTPClient.new
resp = httpclient.get("https://www.quickbase.com/db/#{dbid}")
location = resp.header['Location'][0]
location.sub!("https://","")
parts = location.split(/\./)
@realm = parts[0]
rescue StandardError => error
@realm = nil
end
else
raise "Please get the HTTPClient gem: gem install httpclient"
end
@realm
end
|
ruby
|
{
"resource": ""
}
|
q4109
|
QuickBase.Client.isValidFieldType?
|
train
|
def isValidFieldType?( type )
@validFieldTypes ||= %w{ checkbox dblink date duration email file fkey float formula currency
lookup multiuserid phone percent rating recordid text timeofday timestamp url userid icalendarbutton }
@validFieldTypes.include?( type )
end
|
ruby
|
{
"resource": ""
}
|
q4110
|
QuickBase.Client.isValidFieldProperty?
|
train
|
def isValidFieldProperty?( property )
if @validFieldProperties.nil?
@validFieldProperties = %w{ allow_new_choices allowHTML appears_by_default append_only
blank_is_zero bold carrychoices comma_start cover_text currency_format currency_symbol
decimal_places default_kind default_today default_today default_value display_dow
display_graphic display_month display_relative display_time display_today display_user display_zone
does_average does_total doesdatacopy exact fieldhelp find_enabled foreignkey format formula
has_extension hours24 label max_versions maxlength nowrap num_lines required sort_as_given
source_fid source_fieldname target_dbid target_dbname target_fid target_fieldname unique units
use_new_window width }
end
ret = @validFieldProperties.include?( property )
end
|
ruby
|
{
"resource": ""
}
|
q4111
|
QuickBase.Client.verifyFieldList
|
train
|
def verifyFieldList( fnames, fids = nil, dbid = @dbid )
getSchema( dbid )
@fids = @fnames = nil
if fids
if fids.is_a?( Array ) and fids.length > 0
fids.each { |id|
fid = lookupField( id )
if fid
fname = lookupFieldNameFromID( id )
@fnames ||= []
@fnames << fname
else
raise "verifyFieldList: '#{id}' is not a valid field ID"
end
}
@fids = fids
else
raise "verifyFieldList: fids must be an array of one or more field IDs"
end
elsif fnames
if fnames.is_a?( Array ) and fnames.length > 0
fnames.each { |name|
fid = lookupFieldIDByName( name )
if fid
@fids ||= []
@fids << fid
else
raise "verifyFieldList: '#{name}' is not a valid field name"
end
}
@fnames = fnames
else
raise "verifyFieldList: fnames must be an array of one or more field names"
end
else
raise "verifyFieldList: must specify fids or fnames"
end
@fids
end
|
ruby
|
{
"resource": ""
}
|
q4112
|
QuickBase.Client.getQueryRequestXML
|
train
|
def getQueryRequestXML( query = nil, qid = nil, qname = nil )
@query = @qid = @qname = nil
if query
@query = query == "" ? "{'0'.CT.''}" : query
xmlRequestData = toXML( :query, @query )
elsif qid
@qid = qid
xmlRequestData = toXML( :qid, @qid )
elsif qname
@qname = qname
xmlRequestData = toXML( :qname, @qname )
else
@query = "{'0'.CT.''}"
xmlRequestData = toXML( :query, @query )
end
xmlRequestData
end
|
ruby
|
{
"resource": ""
}
|
q4113
|
QuickBase.Client.getColumnListForQuery
|
train
|
def getColumnListForQuery( id, name )
clistForQuery = nil
if id
query = lookupQuery( id )
elsif name
query = lookupQueryByName( name )
end
if query and query.elements["qyclst"]
clistForQuery = query.elements["qyclst"].text.dup
end
clistForQuery
end
|
ruby
|
{
"resource": ""
}
|
q4114
|
QuickBase.Client.getSortListForQuery
|
train
|
def getSortListForQuery( id, name )
slistForQuery = nil
if id
query = lookupQuery( id )
elsif name
query = lookupQueryByName( name )
end
if query and query.elements["qyslst"]
slistForQuery = query.elements["qyslst"].text.dup
end
slistForQuery
end
|
ruby
|
{
"resource": ""
}
|
q4115
|
QuickBase.Client.getCriteriaForQuery
|
train
|
def getCriteriaForQuery( id, name )
criteriaForQuery = nil
if id
query = lookupQuery( id )
elsif name
query = lookupQueryByName( name )
end
if query and query.elements["qycrit"]
criteriaForQuery = query.elements["qycrit"].text.dup
end
criteriaForQuery
end
|
ruby
|
{
"resource": ""
}
|
q4116
|
QuickBase.Client.verifyQueryOperator
|
train
|
def verifyQueryOperator( operator, fieldType )
queryOperator = ""
if @queryOperators.nil?
@queryOperators = {}
@queryOperatorFieldType = {}
@queryOperators[ "CT" ] = [ "contains", "[]" ]
@queryOperators[ "XCT" ] = [ "does not contain", "![]" ]
@queryOperators[ "EX" ] = [ "is", "==", "eq" ]
@queryOperators[ "TV" ] = [ "true value" ]
@queryOperators[ "XEX" ] = [ "is not", "!=", "ne" ]
@queryOperators[ "SW" ] = [ "starts with" ]
@queryOperators[ "XSW" ] = [ "does not start with" ]
@queryOperators[ "BF" ] = [ "is before", "<" ]
@queryOperators[ "OBF" ] = [ "is on or before", "<=" ]
@queryOperators[ "AF" ] = [ "is after", ">" ]
@queryOperators[ "OAF" ] = [ "is on or after", ">=" ]
@queryOperatorFieldType[ "BF" ] = [ "date" ]
@queryOperatorFieldType[ "OBF" ] = [ "date" ]
@queryOperatorFieldType[ "ABF" ] = [ "date" ]
@queryOperatorFieldType[ "OAF" ] = [ "date" ]
@queryOperators[ "LT" ] = [ "is less than", "<" ]
@queryOperators[ "LTE" ] = [ "is less than or equal to", "<=" ]
@queryOperators[ "GT" ] = [ "is greater than", ">" ]
@queryOperators[ "GTE" ] = [ "is greater than or equal to", ">=" ]
end
upcaseOperator = operator.upcase
@queryOperators.each { |queryop,aliases|
if queryop == upcaseOperator
if @queryOperatorFieldType[ queryop ] and @queryOperatorFieldType[ queryop ].include?( fieldType )
queryOperator = upcaseOperator
break
else
queryOperator = upcaseOperator
break
end
else
aliases.each { |a|
if a == upcaseOperator
if @queryOperatorFieldType[ queryop ] and @queryOperatorFieldType[ queryop ].include?( fieldType )
queryOperator = queryop
break
else
queryOperator = queryop
break
end
end
}
end
}
queryOperator
end
|
ruby
|
{
"resource": ""
}
|
q4117
|
QuickBase.Client.lookupBaseFieldTypeByName
|
train
|
def lookupBaseFieldTypeByName( fieldName )
type = ""
fid = lookupFieldIDByName( fieldName )
field = lookupField( fid ) if fid
type = field.attributes[ "base_type" ] if field
type
end
|
ruby
|
{
"resource": ""
}
|
q4118
|
QuickBase.Client.lookupFieldTypeByName
|
train
|
def lookupFieldTypeByName( fieldName )
type = ""
fid = lookupFieldIDByName( fieldName )
field = lookupField( fid ) if fid
type = field.attributes[ "field_type" ] if field
type
end
|
ruby
|
{
"resource": ""
}
|
q4119
|
QuickBase.Client.formatDate
|
train
|
def formatDate( milliseconds, fmtString = nil, addDay = false )
fmt = ""
fmtString = "%m-%d-%Y" if fmtString.nil?
if milliseconds
milliseconds_s = milliseconds.to_s
if milliseconds_s.length == 13
t = Time.at( milliseconds_s[0,10].to_i, milliseconds_s[10,3].to_i )
t += (60 * 60 * 24) if addDay
fmt = t.strftime( fmtString )
elsif milliseconds_s.length > 0
t = Time.at( (milliseconds_s.to_i) / 1000 )
t += (60 * 60 * 24) if addDay
fmt = t.strftime( fmtString )
end
end
fmt
end
|
ruby
|
{
"resource": ""
}
|
q4120
|
QuickBase.Client.formatDuration
|
train
|
def formatDuration( value, option = "hours" )
option = "hours" if option.nil?
if value.nil?
value = ""
else
seconds = (value.to_i/1000)
minutes = (seconds/60)
hours = (minutes/60)
days = (hours/24)
if option == "days"
value = days.to_s
elsif option == "hours"
value = hours.to_s
elsif option == "minutes"
value = minutes.to_s
end
end
value
end
|
ruby
|
{
"resource": ""
}
|
q4121
|
QuickBase.Client.formatTimeOfDay
|
train
|
def formatTimeOfDay(milliseconds, format = "%I:%M %p" )
format ||= "%I:%M %p"
timeOfDay = ""
timeOfDay = Time.at(milliseconds.to_i/1000).utc.strftime(format) if milliseconds
end
|
ruby
|
{
"resource": ""
}
|
q4122
|
QuickBase.Client.formatCurrency
|
train
|
def formatCurrency( value, options = nil )
value ||= "0.00"
if !value.include?( '.' )
value << ".00"
end
currencySymbol = currencyFormat = nil
if options
currencySymbol = options["currencySymbol"]
currencyFormat = options["currencyFormat"]
end
if currencySymbol
if currencyFormat
if currencyFormat == "0"
value = "#{currencySymbol}#{value}"
elsif currencyFormat == "1"
if value.include?("-")
value.gsub!("-","-#{currencySymbol}")
elsif value.include?("+")
value.gsub!("+","+#{currencySymbol}")
else
value = "#{currencySymbol}#{value}"
end
elsif currencyFormat == "2"
value = "#{value}#{currencySymbol}"
end
else
value = "#{currencySymbol}#{value}"
end
end
value
end
|
ruby
|
{
"resource": ""
}
|
q4123
|
QuickBase.Client.formatPercent
|
train
|
def formatPercent( value, options = nil )
if value
percent = (value.to_f * 100)
value = percent.to_s
if value.include?(".")
int,fraction = value.split('.')
if fraction.to_i == 0
value = int
else
value = "#{int}.#{fraction[0,2]}"
end
end
else
value = "0"
end
value
end
|
ruby
|
{
"resource": ""
}
|
q4124
|
QuickBase.Client.dateToMS
|
train
|
def dateToMS( dateString )
milliseconds = 0
if dateString and dateString.match( /[0-9][0-9]\-[0-9][0-9]\-[0-9][0-9][0-9][0-9]/)
d = Date.new( dateString[7,4], dateString[4,2], dateString[0,2] )
milliseconds = d.jd
end
milliseconds
end
|
ruby
|
{
"resource": ""
}
|
q4125
|
QuickBase.Client.escapeXML
|
train
|
def escapeXML( char )
if @xmlEscapes.nil?
@xmlEscapes = {}
(0..255).each{ |i| @xmlEscapes[ i.chr ] = sprintf( "&#%03d;", i ) }
end
return @xmlEscapes[ char ] if @xmlEscapes[ char ]
char
end
|
ruby
|
{
"resource": ""
}
|
q4126
|
QuickBase.Client.encodingStrings
|
train
|
def encodingStrings( reverse = false )
@encodingStrings = [ {"&" => "&" }, {"<" => "<"} , {">" => ">"}, {"'" => "'"}, {"\"" => """ } ] if @encodingStrings.nil?
if block_given?
if reverse
@encodingStrings.reverse_each{ |s| s.each{|k,v| yield v,k } }
else
@encodingStrings.each{ |s| s.each{|k,v| yield k,v } }
end
else
@encodingStrings
end
end
|
ruby
|
{
"resource": ""
}
|
q4127
|
QuickBase.Client.encodeXML
|
train
|
def encodeXML( text, doNPChars = false )
encodingStrings { |key,value| text.gsub!( key, value ) if text }
text.gsub!( /([^;\/?:@&=+\$,A-Za-z0-9\-_.!~*'()# ])/ ) { |c| escapeXML( $1 ) } if text and doNPChars
text
end
|
ruby
|
{
"resource": ""
}
|
q4128
|
QuickBase.Client.decodeXML
|
train
|
def decodeXML( text )
encodingStrings( true ) { |key,value| text.gsub!( value, key ) if text }
text.gsub!( /&#([0-9]{2,3});/ ) { |c| $1.chr } if text
text
end
|
ruby
|
{
"resource": ""
}
|
q4129
|
QuickBase.Client.fire
|
train
|
def fire( event )
if @eventSubscribers and @eventSubscribers.include?( event )
handlers = @eventSubscribers[ event ]
if handlers
handlers.each{ |handler| handler.handle( event ) }
end
end
end
|
ruby
|
{
"resource": ""
}
|
q4130
|
QuickBase.Client._addRecord
|
train
|
def _addRecord( fvlist = nil, disprec = nil, fform = nil, ignoreError = nil, update_id = nil )
addRecord( @dbid, fvlist, disprec, fform, ignoreError, update_id )
end
|
ruby
|
{
"resource": ""
}
|
q4131
|
QuickBase.Client._doQueryHash
|
train
|
def _doQueryHash( doQueryOptions )
doQueryOptions ||= {}
raise "options must be a Hash" unless doQueryOptions.is_a?(Hash)
doQueryOptions["dbid"] ||= @dbid
doQueryOptions["fmt"] ||= "structured"
doQuery( doQueryOptions["dbid"],
doQueryOptions["query"],
doQueryOptions["qid"],
doQueryOptions["qname"],
doQueryOptions["clist"],
doQueryOptions["slist"],
doQueryOptions["fmt"],
doQueryOptions["options"] )
end
|
ruby
|
{
"resource": ""
}
|
q4132
|
QuickBase.Client.downLoadFile
|
train
|
def downLoadFile( dbid, rid, fid, vid = "0" )
@dbid, @rid, @fid, @vid = dbid, rid, fid, vid
@downLoadFileURL = "http://#{@org}.#{@domain}.com/up/#{dbid}/a/r#{rid}/e#{fid}/v#{vid}"
if @useSSL
@downLoadFileURL.gsub!( "http:", "https:" )
end
@requestHeaders = { "Cookie" => "ticket=#{@ticket}" }
if @printRequestsAndResponses
puts
puts "downLoadFile request: -------------------------------------"
p @downLoadFileURL
p @requestHeaders
end
begin
if USING_HTTPCLIENT
@responseCode = 404
@fileContents = @httpConnection.get_content( @downLoadFileURL, nil, @requestHeaders )
@responseCode = 200 if @fileContents
else
@responseCode, @fileContents = @httpConnection.get( @downLoadFileURL, @requestHeaders )
end
rescue Net::HTTPBadResponse => @lastError
rescue Net::HTTPHeaderSyntaxError => @lastError
rescue StandardError => @lastError
end
if @printRequestsAndResponses
puts
puts "downLoadFile response: -------------------------------------"
p @responseCode
p @fileContents
end
return self if @chainAPIcalls
return @responseCode, @fileContents
end
|
ruby
|
{
"resource": ""
}
|
q4133
|
QuickBase.Client.downloadAndSaveFile
|
train
|
def downloadAndSaveFile( dbid, rid, fid, filename = nil, vid = "0" )
response, fileContents = downLoadFile( dbid, rid, fid, vid )
if fileContents and fileContents.length > 0
if filename and filename.length > 0
Misc.save_file( filename, fileContents )
else
record = getRecord( rid, dbid, [fid] )
if record and record[fid] and record[fid].length > 0
Misc.save_file( record[fid], fileContents )
else
Misc.save_file( "#{dbid}_#{rid}_#{fid}", fileContents )
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q4134
|
QuickBase.Client.fieldAddChoices
|
train
|
def fieldAddChoices( dbid, fid, choice )
@dbid, @fid, @choice = dbid, fid, choice
xmlRequestData = toXML( :fid, @fid )
if @choice.is_a?( Array )
@choice.each { |c| xmlRequestData << toXML( :choice, c ) }
elsif @choice.is_a?( String )
xmlRequestData << toXML( :choice, @choice )
end
sendRequest( :fieldAddChoices, xmlRequestData )
@fid = getResponseValue( :fid )
@fname = getResponseValue( :fname )
@numadded = getResponseValue( :numadded )
return self if @chainAPIcalls
return @fid, @name, @numadded
end
|
ruby
|
{
"resource": ""
}
|
q4135
|
QuickBase.Client.iterateDBPages
|
train
|
def iterateDBPages(dbid)
listDBPages(dbid){|page|
if page.is_a?( REXML::Element) and page.name == "page"
@pageid = page.attributes["id"]
@pagetype = page.attributes["type"]
@pagename = page.text if page.has_text?
@page = { "name" => @pagename, "id" => @pageid, "type" => @pagetype }
yield @page
end
}
end
|
ruby
|
{
"resource": ""
}
|
q4136
|
QuickBase.Client.getAllValuesForFields
|
train
|
def getAllValuesForFields( dbid, fieldNames = nil, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
if dbid
getSchema(dbid)
values = {}
fieldIDs = {}
if fieldNames and fieldNames.is_a?( String )
values[ fieldNames ] = []
fieldID = lookupFieldIDByName( fieldNames )
if fieldID
fieldIDs[ fieldNames ] = fieldID
elsif fieldNames.match(/[0-9]+/) # assume fieldNames is a field ID
fieldIDs[ fieldNames ] = fieldNames
end
elsif fieldNames and fieldNames.is_a?( Array )
fieldNames.each{ |name|
if name
values[ name ] = []
fieldID = lookupFieldIDByName( name )
if fieldID
fieldIDs[ fieldID ] = name
elsif name.match(/[0-9]+/) # assume name is a field ID
fieldIDs[ name ] = name
end
end
}
elsif fieldNames.nil?
getFieldNames(dbid).each{|name|
values[ name ] = []
fieldID = lookupFieldIDByName( name )
fieldIDs[ fieldID ] = name
}
end
if clist
clist << "."
clist = fieldIDs.keys.join('.')
elsif qid.nil? and qname.nil?
clist = fieldIDs.keys.join('.')
end
if clist
clist = clist.split('.')
clist.uniq!
clist = clist.join(".")
end
doQuery( dbid, query, qid, qname, clist, slist, fmt, options )
if @records and values.length > 0 and fieldIDs.length > 0
@records.each { |r|
if r.is_a?( REXML::Element) and r.name == "record"
values.each{ |k,v| v << "" }
r.each{ |f|
if f.is_a?( REXML::Element) and f.name == "f"
fid = f.attributes[ "id" ]
name = fieldIDs[ fid ] if fid
if name and values[ name ]
v = values[ name ]
v[-1] = f.text if v and f.has_text?
end
end
}
end
}
end
end
if values and block_given?
values.each{ |field, values| yield field, values }
else
values
end
end
|
ruby
|
{
"resource": ""
}
|
q4137
|
QuickBase.Client.getAllValuesForFieldsAsArray
|
train
|
def getAllValuesForFieldsAsArray( dbid, fieldNames = nil, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
ret = []
valuesForFields = getAllValuesForFields(dbid, fieldNames, query, qid, qname, clist, slist,fmt,options)
if valuesForFields
fieldNames ||= getFieldNames(@dbid)
if fieldNames and fieldNames[0]
ret = Array.new(valuesForFields[fieldNames[0]].length)
fieldType = {}
fieldNames.each{|field|fieldType[field]=lookupFieldTypeByName(field)}
valuesForFields.each{ |field,values|
values.each_index { |i|
ret[i] ||= {}
ret[i][field]=formatFieldValue(values[i],fieldType[field])
}
}
end
end
ret
end
|
ruby
|
{
"resource": ""
}
|
q4138
|
QuickBase.Client.getAllValuesForFieldsAsJSON
|
train
|
def getAllValuesForFieldsAsJSON( dbid, fieldNames = nil, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
ret = getAllValuesForFieldsAsArray(dbid,fieldNames,query,qid,qname,clist,slist,fmt,options)
ret = JSON.generate(ret) if ret
end
|
ruby
|
{
"resource": ""
}
|
q4139
|
QuickBase.Client.getAllValuesForFieldsAsPrettyJSON
|
train
|
def getAllValuesForFieldsAsPrettyJSON( dbid, fieldNames = nil, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
ret = getAllValuesForFieldsAsArray(dbid,fieldNames,query,qid,qname,clist,slist,fmt,options)
ret = JSON.pretty_generate(ret) if ret
end
|
ruby
|
{
"resource": ""
}
|
q4140
|
QuickBase.Client.getSummaryRecords
|
train
|
def getSummaryRecords( dbid, fieldNames,query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
summaryRecords = []
iterateSummaryRecords(dbid, fieldNames,query, qid, qname, clist, slist, fmt = "structured", options){|summaryRecord|
summaryRecords << summaryRecord.dup
}
summaryRecords
end
|
ruby
|
{
"resource": ""
}
|
q4141
|
QuickBase.Client.iterateRecordInfos
|
train
|
def iterateRecordInfos(dbid, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil)
getSchema(dbid)
recordIDFieldName = lookupFieldNameFromID("3")
fieldNames = getFieldNames
fieldIDs = {}
fieldNames.each{|name|fieldIDs[name] = lookupFieldIDByName(name)}
iterateRecords(dbid, [recordIDFieldName], query, qid, qname, clist, slist, fmt, options){|r|
getRecordInfo(dbid,r[recordIDFieldName])
fieldValues = {}
fieldIDs.each{|k,v|
fieldValues[k] = getFieldDataPrintableValue(v)
fieldValues[k] ||= getFieldDataValue(v)
}
yield fieldValues
}
end
|
ruby
|
{
"resource": ""
}
|
q4142
|
QuickBase.Client.applyPercentToRecords
|
train
|
def applyPercentToRecords( dbid, numericField, percentField,
query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil)
fieldNames = Array[numericField]
total = sum( dbid, fieldNames, query, qid, qname, clist, slist, fmt, options )
fieldNames << "3" # Record ID#
iterateRecords( dbid, fieldNames, query, qid, qname, clist, slist, fmt, options ){|record|
result = percent( [total[numericField],record[numericField]] )
clearFieldValuePairList
addFieldValuePair( percentField, nil, nil, result.to_s )
editRecord( dbid, record["3"], fvlist )
}
end
|
ruby
|
{
"resource": ""
}
|
q4143
|
QuickBase.Client.applyDeviationToRecords
|
train
|
def applyDeviationToRecords( dbid, numericField, deviationField,
query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil)
fieldNames = Array[numericField]
avg = average( dbid, fieldNames, query, qid, qname, clist, slist, fmt, options )
fieldNames << "3" # Record ID#
iterateRecords( dbid, fieldNames, query, qid, qname, clist, slist, fmt, options ){|record|
result = deviation( [avg[numericField],record[numericField]] )
clearFieldValuePairList
addFieldValuePair( deviationField, nil, nil, result.to_s )
editRecord( dbid, record["3"], fvlist )
}
end
|
ruby
|
{
"resource": ""
}
|
q4144
|
QuickBase.Client.percent
|
train
|
def percent( inputValues )
raise "'inputValues' must not be nil" if inputValues.nil?
raise "'inputValues' must be an Array" if not inputValues.is_a?(Array)
raise "'inputValues' must have at least two elements" if inputValues.length < 2
total = inputValues[0].to_f
total = 1.0 if total == 0.00
value = inputValues[1].to_f
((value/total)*100)
end
|
ruby
|
{
"resource": ""
}
|
q4145
|
QuickBase.Client.deviation
|
train
|
def deviation( inputValues )
raise "'inputValues' must not be nil" if inputValues.nil?
raise "'inputValues' must be an Array" if not inputValues.is_a?(Array)
raise "'inputValues' must have at least two elements" if inputValues.length < 2
value = inputValues[0].to_f - inputValues[1].to_f
value.abs
end
|
ruby
|
{
"resource": ""
}
|
q4146
|
QuickBase.Client.getFieldChoices
|
train
|
def getFieldChoices(dbid,fieldName=nil,fid=nil)
getSchema(dbid)
if fieldName
fid = lookupFieldIDByName(fieldName)
elsif not fid
raise "'fieldName' or 'fid' must be specified"
end
field = lookupField( fid )
if field
choices = []
choicesProc = proc { |element|
if element.is_a?(REXML::Element)
if element.name == "choice" and element.has_text?
choices << element.text
end
end
}
processChildElements(field,true,choicesProc)
choices = nil if choices.length == 0
choices
else
nil
end
end
|
ruby
|
{
"resource": ""
}
|
q4147
|
QuickBase.Client.deleteDuplicateRecords
|
train
|
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
|
{
"resource": ""
}
|
q4148
|
QuickBase.Client.copyRecord
|
train
|
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
|
{
"resource": ""
}
|
q4149
|
QuickBase.Client._importFromExcel
|
train
|
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
|
{
"resource": ""
}
|
q4150
|
QuickBase.Client.importCSVFile
|
train
|
def importCSVFile( filename, dbid = @dbid, targetFieldNames = nil, validateLines = true )
importSVFile( filename, ",", dbid, targetFieldNames, validateLines )
end
|
ruby
|
{
"resource": ""
}
|
q4151
|
QuickBase.Client.importTSVFile
|
train
|
def importTSVFile( filename, dbid = @dbid, targetFieldNames = nil, validateLines = true )
importSVFile( filename, "\t", dbid, targetFieldNames, validateLines )
end
|
ruby
|
{
"resource": ""
}
|
q4152
|
QuickBase.Client.makeSVFile
|
train
|
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
|
{
"resource": ""
}
|
q4153
|
QuickBase.Client.makeCSVFileForReport
|
train
|
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
|
{
"resource": ""
}
|
q4154
|
QuickBase.Client.getCSVForReport
|
train
|
def getCSVForReport(dbid,query=nil,qid=nil,qname=nil)
genResultsTable(dbid,query,nil,nil,nil,nil,"csv",qid,qname)
end
|
ruby
|
{
"resource": ""
}
|
q4155
|
QuickBase.Client.doSQLUpdate
|
train
|
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
|
{
"resource": ""
}
|
q4156
|
QuickBase.Client.doSQLInsert
|
train
|
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
|
{
"resource": ""
}
|
q4157
|
QuickBase.Client.eachField
|
train
|
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
|
{
"resource": ""
}
|
q4158
|
QuickBase.Client.alias_methods
|
train
|
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
|
{
"resource": ""
}
|
q4159
|
CommunityZero.Cookbook.to_hash
|
train
|
def to_hash
methods = instance_variables.map { |i| i.to_s.gsub('@', '') }
Hash[*methods.map { |m| [m, send(m.to_sym)] }.flatten]
end
|
ruby
|
{
"resource": ""
}
|
q4160
|
PEROBS.Array._referenced_object_ids
|
train
|
def _referenced_object_ids
@data.each.select do |v|
v && v.respond_to?(:is_poxreference?)
end.map { |o| o.id }
end
|
ruby
|
{
"resource": ""
}
|
q4161
|
AssertDifference.Expectation.generate_expected_value
|
train
|
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
|
{
"resource": ""
}
|
q4162
|
NdrSupport.Obfuscator.obfuscate
|
train
|
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
|
{
"resource": ""
}
|
q4163
|
CommunityZero.Server.start_background
|
train
|
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
|
{
"resource": ""
}
|
q4164
|
CommunityZero.Server.running?
|
train
|
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
|
{
"resource": ""
}
|
q4165
|
CommunityZero.Server.stop
|
train
|
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
|
{
"resource": ""
}
|
q4166
|
CommunityZero.Server.app
|
train
|
def app
lambda do |env|
request = Request.new(env)
response = router.call(request)
response[-1] = Array(response[-1])
response
end
end
|
ruby
|
{
"resource": ""
}
|
q4167
|
CommunityZero.CookbooksEndpoint.create_cookbook
|
train
|
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
|
{
"resource": ""
}
|
q4168
|
CommunityZero.CookbooksEndpoint.find_metadata
|
train
|
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
|
{
"resource": ""
}
|
q4169
|
Gnucash.Account.finalize
|
train
|
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
|
{
"resource": ""
}
|
q4170
|
Iglu.Resolver.lookup_schema
|
train
|
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
|
{
"resource": ""
}
|
q4171
|
Iglu.Resolver.validate
|
train
|
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
|
{
"resource": ""
}
|
q4172
|
Effective.MenuItem.visible_for?
|
train
|
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
|
{
"resource": ""
}
|
q4173
|
PEROBS.Store.copy
|
train
|
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
|
{
"resource": ""
}
|
q4174
|
PEROBS.Store.exit
|
train
|
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
|
{
"resource": ""
}
|
q4175
|
PEROBS.Store.new
|
train
|
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
|
{
"resource": ""
}
|
q4176
|
PEROBS.Store._construct_po
|
train
|
def _construct_po(klass, id, *args)
klass.new(Handle.new(self, id), *args)
end
|
ruby
|
{
"resource": ""
}
|
q4177
|
PEROBS.Store.sync
|
train
|
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
|
{
"resource": ""
}
|
q4178
|
PEROBS.Store.object_by_id
|
train
|
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
|
{
"resource": ""
}
|
q4179
|
PEROBS.Store.check
|
train
|
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
|
{
"resource": ""
}
|
q4180
|
PEROBS.Store.each
|
train
|
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
|
{
"resource": ""
}
|
q4181
|
PEROBS.Store.mark
|
train
|
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
|
{
"resource": ""
}
|
q4182
|
PEROBS.Store.check_object
|
train
|
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
|
{
"resource": ""
}
|
q4183
|
PEROBS.Object._referenced_object_ids
|
train
|
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
|
{
"resource": ""
}
|
q4184
|
PEROBS.Object._delete_reference_to_id
|
train
|
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
|
{
"resource": ""
}
|
q4185
|
PEROBS.Object.inspect
|
train
|
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
|
{
"resource": ""
}
|
q4186
|
PEROBS.Object._serialize
|
train
|
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
|
{
"resource": ""
}
|
q4187
|
PolyBelongsTo.SingletonSet.add?
|
train
|
def add?(record)
result = @set.add?( formatted_name( record ) )
return result if result
flag(record)
result
end
|
ruby
|
{
"resource": ""
}
|
q4188
|
PolyBelongsTo.SingletonSet.method_missing
|
train
|
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
|
{
"resource": ""
}
|
q4189
|
EPPClient.XML.get_result
|
train
|
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
|
{
"resource": ""
}
|
q4190
|
EPPClient.XML.command
|
train
|
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
|
{
"resource": ""
}
|
q4191
|
RegApi2.Action.create_http
|
train
|
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
|
{
"resource": ""
}
|
q4192
|
RegApi2.Action.get_form_data
|
train
|
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
|
{
"resource": ""
}
|
q4193
|
Summer.Connection.startup!
|
train
|
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
|
{
"resource": ""
}
|
q4194
|
Summer.Connection.parse
|
train
|
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
|
{
"resource": ""
}
|
q4195
|
SwissMatch.ZipCodes.[]
|
train
|
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
|
{
"resource": ""
}
|
q4196
|
CsvPirate.TheCapn.poop_deck
|
train
|
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
|
{
"resource": ""
}
|
q4197
|
CsvPirate.TheCapn.unfurl
|
train
|
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
|
{
"resource": ""
}
|
q4198
|
CsvPirate.TheCapn.binnacle
|
train
|
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
|
{
"resource": ""
}
|
q4199
|
CsvPirate.TheCapn.boatswain
|
train
|
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
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.