_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q6500
|
KeytechKit.ElementFileHandler.load
|
train
|
def load(element_key)
parameter = { basic_auth: @auth }
response = self.class.get("/elements/#{element_key}/files", parameter)
parse_files(response['FileInfos']) if response.success?
end
|
ruby
|
{
"resource": ""
}
|
q6501
|
KeytechKit.ElementFileHandler.load_masterfile
|
train
|
def load_masterfile(element_key)
parameter = { basic_auth: @auth }
response = self.class.get("/elements/#{element_key}/files/masterfile", parameter)
return response if response.success?
end
|
ruby
|
{
"resource": ""
}
|
q6502
|
KeytechKit.ElementFileHandler.upload_masterfile
|
train
|
def upload_masterfile(element_key, file, original_filename)
# file, elementkey , name??
content_length = file.size
content_type = 'application/octet-stream; charset=utf-8'
parameter = { basic_auth: @auth,
headers: { 'Content-Type' => content_type,
'Content-Length' => content_length.to_s,
'storageType' => 'MASTER',
'filename' => original_filename.to_s },
body: file.read }
upload_file element_key, parameter
end
|
ruby
|
{
"resource": ""
}
|
q6503
|
Shells.ShellBase.change_quit
|
train
|
def change_quit(quit_command)
raise Shells::NotRunning unless running?
self.options = options.dup.merge( quit: quit_command ).freeze
self
end
|
ruby
|
{
"resource": ""
}
|
q6504
|
Taaze.TaazeComments.url_get_html
|
train
|
def url_get_html(url_str)
url = URI.parse(URI.encode(url_str)) # first get total size
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) { |http| http.request(req) }
res.body
end
|
ruby
|
{
"resource": ""
}
|
q6505
|
Taaze.TaazeComments.extract_comments
|
train
|
def extract_comments(content, user_id)
# Json format~
# "content":"勇氣就是熱誠,來自於我們對自己工作的自信心;.....",
# "title":"",
# "status":"C",
# "stars":"5",
# "prodId":"11100597685",
# "titleMain":"行銷之神原一平全集(精裝版)",
# "orgProdId":"11100597685",
# "pkNo":"1000243977",
# "mdf_time":"2015/10/15",
# "crt_time":"2015/10/15"
#
# orgProdId -> bookID -> 11100597685
# title -> book title
# content -> comment
# comment_url
# pkNo -> comment ID ->13313301
#
# http://www.taaze.tw/container_zekeaclt_view.html?co=1000238964&ci=12522728&cp=3
# co->comment ci->user
data_arr = []
if content
content.each do |cmtItem|
data_hash_sub = Hash.new {}
data_hash_sub['title'] = cmtItem['titleMain']
data_hash_sub['comment'] = cmtItem['content']
data_hash_sub['book_url'] = BOOK_URL + cmtItem['orgProdId']
url = MAIN_URL + 'co=' + cmtItem['pkNo'] + '&ci=' + user_id + '&cp=3'
data_hash_sub['comment_url'] = url
data_hash_sub['crt_time'] = cmtItem['crt_time']
data_arr.push(data_hash_sub)
end
else
data_arr = []
end
@comments_found ||= data_arr
end
|
ruby
|
{
"resource": ""
}
|
q6506
|
Model.ClassMethods.find!
|
train
|
def find!( *args )
raise_not_found_error_was = Mongoid.raise_not_found_error
begin
Mongoid.raise_not_found_error = true
self.find( *args )
ensure
Mongoid.raise_not_found_error = raise_not_found_error_was
end
end
|
ruby
|
{
"resource": ""
}
|
q6507
|
ThinkFeelDoDashboard.ApplicationHelper.breadcrumbs
|
train
|
def breadcrumbs
return unless show_breadcrumbs?
content_for(
:breadcrumbs,
content_tag(:ol, class: "breadcrumb") do
concat(content_tag(:li, link_to("Home", root_path)))
if can_view_resource_index?
concat(
content_tag(
:li, controller_link
)
)
end
end
)
end
|
ruby
|
{
"resource": ""
}
|
q6508
|
Sndacs.Bucket.put_bucket_policy
|
train
|
def put_bucket_policy(bucket_policy)
if bucket_policy && bucket_policy.is_a?(String) && bucket_policy.strip != ''
bucket_request(:put,:body => bucket_policy,:subresource=>"policy")
true
else
false
end
end
|
ruby
|
{
"resource": ""
}
|
q6509
|
Bebox.ProfileWizard.create_new_profile
|
train
|
def create_new_profile(project_root, profile_name, profile_base_path)
# Clean the profile_path to make it a valid path
profile_base_path = Bebox::Profile.cleanpath(profile_base_path)
# Check if the profile name is valid
return unless name_valid?(profile_name, profile_base_path)
# Check if the profile exist
profile_path = profile_base_path.empty? ? profile_name : profile_complete_path(profile_base_path, profile_name)
return error(_('wizard.profile.name_exist')%{profile: profile_path}) if profile_exists?(project_root, profile_path)
# Profile creation
profile = Bebox::Profile.new(profile_name, project_root, profile_base_path)
output = profile.create
ok _('wizard.profile.creation_success')%{profile: profile_path}
return output
end
|
ruby
|
{
"resource": ""
}
|
q6510
|
Bebox.ProfileWizard.name_valid?
|
train
|
def name_valid?(profile_name, profile_base_path)
unless valid_puppet_class_name?(profile_name)
error _('wizard.profile.invalid_name')%{words: Bebox::RESERVED_WORDS.join(', ')}
return false
end
return true if profile_base_path.empty?
# Check if the path name is valid
unless Bebox::Profile.valid_pathname?(profile_base_path)
error _('wizard.profile.invalid_path')%{words: Bebox::RESERVED_WORDS.join(', ')}
return false
end
true
end
|
ruby
|
{
"resource": ""
}
|
q6511
|
Bebox.ProfileWizard.remove_profile
|
train
|
def remove_profile(project_root)
# Choose a profile from the availables
profiles = Bebox::Profile.list(project_root)
# Get a profile if exist
if profiles.count > 0
profile = choose_option(profiles, _('wizard.choose_remove_profile'))
else
return error _('wizard.profile.no_deletion_profiles')
end
# Ask for deletion confirmation
return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.profile.confirm_deletion'))
# Profile deletion
profile_name = profile.split('/').last
profile_base_path = profile.split('/')[0...-1].join('/')
profile = Bebox::Profile.new(profile_name, project_root, profile_base_path)
output = profile.remove
ok _('wizard.profile.deletion_success')
return output
end
|
ruby
|
{
"resource": ""
}
|
q6512
|
Remi.DataSubject.field_symbolizer
|
train
|
def field_symbolizer(arg = nil)
return @field_symbolizer unless arg
@field_symbolizer = if arg.is_a? Symbol
Remi::FieldSymbolizers[arg]
else
arg
end
end
|
ruby
|
{
"resource": ""
}
|
q6513
|
Remi.DataSubject.df=
|
train
|
def df=(new_dataframe)
dsl_eval
if new_dataframe.respond_to? :df_type
@dataframe = new_dataframe
else
@dataframe = Remi::DataFrame.create(df_type, new_dataframe)
end
end
|
ruby
|
{
"resource": ""
}
|
q6514
|
Jinx.MultiEnumerator.method_missing
|
train
|
def method_missing(symbol, *args)
self.class.new(@components.map { |enum|enum.send(symbol, *args) })
end
|
ruby
|
{
"resource": ""
}
|
q6515
|
Gogetit.GogetLXD.generate_user_data
|
train
|
def generate_user_data(lxd_params, options)
logger.info("Calling <#{__method__.to_s}>")
lxd_params[:config] = {}
if options[:'no-maas']
lxd_params[:config][:"user.user-data"] = {}
else
sshkeys = maas.get_sshkeys
pkg_repos = maas.get_package_repos
lxd_params[:config][:'user.user-data'] = { 'ssh_authorized_keys' => [] }
sshkeys.each do |key|
lxd_params[:config][:'user.user-data']['ssh_authorized_keys'].push(key['key'])
end
pkg_repos.each do |repo|
if repo['name'] == 'main_archive'
lxd_params[:config][:'user.user-data']['apt_mirror'] = repo['url']
end
end
lxd_params[:config][:"user.user-data"]['source_image_alias'] = lxd_params[:alias]
lxd_params[:config][:"user.user-data"]['maas'] = true
end
if options[:'maas-on-lxc']
lxd_params[:config][:"security.privileged"] = "true"
end
if options[:'lxd-in-lxd']
lxd_params[:config][:"security.privileged"] = "true"
lxd_params[:config][:"security.nesting"] = "true"
end
if options[:'kvm-in-lxd']
lxd_params[:config][:"security.nesting"] = "true"
lxd_params[:config][:"linux.kernel_modules"] = "iptable_nat, ip6table_nat, ebtables, openvswitch, kvm, kvm_intel, tap, vhost, vhost_net, vhost_scsi, vhost_vsock"
end
lxd_params[:config][:"user.user-data"]['gogetit'] = true
# To disable to update apt database on first boot
# so chef client can keep doing its job.
lxd_params[:config][:'user.user-data']['package_update'] = false
lxd_params[:config][:'user.user-data']['package_upgrade'] = false
lxd_params[:config][:'user.user-data'] = generate_cloud_init_config(
options,
config,
lxd_params[:config][:'user.user-data']
)
lxd_params[:config][:"user.user-data"] = \
"#cloud-config\n" + YAML.dump(lxd_params[:config][:"user.user-data"])[4..-1]
return lxd_params
end
|
ruby
|
{
"resource": ""
}
|
q6516
|
Pyrite.Dsl.fill_in
|
train
|
def fill_in(element, value)
if element.match /date/ # Try to guess at date selects
select_date(element, value)
else
browser.type("jquery=#{element}", value)
end
end
|
ruby
|
{
"resource": ""
}
|
q6517
|
Pyrite.Dsl.select_date
|
train
|
def select_date(element, value)
suffixes = {
:year => '1i',
:month => '2i',
:day => '3i',
:hour => '4i',
:minute => '5i'
}
date = value.respond_to?(:year) ? value : Date.parse(value)
browser.select "jquery=#{element}_#{suffixes[:year]}", date.year
browser.select "jquery=#{element}_#{suffixes[:month]}", date.strftime('%B')
browser.select "jquery=#{element}_#{suffixes[:day]}", date.day
end
|
ruby
|
{
"resource": ""
}
|
q6518
|
Pyrite.Dsl.wait_for
|
train
|
def wait_for(element)
case element
when :page_load
browser.wait_for(:wait_for => :page)
when :ajax
browser.wait_for(:wait_for => :ajax, :javascript_framework => Pyrite.js_framework)
else
browser.wait_for(:element => "jquery=#{element}")
end
end
|
ruby
|
{
"resource": ""
}
|
q6519
|
Maguro.Features.create_database_files
|
train
|
def create_database_files
username = builder.options['database-username']
password = builder.options['database-password']
builder.remove_file "config/database.yml"
create_database_yml_file("config/database.sample.yml", "username", "pass")
create_database_yml_file("config/database.yml", username, password)
end
|
ruby
|
{
"resource": ""
}
|
q6520
|
Kamaze::Project::Concern::Observable.ClassMethods.add_observer
|
train
|
def add_observer(observer_class, func = :handle_event)
func = func.to_sym
unless observer_class.instance_methods.include?(func)
m = "#<#{observer_class}> does not respond to `#{func}'"
raise NoMethodError, m
end
observer_peers[observer_class] = func
self
end
|
ruby
|
{
"resource": ""
}
|
q6521
|
MuckEngine.SslRequirement.ssl_required?
|
train
|
def ssl_required?
return ENV['SSL'] == 'on' ? true : false if defined? ENV['SSL']
return false if local_request?
return false if RAILS_ENV == 'test'
((self.class.read_inheritable_attribute(:ssl_required_actions) || []).include?(action_name.to_sym)) && (::Rails.env == 'production' || ::Rails.env == 'staging')
end
|
ruby
|
{
"resource": ""
}
|
q6522
|
RootedTree.Node.ancestors
|
train
|
def ancestors
return to_enum(__callee__) unless block_given?
node = self
loop do
node = node.parent
yield node
end
end
|
ruby
|
{
"resource": ""
}
|
q6523
|
RootedTree.Node.child
|
train
|
def child(index = nil)
unless index
raise ArgumentError, 'No index for node with degree != 1' if degree != 1
return first
end
rtl, index = wrap_index index
raise RangeError, 'Child index out of range' if index >= degree
children(rtl: rtl).each do |c|
break c if index.zero?
index -= 1
end
end
|
ruby
|
{
"resource": ""
}
|
q6524
|
RootedTree.Node.edges
|
train
|
def edges(&block)
return to_enum(__callee__) unless block_given?
children do |v|
yield self, v
v.edges(&block)
end
end
|
ruby
|
{
"resource": ""
}
|
q6525
|
RootedTree.Node.+
|
train
|
def +(other)
unless root? && other.root?
raise StructureException, 'Only roots can be added'
end
a = frozen? ? dup : self
b = other.frozen? ? other.dup : other
ab = self.class.new
ab << a << b
end
|
ruby
|
{
"resource": ""
}
|
q6526
|
SwaggerDocsGenerator.Methods.swagger_doc
|
train
|
def swagger_doc(action, &block)
parse = ParserAction.new(action, &block)
parse.adding_path
end
|
ruby
|
{
"resource": ""
}
|
q6527
|
SwaggerDocsGenerator.Methods.swagger_definition
|
train
|
def swagger_definition(name, &block)
parse = ParserDefinition.new(name, &block)
parse.adding_definition
end
|
ruby
|
{
"resource": ""
}
|
q6528
|
Whenner.Conversions.Promise
|
train
|
def Promise(obj)
return obj.to_promise if obj.respond_to?(:to_promise)
Deferred.new.fulfill(obj)
end
|
ruby
|
{
"resource": ""
}
|
q6529
|
RogerEslint.Lint.normalize_path
|
train
|
def normalize_path(test, path)
Pathname.new(path).relative_path_from(test.project.path.realpath).to_s
end
|
ruby
|
{
"resource": ""
}
|
q6530
|
MMETools.ArgsProc.assert_valid_keys
|
train
|
def assert_valid_keys(options, valid_options)
unknown_keys = options.keys - valid_options.keys
raise(ArgumentError, "Unknown options(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty?
end
|
ruby
|
{
"resource": ""
}
|
q6531
|
CLIntegracon.Formatter.describe_file_diff
|
train
|
def describe_file_diff(diff, max_width=80)
description = []
description << "File comparison error `#{diff.relative_path}` for #{spec.spec_folder}:"
description << "--- DIFF ".ljust(max_width, '-')
description += diff.map do |line|
case line
when /^\+/ then line.green
when /^-/ then line.red
else line
end.gsub("\n",'').gsub("\r", '\r')
end
description << "--- END ".ljust(max_width, '-')
description << ''
description * "\n"
end
|
ruby
|
{
"resource": ""
}
|
q6532
|
Gitkite.GitkitController.sign_in_success
|
train
|
def sign_in_success
g_user = signed_in?
if g_user
user = {
:email => g_user.email,
:user_id => g_user.user_id,
:name => g_user.name,
:photo_url => g_user.photo_url,
:provider_id => g_user.provider_id
}
@user = User.find_by(user_id: user[:user_id])
if @user.nil?
@user = User.create user
else
@user.update user
end
session[:user] = @user.id
if session[:previous_url]
previous_url = session[:previous_url]
session.delete :previous_url
redirect_to previous_url
else
redirect_to main_app.root_url
end
else
@user = false
session.delete :user
flash.alert = "Sign in failed. Please try again."
redirect_to gitkit_sign_in_url
end
end
|
ruby
|
{
"resource": ""
}
|
q6533
|
Bebox.FilesHelper.render_erb_template
|
train
|
def render_erb_template(template_path, options)
require 'tilt'
Tilt::ERBTemplate.new(template_path).render(nil, options)
end
|
ruby
|
{
"resource": ""
}
|
q6534
|
Bebox.FilesHelper.write_content_to_file
|
train
|
def write_content_to_file(file_path, content)
File.open(file_path, 'w') do |f|
f.write content
end
end
|
ruby
|
{
"resource": ""
}
|
q6535
|
TriglavClient.ResourcesApi.create_resource
|
train
|
def create_resource(resource, opts = {})
data, _status_code, _headers = create_resource_with_http_info(resource, opts)
return data
end
|
ruby
|
{
"resource": ""
}
|
q6536
|
TriglavClient.ResourcesApi.get_resource
|
train
|
def get_resource(id_or_uri, opts = {})
data, _status_code, _headers = get_resource_with_http_info(id_or_uri, opts)
return data
end
|
ruby
|
{
"resource": ""
}
|
q6537
|
TriglavClient.ResourcesApi.list_aggregated_resources
|
train
|
def list_aggregated_resources(uri_prefix, opts = {})
data, _status_code, _headers = list_aggregated_resources_with_http_info(uri_prefix, opts)
return data
end
|
ruby
|
{
"resource": ""
}
|
q6538
|
TriglavClient.ResourcesApi.update_resource
|
train
|
def update_resource(id_or_uri, resource, opts = {})
data, _status_code, _headers = update_resource_with_http_info(id_or_uri, resource, opts)
return data
end
|
ruby
|
{
"resource": ""
}
|
q6539
|
Coinstack.UserPair.add_list_data
|
train
|
def add_list_data(data)
raise symbol.to_s if data.nil?
self.exchange_rate = data['price_usd'].to_f
self.perchant_change_week = data['percent_change_7d'].to_f
self.perchant_change_day = data['percent_change_24h'].to_f
end
|
ruby
|
{
"resource": ""
}
|
q6540
|
Poster.Forum.new_topic
|
train
|
def new_topic board: 92, subj: 'test', msg: 'msg', icon: "exclamation"
board = board.instance_of?(Symbol) ? @opts[:boards][board] : board
# Check board posting page first (to get sequence numbers)
get "/index.php?action=post;board=#{board}.0"
raise "Not logged, cannot post!" unless logged?
p msg
# Create new post
seqnum, sc = find_fields 'seqnum', 'sc'
subj = xml_encode(subj_encode(subj))
msg = xml_encode(msg)
# p subj, msg
# exit
post "/index.php?action=post2;start=0;board=#{board}",
content_type: 'multipart/form-data; charset=ISO-8859-1',
body: { topic: 0, subject: subj, icon: icon, message: msg,
notify: 0, do_watch: 0, selfmod: 0, lock: 0, goback: 1, ns: "NS", post: "Post",
additional_options: 0, sc: sc, seqnum: seqnum },
options: {timeout: 5} # open/read timeout in seconds
# Make sure the message was posted, return topic page
new_topic = @response.headers['location']
# p @response.body
raise "No redirect to posted topic!" unless new_topic && @response.status == 302
get new_topic
end
|
ruby
|
{
"resource": ""
}
|
q6541
|
Tangle.BaseGraphPrivate.each_vertex_breadth_first
|
train
|
def each_vertex_breadth_first(start_vertex, walk_method)
remaining = [start_vertex]
remaining.each_with_object([]) do |vertex, history|
history << vertex
yield vertex
send(walk_method, vertex).each do |other|
remaining << other unless history.include?(other)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6542
|
RequiresApproval.ClassMethods.create_versions_class
|
train
|
def create_versions_class
versions_table_name = self.versions_table_name
self.const_set self.versions_class_name, Class.new(ActiveRecord::Base)
self.versions_class.class_eval do
self.table_name = versions_table_name
# Whitelist public attributes
# Everything since this class is for internal use only
public_attributes = self.column_names.reject{|attr| self.protected_attributes.deny?(attr)}
self.attr_accessible(*public_attributes)
end
end
|
ruby
|
{
"resource": ""
}
|
q6543
|
Aims.Geometry.make_bonds
|
train
|
def make_bonds(bond_length = 3.0)
# initialize an empty array
@bonds = Array.new
# Make bonds between all atoms
# stack = atoms.dup
atoms_extended = atoms.dup
if periodic?
v1 = lattice_vectors[0]
v2 = lattice_vectors[1]
atoms.each{|a|
[-1, 0, 1].each{|n1|
[-1, 0, 1].each{|n2|
atoms_extended << a.displace(n1*v1[0] + n2*v2[0], n1*v1[1] + n2*v2[1], n1*v1[2] + n2*v2[2])
}
}
}
end
tree = KDTree.new(atoms_extended, 3)
atoms.each{|a|
r = 4
neighbors = tree.find([a.x-r, a.x+r], [a.y-r, a.y+r], [a.z-r, a.z+r])
neighbors.each{|n|
b = Bond.new(a, n)
@bonds << b if b.length < bond_length
}
}
# atom1 = stack.pop
# while (not stack.empty?)
# stack.each{|atom2|
# b = Bond.new(atom1, atom2)
# @bonds << b if b.length < bond_length
# if periodic?
# v1 = lattice_vectors[0]
# v2 = lattice_vectors[1]
# [-1, 0, 1].each{|n1|
# [-1, 0, 1].each{|n2|
# b = Bond.new(atom1, atom2.displace(n1*v1[0] + n2*v2[0], n1*v1[1] + n2*v2[1], n1*v1[2] + n2*v2[2]))
# @bonds << b if b.length < bond_length
# }
# }
# end
# }
# atom1 = stack.pop
# end
end
|
ruby
|
{
"resource": ""
}
|
q6544
|
Aims.Geometry.recache_visible_atoms
|
train
|
def recache_visible_atoms(makeBonds = false)
plane_count = (@clip_planes ? @clip_planes.length : 0)
return if plane_count == 0
if @visibleAtoms
@visibleAtoms.clear
else
@visibleAtoms = []
end
@atoms.each{|a|
i = plane_count
@clip_planes.each{|p|
i = i-1 if 0 >= p.distance_to_point(a.x, a.y, a.z)
}
@visibleAtoms << a if i == 0
}
if @visibleBonds
@visibleBonds.clear
else
@visibleBonds = []
end
make_bonds if (makeBonds or @bonds.nil?)
@bonds.each{|b|
a0 = b[0]
a1 = b[1]
i0 = plane_count
i1 = plane_count
@clip_planes.each{|p|
i0 = i0-1 if 0 >= p.distance_to_point(a0.x, a0.y, a0.z)
i1 = i1-1 if 0 >= p.distance_to_point(a1.x, a1.y, a1.z)
}
@visibleBonds << b if (i0 + i1) < 2
}
end
|
ruby
|
{
"resource": ""
}
|
q6545
|
Aims.Geometry.center
|
train
|
def center(visible_only = true)
if atoms.empty?
return Atom.new(0,0,0)
else
bounds = bounding_box(visible_only)
x = (bounds[0].x + bounds[1].x)/2.0
y = (bounds[0].y + bounds[1].y)/2.0
z = (bounds[0].z + bounds[1].z)/2.0
return Atom.new(x,y,z)
end
end
|
ruby
|
{
"resource": ""
}
|
q6546
|
Aims.Geometry.displace
|
train
|
def displace(x,y,z)
Geometry.new(atoms(:all).collect{|a|
a.displace(x,y,z)
}, self.lattice_vectors)
#TODO copy miller indices
end
|
ruby
|
{
"resource": ""
}
|
q6547
|
Aims.Geometry.repeat
|
train
|
def repeat(nx=1, ny=1, nz=1)
raise "Not a periodic system." if self.lattice_vectors.nil?
u = self.copy
v1 = self.lattice_vectors[0]
v2 = self.lattice_vectors[1]
v3 = self.lattice_vectors[2]
nx_sign = (0 < nx) ? 1 : -1
ny_sign = (0 < ny) ? 1 : -1
nz_sign = (0 < nz) ? 1 : -1
new_atoms = []
nx.to_i.abs.times do |i|
ny.to_i.abs.times do |j|
nz.to_i.abs.times do |k|
new_atoms << self.displace(nx_sign*i*v1[0] + ny_sign*j*v2[0] + nz_sign*k*v3[0],
nx_sign*i*v1[1] + ny_sign*j*v2[1] + nz_sign*k*v3[1],
nx_sign*i*v1[2] + ny_sign*j*v2[2] + nz_sign*k*v3[2]).atoms
end
end
end
u.atoms = new_atoms.flatten
u.lattice_vectors = [Vector[nx.abs*v1[0], nx.abs*v1[1], nx.abs*v1[2]],
Vector[ny.abs*v2[0], ny.abs*v2[1], ny.abs*v2[2]],
Vector[nz.abs*v3[0], nz.abs*v3[1], nz.abs*v3[2]]]
# u.make_bonds
return u
end
|
ruby
|
{
"resource": ""
}
|
q6548
|
Aims.Geometry.format_geometry_in
|
train
|
def format_geometry_in
output = ""
if self.lattice_vectors
output << self.lattice_vectors.collect{|v| "lattice_vector #{v[0]} #{v[1]} #{v[2]}"}.join("\n")
output << "\n"
end
output << self.atoms.collect{|a| a.format_geometry_in}.join("\n")
output
end
|
ruby
|
{
"resource": ""
}
|
q6549
|
Aims.Geometry.format_xyz
|
train
|
def format_xyz(title = "Aims Geoemtry")
output = self.atoms.size.to_s + "\n"
output << "#{title} \n"
self.atoms.each{ |a|
output << [a.species, a.x.to_s, a.y.to_s, a.z.to_s].join("\t") + "\n"
}
output
end
|
ruby
|
{
"resource": ""
}
|
q6550
|
Aims.Geometry.delta
|
train
|
def delta(aCell)
raise "Cells do not have the same number of atoms" unless self.atoms.size == aCell.atoms.size
pseudo_atoms = []
self.atoms.size.times {|i|
a1 = self.atoms[i]
a2 = aCell.atoms[i]
raise "Species do not match" unless a1.species == a2.species
a = Atom.new
a.species = a1.species
a.x = a1.x - a2.x
a.y = a1.y - a2.y
a.z = a1.z - a2.z
pseudo_atoms << a
}
Geometry.new(pseudo_atoms)
end
|
ruby
|
{
"resource": ""
}
|
q6551
|
Dynabix.Metadata.has_metadata
|
train
|
def has_metadata(serializer=:metadata, *attributes)
serialize(serializer, HashWithIndifferentAccess)
if RUBY_VERSION < '1.9'
raise "has_metadata serializer must be named ':metadata', this restriction is lifted in Ruby 1.9+" unless serializer == :metadata
else
# we can safely define additional accessors, Ruby 1.8 will only
# be able to use the statically defined :metadata_accessor
if serializer != :metadata
# define the class accessor
define_singleton_method "#{serializer}_accessor" do |*attrs|
attrs.each do |attr|
create_reader(serializer, attr)
create_writer(serializer, attr)
end
end
# define the class read accessor
define_singleton_method "#{serializer}_reader" do |*attrs|
attrs.each do |attr|
create_reader(serializer, attr)
end
end
# define the class write accessor
define_singleton_method "#{serializer}_writer" do |*attrs|
attrs.each do |attr|
create_writer(serializer, attr)
end
end
end
end
# Define each of the attributes for this serializer
attributes.each do |attr|
create_reader(serializer, attr)
create_writer(serializer, attr)
end
end
|
ruby
|
{
"resource": ""
}
|
q6552
|
Shells.ShellBase.queue_input
|
train
|
def queue_input(data) #:doc:
sync do
if options[:unbuffered_input]
data = data.chars
input_fifo.push *data
else
input_fifo.push data
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6553
|
CLIntegracon::Adapter::Bacon.Context.subject
|
train
|
def subject &block
@subject ||= CLIntegracon::shared_config.subject.dup
return @subject if block.nil?
instance_exec(@subject, &block)
end
|
ruby
|
{
"resource": ""
}
|
q6554
|
CLIntegracon::Adapter::Bacon.Context.file_tree_spec_context
|
train
|
def file_tree_spec_context &block
@file_tree_spec_context ||= CLIntegracon.shared_config.file_tree_spec_context.dup
return @file_tree_spec_context if block.nil?
instance_exec(@file_tree_spec_context, &block)
end
|
ruby
|
{
"resource": ""
}
|
q6555
|
Garcon.ReadWriteLock.acquire_read_lock
|
train
|
def acquire_read_lock
while(true)
c = @counter.value
raise ResourceLimitError, 'Too many reader threads' if max_readers?(c)
if waiting_writer?(c)
@reader_mutex.synchronize do
@reader_q.wait(@reader_mutex) if waiting_writer?
end
while(true)
c = @counter.value
if running_writer?(c)
@reader_mutex.synchronize do
@reader_q.wait(@reader_mutex) if running_writer?
end
else
return if @counter.compare_and_swap(c,c+1)
end
end
else
break if @counter.compare_and_swap(c,c+1)
end
end
true
end
|
ruby
|
{
"resource": ""
}
|
q6556
|
Garcon.ReadWriteLock.release_read_lock
|
train
|
def release_read_lock
while(true)
c = @counter.value
if @counter.compare_and_swap(c,c-1)
if waiting_writer?(c) && running_readers(c) == 1
@writer_mutex.synchronize { @writer_q.signal }
end
break
end
end
true
end
|
ruby
|
{
"resource": ""
}
|
q6557
|
Garcon.ReadWriteLock.acquire_write_lock
|
train
|
def acquire_write_lock
while(true)
c = @counter.value
raise ResourceLimitError, 'Too many writer threads' if max_writers?(c)
if c == 0
break if @counter.compare_and_swap(0,RUNNING_WRITER)
elsif @counter.compare_and_swap(c,c+WAITING_WRITER)
while(true)
@writer_mutex.synchronize do
c = @counter.value
if running_writer?(c) || running_readers?(c)
@writer_q.wait(@writer_mutex)
end
end
c = @counter.value
break if !running_writer?(c) && !running_readers?(c) &&
@counter.compare_and_swap(c,c+RUNNING_WRITER-WAITING_WRITER)
end
break
end
end
true
end
|
ruby
|
{
"resource": ""
}
|
q6558
|
Garcon.ReadWriteLock.release_write_lock
|
train
|
def release_write_lock
while(true)
c = @counter.value
if @counter.compare_and_swap(c,c-RUNNING_WRITER)
@reader_mutex.synchronize { @reader_q.broadcast }
if waiting_writers(c) > 0
@writer_mutex.synchronize { @writer_q.signal }
end
break
end
end
true
end
|
ruby
|
{
"resource": ""
}
|
q6559
|
CommandModel.Model.parameters
|
train
|
def parameters
self.class.parameters.each_with_object({}) do |parameter, hash|
hash[parameter.name] = send(parameter.name)
end
end
|
ruby
|
{
"resource": ""
}
|
q6560
|
ModelsAuditor.Controller.user_for_models_auditor
|
train
|
def user_for_models_auditor
user =
case
when defined?(current_user)
current_user
when defined?(current_employee)
current_employee
else
return
end
ActiveSupport::VERSION::MAJOR >= 4 ? user.try!(:id) : user.try(:id)
rescue NoMethodError
user
end
|
ruby
|
{
"resource": ""
}
|
q6561
|
ModelsAuditor.Controller.info_for_models_auditor
|
train
|
def info_for_models_auditor
{
ip: request.remote_ip,
user_agent: request.user_agent,
controller: self.class.name,
action: action_name,
path: request.path_info
}
end
|
ruby
|
{
"resource": ""
}
|
q6562
|
AuthRocket.Credential.verify
|
train
|
def verify(code, attribs={})
params = parse_request_params(attribs.merge(code: code), json_root: json_root).merge credentials: api_creds
parsed, _ = request(:post, url+'/verify', params)
load(parsed)
errors.empty? ? self : false
end
|
ruby
|
{
"resource": ""
}
|
q6563
|
Bullring.RhinoServer.fetch_library
|
train
|
def fetch_library(name)
library_script = @server_registry['library', name]
logger.debug {"#{logname}: Tried to fetch script '#{name}' from the registry and it " +
"was #{'not ' if library_script.nil?}found."}
raise NameError, "Server cannot find a script named #{name}" if library_script.nil?
library_script
end
|
ruby
|
{
"resource": ""
}
|
q6564
|
RailsExtension::ActionControllerExtension::AccessibleViaUser.ClassMethods.assert_access_without_login
|
train
|
def assert_access_without_login(*actions)
user_options = actions.extract_options!
options = {}
if ( self.constants.include?('ASSERT_ACCESS_OPTIONS') )
options.merge!(self::ASSERT_ACCESS_OPTIONS)
end
options.merge!(user_options)
actions += options[:actions]||[]
m_key = options[:model].try(:underscore).try(:to_sym)
test "#{brand}AWoL should get new without login" do
get :new
assert_response :success
assert_template 'new'
assert assigns(m_key), "#{m_key} was not assigned."
assert_nil flash[:error], "flash[:error] was not nil"
end if actions.include?(:new) || options.keys.include?(:new)
test "#{brand}AWoL should post create without login" do
args = if options[:create]
options[:create]
elsif options[:attributes_for_create]
{m_key => send(options[:attributes_for_create])}
else
{}
end
assert_difference("#{options[:model]}.count",1) do
send(:post,:create,args)
end
assert_response :redirect
assert_nil flash[:error], "flash[:error] was not nil"
end if actions.include?(:create) || options.keys.include?(:create)
# test "should NOT get edit without login" do
# args=[]
# if options[:factory]
# obj = Factory(options[:factory])
# args.push(:id => obj.id)
# end
# send(:get,:edit, *args)
# assert_redirected_to_login
# end if actions.include?(:edit) || options.keys.include?(:edit)
#
# test "should NOT put update without login" do
# args={}
# if options[:factory]
# obj = Factory(options[:factory])
# args[:id] = obj.id
# args[options[:factory]] = Factory.attributes_for(options[:factory])
# end
# send(:put,:update, args)
# assert_redirected_to_login
# end if actions.include?(:update) || options.keys.include?(:update)
test "#{brand}AWoL should get show without login" do
args={}
if options[:method_for_create]
obj = send(options[:method_for_create])
args[:id] = obj.id
end
send(:get,:show, args)
assert_response :success
assert_template 'show'
assert assigns(m_key), "#{m_key} was not assigned."
assert_nil flash[:error], "flash[:error] was not nil"
end if actions.include?(:show) || options.keys.include?(:show)
# test "should NOT delete destroy without login" do
# args=[]
# if options[:factory]
# obj = Factory(options[:factory])
# args.push(:id => obj.id)
# end
# assert_no_difference("#{options[:model]}.count") do
# send(:delete,:destroy,*args)
# end
# assert_redirected_to_login
# end if actions.include?(:destroy) || options.keys.include?(:destroy)
#
# test "should NOT get index without login" do
# get :index
# assert_redirected_to_login
# end if actions.include?(:index) || options.keys.include?(:index)
test "#{brand}should get index without login" do
get :index
assert_response :success
assert_template 'index'
assert assigns(m_key.try(:to_s).try(:pluralize).try(:to_sym)),
"#{m_key.try(:to_s).try(:pluralize).try(:to_sym)} was not assigned."
assert_nil flash[:error], "flash[:error] was not nil"
end if actions.include?(:index) || options.keys.include?(:index)
test "#{brand}should get index without login and items" do
send(options[:before]) if !options[:before].blank?
3.times{ send(options[:method_for_create]) } if !options[:method_for_create].blank?
get :index
assert_response :success
assert_template 'index'
assert assigns(m_key.try(:to_s).try(:pluralize).try(:to_sym)),
"#{m_key.try(:to_s).try(:pluralize).try(:to_sym)} was not assigned."
assert_nil flash[:error], "flash[:error] was not nil"
end if actions.include?(:index) || options.keys.include?(:index)
end
|
ruby
|
{
"resource": ""
}
|
q6565
|
Jinx.Collection.to_json
|
train
|
def to_json(state=nil)
# Make a new State from the options if this is a top-level call.
state = JSON::State.for(state) unless JSON::State === state
to_a.to_json(state)
end
|
ruby
|
{
"resource": ""
}
|
q6566
|
Myreplicator.Export.export
|
train
|
def export
Log.run(:job_type => "export", :name => schedule_name,
:file => filename, :export_id => id) do |log|
exporter = MysqlExporter.new
exporter.export_table self # pass current object to exporter
end
end
|
ruby
|
{
"resource": ""
}
|
q6567
|
Myreplicator.Export.is_running?
|
train
|
def is_running?
return false if state != "exporting"
begin
Process.getpgid(exporter_pid)
raise Exceptions::ExportIgnored.new("Ignored")
rescue Errno::ESRCH
return false
end
end
|
ruby
|
{
"resource": ""
}
|
q6568
|
Furnish.SSH.run
|
train
|
def run(cmd)
ret = {
:exit_status => 0,
:stdout => "",
:stderr => ""
}
port = ssh_args[:port]
Net::SSH.start(host, username, ssh_args) do |ssh|
ssh.open_channel do |ch|
if stdin
ch.send_data(stdin)
ch.eof!
end
if require_pty
ch.request_pty do |ch, success|
unless success
raise "The use_sudo setting requires a PTY, and your SSH is rejecting our attempt to get one."
end
end
end
ch.on_open_failed do |ch, code, desc|
raise "Connection Error to #{username}@#{host}: #{desc}"
end
ch.exec(cmd) do |ch, success|
unless success
raise "Could not execute command '#{cmd}' on #{username}@#{host}"
end
if merge_output
ch.on_data do |ch, data|
log(host, port, data)
ret[:stdout] << data
end
ch.on_extended_data do |ch, type, data|
if type == 1
log(host, port, data)
ret[:stdout] << data
end
end
else
ch.on_data do |ch, data|
log(host, port, data)
ret[:stdout] << data
end
ch.on_extended_data do |ch, type, data|
ret[:stderr] << data if type == 1
end
end
ch.on_request("exit-status") do |ch, data|
ret[:exit_status] = data.read_long
end
end
end
ssh.loop
end
return ret
end
|
ruby
|
{
"resource": ""
}
|
q6569
|
TrackableTasks.TaskRun.run_time_or_time_elapsed
|
train
|
def run_time_or_time_elapsed
if self.end_time
return Time.at(self.end_time - self.start_time)
else
return Time.at(Time.now - self.start_time)
end
end
|
ruby
|
{
"resource": ""
}
|
q6570
|
BarkestCore.DatabaseConfig.extra_label
|
train
|
def extra_label(index)
return nil if index < 1 || index > 5
txt = send("extra_#{index}_label")
txt = extra_name(index).to_s.humanize.capitalize if txt.blank?
txt
end
|
ruby
|
{
"resource": ""
}
|
q6571
|
BarkestCore.DatabaseConfig.extra_field_type
|
train
|
def extra_field_type(index)
t = extra_type(index).to_s
case t
when 'password'
'password'
when 'integer', 'float'
'number'
when 'boolean'
'checkbox'
else
if t.downcase.index('in:')
'select'
else
'text'
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6572
|
BarkestCore.DatabaseConfig.extra_value
|
train
|
def extra_value(index, convert = false)
return nil if index < 1 || index > 5
val = send "extra_#{index}_value"
if convert
case extra_type(index)
when 'boolean'
BarkestCore::BooleanParser.parse_for_boolean_column(val)
when 'integer'
BarkestCore::NumberParser.parse_for_int_column(val)
when 'float'
BarkestCore::NumberParser.parse_for_float_column(val)
else
val.to_s
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6573
|
MailRelay.Base.resend_to
|
train
|
def resend_to(destinations)
if destinations.size > 0
message.smtp_envelope_to = destinations
# Set envelope from and sender to local server to satisfy SPF:
# http://www.openspf.org/Best_Practices/Webgenerated
message.sender = envelope_sender
message.smtp_envelope_from = envelope_sender
# set list headers
message.header['Precedence'] = 'list'
message.header['List-Id'] = list_id
deliver(message)
end
end
|
ruby
|
{
"resource": ""
}
|
q6574
|
MailRelay.Base.receiver_from_received_header
|
train
|
def receiver_from_received_header
if received = message.received
received = received.first if received.respond_to?(:first)
received.info[/ for .*?([^\s<>]+)@[^\s<>]+/, 1]
end
end
|
ruby
|
{
"resource": ""
}
|
q6575
|
HttpMonkey.Client::Environment.uri=
|
train
|
def uri=(uri)
self['SERVER_NAME'] = uri.host
self['SERVER_PORT'] = uri.port.to_s
self['QUERY_STRING'] = (uri.query || "")
self['PATH_INFO'] = (!uri.path || uri.path.empty?) ? "/" : uri.path
self['rack.url_scheme'] = uri.scheme
self['HTTPS'] = (uri.scheme == "https" ? "on" : "off")
self['REQUEST_URI'] = uri.request_uri
self['HTTP_HOST'] = uri.host
end
|
ruby
|
{
"resource": ""
}
|
q6576
|
HttpMonkey.Client::Environment.uri
|
train
|
def uri
uri = %Q{#{self['rack.url_scheme']}://#{self['SERVER_NAME']}:#{self['SERVER_PORT']}#{self['REQUEST_URI']}}
begin
URI.parse(uri)
rescue StandardError => e
raise ArgumentError, "Invalid #{uri}", e.backtrace
end
end
|
ruby
|
{
"resource": ""
}
|
q6577
|
Roroacms.Admin::MenusController.edit
|
train
|
def edit
@menu = Menu.find(params[:id])
# add breadcrumb and set title
add_breadcrumb I18n.t("controllers.admin.menus.edit.breadcrumb", menu_name: @menu.name)
set_title(I18n.t("controllers.admin.menus.edit.title", menu_name: @menu.name))
end
|
ruby
|
{
"resource": ""
}
|
q6578
|
Roroacms.Admin::MenusController.destroy
|
train
|
def destroy
@menu = Menu.find(params[:id])
@menu.destroy
respond_to do |format|
format.html { redirect_to admin_menus_path, notice: I18n.t("controllers.admin.menus.destroy.flash.success") }
end
end
|
ruby
|
{
"resource": ""
}
|
q6579
|
Chap.Hook.symlink_configs
|
train
|
def symlink_configs
paths = Dir.glob("#{shared_path}/config/**/*").
select {|p| File.file?(p) }
paths.each do |src|
relative_path = src.gsub(%r{.*config/},'config/')
dest = "#{release_path}/#{relative_path}"
# make sure the directory exist for symlink creation
dirname = File.dirname(dest)
FileUtils.mkdir_p(dirname) unless File.exist?(dirname)
FileUtils.rm_rf(dest) if File.exist?(dest)
FileUtils.ln_s(src,dest)
end
end
|
ruby
|
{
"resource": ""
}
|
q6580
|
MotionMastr.MastrBuilder.apply_attributes
|
train
|
def apply_attributes(attributed_string, start, length, styles)
return unless attributed_string && start && length && styles # sanity
return unless start >= 0 && length > 0 && styles.length > 0 # minimums
return unless start + length <= attributed_string.length # maximums
range = [start, length]
ATTRIBUTES.each_pair do |method_name, attribute_name|
value = send method_name, styles
attributed_string.addAttribute(attribute_name, value: value, range: range) if value
end
end
|
ruby
|
{
"resource": ""
}
|
q6581
|
TransactionReliability.Helpers.with_transaction_retry
|
train
|
def with_transaction_retry(options = {})
retry_count = options.fetch(:retry_count, 4)
backoff = options.fetch(:backoff, 0.25)
exit_on_fail = options.fetch(:exit_on_fail, false)
exit_on_disconnect = options.fetch(:exit_on_disconnect, true)
count = 0
# list of exceptions we may catch
exceptions = ['ActiveRecord::StatementInvalid', 'PG::Error', 'Mysql2::Error'].
map {|name| name.safe_constantize}.
compact
#
# There are times when, for example,
# a raw PG::Error is throw rather than a wrapped ActiveRecord::StatementInvalid
#
# Also, connector-specific classes like PG::Error may not be defined
#
begin
connection_lost = false
yield
rescue *exceptions => e
translated = TransactionReliability.rewrap_exception(e)
case translated
when ConnectionLost
(options[:connection] || ActiveRecord::Base.connection).reconnect!
connection_lost = true
when DeadlockDetected, SerializationFailure
else
raise translated
end
# Retry up to retry_count times
if count < retry_count
sleep backoff
count += 1
backoff *= 2
retry
else
if (connection_lost && exit_on_disconnect) || exit_on_fail
exit
else
raise(translated)
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6582
|
TransactionReliability.Helpers.transaction_with_retry
|
train
|
def transaction_with_retry(txn_options = {}, retry_options = {})
base_obj = self.respond_to?(:transaction) ? self : ActiveRecord::Base
with_transaction_retry(retry_options) do
base_obj.transaction(txn_options) do
yield
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6583
|
GoogleAnymote.TV.connect_to_unit
|
train
|
def connect_to_unit
puts "Connecting to '#{@host}..."
begin
tcp_client = TCPSocket.new @host, @port
@ssl_client = OpenSSL::SSL::SSLSocket.new tcp_client, @context
@ssl_client.connect
rescue Exception => e
puts "Could not connect to '#{@host}: #{e}"
end
end
|
ruby
|
{
"resource": ""
}
|
q6584
|
GoogleAnymote.TV.fling_uri
|
train
|
def fling_uri(uri)
send_request RequestMessage.new(fling_message: Fling.new(uri: uri))
end
|
ruby
|
{
"resource": ""
}
|
q6585
|
GoogleAnymote.TV.send_keycode
|
train
|
def send_keycode(keycode)
send_request RequestMessage.new(key_event_message: KeyEvent.new(keycode: keycode, action: Action::DOWN))
send_request RequestMessage.new(key_event_message: KeyEvent.new(keycode: keycode, action: Action::UP))
end
|
ruby
|
{
"resource": ""
}
|
q6586
|
GoogleAnymote.TV.send_data
|
train
|
def send_data(msg)
send_request RequestMessage.new(data_message: Data1.new(type: "com.google.tv.string", data: msg))
end
|
ruby
|
{
"resource": ""
}
|
q6587
|
GoogleAnymote.TV.move_mouse
|
train
|
def move_mouse(x_delta, y_delta)
send_request RequestMessage.new(mouse_event_message: MouseEvent.new(x_delta: x_delta, y_delta: y_delta))
end
|
ruby
|
{
"resource": ""
}
|
q6588
|
GoogleAnymote.TV.scroll_mouse
|
train
|
def scroll_mouse(x_amount, y_amount)
send_request RequestMessage.new(mouse_wheel_message: MouseWheel.new(x_scroll: x_amount, y_scroll: y_amount))
end
|
ruby
|
{
"resource": ""
}
|
q6589
|
GoogleAnymote.TV.send_request
|
train
|
def send_request(request)
message = RemoteMessage.new(request_message: request).serialize_to_string
message_size = [message.length].pack('N')
@ssl_client.write(message_size + message)
end
|
ruby
|
{
"resource": ""
}
|
q6590
|
GoogleAnymote.TV.send_message
|
train
|
def send_message(msg)
# Build the message and get it's size
message = msg.serialize_to_string
message_size = [message.length].pack('N')
# Try to send the message
try_again = true
begin
data = ""
@ssl_client.write(message_size + message)
@ssl_client.readpartial(1000,data)
rescue
# Sometimes our connection might drop or something, so
# we'll reconnect to the unit and try to send the message again.
if try_again
try_again = false
connect_to_unit
retry
else
# Looks like we couldn't connect to the unit after all.
puts "message not sent"
end
end
return data
end
|
ruby
|
{
"resource": ""
}
|
q6591
|
CabooseStore.CabooseStoreHelper.init_routes
|
train
|
def init_routes
puts "Adding the caboose store routes..."
filename = File.join(@app_path,'config','routes.rb')
return if !File.exists?(filename)
return if !@force
str = ""
str << "\t# Catch everything with caboose\n"
str << "\tmount CabooseStore::Engine => '/'\n"
file = File.open(filename, 'rb')
contents = file.read
file.close
if (contents.index(str).nil?)
arr = contents.split('end', -1)
str2 = arr[0] + "\n" + str + "\nend" + arr[1]
File.open(filename, 'w') {|file| file.write(str2) }
end
end
|
ruby
|
{
"resource": ""
}
|
q6592
|
Cashboard.BadRequest.errors
|
train
|
def errors
parsed_errors = XmlSimple.xml_in(response.response.body)
error_hash = {}
parsed_errors['error'].each do |e|
error_hash[e['field']] = e['content']
end
return error_hash
end
|
ruby
|
{
"resource": ""
}
|
q6593
|
Tickspot.Client.clients
|
train
|
def clients(options = {})
post("/clients", options)["clients"].map {|obj| Hashie::Mash.new obj }
end
|
ruby
|
{
"resource": ""
}
|
q6594
|
Tickspot.Client.projects
|
train
|
def projects(options = {})
post("/projects", options)["projects"].map {|obj| Hashie::Mash.new obj }
end
|
ruby
|
{
"resource": ""
}
|
q6595
|
Tickspot.Client.tasks
|
train
|
def tasks(options = {})
post("/tasks", options)["tasks"].map {|obj| Hashie::Mash.new obj }
end
|
ruby
|
{
"resource": ""
}
|
q6596
|
Tickspot.Client.entries
|
train
|
def entries(options = {})
post("/entries", options)["entries"].map {|obj| Hashie::Mash.new obj }
end
|
ruby
|
{
"resource": ""
}
|
q6597
|
Tickspot.Client.users
|
train
|
def users(options = {})
post("/users", options)['users'].map {|obj| Hashie::Mash.new obj }
end
|
ruby
|
{
"resource": ""
}
|
q6598
|
BasicCache.TimeCache.cache
|
train
|
def cache(key = nil)
key ||= BasicCache.caller_name
key = key.to_sym
if include? key
@store[key].value
else
value = yield
@store[key] = TimeCacheItem.new Time.now, value
value
end
end
|
ruby
|
{
"resource": ""
}
|
q6599
|
BasicCache.TimeCache.include?
|
train
|
def include?(key = nil)
key ||= BasicCache.caller_name
key = key.to_sym
@store.include?(key) && Time.now - @store[key].stamp < @lifetime
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.