code
stringlengths 12
2.05k
| label_name
stringclasses 5
values | label
int64 0
4
|
---|---|---|
def check_owner
return if params[:id].nil? or params[:id].empty? or @login_user.nil?
email = Email.find(params[:id])
if !@login_user.admin?(User::AUTH_MAIL) and email.user_id != @login_user.id
Log.add_check(request, '[check_owner]'+request.to_s)
flash[:notice] = t('msg.need_to_be_owner')
redirect_to(:controller => 'desktop', :action => 'show')
end
end | Base | 1 |
def send_password
Log.add_info(request, params.inspect)
mail_addr = params[:thetisBoxEdit]
SqlHelper.validate_token([mail_addr])
begin
users = User.where("email='#{mail_addr}'").to_a
rescue => evar
end
if users.nil? or users.empty?
Log.add_error(request, evar)
flash[:notice] = 'ERROR:' + t('email.address_not_found')
else
user_passwords_h = {}
users.each do |user|
newpass = UsersHelper.generate_password
user.update_attribute(:pass_md5, UsersHelper.generate_digest_pass(user.name, newpass))
user_passwords_h[user] = newpass
end
NoticeMailer.password(user_passwords_h, ApplicationHelper.root_url(request)).deliver;
flash[:notice] = t('email.sent')
end
render(:controller => 'login', :action => 'index')
end | Base | 1 |
it "returns the right category group permission for a staff user ordered by ascending group name" do
json = described_class.new(category, scope: Guardian.new(admin), root: false).as_json
expect(json[:group_permissions]).to eq([
{ permission_type: CategoryGroup.permission_types[:readonly], group_name: group.name },
{ permission_type: CategoryGroup.permission_types[:full], group_name: private_group.name },
{ permission_type: CategoryGroup.permission_types[:full], group_name: user_group.name },
{ permission_type: CategoryGroup.permission_types[:readonly], group_name: 'everyone' },
])
end | Base | 1 |
def sanitize_value(value)
case value
when Array then value.collect { |i| i.to_s.shellescape }
when NilClass then value
else value.to_s.shellescape
end | Base | 1 |
it 'removes existing content types' do
subject.content_type :xls, 'application/vnd.ms-excel'
subject.get :excel do
'some binary content'
end
get '/excel.json'
expect(last_response.status).to eq(406)
expect(last_response.body).to eq("The requested format 'txt' is not supported.")
end | Base | 1 |
def new_ally_request_link(uniqueid, data)
link = "/profile?uid=#{data[:uid]}"
link_html = "<a href=\"#{link}\">#{data[:user]}</a>"
# rubocop:disable Layout/LineLength
"<div id=\"#{uniqueid}\"><div>#{t('notifications.ally.sent_html', link_to_user: link_html)}</div>#{request_actions(data[:user_id])}</div>"
# rubocop:enable Layout/LineLength
end | Base | 1 |
def initialize(data = nil, time = nil)
if data
@data = data
elsif time
@data = @@generator.generate(time.to_i)
else
@data = @@generator.next
end
end | Class | 2 |
def self.search_by_puppetclass(key, operator, value)
conditions = "puppetclasses.name #{operator} '#{value_to_sql(operator, value)}'"
hosts = Host.my_hosts.all(:conditions => conditions, :joins => :puppetclasses, :select => 'DISTINCT hosts.id').map(&:id)
host_groups = Hostgroup.all(:conditions => conditions, :joins => :puppetclasses, :select => 'DISTINCT hostgroups.id').map(&:id)
opts = ''
opts += "hosts.id IN(#{hosts.join(',')})" unless hosts.blank?
opts += " OR " unless hosts.blank? || host_groups.blank?
opts += "hostgroups.id IN(#{host_groups.join(',')})" unless host_groups.blank?
opts = "hosts.id < 0" if hosts.blank? && host_groups.blank?
return {:conditions => opts, :include => :hostgroup}
end | Base | 1 |
it "returns the document" do
session.simple_query(query).should eq(a: 1)
end | Class | 2 |
it "syncs the cluster" do
cluster.should_receive(:sync) do
cluster.servers << server
end
cluster.socket_for :write
end | Class | 2 |
def self.get_for_user(user)
return [] if user.nil?
toys = Toy.where("user_id=#{user.id}").to_a
deleted_ary = []
return [] if toys.nil?
toys.each do |toy|
case toy.xtype
when Toy::XTYPE_ITEM
item = Item.find_by_id(toy.target_id)
if item.nil?
deleted_ary << toy
next
end
Toy.copy(toy, item)
when Toy::XTYPE_COMMENT
comment = Comment.find_by_id(toy.target_id)
if comment.nil?
deleted_ary << toy
next
end
Toy.copy(toy, comment)
when Toy::XTYPE_WORKFLOW
workflow = Workflow.find_by_id(toy.target_id)
if workflow.nil?
deleted_ary << toy
next
end
Toy.copy(toy, workflow)
when Toy::XTYPE_SCHEDULE
schedule = Schedule.find_by_id(toy.target_id)
if schedule.nil?
deleted_ary << toy
next
end
Toy.copy(toy, schedule)
when Toy::XTYPE_FOLDER
folder = Folder.find_by_id(toy.target_id)
if folder.nil?
deleted_ary << toy
next
end
Toy.copy(toy, folder)
end
end | Base | 1 |
def self.normalize_key_names(options)
options = options.dup
if options.key?(:key_prefix) && !options.key?(:namespace)
options[:namespace] = options.delete(:key_prefix) # RailsSessionStore
end
options[:raw] = !options[:marshalling]
options
end | Base | 1 |
def write!(headers)
if @orig_disable_profiling != @disable_profiling || @orig_backtrace_level != @backtrace_level || @cookie.nil?
settings = {"p" => "t" }
settings["dp"] = "t" if @disable_profiling
settings["bt"] = @backtrace_level if @backtrace_level
settings_string = settings.map{|k,v| "#{k}=#{v}"}.join(",")
Rack::Utils.set_cookie_header!(headers, COOKIE_NAME, :value => settings_string, :path => '/')
end
end | Class | 2 |
def forwarded_for
@env[FORWARDED_FOR]
end | Class | 2 |
def base_api_url
computed_api_endpoint = "https://#{get_data_center_from_api_key(self.api_key)}api.mailchimp.com"
raise Gibbon::GibbonError, "SSRF attempt" unless URI(computed_api_endpoint).host.include?("api.mailchimp.com")
"#{self.api_endpoint || computed_api_endpoint}/3.0/"
end | Base | 1 |
def set_configs(params, request, session)
if not allowed_for_local_cluster(session, Permissions::FULL)
return 403, 'Permission denied'
end
return JSON.generate({'status' => 'bad_json'}) if not params['configs']
begin
configs_json = JSON.parse(params['configs'])
rescue JSON::ParserError
return JSON.generate({'status' => 'bad_json'})
end
has_cluster = !($cluster_name == nil or $cluster_name.empty?)
if has_cluster and $cluster_name != configs_json['cluster_name']
return JSON.generate({'status' => 'wrong_cluster_name'})
end
$semaphore_cfgsync.synchronize {
force = configs_json['force']
remote_configs, unknown_cfg_names = Cfgsync::sync_msg_to_configs(configs_json)
local_configs = Cfgsync::get_configs_local
result = {}
unknown_cfg_names.each { |name| result[name] = 'not_supported' }
remote_configs.each { |name, remote_cfg|
begin
# Save a remote config if it is a newer version than local. If the config
# is not present on a local node, the node is beeing added to a cluster,
# so we need to save the config as well.
if force or not local_configs.key?(name) or remote_cfg > local_configs[name]
local_configs[name].class.backup() if local_configs.key?(name)
remote_cfg.save()
result[name] = 'accepted'
elsif remote_cfg == local_configs[name]
# Someone wants this node to have a config that it already has.
# So the desired state is met and the result is a success then.
result[name] = 'accepted'
else
result[name] = 'rejected'
end
rescue => e
$logger.error("Error saving config '#{name}': #{e}")
result[name] = 'error'
end
}
return JSON.generate({'status' => 'ok', 'result' => result})
}
end | Compound | 4 |
def private_messages_for(user, type)
options = @options
options.reverse_merge!(per_page: per_page_setting)
result = Topic.includes(:allowed_users)
result = result.includes(:tags) if SiteSetting.tagging_enabled
if type == :group
result = result.joins(
"INNER JOIN topic_allowed_groups tag ON tag.topic_id = topics.id AND tag.group_id IN (SELECT id FROM groups WHERE LOWER(name) = '#{PG::Connection.escape_string(@options[:group_name].downcase)}')"
)
unless user.admin?
result = result.joins("INNER JOIN group_users gu ON gu.group_id = tag.group_id AND gu.user_id = #{user.id.to_i}")
end
elsif type == :user
result = result.where("topics.id IN (SELECT topic_id FROM topic_allowed_users WHERE user_id = #{user.id.to_i})")
elsif type == :all
result = result.where("topics.id IN (
SELECT topic_id
FROM topic_allowed_users
WHERE user_id = #{user.id.to_i}
UNION ALL
SELECT topic_id FROM topic_allowed_groups
WHERE group_id IN (
SELECT group_id FROM group_users WHERE user_id = #{user.id.to_i}
)
)")
end
result = result.joins("LEFT OUTER JOIN topic_users AS tu ON (topics.id = tu.topic_id AND tu.user_id = #{user.id.to_i})")
.order("topics.bumped_at DESC")
.private_messages
result = result.limit(options[:per_page]) unless options[:limit] == false
result = result.visible if options[:visible] || @user.nil? || @user.regular?
if options[:page]
offset = options[:page].to_i * options[:per_page]
result = result.offset(offset) if offset > 0
end
result
end | Class | 2 |
it "removes the stored credentials" do
cluster.logout :admin
cluster.auth.should be_empty
end | Class | 2 |
it "executes a distinct command" do
database.should_receive(:command).with(
distinct: collection.name,
key: "name",
query: selector
).and_return("values" => [ "durran", "bernerd" ])
query.distinct(:name)
end | Class | 2 |
def _marshal(val, options)
yield marshal?(options) ? Marshal.dump(val) : val
end | Base | 1 |
def remove_all
delete = Protocol::Delete.new(
operation.database,
operation.collection,
operation.selector
)
session.with(consistency: :strong) do |session|
session.execute delete
end
end | Class | 2 |
it "has an empty list of secondaries" do
cluster.secondaries.should be_empty
end | Class | 2 |
it "updates the selector to mongo's advanced selector" do
query.sort(a: 1)
query.operation.selector.should eq(
"$query" => selector,
"$orderby" => { a: 1 }
)
end | Class | 2 |
def verify_active_session
if !request.post? && params[:status].blank? && User.exists?(session[:user].presence)
warning _("You have already logged in")
redirect_back_or_to hosts_path
return
end
end | Class | 2 |
def test_create_valid
AuthSourceLdap.any_instance.stubs(:valid?).returns(true)
post :create, {:auth_source_ldap => {:name => AuthSourceLdap.first.name}}, set_session_user
assert_redirected_to auth_source_ldaps_url
end | Class | 2 |
def remove_acl_usergroup(session, role_id, usergroup_id)
stdout, stderror, retval = run_cmd(
session, PCS, "acl", "role", "unassign", role_id.to_s, usergroup_id.to_s,
"--autodelete"
)
if retval != 0
if stderror.empty?
return "Error removing user / group"
else
return stderror.join("\n").strip
end
end
return ""
end | Compound | 4 |
it "handles Symbol keys with underscore" do
cl = subject.build_command_line("true", :abc_def => "ghi")
expect(cl).to eq "true --abc-def ghi"
end | Base | 1 |
def get_permissions_remote(params, request, session)
if not allowed_for_local_cluster(session, Permissions::GRANT)
return 403, 'Permission denied'
end
pcs_config = PCSConfig.new(Cfgsync::PcsdSettings.from_file('{}').text())
data = {
'user_types' => Permissions::get_user_types(),
'permission_types' => Permissions::get_permission_types(),
'permissions_dependencies' => Permissions::permissions_dependencies(),
'users_permissions' => pcs_config.permissions_local.to_hash(),
}
return [200, JSON.generate(data)]
end | Compound | 4 |
def decode_compact_serialized(input, public_key_or_secret, algorithms = nil, allow_blank_payload = false)
unless input.count('.') + 1 == NUM_OF_SEGMENTS
raise InvalidFormat.new("Invalid JWS Format. JWS should include #{NUM_OF_SEGMENTS} segments.")
end
header, claims, signature = input.split('.', JWS::NUM_OF_SEGMENTS).collect do |segment|
Base64.urlsafe_decode64 segment.to_s
end
header = JSON.parse(header).with_indifferent_access
if allow_blank_payload && claims == ''
claims = nil
else
claims = JSON.parse(claims).with_indifferent_access
end
jws = new claims
jws.header = header
jws.signature = signature
jws.signature_base_string = input.split('.')[0, JWS::NUM_OF_SEGMENTS - 1].join('.')
jws.verify! public_key_or_secret, algorithms unless public_key_or_secret == :skip_verification
jws
end | Class | 2 |
def initialize(file)
@file = file.is_a?(String) ? StringIO.new(file) : file
end | Base | 1 |
def send(force=false)
nodes_txt = @nodes.join(', ')
@configs.each { |cfg|
$logger.info(
"Sending config '#{cfg.class.name}' version #{cfg.version} #{cfg.hash}"\
+ " to nodes: #{nodes_txt}"
)
}
data = self.prepare_request_data(@configs, @cluster_name, force)
node_response = {}
threads = []
@nodes.each { |node|
threads << Thread.new {
code, out = send_request_with_token(
@session, node, 'set_configs', true, data, true, nil, 30,
@additional_tokens
)
if 200 == code
begin
node_response[node] = JSON.parse(out)
rescue JSON::ParserError
end
elsif 404 == code
node_response[node] = {'status' => 'not_supported'}
else
begin
response = JSON.parse(out)
if true == response['notauthorized'] or true == response['notoken']
node_response[node] = {'status' => 'notauthorized'}
end
rescue JSON::ParserError
end
end
if not node_response.key?(node)
node_response[node] = {'status' => 'error'}
end
# old pcsd returns this instead of 404 if pacemaker isn't running there
if node_response[node]['pacemaker_not_running']
node_response[node] = {'status' => 'not_supported'}
end
}
}
threads.each { |t| t.join }
node_response.each { |node, response|
$logger.info("Sending config response from #{node}: #{response}")
}
return node_response
end | Compound | 4 |
it "syncs each seed node" do
server = Moped::Server.allocate
Moped::Server.should_receive(:new).with("127.0.0.1:27017").and_return(server)
cluster.should_receive(:sync_server).with(server).and_return([])
cluster.sync
end | Class | 2 |
def test_private_address
assert_raises PrivateAddressCheck::PrivateConnectionAttemptedError do
PrivateAddressCheck.only_public_connections do
TCPSocket.new("localhost", 80)
end
end
end | Class | 2 |
def initialize(seeds, direct = false)
@seeds = seeds
@direct = direct
@servers = []
@dynamic_seeds = []
end | Class | 2 |
def fence_device_metadata(params, request, session)
if not allowed_for_local_cluster(session, Permissions::READ)
return 403, 'Permission denied'
end
return 200 if not params[:resourcename] or params[:resourcename] == ""
@fenceagent = FenceAgent.new(params[:resourcename])
@fenceagent.required_options, @fenceagent.optional_options, @fenceagent.advanced_options, @fenceagent.info = getFenceAgentMetadata(session, params[:resourcename])
@new_fenceagent = params[:new]
erb :fenceagentform
end | Compound | 4 |
def handle_meta(message, local, &callback)
method = Channel.parse(message['channel'])[1]
unless META_METHODS.include?(method)
response = make_response(message)
response['error'] = Faye::Error.channel_forbidden(message['channel'])
response['successful'] = false
return callback.call([response])
end
__send__(method, message, local) do |responses|
responses = [responses].flatten
responses.each { |r| advize(r, message['connectionType']) }
callback.call(responses)
end
end | Class | 2 |
def node_unstandby(params, request, session)
if params[:name]
code, response = send_request_with_token(
session, params[:name], 'node_unstandby', true, {"node"=>params[:name]}
)
# data={"node"=>params[:name]} for backward compatibility with older versions of pcs/pcsd
else
if not allowed_for_local_cluster(session, Permissions::WRITE)
return 403, 'Permission denied'
end
$logger.info "Unstandby Node"
stdout, stderr, retval = run_cmd(session, PCS, "cluster", "unstandby")
return stdout
end
end | Compound | 4 |
def add_fence_level(session, level, devices, node, remove = false)
if not remove
stdout, stderr, retval = run_cmd(
session, PCS, "stonith", "level", "add", level, node, devices
)
return retval,stdout, stderr
else
stdout, stderr, retval = run_cmd(
session, PCS, "stonith", "level", "remove", level, node, devices
)
return retval,stdout, stderr
end
end | Compound | 4 |
def get_group_users
Log.add_info(request, params.inspect)
@group_id = nil
if !params[:thetisBoxSelKeeper].nil?
@group_id = params[:thetisBoxSelKeeper].split(':').last
elsif !params[:group_id].nil? and !params[:group_id].empty?
@group_id = params[:group_id]
end
submit_url = url_for(:controller => 'send_mails', :action => 'get_group_users')
render(:partial => 'common/select_users', :layout => false, :locals => {:target_attr => :email, :submit_url => submit_url})
end | Base | 1 |
def wizard_submit(params, request, session)
if not allowed_for_local_cluster(session, Permissions::WRITE)
return 403, 'Permission denied'
end
wizard = PCSDWizard.getWizard(params["wizard"])
if wizard != nil
return erb wizard.process_responses(params)
else
return "Error finding Wizard - #{params["wizard"]}"
end
end | Compound | 4 |
it "applies the cached authentication" do
cluster.stub(:sync) { cluster.servers << server }
socket.should_receive(:apply_auth).with(cluster.auth)
cluster.socket_for(:write)
end | Class | 2 |
it 'should return a second factor prompt' do
get "/session/email-login/#{email_token.token}"
expect(response.status).to eq(200)
response_body = CGI.unescapeHTML(response.body)
expect(response_body).to include(I18n.t(
"login.second_factor_title"
))
expect(response_body).to_not include(I18n.t(
"login.invalid_second_factor_code"
))
end | Class | 2 |
def get_cluster_properties_definition(params, request, session)
unless allowed_for_local_cluster(session, Permissions::READ)
return 403, 'Permission denied'
end
stdout, _, retval = run_cmd(
session, PCS, 'property', 'get_cluster_properties_definition'
)
if retval == 0
return [200, stdout]
end
return [400, '{}']
end | Compound | 4 |
it "returns a hex string representation of the id" do
Moped::BSON::ObjectId.new(bytes).to_s.should eq "4e4d66343b39b68407000001"
end | Class | 2 |
it 'fails when local logins is disabled' do
SiteSetting.enable_local_logins = false
get "/session/email-login/#{email_token.token}"
expect(response.status).to eq(500)
end | Class | 2 |
it "yields the new session" do
session.stub(with: new_session)
session.new(new_options) do |session|
session.should eql new_session
end
end | Class | 2 |
it "converts to Punycode URI" do
expect(subject.process_uri(uri).to_s).to eq 'http://xn--eckwd4c7cu47r2wf.jp/test.jpg'
end | Base | 1 |
def getAllSettings(session, cib_dom=nil)
unless cib_dom
cib_dom = get_cib_dom(session)
end
ret = {}
if cib_dom
cib_dom.elements.each('/cib/configuration/crm_config//nvpair') { |e|
ret[e.attributes['name']] = e.attributes['value']
}
end
return ret
end | Compound | 4 |
it 'should not overwrite an existing file if overwrite_stored_key is not set' do
@plugin.stubs(:lookup_config_option).with('learn_public_keys').returns('1')
@plugin.stubs(:lookup_config_option).with('publickey_dir').returns('ssh/pkd')
@plugin.stubs(:lookup_config_option).with('overwrite_stored_keys', 'n').returns('n')
File.stubs(:directory?).with('ssh/pkd').returns(true)
File.stubs(:exists?).with('ssh/pkd/rspec_pub.pem').returns(true)
File.stubs(:read).with('ssh/pkd/rspec_pub.pem').returns('ssh-rsa dcba')
Log.expects(:warn)
File.expects(:open).never
@plugin.send(:write_key_to_disk, 'ssh-rsa abcd', 'rspec')
end | Class | 2 |
it "executes a simple query" do
session.should_receive(:simple_query).with(query.operation)
query.one
end | Class | 2 |
it "adds the credentials to the auth cache" do
cluster.login("admin", "username", "password")
cluster.auth.should eq("admin" => ["username", "password"])
end | Class | 2 |
def check_action_permission!(skip_source = nil)
super(skip_source)
# only perform the following check, if we are called from
# BsRequest.permission_check_change_state! (that is, if
# skip_source is set to true). Always executing this check
# would be a regression, because this code is also executed
# if a new request is created (which could fail if User.current
# cannot modify the source_package).
return unless skip_source
target_project = Project.get_by_name(self.target_project)
return unless target_project && target_project.is_a?(Project)
target_package = target_project.packages.find_by_name(self.target_package)
initialize_devel_package = target_project.find_attribute('OBS', 'InitializeDevelPackage')
return if target_package || !initialize_devel_package
source_package = Package.get_by_project_and_name(source_project, self.source_package)
return if !source_package || User.current.can_modify?(source_package)
msg = 'No permission to initialize the source package as a devel package'
raise PostRequestNoPermission, msg
end | Class | 2 |
it "sets slave_ok on the query flags" do
session.stub(socket_for: socket)
socket.should_receive(:execute) do |query|
query.flags.should include :slave_ok
end
session.query(query)
end | Class | 2 |
def show_owners name
response = rubygems_api_request :get, "api/v1/gems/#{name}/owners.yaml" do |request|
request.add_field "Authorization", api_key
end
with_response response do |resp|
owners = YAML.load resp.body
say "Owners for gem: #{name}"
owners.each do |owner|
say "- #{owner['email'] || owner['handle'] || owner['id']}"
end
end
end | Base | 1 |
def self.get_for(user, mail_account_id, xtype)
return nil if user.nil? or mail_account_id.blank?
if user.kind_of?(User)
user_id = user.id
else
user_id = user.to_s
end
SqlHelper.validate_token([user_id, mail_account_id, xtype])
con = []
con << "(user_id=#{user_id})"
con << "(mail_account_id=#{mail_account_id})"
con << "(xtype='#{xtype}')"
return MailFolder.where(con.join(' and ')).first
end | Base | 1 |
def initialize(seeds, direct = false)
@seeds = seeds
@direct = direct
@servers = []
@dynamic_seeds = []
end | Class | 2 |
it "returns a session" do
session.with(new_options).should be_a Moped::Session
end | Class | 2 |
def order_by
order_option = ''
if self.order_column
direction = self.order_direction || 'ASC'
order_option = "#{self.order_column} #{direction}"
end
order_option.present? ? order_option : @@default_order
end | Base | 1 |
it "should get the script it asks for" do
def @bus.is_admin_lookup
proc { |_| true }
end
get "/message-bus/_diagnostics/assets/message-bus.js"
last_response.status.must_equal 200
last_response.content_type.must_equal "application/javascript;charset=UTF-8"
end | Base | 1 |
it "returns all other known hosts" do
cluster.sync_server(server).should =~ ["localhost:61085", "localhost:61086", "localhost:61084"]
end | Class | 2 |
def index
html = <<~HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="app"></div>
#{js_asset "jquery-1.8.2.js"}
#{js_asset "react.js"}
#{js_asset "react-dom.js"}
#{js_asset "babel.min.js"}
#{js_asset "message-bus.js"}
#{js_asset "application.jsx", "text/jsx"}
</body>
</html>
HTML
[200, { "content-type" => "text/html;" }, [html]]
end | Base | 1 |
it "stores the selector" do
query.selector.should eq selector
end | Class | 2 |
def set_auth_teams
Log.add_info(request, params.inspect)
@folder = Folder.find(params[:id])
if Folder.check_user_auth(@folder.id, @login_user, 'w', true)
read_teams = []
write_teams = []
teams_auth = params[:teams_auth]
unless teams_auth.nil?
teams_auth.each do |auth_param|
user_id = auth_param.split(':').first
auths = auth_param.split(':').last.split('+')
if auths.include?('r')
read_teams << user_id
end
if auths.include?('w')
write_teams << user_id
end
end
end
@folder.set_read_teams read_teams
@folder.set_write_teams write_teams
@folder.save
flash[:notice] = t('msg.register_success')
else
flash[:notice] = 'ERROR:' + t('folder.need_auth_to_modify')
end
target_user_id = (@login_user.admin?(User::AUTH_TEAM))?(nil):(@login_user.id)
@teams = Team.get_for(target_user_id, true)
render(:partial => 'ajax_auth_teams', :layout => false)
rescue => evar
Log.add_error(request, evar)
render(:partial => 'ajax_auth_teams', :layout => false)
end | Base | 1 |
def setup_cluster(params, request, session)
if not allowed_for_superuser(session)
return 403, 'Permission denied'
end
$logger.info("Setting up cluster: " + params.inspect)
nodes_rrp = params[:nodes].split(';')
options = []
myoptions = JSON.parse(params[:options])
transport_udp = false
options_udp = []
myoptions.each { |o,v|
if ["wait_for_all", "last_man_standing", "auto_tie_breaker"].include?(o)
options << "--" + o + "=1"
end
options << "--" + o + "=" + v if [
"token", "token_coefficient", "join", "consensus", "miss_count_const",
"fail_recv_const", "last_man_standing_window",
].include?(o)
if o == "transport" and v == "udp"
options << "--transport=udp"
transport_udp = true
end
if o == "transport" and v == "udpu"
options << "--transport=udpu"
transport_udp = false
end
if ["addr0", "addr1", "mcast0", "mcast1", "mcastport0", "mcastport1", "ttl0", "ttl1"].include?(o)
options_udp << "--" + o + "=" + v
end
if ["broadcast0", "broadcast1"].include?(o)
options_udp << "--" + o
end
if o == "ipv6"
options << "--ipv6"
end
}
if transport_udp
nodes = []
nodes_rrp.each { |node| nodes << node.split(',')[0] }
else
nodes = nodes_rrp
end
nodes_options = nodes + options
nodes_options += options_udp if transport_udp
stdout, stderr, retval = run_cmd(
session, PCS, "cluster", "setup", "--enable", "--start",
"--name", params[:clustername], *nodes_options
)
if retval != 0
return [
400,
(stdout + [''] + stderr).collect { |line| line.rstrip() }.join("\n")
]
end
return 200
end | Compound | 4 |
def quote_column_name(name) #:nodoc:
@quoted_column_names[name] ||= "`#{name}`"
end | Base | 1 |
def remove
delete = Protocol::Delete.new(
operation.database,
operation.collection,
operation.selector,
flags: [:remove_first]
)
session.with(consistency: :strong) do |session|
session.execute delete
end
end | Class | 2 |
def get_folders_order
Log.add_info(request, params.inspect)
@folder_id = params[:id]
if @folder_id == '0'
@folders = MailFolder.get_account_roots_for(@login_user)
else
mail_folder = MailFolder.find(@folder_id)
if mail_folder.user_id == @login_user.id
@folders = MailFolder.get_childs(@folder_id, false, true)
end
end
render(:partial => 'ajax_folders_order', :layout => false)
rescue => evar
Log.add_error(request, evar)
render(:partial => 'ajax_folders_order', :layout => false)
end | Base | 1 |
def get_auth_teams
Log.add_info(request, params.inspect)
begin
@folder = Folder.find(params[:id])
rescue
@folder = nil
end
target_user_id = (@login_user.admin?(User::AUTH_TEAM))?(nil):(@login_user.id)
@teams = Team.get_for(target_user_id, true)
session[:folder_id] = params[:id]
render(:partial => 'ajax_auth_teams', :layout => false)
end | Base | 1 |
def initialize(data = nil, time = nil)
if data
@data = data
elsif time
@data = @@generator.generate(time.to_i)
else
@data = @@generator.next
end
end | Class | 2 |
it 'should overwrite the existing public key if overwrite_stored_key is set' do
@plugin.stubs(:lookup_config_option).with('learn_public_keys').returns('1')
@plugin.stubs(:lookup_config_option).with('publickey_dir').returns('ssh/pkd')
@plugin.stubs(:lookup_config_option).with('overwrite_stored_keys', 'n').returns('1')
File.stubs(:directory?).with('ssh/pkd').returns(true)
File.stubs(:exists?).with('ssh/pkd/rspec_pub.pem').returns(true)
File.stubs(:read).with('ssh/pkd/rspec_pub.pem').returns('ssh-rsa dcba')
file = mock
File.expects(:open).with('ssh/pkd/rspec_pub.pem', 'w').yields(file)
file.expects(:puts).with('ssh-rsa abcd')
Log.expects(:warn)
@plugin.send(:write_key_to_disk, 'ssh-rsa abcd', 'rspec')
end | Class | 2 |
def self.map_library_name(lib)
# Mangle the library name to reflect the native library naming conventions
lib = lib.to_s unless lib.kind_of?(String)
lib = Library::LIBC if lib == 'c'
if lib && File.basename(lib) == lib
lib = Platform::LIBPREFIX + lib unless lib =~ /^#{Platform::LIBPREFIX}/
r = Platform::IS_GNU ? "\\.so($|\\.[1234567890]+)" : "\\.#{Platform::LIBSUFFIX}$"
lib += ".#{Platform::LIBSUFFIX}" unless lib =~ /#{r}/
end
lib
end | Base | 1 |
def cama_current_user
return @cama_current_user if defined?(@cama_current_user)
# api current user...
@cama_current_user = cama_calc_api_current_user
return @cama_current_user if @cama_current_user
return nil unless cookies[:auth_token].present?
c = cookies[:auth_token].split("&")
return nil unless c.size == 3
@cama_current_user = current_site.users_include_admins.find_by_auth_token(c[0]).try(:decorate)
end | Base | 1 |
def show
filename = Rails.root.join("attachments", @attachment.filename)
unless File.exist?(filename)
COURSE_LOGGER.log("Cannot find the file '#{@attachment.filename}' for"\
" attachment #{@attachment.name}")
flash[:error] = "Error loading #{@attachment.name} from #{@attachment.filename}"
redirect_to([@course, :attachments]) && return
end
send_file(filename, disposition: "inline",
type: @attachment.mime_type, filename: @attachment.filename) && return
end | Base | 1 |
it "returns a new session" do
session.with(new_options).should_not eql session
end | Class | 2 |
def get_mail_attachment
Log.add_info(request, params.inspect)
attached_id = params[:id].to_i
mail_attach = MailAttachment.find_by_id(attached_id)
if mail_attach.nil?
redirect_to(THETIS_RELATIVE_URL_ROOT + '/404.html')
return
end
email = Email.find_by_id(mail_attach.email_id)
if email.nil? or email.user_id != @login_user.id
render(:text => '')
return
end
mail_attach_name = mail_attach.name
agent = request.env['HTTP_USER_AGENT']
unless agent.nil?
ie_ver = nil
agent.scan(/\sMSIE\s?(\d+)[.](\d+)/){|m|
ie_ver = m[0].to_i + (0.1 * m[1].to_i)
}
mail_attach_name = CGI::escape(mail_attach_name) unless ie_ver.nil?
end
filepath = mail_attach.get_path
if FileTest.exist?(filepath)
send_file(filepath, :filename => mail_attach_name, :stream => true, :disposition => 'attachment')
else
send_data('', :type => 'application/octet-stream;', :disposition => 'attachment;filename="'+mail_attach_name+'"')
end
end | Base | 1 |
def munge_name(name)
# LAK:NOTE http://snurl.com/21zf8 [groups_google_com]
# Change to name.downcase.split(".",-1).reverse for FQDN support
name.downcase.split(".").reverse
end | Class | 2 |
def get_group_users
Log.add_info(request, params.inspect)
@group_id = nil
if !params[:thetisBoxSelKeeper].nil?
@group_id = params[:thetisBoxSelKeeper].split(':').last
elsif !params[:group_id].nil? and !params[:group_id].empty?
@group_id = params[:group_id]
end
submit_url = url_for(:controller => 'desktop', :action => 'get_group_users')
render(:partial => 'common/select_users', :layout => false, :locals => {:target_attr => :id, :submit_url => submit_url})
end | Base | 1 |
def known_addresses
[].tap do |addresses|
addresses.concat seeds
addresses.concat dynamic_seeds
addresses.concat servers.map { |server| server.address }
end.uniq
end | Class | 2 |
def initialize(database, command)
super database, :$cmd, command, limit: -1
end | Class | 2 |
def authorize_params
super.tap do |params|
%w[display state scope].each do |v|
if request.params[v]
params[v.to_sym] = request.params[v]
# to support omniauth-oauth2's auto csrf protection
session['omniauth.state'] = params[:state] if v == 'state'
end
end
params[:scope] ||= DEFAULT_SCOPE
end
end | Compound | 4 |
it "returns the master connection" do
cluster.socket_for(:read).should eq socket
end | Class | 2 |
def more?
@get_more_op.cursor_id != 0
end | Class | 2 |
def self.getSuperuserSession()
return {
:username => SUPERUSER,
:usergroups => [],
}
end | Compound | 4 |
def ffi_lib(*names)
raise LoadError.new("library names list must not be empty") if names.empty?
lib_flags = defined?(@ffi_lib_flags) ? @ffi_lib_flags : FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL
ffi_libs = names.map do |name|
if name == FFI::CURRENT_PROCESS
FFI::DynamicLibrary.open(nil, FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL)
else
libnames = (name.is_a?(::Array) ? name : [ name ]).map(&:to_s).map { |n| [ n, FFI.map_library_name(n) ].uniq }.flatten.compact
lib = nil
errors = {}
libnames.each do |libname|
begin
orig = libname
lib = FFI::DynamicLibrary.open(libname, lib_flags)
break if lib
rescue Exception => ex
ldscript = false
if ex.message =~ /(([^ \t()])+\.so([^ \t:()])*):([ \t])*(invalid ELF header|file too short|invalid file format)/
if File.read($1) =~ /(?:GROUP|INPUT) *\( *([^ \)]+)/
libname = $1
ldscript = true
end
end
if ldscript
retry
else
# TODO better library lookup logic
unless libname.start_with?("/")
path = ['/usr/lib/','/usr/local/lib/'].find do |pth|
File.exist?(pth + libname)
end
if path
libname = path + libname
retry
end
end
libr = (orig == libname ? orig : "#{orig} #{libname}")
errors[libr] = ex
end
end
end
if lib.nil?
raise LoadError.new(errors.values.join(".\n"))
end
# return the found lib
lib
end
end
@ffi_libs = ffi_libs
end | Base | 1 |
def legal?(str)
!!str.match(/^[0-9a-f]{24}$/i)
end | Class | 2 |
it "removes the first matching document" do
session.should_receive(:with, :consistency => :strong).
and_yield(session)
session.should_receive(:execute).with do |delete|
delete.flags.should eq [:remove_first]
delete.selector.should eq query.operation.selector
end
query.remove
end | Class | 2 |
def self.on_desktop?(user, xtype, target_id)
return false if user.nil? or xtype.nil? or target_id.nil?
SqlHelper.validate_token([xtype, target_id])
con = "(user_id=#{user.id}) and (xtype='#{xtype}') and (target_id=#{target_id})"
begin
toy = Toy.where(con).first
rescue => evar
Log.add_error(nil, evar)
end
return (!toy.nil?)
end | Base | 1 |
def include_allowed?(target, reader)
doc = reader.document
return false if doc.safe >= ::Asciidoctor::SafeMode::SECURE
return false if doc.attributes.fetch('max-include-depth', 64).to_i < 1
return false if target_uri?(target) && !doc.attributes.key?('allow-uri-read')
true
end | Base | 1 |
def add_acl_usergroup(session, acl_role_id, user_group, name)
if (user_group == "user") or (user_group == "group")
stdout, stderr, retval = run_cmd(
session, PCS, "acl", user_group, "create", name.to_s, acl_role_id.to_s
)
if retval == 0
return ""
end
if not /^error: (user|group) #{name.to_s} already exists$/i.match(stderr.join("\n").strip)
return stderr.join("\n").strip
end
end
stdout, stderror, retval = run_cmd(
session, PCS, "acl", "role", "assign", acl_role_id.to_s, name.to_s
)
if retval != 0
if stderror.empty?
return "Error adding #{user_group}"
else
return stderror.join("\n").strip
end
end
return ""
end | Compound | 4 |
def check_image_content_type!(new_file)
if image?(new_file)
magic_type = mime_magic_content_type(new_file)
if magic_type != new_file.content_type
raise CarrierWave::IntegrityError, "has MIME type mismatch"
end
end
end | Base | 1 |
it "converts the comment markup to HTML" do
expect(comment.generate_html(:body)).to match(%r{<em>italic</em>})
expect(comment.generate_html(:body)).to match(%r{<strong>bold</strong>})
end | Base | 1 |
it "updates to a mongo advanced selector" do
query.explain
query.operation.selector.should eq(
"$query" => selector,
"$explain" => true,
"$orderby" => { _id: 1 }
)
end | Class | 2 |
def remote_node_available(params, request, session)
if (not ISRHEL6 and File.exist?(Cfgsync::CorosyncConf.file_path)) or (ISRHEL6 and File.exist?(Cfgsync::ClusterConf.file_path)) or File.exist?("/var/lib/pacemaker/cib/cib.xml")
return JSON.generate({:node_available => false})
end
return JSON.generate({:node_available => true})
end | Compound | 4 |
def self.taxonomy_conditions
org = Organization.expand(Organization.current) if SETTINGS[:organizations_enabled]
loc = Location.expand(Location.current) if SETTINGS[:locations_enabled]
conditions = {}
conditions[:organization_id] = Array(org).map { |o| o.subtree_ids }.flatten.uniq if org.present?
conditions[:location_id] = Array(loc).map { |l| l.subtree_ids }.flatten.uniq if loc.present?
conditions
end | Class | 2 |
it "should redeem the invite if invited by staff" do
SiteSetting.must_approve_users = true
inviter = invite.invited_by
inviter.admin = true
user = invite_redeemer.redeem
invite.reload
expect(user.name).to eq(name)
expect(user.username).to eq(username)
expect(user.invited_by).to eq(inviter)
expect(inviter.notifications.count).to eq(1)
expect(user.approved).to eq(true)
end | Class | 2 |
def add_node(session, new_nodename, all=false, auto_start=true)
if all
command = [PCS, "cluster", "node", "add", new_nodename]
if auto_start
command << '--start'
command << '--enable'
end
out, stderror, retval = run_cmd(session, *command)
else
out, stderror, retval = run_cmd(
session, PCS, "cluster", "localnode", "add", new_nodename
)
end
$logger.info("Adding #{new_nodename} to pcs_settings.conf")
corosync_nodes = get_corosync_nodes()
pcs_config = PCSConfig.new(Cfgsync::PcsdSettings.from_file('{}').text())
pcs_config.update_cluster($cluster_name, corosync_nodes)
sync_config = Cfgsync::PcsdSettings.from_text(pcs_config.text())
# on version conflict just go on, config will be corrected eventually
# by displaying the cluster in the web UI
Cfgsync::save_sync_new_version(
sync_config, corosync_nodes, $cluster_name, true
)
return retval, out.join("\n") + stderror.join("\n")
end | Compound | 4 |
it "raises with a valid SSRF attack" do
@api_key = "-attacker.net/test/?"
@gibbon.api_key = @api_key
expect {@gibbon.try.retrieve}.to raise_error(Gibbon::MailChimpError, /SSRF attempt/)
end | Base | 1 |
it "can set the password and ip_address" do
password = 's3cure5tpasSw0rD'
ip_address = '192.168.1.1'
invite = Fabricate(:invite, email: '[email protected]')
user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White', password: password, ip_address: ip_address)
expect(user).to have_password
expect(user.confirm_password?(password)).to eq(true)
expect(user.approved).to eq(true)
expect(user.ip_address).to eq(ip_address)
expect(user.registration_ip_address).to eq(ip_address)
end | Class | 2 |
it "returns true" do
Moped::BSON::ObjectId.new(bytes).should == Moped::BSON::ObjectId.new(bytes)
end | Class | 2 |
def team
Log.add_info(request, params.inspect)
date_s = params[:date]
if date_s.nil? or date_s.empty?
@date = Date.today
else
@date = Date.parse(date_s)
end
begin
team = Team.find(params[:id])
team_users = team.get_users_a
rescue => evar
Log.add_error(request, evar)
end
@user_schedule_hash = {}
unless team_users.nil?
@holidays = Schedule.get_holidays
team_users.each do |user_id|
@user_schedule_hash[user_id] = Schedule.get_somebody_week(@login_user, user_id, @date, @holidays)
end
end
params[:display] = params[:action] + '_' + params[:id]
end | Base | 1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.