_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q27200 | Snoo.Flair.flair_template | test | def flair_template subreddit, opts = {}
logged_in?
params = {
flair_type: 'USER_FLAIR',
text_editable: false,
uh: @modhash,
r: subreddit,
api_type: 'json'
}
params.merge! opts
post('/api/flairtemplate', body: params)
end | ruby | {
"resource": ""
} |
q27201 | Snoo.Flair.select_flair_template | test | def select_flair_template template_id, subreddit, opts = {}
logged_in?
params = {
flair_template_id: template_id,
uh: @modhash,
r: subreddit,
api_type: 'json'
}
params.merge! opts
post('/api/selectflair', body: params)
end | ruby | {
"resource": ""
} |
q27202 | Snoo.Flair.flair_toggle | test | def flair_toggle enabled, subreddit
logged_in?
post('/api/setflairenabled', body: {flair_enabled: enabled, uh: @modhash, r: subreddit, api_type: 'json'})
end | ruby | {
"resource": ""
} |
q27203 | Snoo.Listings.get_comments | test | def get_comments opts = {}
query = { limit: 100 }
query.merge! opts
url = "%s/comments/%s%s.json" % [('/r/' + opts[:subreddit] if opts[:subreddit]), opts[:link_id], ('/blah/' + opts[:comment_id] if opts[:comment_id])]
get(url, query: query)
end | ruby | {
"resource": ""
} |
q27204 | Snoo.Listings.get_listing | test | def get_listing opts = {}
# Build the basic url
url = "%s/%s.json" % [('/r/' + opts[:subreddit] if opts[:subreddit] ), (opts[:page] if opts[:page])]
# Delete subreddit and page from the hash, they dont belong in the query
[:subreddit, :page].each {|k| opts.delete k}
query = opts
# Make the request
get(url, query: query)
end | ruby | {
"resource": ""
} |
q27205 | Snoo.Moderation.distinguish | test | def distinguish id, how = "yes"
logged_in?
hows = %w{yes no admin special}
post('/api/distinguish', body: {id: id, how: how, uh: @modhash, api_type: 'json'})
end | ruby | {
"resource": ""
} |
q27206 | Snoo.Moderation.remove | test | def remove id, spam = false
logged_in?
post('/api/remove', body: {id: id, spam: spam, uh: @modhash, api_type: 'json'})
end | ruby | {
"resource": ""
} |
q27207 | Snoo.Moderation.get_modlog | test | def get_modlog subreddit, opts = {}
logged_in?
options = {
limit: 100
}.merge opts
data = Nokogiri::HTML.parse(get("/r/#{subreddit}/about/log", query: options).body).css('.modactionlisting tr')
processed = {
data: [],
first: data[0]['data-fullname'],
first_date: Time.parse(data[0].children[0].child['datetime']),
last: data[-1]['data-fullname'],
last_date: Time.parse(data[-1].children[0].child['datetime']),
}
data.each do |tr|
processed[:data] << {
fullname: tr['data-fullname'],
time: Time.parse(tr.children[0].child['datetime']),
author: tr.children[1].child.content,
action: tr.children[2].child['class'].split[1],
description: tr.children[3].content,
href: tr.children[3].css('a').count == 0 ? nil : tr.children[3].css('a')[0]['href']
}
end
return processed
end | ruby | {
"resource": ""
} |
q27208 | Maxmind.ChargebackRequest.post | test | def post(query_params)
servers ||= SERVERS.map{|hostname| "https://#{hostname}/minfraud/chargeback"}
url = URI.parse(servers.shift)
req = Net::HTTP::Post.new(url.path, initheader = {'Content-Type' =>'application/json'})
req.basic_auth Maxmind::user_id, Maxmind::license_key
req.body = query_params
h = Net::HTTP.new(url.host, url.port)
h.use_ssl = true
h.verify_mode = OpenSSL::SSL::VERIFY_NONE
# set some timeouts
h.open_timeout = 60 # this blocks forever by default, lets be a bit less crazy.
h.read_timeout = self.class.timeout || DefaultTimeout
h.ssl_timeout = self.class.timeout || DefaultTimeout
h.start { |http| http.request(req) }
rescue Exception => e
retry if servers.size > 0
raise e
end | ruby | {
"resource": ""
} |
q27209 | Clipster.Clip.lifespan= | test | def lifespan=(lifespan)
@lifespan = lifespan
@@lifespans.each_with_index do |span, index|
if span[0] == lifespan && lifespan != "Forever"
self.expires = DateTime.now.advance(@@lifespans[index][1])
end
end
end | ruby | {
"resource": ""
} |
q27210 | Clipster.Clip.div | test | def div
cr_scanner = CodeRay.scan(self.clip, self.language)
# Only show line numbers if its greater than 1
if cr_scanner.loc <= 1
return cr_scanner.div
else
return cr_scanner.div(:line_numbers => :table)
end
end | ruby | {
"resource": ""
} |
q27211 | Htmless.Abstract.set_variables | test | def set_variables(instance_variables)
instance_variables.each { |name, value| instance_variable_set("@#{name}", value) }
yield(self)
instance_variables.each { |name, _| remove_instance_variable("@#{name}") }
self
end | ruby | {
"resource": ""
} |
q27212 | Htmless.Abstract.render | test | def render(object, method, *args, &block)
object.__send__ method, self, *args, &block
self
end | ruby | {
"resource": ""
} |
q27213 | Htmless.Abstract.join | test | def join(collection, glue = nil, &it)
# TODO as helper? two block method call #join(collection, &item).with(&glue)
glue_block = case glue
when String
lambda { text glue }
when Proc
glue
else
lambda {}
end
collection.each_with_index do |obj, i|
glue_block.call() if i > 0
obj.is_a?(Proc) ? obj.call : it.call(obj)
end
end | ruby | {
"resource": ""
} |
q27214 | IsbmAdaptor.ProviderPublication.open_session | test | def open_session(uri)
validate_presence_of uri, 'Channel URI'
response = @client.call(:open_publication_session, message: { 'ChannelURI' => uri })
response.to_hash[:open_publication_session_response][:session_id].to_s
end | ruby | {
"resource": ""
} |
q27215 | IsbmAdaptor.ProviderPublication.post_publication | test | def post_publication(session_id, content, topics, expiry = nil)
validate_presence_of session_id, 'Session Id'
validate_presence_of content, 'Content'
validate_presence_of topics, 'Topics'
validate_xml content
topics = [topics].flatten
# Use Builder to generate XML body as we need to concatenate XML message content
xml = Builder::XmlMarkup.new
xml.isbm :SessionID, session_id
xml.isbm :MessageContent do
xml << content
end
topics.each do |topic|
xml.isbm :Topic, topic
end
duration = expiry.to_s
xml.isbm :Expiry, duration unless duration.nil?
response = @client.call(:post_publication, message: xml.target!)
response.to_hash[:post_publication_response][:message_id].to_s
end | ruby | {
"resource": ""
} |
q27216 | IsbmAdaptor.ProviderPublication.expire_publication | test | def expire_publication(session_id, message_id)
validate_presence_of session_id, 'Session Id'
validate_presence_of message_id, 'Message Id'
@client.call(:expire_publication, message: { 'SessionID' => session_id, 'MessageID' => message_id })
return true
end | ruby | {
"resource": ""
} |
q27217 | IsbmAdaptor.Client.validate_presence_of | test | def validate_presence_of(value, name)
if value.respond_to?(:each)
value.each do |v|
if v.blank?
raise ArgumentError, "Values in #{name} must not be blank"
end
end
else
if value.blank?
raise ArgumentError, "#{name} must not be blank"
end
end
end | ruby | {
"resource": ""
} |
q27218 | IsbmAdaptor.Client.validate_xml | test | def validate_xml(xml)
doc = Nokogiri.XML(xml)
raise ArgumentError, "XML is not well formed: #{xml}" unless doc.errors.empty?
end | ruby | {
"resource": ""
} |
q27219 | IsbmAdaptor.Client.default_savon_options | test | def default_savon_options(options)
options[:logger] = Rails.logger if options[:logger].nil? && defined?(Rails)
options[:log] = false if options[:log].nil?
options[:pretty_print_xml] = true if options[:pretty_print_xml].nil?
end | ruby | {
"resource": ""
} |
q27220 | IsbmAdaptor.ConsumerPublication.read_publication | test | def read_publication(session_id)
validate_presence_of session_id, 'Session Id'
response = @client.call(:read_publication, message: { 'SessionID' => session_id })
extract_message(response)
end | ruby | {
"resource": ""
} |
q27221 | IsbmAdaptor.ConsumerRequest.open_session | test | def open_session(uri, listener_url = nil)
validate_presence_of uri, 'Channel URI'
message = { 'ChannelURI' => uri }
message['ListenerURL'] = listener_url if listener_url
response = @client.call(:open_consumer_request_session, message: message)
response.to_hash[:open_consumer_request_session_response][:session_id].to_s
end | ruby | {
"resource": ""
} |
q27222 | IsbmAdaptor.ConsumerRequest.post_request | test | def post_request(session_id, content, topic, expiry = nil)
validate_presence_of session_id, 'Session Id'
validate_presence_of content, 'Content'
validate_presence_of topic, 'Topic'
validate_xml content
# Use Builder to generate XML body as we need to concatenate XML message content
xml = Builder::XmlMarkup.new
xml.isbm :SessionID, session_id
xml.isbm :MessageContent do
xml << content
end
xml.isbm :Topic, topic
duration = expiry.to_s
xml.isbm :Expiry, duration unless duration.nil?
response = @client.call(:post_request, message: xml.target!)
response.to_hash[:post_request_response][:message_id].to_s
end | ruby | {
"resource": ""
} |
q27223 | IsbmAdaptor.ConsumerRequest.expire_request | test | def expire_request(session_id, message_id)
validate_presence_of session_id, 'Session Id'
validate_presence_of message_id, 'Message Id'
@client.call(:expire_request, message: { 'SessionID' => session_id, 'MessageID' => message_id })
return true
end | ruby | {
"resource": ""
} |
q27224 | IsbmAdaptor.ConsumerRequest.read_response | test | def read_response(session_id, request_message_id)
validate_presence_of session_id, 'Session Id'
validate_presence_of request_message_id, 'Request Message Id'
message = { 'SessionID' => session_id, 'RequestMessageID' => request_message_id }
response = @client.call(:read_response, message: message)
extract_message(response)
end | ruby | {
"resource": ""
} |
q27225 | IsbmAdaptor.ConsumerRequest.remove_response | test | def remove_response(session_id, request_message_id)
validate_presence_of session_id, 'Session Id'
validate_presence_of request_message_id, 'Request Message Id'
message = { 'SessionID' => session_id, 'RequestMessageID' => request_message_id }
@client.call(:remove_response, message: message)
return true
end | ruby | {
"resource": ""
} |
q27226 | IsbmAdaptor.ProviderRequest.open_session | test | def open_session(uri, topics, listener_url = nil, xpath_expression = nil, xpath_namespaces = [])
validate_presence_of uri, 'Channel URI'
validate_presence_of topics, 'Topics'
validate_presence_of xpath_expression, 'XPath Expression' if xpath_namespaces.present?
topics = [topics].flatten
# Use Builder to generate XML body as we may have multiple Topic elements
xml = Builder::XmlMarkup.new
xml.isbm :ChannelURI, uri
topics.each do |topic|
xml.isbm :Topic, topic
end
xml.isbm :ListenerURL, listener_url unless listener_url.nil?
xml.isbm :XPathExpression, xpath_expression unless xpath_expression.nil?
xpath_namespaces.each do |prefix, name|
xml.isbm :XPathNamespace do
xml.isbm :NamespacePrefix, prefix
xml.isbm :NamespaceName, name
end
end
response = @client.call(:open_provider_request_session, message: xml.target!)
response.to_hash[:open_provider_request_session_response][:session_id].to_s
end | ruby | {
"resource": ""
} |
q27227 | IsbmAdaptor.ProviderRequest.post_response | test | def post_response(session_id, request_message_id, content)
validate_presence_of session_id, 'Session Id'
validate_presence_of request_message_id, 'Request Message Id'
validate_presence_of content, 'Content'
validate_xml content
# Use Builder to generate XML body as we need to concatenate XML message content
xml = Builder::XmlMarkup.new
xml.isbm :SessionID, session_id
xml.isbm :RequestMessageID, request_message_id
xml.isbm :MessageContent do
xml << content
end
response = @client.call(:post_response, message: xml.target!)
response.to_hash[:post_response_response][:message_id].to_s
end | ruby | {
"resource": ""
} |
q27228 | IsbmAdaptor.ChannelManagement.create_channel | test | def create_channel(uri, type, description = nil, tokens = {})
validate_presence_of uri, 'Channel URI'
validate_presence_of type, 'Channel Type'
channel_type = type.to_s.downcase.capitalize
validate_inclusion_in channel_type, IsbmAdaptor::Channel::TYPES, 'Channel Type'
message = { 'ChannelURI' => uri,
'ChannelType' => channel_type }
message['ChannelDescription'] = description unless description.nil?
message['SecurityToken'] = security_token_hash(tokens) if tokens.any?
@client.call(:create_channel, message: message)
return true
end | ruby | {
"resource": ""
} |
q27229 | IsbmAdaptor.ChannelManagement.add_security_tokens | test | def add_security_tokens(uri, tokens = {})
validate_presence_of uri, 'Channel URI'
validate_presence_of tokens, 'Security Tokens'
message = { 'ChannelURI' => uri,
'SecurityToken' => security_token_hash(tokens) }
@client.call(:add_security_tokens, message: message)
return true
end | ruby | {
"resource": ""
} |
q27230 | IsbmAdaptor.ChannelManagement.remove_security_tokens | test | def remove_security_tokens(uri, tokens = {})
validate_presence_of uri, 'Channel URI'
validate_presence_of tokens, 'Security Tokens'
message = { 'ChannelURI' => uri,
'SecurityToken' => security_token_hash(tokens) }
@client.call(:remove_security_tokens, message: message)
return true
end | ruby | {
"resource": ""
} |
q27231 | IsbmAdaptor.ChannelManagement.get_channel | test | def get_channel(uri, &block)
validate_presence_of uri, 'Channel URI'
response = @client.call(:get_channel, message: { 'ChannelURI' => uri }, &block)
hash = response.to_hash[:get_channel_response][:channel]
IsbmAdaptor::Channel.from_hash(hash)
end | ruby | {
"resource": ""
} |
q27232 | IsbmAdaptor.ChannelManagement.get_channels | test | def get_channels(&block)
response = @client.call(:get_channels, {}, &block)
channels = response.to_hash[:get_channels_response][:channel]
channels = [channels].compact unless channels.is_a?(Array)
channels.map do |hash|
IsbmAdaptor::Channel.from_hash(hash)
end
end | ruby | {
"resource": ""
} |
q27233 | Idioma.Phrase.update_backend | test | def update_backend
if Idioma.configuration.redis_backend
if i18n_value.present?
Idioma::RedisBackend.update_phrase(self)
else
Idioma::RedisBackend.delete_phrase(self)
end
end
end | ruby | {
"resource": ""
} |
q27234 | Idioma.PhrasesController.set_phrase | test | def set_phrase
@phrase = Phrase.find(params[:id])
rescue ActiveRecord::RecordNotFound
respond_to do |format|
format.json { render json: {}.to_json, status: :not_found }
format.html {
flash[:error] = t('idioma.record_not_found')
redirect_to phrases_path
}
end
end | ruby | {
"resource": ""
} |
q27235 | IsbmAdaptor.Duration.to_s | test | def to_s
date = []
date << "#{@years}Y" unless @years.nil?
date << "#{@months}M" unless @months.nil?
date << "#{@days}D" unless @days.nil?
time = []
time << "#{@hours}H" unless @hours.nil?
time << "#{@minutes}M" unless @minutes.nil?
time << "#{@seconds}S" unless @seconds.nil?
result = nil
if !date.empty? || !time.empty?
result = 'P'
result += date.join unless date.empty?
result += 'T' + time.join unless time.empty?
end
result
end | ruby | {
"resource": ""
} |
q27236 | GeoCalc.PrettyPrint.to_lat | test | def to_lat format = :dms, dp = 0
return lat if !format
GeoUnits::Converter.to_lat lat, format, dp
end | ruby | {
"resource": ""
} |
q27237 | Optimizely.Engine.projects | test | def projects
if @projects.nil?
response = self.get("projects")
@projects = response.collect { |project_json| Project.new(project_json) }
end
@projects
end | ruby | {
"resource": ""
} |
q27238 | Optimizely.Engine.project | test | def project(id)
@url = "projects/#{id}"
raise OptimizelyError::NoProjectID, "A Project ID is required to retrieve the project." if id.nil?
response = self.get(@url)
Project.new(response)
end | ruby | {
"resource": ""
} |
q27239 | Optimizely.Engine.experiments | test | def experiments(project_id)
raise OptimizelyError::NoProjectID, "A Project ID is required to retrieve experiments." if project_id.nil?
response = self.get("projects/#{project_id}/experiments")
response.collect { |response_json| Experiment.new(response_json) }
end | ruby | {
"resource": ""
} |
q27240 | Optimizely.Engine.experiment | test | def experiment(id)
@url = "experiments/#{id}"
raise OptimizelyError::NoExperimentID, "An Experiment ID is required to retrieve the experiment." if id.nil?
response = self.get(@url)
Experiment.new(response)
end | ruby | {
"resource": ""
} |
q27241 | Optimizely.Engine.stats | test | def stats(experiment_id)
@url = "experiments/#{experiment_id}/stats"
raise OptimizelyError::NoExperimentID, "An Experiment ID is required to retrieve the stats." if experiment_id.nil?
response = self.get(@url)
response.collect { |response_json| Stat.new(response_json) }
end | ruby | {
"resource": ""
} |
q27242 | Optimizely.Engine.variations | test | def variations(experiment_id)
raise OptimizelyError::NoExperimentID, "An Experiment ID is required to retrieve variations." if experiment_id.nil?
response = self.get("experiments/#{experiment_id}/variations")
response.collect { |variation_json| Variation.new(variation_json) }
end | ruby | {
"resource": ""
} |
q27243 | Optimizely.Engine.variation | test | def variation(id)
@url = "variations/#{id}"
raise OptimizelyError::NoVariationID, "A Variation ID is required to retrieve the variation." if id.nil?
response = self.get(@url)
Variation.new(response)
end | ruby | {
"resource": ""
} |
q27244 | Optimizely.Engine.audiences | test | def audiences(project_id)
raise OptimizelyError::NoProjectID, "A Project ID is required to retrieve audiences." if project_id.nil?
response = self.get("projects/#{project_id}/audiences")
response.collect { |audience_json| Audience.new(audience_json) }
end | ruby | {
"resource": ""
} |
q27245 | Optimizely.Engine.audience | test | def audience(id)
@url = "audiences/#{id}"
raise OptimizelyError::NoAudienceID, "An Audience ID is required to retrieve the audience." if id.nil?
response = self.get(@url)
Audience.new(response)
end | ruby | {
"resource": ""
} |
q27246 | Optimizely.Engine.get | test | def get(url)
uri = URI.parse("#{BASE_URL}#{url}/")
https = Net::HTTP.new(uri.host, uri.port)
https.read_timeout = @options[:timeout] if @options[:timeout]
https.verify_mode = OpenSSL::SSL::VERIFY_NONE
https.use_ssl = true
request = Net::HTTP::Get.new(uri.request_uri, @headers)
response = https.request(request)
# Response code error checking
if response.code != '200'
check_response(response.code, response.body)
else
parse_json(response.body)
end
end | ruby | {
"resource": ""
} |
q27247 | Rufus::Edo.NetTyrantTable.lget | test | def lget (*keys)
h = keys.flatten.inject({}) { |hh, k| hh[k] = nil; hh }
r = @db.mget(h)
raise 'lget failure' if r == -1
h
end | ruby | {
"resource": ""
} |
q27248 | SecretSharing.Shamir.get_random_number | test | def get_random_number(bytes)
RbNaCl::Util.bin2hex(RbNaCl::Random.random_bytes(bytes).to_s).to_i(16)
end | ruby | {
"resource": ""
} |
q27249 | SecretSharing.Shamir.get_random_number_with_bitlength | test | def get_random_number_with_bitlength(bits)
byte_length = (bits / 8.0).ceil + 10
random_num = get_random_number(byte_length)
random_num_bin_str = random_num.to_s(2) # Get 1's and 0's
# Slice off only the bits we require, convert Bits to Numeric (Bignum)
random_num_bin_str.slice(0, bits).to_i(2)
end | ruby | {
"resource": ""
} |
q27250 | Rufus::Edo.TableQuery.add | test | def add (colname, operator, val, affirmative=true, no_index=false)
colname = colname.to_s
val = val.to_s
op = operator.is_a?(Fixnum) ? operator : OPERATORS[operator]
op = op | TDBQCNEGATE unless affirmative
op = op | TDBQCNOIDX if no_index
@query.addcond(colname, op, val)
end | ruby | {
"resource": ""
} |
q27251 | Rufus::Edo.CabinetCore.keys | test | def keys (options={})
if @db.respond_to? :fwmkeys
pref = options.fetch(:prefix, "")
@db.fwmkeys(pref, options[:limit] || -1)
elsif @db.respond_to? :range
@db.range("[min,max]", nil)
else
raise NotImplementedError, "Database does not support keys()"
end
end | ruby | {
"resource": ""
} |
q27252 | DynamicNestedForms.ViewHelpers.autocomplete_to_add_item | test | def autocomplete_to_add_item(name, f, association, source, options = {})
new_object = f.object.send(association).klass.new
options[:class] = ["autocomplete add-item", options[:class]].compact.join " "
options[:data] ||= {}
options[:data][:id] = new_object.object_id
options[:data][:source] = source
options[:data][:item] = f.fields_for(association, new_object, child_index: options[:data][:id]) do |builder|
render(association.to_s.singularize + "_item", f: builder).gsub "\n", ""
end
text_field_tag "autocomplete_nested_content", nil, options
end | ruby | {
"resource": ""
} |
q27253 | Rufus::Tokyo::Dystopia.Core.fetch | test | def fetch( id )
r = nil
begin
r = lib.tcidbget( @db, id )
rescue => e
# if we have 'no record found' then return nil
if lib.tcidbecode( @db ) == 22 then
return nil
else
raise_error
end
end
return r
end | ruby | {
"resource": ""
} |
q27254 | Rufus::Tokyo::Dystopia.Core.search | test | def search( expression )
out_count = ::FFI::MemoryPointer.new :pointer
out_list = ::FFI::MemoryPointer.new :pointer
out_list = lib.tcidbsearch2( @db, expression, out_count )
count = out_count.read_int
results = out_list.get_array_of_uint64(0, count )
return results
end | ruby | {
"resource": ""
} |
q27255 | GameIcons.DidYouMean.char_freq | test | def char_freq(str)
freqs = Hash.new(0)
(1..4).each do |i|
str.chars.each_cons(i).inject(freqs) do |freq, ngram|
ngram = ngram.join
freq[ngram] = freq[ngram] + 1
freq
end
end
freqs
end | ruby | {
"resource": ""
} |
q27256 | GameIcons.DidYouMean.top | test | def top(n, scores)
scores.sort {|a,b| a[1] <=> b[1]}.map{|x| x[0]}.first(n)
end | ruby | {
"resource": ""
} |
q27257 | GameIcons.Icon.recolor | test | def recolor(bg: '#000', fg: '#fff', bg_opacity: "1.0", fg_opacity: "1.0")
OptionalDeps.require_nokogiri
bg.prepend('#') unless bg.start_with? '#'
fg.prepend('#') unless fg.start_with? '#'
doc = Nokogiri::XML(self.string)
doc.css('path')[0]['fill'] = bg # dark backdrop
doc.css('path')[1]['fill'] = fg # light drawing
doc.css('path')[0]['fill-opacity'] = bg_opacity.to_s # dark backdrop
doc.css('path')[1]['fill-opacity'] = fg_opacity.to_s # light drawing
@svgstr = doc.to_xml
self
end | ruby | {
"resource": ""
} |
q27258 | Rufus::Tokyo.Cabinet.compact_copy | test | def compact_copy (target_path)
@other_db = Cabinet.new(target_path)
self.each { |k, v| @other_db[k] = v }
@other_db.close
end | ruby | {
"resource": ""
} |
q27259 | Rufus::Tokyo.Cabinet.keys | test | def keys (options={})
if @type == "tcf"
min, max = "min", "max"
l = lib.tcfdbrange2( as_fixed, min, Rufus::Tokyo.blen(min),
max, Rufus::Tokyo.blen(max), -1)
else
pre = options.fetch(:prefix, "")
l = lib.abs_fwmkeys(
@db, pre, Rufus::Tokyo.blen(pre), options[:limit] || -1)
end
l = Rufus::Tokyo::List.new(l)
options[:native] ? l : l.release
end | ruby | {
"resource": ""
} |
q27260 | Rufus::Tokyo.Cabinet.get4 | test | def get4 (k)
l = lib.tcbdbget4(as_btree, k, Rufus::Tokyo.blen(k))
Rufus::Tokyo::List.new(l).release
end | ruby | {
"resource": ""
} |
q27261 | Rufus::Tokyo.Map.[]= | test | def []= (k, v)
clib.tcmapput(pointer, k, Rufus::Tokyo::blen(k), v, Rufus::Tokyo::blen(v))
v
end | ruby | {
"resource": ""
} |
q27262 | Rufus::Tokyo.Map.delete | test | def delete (k)
v = self[k]
return nil unless v
clib.tcmapout(pointer_or_raise, k, Rufus::Tokyo::blen(k)) ||
raise("failed to remove key '#{k}'")
v
end | ruby | {
"resource": ""
} |
q27263 | Rufus::Tokyo.Map.keys | test | def keys
clib.tcmapiterinit(pointer_or_raise)
a = []
klen = FFI::MemoryPointer.new(:int)
loop do
k = clib.tcmapiternext(@pointer, klen)
break if k.address == 0
a << k.get_bytes(0, klen.get_int(0))
end
return a
ensure
klen.free
end | ruby | {
"resource": ""
} |
q27264 | Rufus::Tokyo.List.[]= | test | def []= (a, b, c=nil)
i, s = c.nil? ? [ a, b ] : [ [a, b], c ]
range = if i.is_a?(Range)
i
elsif i.is_a?(Array)
start, count = i
(start..start + count - 1)
else
[ i ]
end
range = norm(range)
values = s.is_a?(Array) ? s : [ s ]
# not "values = Array(s)"
range.each_with_index do |offset, index|
val = values[index]
if val
clib.tclistover(@pointer, offset, val, Rufus::Tokyo.blen(val))
else
outlen_op(:tclistremove, values.size)
end
end
self
end | ruby | {
"resource": ""
} |
q27265 | Rufus::Tokyo.Table.keys | test | def keys (options={})
pre = options.fetch(:prefix, "")
l = lib.tab_fwmkeys(
@db, pre, Rufus::Tokyo.blen(pre), options[:limit] || -1)
l = Rufus::Tokyo::List.new(l)
options[:native] ? l : l.release
end | ruby | {
"resource": ""
} |
q27266 | Rufus::Tokyo.Table.lget | test | def lget (*keys)
keys.flatten.inject({}) { |h, k|
k = k.to_s
v = self[k]
h[k] = v if v
h
}
end | ruby | {
"resource": ""
} |
q27267 | Rufus::Tokyo.Table.raise_error | test | def raise_error
err_code = lib.tab_ecode(@db)
err_msg = lib.tab_errmsg(err_code)
raise TokyoError.new("(err #{err_code}) #{err_msg}")
end | ruby | {
"resource": ""
} |
q27268 | Rufus::Tokyo.TableResultSet.each | test | def each
(0..size-1).each do |i|
pk = @list[i]
if @opts[:pk_only]
yield(pk)
else
val = @table[pk]
val[:pk] = pk unless @opts[:no_pk]
yield(val)
end
end
end | ruby | {
"resource": ""
} |
q27269 | GameIcons.Finder.find | test | def find(icon)
str = icon.to_s.downcase
file = DB.files[str] ||
DB.files[str.sub(/\.svg$/,'')] ||
not_found(str, icon)
Icon.new(file)
end | ruby | {
"resource": ""
} |
q27270 | ToARFF.SQLiteDB.get_columns | test | def get_columns(table_name)
columns_arr = []
pst = @db.prepare "SELECT * FROM #{table_name} LIMIT 6"
pst.columns.each do |c|
columns_arr.push(c)
end
columns_arr
end | ruby | {
"resource": ""
} |
q27271 | ToARFF.SQLiteDB.is_numeric | test | def is_numeric(table_name, column_name)
if @db.execute("SELECT #{column_name} from #{table_name} LIMIT 1").first.first.is_a? Numeric
return true
else
return false
end
end | ruby | {
"resource": ""
} |
q27272 | ToARFF.SQLiteDB.deal_with_valid_option | test | def deal_with_valid_option(temp_tables, temp_columns, temp_column_types, res)
if !temp_tables.empty?
check_given_tables_validity(temp_tables)
temp_tables.each do |t|
res << convert_table(t)
end
elsif !temp_columns.keys.empty?
check_given_columns_validity(temp_columns)
res << convert_from_columns_hash(temp_columns)
elsif !temp_column_types.empty?
check_given_columns_validity(temp_column_types)
res << convert_from_column_types_hash(temp_column_types)
end
end | ruby | {
"resource": ""
} |
q27273 | DRYSpec.Helpers.let_context | test | def let_context(*args, &block)
context_string, hash =
case args.map(&:class)
when [String, Hash] then ["#{args[0]} #{args[1]}", args[1]]
when [Hash] then [args[0].inspect, args[0]]
end
context(context_string) do
hash.each { |var, value| let(var) { value } }
instance_eval(&block)
end
end | ruby | {
"resource": ""
} |
q27274 | DRYSpec.Helpers.subject_should_raise | test | def subject_should_raise(*args)
error, message = args
it_string = "subject should raise #{error}"
it_string += " (#{message.inspect})" if message
it it_string do
expect { subject }.to raise_error error, message
end
end | ruby | {
"resource": ""
} |
q27275 | DRYSpec.Helpers.subject_should_not_raise | test | def subject_should_not_raise(*args)
error, message = args
it_string = "subject should not raise #{error}"
it_string += " (#{message.inspect})" if message
it it_string do
expect { subject }.not_to raise_error error, message
end
end | ruby | {
"resource": ""
} |
q27276 | Janus.Manager.login | test | def login(user, options = {})
options[:scope] ||= Janus.scope_for(user)
set_user(user, options)
Janus::Manager.run_callbacks(:login, user, self, options)
end | ruby | {
"resource": ""
} |
q27277 | Janus.Manager.logout | test | def logout(*scopes)
scopes = janus_sessions.keys if scopes.empty?
scopes.each do |scope|
_user = user(scope)
unset_user(scope)
Janus::Manager.run_callbacks(:logout, _user, self, :scope => scope)
end
request.reset_session if janus_sessions.empty?
end | ruby | {
"resource": ""
} |
q27278 | Janus.Manager.set_user | test | def set_user(user, options = {})
scope = options[:scope] || Janus.scope_for(user)
janus_sessions[scope.to_s] = { 'user_class' => user.class.name, 'user_id' => user.id }
end | ruby | {
"resource": ""
} |
q27279 | Janus.Manager.unset_user | test | def unset_user(scope)
janus_sessions.delete(scope.to_s)
@users.delete(scope.to_sym) unless @users.nil?
end | ruby | {
"resource": ""
} |
q27280 | Janus.Manager.user | test | def user(scope)
scope = scope.to_sym
@users ||= {}
if authenticated?(scope)
if @users[scope].nil?
begin
@users[scope] = user_class(scope).find(session(scope)['user_id'])
rescue ActiveRecord::RecordNotFound
unset_user(scope)
else
Janus::Manager.run_callbacks(:fetch, @users[scope], self, :scope => scope)
end
end
@users[scope]
end
end | ruby | {
"resource": ""
} |
q27281 | Tml.Cache.namespace | test | def namespace
return '#' if Tml.config.disabled?
@namespace || Tml.config.cache[:namespace] || Tml.config.application[:key][0..5]
end | ruby | {
"resource": ""
} |
q27282 | Tml.Cache.extract_version | test | def extract_version(app, version = nil)
if version
Tml.cache.version.set(version.to_s)
else
version_data = app.api_client.get_from_cdn('version', {t: Time.now.to_i}, {uncompressed: true})
unless version_data
Tml.logger.debug('No releases have been generated yet. Please visit your Dashboard and publish translations.')
return
end
Tml.cache.version.set(version_data['version'])
end
end | ruby | {
"resource": ""
} |
q27283 | Tml.Cache.warmup | test | def warmup(version = nil, cache_path = nil)
if cache_path.nil?
warmup_from_cdn(version)
else
warmup_from_files(version, cache_path)
end
end | ruby | {
"resource": ""
} |
q27284 | Tml.Cache.warmup_from_files | test | def warmup_from_files(version = nil, cache_path = nil)
t0 = Time.now
Tml.logger = Logger.new(STDOUT)
Tml.logger.debug('Starting cache warmup from local files...')
version ||= Tml.config.cache[:version]
cache_path ||= Tml.config.cache[:path]
cache_path = "#{cache_path}/#{version}"
Tml.cache.version.set(version.to_s)
Tml.logger.debug("Warming Up Version: #{Tml.cache.version}")
application = JSON.parse(File.read("#{cache_path}/application.json"))
Tml.cache.store(Tml::Application.cache_key, application)
sources = JSON.parse(File.read("#{cache_path}/sources.json"))
application['languages'].each do |lang|
locale = lang['locale']
language = JSON.parse(File.read("#{cache_path}/#{locale}/language.json"))
Tml.cache.store(Tml::Language.cache_key(locale), language)
sources.each do |src|
source = JSON.parse(File.read("#{cache_path}/#{locale}/sources/#{src}.json"))
Tml.cache.store(Tml::Source.cache_key(locale, src), source)
end
end
t1 = Time.now
Tml.logger.debug("Cache warmup took #{t1-t0}s")
end | ruby | {
"resource": ""
} |
q27285 | Tml.Cache.warmup_from_cdn | test | def warmup_from_cdn(version = nil)
t0 = Time.now
Tml.logger = Logger.new(STDOUT)
Tml.logger.debug('Starting cache warmup from CDN...')
app = Tml::Application.new(key: Tml.config.application[:key], cdn_host: Tml.config.application[:cdn_host])
extract_version(app, version)
Tml.logger.debug("Warming Up Version: #{Tml.cache.version}")
application = app.api_client.get_from_cdn('application', {t: Time.now.to_i})
Tml.cache.store(Tml::Application.cache_key, application)
sources = app.api_client.get_from_cdn('sources', {t: Time.now.to_i}, {uncompressed: true})
application['languages'].each do |lang|
locale = lang['locale']
language = app.api_client.get_from_cdn("#{locale}/language", {t: Time.now.to_i})
Tml.cache.store(Tml::Language.cache_key(locale), language)
sources.each do |src|
source = app.api_client.get_from_cdn("#{locale}/sources/#{src}", {t: Time.now.to_i})
Tml.cache.store(Tml::Source.cache_key(locale, src), source)
end
end
t1 = Time.now
Tml.logger.debug("Cache warmup took #{t1-t0}s")
end | ruby | {
"resource": ""
} |
q27286 | Tml.Cache.default_cache_path | test | def default_cache_path
@cache_path ||= begin
path = Tml.config.cache[:path]
path ||= 'config/tml'
FileUtils.mkdir_p(path)
FileUtils.chmod(0777, path)
path
end
end | ruby | {
"resource": ""
} |
q27287 | Tml.Cache.download | test | def download(cache_path = default_cache_path, version = nil)
t0 = Time.now
Tml.logger = Logger.new(STDOUT)
Tml.logger.debug('Starting cache download...')
app = Tml::Application.new(key: Tml.config.application[:key], cdn_host: Tml.config.application[:cdn_host])
extract_version(app, version)
Tml.logger.debug("Downloading Version: #{Tml.cache.version}")
archive_name = "#{Tml.cache.version}.tar.gz"
path = "#{cache_path}/#{archive_name}"
url = "#{app.cdn_host}/#{Tml.config.application[:key]}/#{archive_name}"
Tml.logger.debug("Downloading cache file: #{url}")
open(path, 'wb') do |file|
file << open(url).read
end
Tml.logger.debug('Extracting cache file...')
version_path = "#{cache_path}/#{Tml.cache.version}"
Tml::Utils.untar(Tml::Utils.ungzip(File.new(path)), version_path)
Tml.logger.debug("Cache has been stored in #{version_path}")
File.unlink(path)
begin
current_path = 'current'
FileUtils.chdir(cache_path)
FileUtils.rm(current_path) if File.exist?(current_path)
FileUtils.ln_s(Tml.cache.version.to_s, current_path)
Tml.logger.debug("The new version #{Tml.cache.version} has been marked as current")
rescue Exception => ex
Tml.logger.debug("Could not generate current symlink to the cache path: #{ex.message}")
end
t1 = Time.now
Tml.logger.debug("Cache download took #{t1-t0}s")
end | ruby | {
"resource": ""
} |
q27288 | CouchWatcher.DatabaseListener.say | test | def say(message, color=nil)
@shell ||= Thor::Shell::Basic.new
@shell.say message, color
end | ruby | {
"resource": ""
} |
q27289 | Tml.CacheVersion.validate_cache_version | test | def validate_cache_version(version)
# if cache version is hardcoded, use it
if Tml.config.cache[:version]
return Tml.config.cache[:version]
end
return version unless version.is_a?(Hash)
return 'undefined' unless version['t'].is_a?(Numeric)
return version['version'] if cache.read_only?
# if version check interval is disabled, don't try to check for the new
# cache version on the CDN
if version_check_interval == -1
Tml.logger.debug('Cache version check is disabled')
return version['version']
end
expires_at = version['t'] + version_check_interval
if expires_at < Time.now.to_i
Tml.logger.debug('Cache version is outdated, needs refresh')
return 'undefined'
end
delta = expires_at - Time.now.to_i
Tml.logger.debug("Cache version is up to date, expires in #{delta}s")
version['version']
end | ruby | {
"resource": ""
} |
q27290 | Tml.CacheVersion.fetch | test | def fetch
self.version = begin
ver = cache.fetch(CACHE_VERSION_KEY) do
{'version' => Tml.config.cache[:version] || 'undefined', 't' => cache_timestamp}
end
validate_cache_version(ver)
end
end | ruby | {
"resource": ""
} |
q27291 | SBDB.Environment.[] | test | def [] file, *ps, &exe
opts = ::Hash === ps.last ? ps.pop : {}
opts[:env] = self
name, type, flg = ps[0] || opts[:name], ps[1] || opts[:type], ps[2] || opts[:flags]
ps.push opts
@dbs[ [file, name, flg | CREATE]] ||= (type || SBDB::Unknown).new file, *ps, &exe
end | ruby | {
"resource": ""
} |
q27292 | Janus.Strategies.run_strategies | test | def run_strategies(scope)
Janus::Manager.strategies.each { |name| break if run_strategy(name, scope) }
end | ruby | {
"resource": ""
} |
q27293 | Janus.Strategies.run_strategy | test | def run_strategy(name, scope)
strategy = "Janus::Strategies::#{name.to_s.camelize}".constantize.new(scope, self)
if strategy.valid?
strategy.authenticate!
if strategy.success?
send(strategy.auth_method, strategy.user, :scope => scope)
Janus::Manager.run_callbacks(:authenticate, strategy.user, self, :scope => scope)
end
end
strategy.success?
end | ruby | {
"resource": ""
} |
q27294 | Paraduct.Runner.perform | test | def perform(script)
export_variables = @params.reverse_merge("PARADUCT_JOB_ID" => @job_id, "PARADUCT_JOB_NAME" => job_name)
variable_string = export_variables.map { |key, value| %(export #{key}="#{value}";) }.join(" ")
Array.wrap(script).inject("") do |stdout, command|
stdout << run_command("#{variable_string} #{command}")
stdout
end
end | ruby | {
"resource": ""
} |
q27295 | Sixword.CLI.print_hex | test | def print_hex(data, chunk_index, cols=80)
case hex_style
when 'lower', 'lowercase'
# encode to lowercase hex with no newlines
print Sixword::Hex.encode(data)
when 'finger', 'fingerprint'
# encode to GPG fingerprint like hex with newlines
newlines_every = cols / 5
if chunk_index != 0
if chunk_index % newlines_every == 0
print "\n"
else
print ' '
end
end
print Sixword::Hex.encode_fingerprint(data)
when 'colon', 'colons'
# encode to SSL/SSH fingerprint like hex with colons
print ':' unless chunk_index == 0
print Sixword::Hex.encode_colons(data)
end
end | ruby | {
"resource": ""
} |
q27296 | Sixword.CLI.read_input_by_6_words | test | def read_input_by_6_words
word_arr = []
while true
line = stream.gets
if line.nil?
break # EOF
end
line.scan(/\S+/) do |word|
word_arr << word
# return the array if we have accumulated 6 words
if word_arr.length == 6
yield word_arr
word_arr.clear
end
end
end
# yield whatever we have left, if anything
if !word_arr.empty?
yield word_arr
end
end | ruby | {
"resource": ""
} |
q27297 | Oedipus.QueryBuilder.select | test | def select(query, filters)
where, *bind_values = conditions(query, filters)
[
[
from(filters),
where,
order_by(filters),
limits(filters)
].join(" "),
*bind_values
]
end | ruby | {
"resource": ""
} |
q27298 | Oedipus.QueryBuilder.update | test | def update(id, attributes)
set_attrs, *bind_values = update_attributes(attributes)
[
[
"UPDATE #{@index_name} SET",
set_attrs,
"WHERE id = ?"
].join(" "),
*bind_values.push(id)
]
end | ruby | {
"resource": ""
} |
q27299 | Oedipus.Connection.query | test | def query(sql, *bind_values)
@pool.acquire { |conn| conn.query(sql, *bind_values).first }
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.