code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
def resource_stop(params, request, session) if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end stdout, stderr, retval = run_cmd( session, PCS, "resource", "disable", params[:resource] ) if retval == 0 return JSON.generate({"success" => "true"}) else...
Compound
4
def self.trim(user_id, mail_account_id, max) SqlHelper.validate_token([user_id, mail_account_id]) begin count = Email.where("mail_account_id=#{mail_account_id}").count if count > max #logger.fatal("[INFO] Email.trim(user_id:#{user_id}, mail_account_id:#{mail_account_id}, max:#{max})") ov...
Base
1
it "returns false" do indexes.drop(other: 1).should be_false end
Class
2
def add_meta_attr(session, resource, key, value) stdout, stderr, retval = run_cmd( session, PCS, "resource", "meta", resource, key.to_s + "=" + value.to_s ) return retval end
Compound
4
def authenticate! unless Setting['oauth_active'] Rails.logger.warn 'Trying to authenticate with OAuth, but OAuth is not active' return nil end unless (incoming_key = OAuth::RequestProxy.proxy(request).oauth_consumer_key) == Setting['oauth_consumer_key'] Rails.logger.warn "...
Class
2
def protected! gui_request = ( # these are URLs for web pages request.path == '/' or request.path == '/manage' or request.path == '/permissions' or request.path.match('/managec/.+/main') ) if request.path.start_with?('/remote/') or request.path == '/run_pcs' unless PCSAuth.lo...
Compound
4
def deliver!(mail) envelope_from = mail.return_path || mail.sender || mail.from_addrs.first return_path = "-f \"#{envelope_from.to_s.shellescape}\"" if envelope_from arguments = [settings[:arguments], return_path].compact.join(" ") self.class.call(settings[:location], arguments, mail) en...
Class
2
it "returns the new session" do session.stub(with: new_session) session.new(new_options).should eql new_session end
Class
2
it "requires an account with mail" do user = FactoryGirl.create(:user) get :index, {}, set_session_user.merge(:user => user.id) assert_response :redirect assert_redirected_to edit_user_path(user) assert_equal "An email address is required, please update your account details", flash[:er...
Class
2
def generate(type, str) case type when :md5 attribute_value = '{MD5}' + Base64.encode64(Digest::MD5.digest(str)).chomp! when :sha attribute_value = '{SHA}' + Base64.encode64(Digest::SHA1.digest(str)).chomp! when :ssha srand; salt = (rand * 1000).to_i.to_s ...
Base
1
def test_should_sanitize_illegal_style_properties raw = %(display:block; position:absolute; left:0; top:0; width:100%; height:100%; z-index:1; background-color:black; background-image:url(http://www.ragingplatypus.com/i/cam-full.jpg); background-x:center; background-y:center; background-repeat:repeat;) e...
Base
1
def self.validate_token(tokens, extra_chars=nil) extra_chars = Regexp.escape((extra_chars || []).join()) regexp = Regexp.new("^[ ]*[a-zA-Z0-9_.#{extra_chars}]+[ ]*$") [tokens].flatten.each do |token| next if token.blank? if token.to_s.match(regexp).nil? raise("[ERROR] SqlHelper.vali...
Base
1
it "returns the right category group permissions for a regular user ordered by ascending group name" do json = described_class.new(category, scope: Guardian.new(user), root: false).as_json expect(json[:group_permissions]).to eq([ { permission_type: CategoryGroup.permission_types[:readon...
Base
1
def wf_issue Log.add_info(request, params.inspect) begin @item = Item.find(params[:id]) @workflow = @item.workflow rescue => evar Log.add_error(request, evar) end attrs = ActionController::Parameters.new({status: Workflow::STATUS_ACTIVE, issued_at: Time.now}) @workflow.upda...
Base
1
it "should not display completed tasks" do task_1 = FactoryGirl.create(:task, :user_id => current_user.id, :name => "Your first task", :bucket => "due_asap", :assigned_to => current_user.id) task_2 = FactoryGirl.create(:task, :user_id => current_user.id, :name => "Completed task", :bucket => "due_asap", :comple...
Base
1
it "doesn't try to set flags" do session.stub(socket_for: socket) expect { session.query(query) }.not_to raise_exception end
Class
2
def self.save_group_value(group_id, category, key, value) SqlHelper.validate_token([group_id, category, key]) con = [] con << "(group_id=#{group_id})" con << "(category='#{category}')" con << "(xkey='#{key}')" setting = Setting.where(con.join(' and ')).first if value.nil? unless ...
Base
1
it "returns a new indexes instance" do collection.indexes.should be_an_instance_of Moped::Indexes end
Class
2
it "returns the same hash" do Moped::BSON::ObjectId.new(bytes).hash.should eq Moped::BSON::ObjectId.new(bytes).hash end
Class
2
it "sets the query operation's skip field" do query.skip(5) query.operation.skip.should eq 5 end
Class
2
def resource_start(params, request, session) if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end stdout, stderr, retval = run_cmd( session, PCS, "resource", "enable", params[:resource] ) if retval == 0 return JSON.generate({"success" => "true"}) else...
Compound
4
it 'should authenticate user and delete token' do user = Fabricate(:user) get "/session/current.json" expect(response.status).to eq(404) token = SecureRandom.hex $redis.setex "otp_#{token}", 10.minutes, user.username get "/session/otp/#{token}" ...
Class
2
def test_destroy domain = Domain.first domain.hosts.clear domain.hostgroups.clear domain.subnets.clear delete :destroy, {:id => domain}, set_session_user assert_redirected_to domains_url assert !Domain.exists?(domain.id) end
Class
2
def add_acl_role(session, name, description) cmd = [PCS, "acl", "role", "create", name.to_s] if description.to_s != "" cmd << "description=#{description.to_s}" end stdout, stderror, retval = run_cmd(session, *cmd) if retval != 0 return stderror.join("\n").strip end return "" end
Compound
4
def self.using(file, name) new(file, name) end
Base
1
def bbs Log.add_info(request, params.inspect) if !params[:select_sorting].nil? sort_a = params[:select_sorting].split(' ') params[:sort_col] = sort_a.first params[:sort_type] = sort_a.last end list render(:action => 'bbs') end
Base
1
it "activates user invited via email with a token" do invite = Fabricate(:invite, invited_by: Fabricate(:admin), email: 'walter.white@email.com', emailed_status: Invite.emailed_status_types[:sent]) user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', nam...
Class
2
it "unmemoizes the current database" do db = session.current_database session.with(new_options) do |new_session| new_session.current_database.should_not eql db end end
Class
2
def reconnect @servers = servers.map { |server| Server.new(server.address) } end
Class
2
def meeting_link(uniqueid, data) notification = t( "notifications.meeting.#{data[:type]}", name: data[:user], group_name: data[:group], meeting_name: data[:typename] ) link = specific_meeting_link(data[:type], data[:typeid], data[:group_id]) notification_link(uniqueid, link, no...
Base
1
def filename_from_uri CGI.unescape(File.basename(file.base_uri.path)) end
Base
1
def test_update_invalid put :update, {:id => Hostgroup.first, :hostgroup => { :name => '' }}, set_session_user assert_template 'edit' end
Class
2
def remove_constraint_remote(params, request, session) if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end if params[:constraint_id] retval = remove_constraint(session, params[:constraint_id]) if retval == 0 return "Constraint #{params[:constraint_id...
Compound
4
def self.open(path_or_url, ext = nil, options = {}) options, ext = ext, nil if ext.is_a?(Hash) ext ||= if File.exist?(path_or_url) File.extname(path_or_url) else File.extname(URI(path_or_url).path) end ext.sub!(/:.*/, '') # hack for filenames or URLs t...
Base
1
def email_login raise Discourse::NotFound if !SiteSetting.enable_local_logins_via_email second_factor_token = params[:second_factor_token] second_factor_method = params[:second_factor_method].to_i token = params[:token] valid_token = !!EmailToken.valid_token_format?(token) user = EmailToken.co...
Class
2
def current_database return @current_database if defined? @current_database if database = options[:database] set_current_database(database) else raise "No database set for session. Call #use or #with before accessing the database" end end
Class
2
it "updates a hostgroup with a parent parameter, allows empty values" do child = FactoryGirl.create(:hostgroup, :parent => @base) as_admin do assert_equal "original", child.parameters["x"] end post :update, {"id" => child.id, "hostgroup" => {"name" => child.name, ...
Class
2
def redirect_url return "/" unless member_login_node member_login_node.redirect_url || "/" end
Base
1
def test_destroy auth_source_ldap = AuthSourceLdap.first User.where(:auth_source_id => auth_source_ldap.id).update_all(:auth_source_id => nil) delete :destroy, {:id => auth_source_ldap}, set_session_user assert_redirected_to auth_source_ldaps_url assert !AuthSourceLdap.exists?(auth_source_ldap.id)...
Class
2
it "creates a hostgroup with a parent parameter" do post :create, {"hostgroup" => {"name"=>"test_it", "parent_id" => @base.id, :realm_id => realms(:myrealm).id, :group_parameters_attributes => {"0" => {:name => "x", :value =>"overridden", :_destroy => ""}}}}, set_session_u...
Class
2
it "raises a connection failure exception" do cluster.sync_server(server).should be_empty end
Class
2
it "respects custom options" do expect(app.as_json(except: :secret)).not_to include("secret") expect(app.as_json(only: :id)).to match("id" => app.id) end
Class
2
def destroy Log.add_info(request, params.inspect) begin OfficialTitle.destroy(params[:id]) rescue => evar Log.add_error(nil, evar) end @group_id = params[:group_id] if @group_id.nil? or @group_id.empty? @group_id = '0' # '0' for ROOT end render(:partial => 'grou...
Base
1
def supplied_file_media_types @supplied_file_media_types ||= MIME::Types.type_for(@name).collect(&:media_type) end
Base
1
def mget(*keys) options = (keys.pop if keys.last.is_a? Hash) || {} if keys.any? # Marshalling gets extended before Namespace does, so we need to pass options further if singleton_class.ancestors.include? Marshalling super(*keys.map {|key| interpolate(key) }, options...
Base
1
def do_execute Log.add_info(request, params.inspect) mail_account = MailAccount.find_by_id(params[:mail_account_id]) mail_folder = MailFolder.find_by_id(params[:mail_folder_id]) if mail_account.user_id != @login_user.id \ or mail_folder.user_id != @login_user.id render(:text => t('msg....
Base
1
def self.get_next_revision(user_id, source_id) SqlHelper.validate_token([user_id, source_id]) copied_items = Item.where("user_id=#{user_id} and source_id=#{source_id}").order('created_at DESC').to_a rev = 0 copied_items.each do |item| rev_ary = item.title.scan(/[#](\d\d\d)$/) next if re...
Base
1
it "allows/disable marshalling" do store = Redis::Store::Factory.create :marshalling => false store.instance_variable_get(:@marshalling).must_equal(false) store.instance_variable_get(:@options)[:raw].must_equal(true) end
Base
1
def initialize(seeds, options = {}) @cluster = Cluster.new(seeds) @options = options @options[:consistency] ||= :eventual end
Class
2
def cluster_status_gui(session, cluster_name, dont_update_config=false) cluster_nodes = get_cluster_nodes(cluster_name) status = cluster_status_from_nodes(session, cluster_nodes, cluster_name) unless status return 403, 'Permission denied' end new_cluster_nodes = [] new_cluster_nodes += status[:corosync...
Compound
4
it 'logs in correctly' do post "/session/email-login/#{email_token.token}", params: { second_factor_token: ROTP::TOTP.new(user_second_factor.data).now, second_factor_method: UserSecondFactor.methods[:totp] } expect(response).to redir...
Class
2
def assemble_params(sanitized_params) sanitized_params.collect do |pair| pair_joiner = pair.first.to_s.end_with?("=") ? "" : " " pair.flatten.compact.join(pair_joiner) end.join(" ") end
Base
1
def comments_closed? !(allow_comments? && in_feedback_window?) end
Class
2
it "without params" do cl = subject.build_command_line("true") expect(cl).to eq "true" end
Base
1
def test_formats_valid AuthSourceLdap.any_instance.stubs(:valid?).returns(false) put :update, {:id => AuthSourceLdap.first.id, :format => "weird", :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user assert_response :success wierd_id = "#{AuthSourceLdap.first.id}.weird" p...
Class
2
def destroy_workflow Log.add_info(request, params.inspect) Item.find(params[:id]).destroy @tmpl_folder, @tmpl_workflows_folder = TemplatesHelper.get_tmpl_subfolder(TemplatesHelper::TMPL_WORKFLOWS) @group_id = params[:group_id] if @group_id.nil? or @group_id.empty? @group_id = '0' # '0'...
Base
1
it "has an empty list of dynamic seeds" do cluster.dynamic_seeds.should be_empty end
Class
2
def self.get_for_group(group_id, category=nil) SqlHelper.validate_token([group_id, category]) con = [] con << "(group_id=#{group_id})" con << "(category='#{category}')" unless category.nil? settings = Setting.where(con.join(' and ')).to_a return nil if settings.nil? or settings.empty? ...
Base
1
def test_AES_crush 500.times do assert_nothing_raised("[Bug #2768]") do # it caused OpenSSL SEGV by uninitialized key OpenSSL::Cipher::AES128.new("ECB").update "." * 17 end end end
Class
2
def command(command) operation = Protocol::Command.new(name, command) result = session.with(consistency: :strong) do |session| session.simple_query(operation) end raise Errors::OperationFailure.new( operation, result ) unless result["ok"] == 1.0 result end
Class
2
def initialize # Generate and cache 3 bytes of identifying information from the current # machine. @machine_id = Digest::MD5.digest(Socket.gethostname).unpack("C3") @mutex = Mutex.new @last_timestamp = nil @counter = 0 end
Class
2
def remove_acl_remote(params, request, session) if not allowed_for_local_cluster(session, Permissions::GRANT) return 403, 'Permission denied' end if params["item"] == "permission" retval = remove_acl_permission(session, params["acl_perm_id"]) elsif params["item"] == "usergroup" retval = remove_acl_u...
Compound
4
def read_lines(path, selector) if selector IO.foreach(path).select.with_index(1, &selector) else URI.open(path, &:read) end end
Base
1
it "inserts the documents" do session.should_receive(:execute).with do |insert| insert.documents.should eq [{a: 1}, {b: 2}] end collection.insert([{a: 1}, {b: 2}]) end
Class
2
def sanitize(params) return [] if params.nil? || params.empty? params.collect do |k, v| [sanitize_key(k), sanitize_value(v)] end end
Base
1
it "drops the index that matches the key" do indexes[name: 1].should be_nil end
Class
2
def install_location filename, destination_dir # :nodoc: raise Gem::Package::PathError.new(filename, destination_dir) if filename.start_with? '/' destination_dir = File.realpath destination_dir if File.respond_to? :realpath destination_dir = File.expand_path destination_dir destination =...
Base
1
it "delegates to the cluster" do session.cluster.should_receive(:socket_for).with(:read) session.send(:socket_for, :read) end
Class
2
def update article = Ticket::Article.find(params[:id]) authorize!(article) clean_params = Ticket::Article.association_name_to_id_convert(params) clean_params = Ticket::Article.param_cleanup(clean_params, true) # only apply preferences changes (keep not updated keys/values) clean_params = art...
Class
2
def self.get_for(group_id, include_parents=false, enabled=nil) SqlHelper.validate_token([group_id]) con = [] #con << "(disabled=#{!enabled})" unless enabled.nil? if include_parents group_con = '(group_id is null)' unless group_id.nil? or group_id.to_s == '0' group_obj_cache = {...
Base
1
it "should should be a subclass of Base" do Puppet::FileServing::Metadata.superclass.should equal(Puppet::FileServing::Base) end
Class
2
it "downloads a file" do expect(subject.download(uri).file.read).to eq file end
Base
1
def update Log.add_info(request, params.inspect) @equipment = Equipment.find(params[:id]) if (params[:groups].nil? or params[:groups].empty?) params[:equipment][:groups] = nil else params[:equipment][:groups] = '|' + params[:groups].join('|') + '|' end if (params[:teams].nil? or...
Base
1
it "returns the master connection" do cluster.socket_for(:read).should eq socket end
Class
2
def remove_constraint_rule_remote(params, request, session) if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end if params[:rule_id] retval = remove_constraint_rule(session, params[:rule_id]) if retval == 0 return "Constraint rule #{params[:rule_id]} ...
Compound
4
def insert(documents) documents = [documents] unless documents.is_a? Array insert = Protocol::Insert.new(database.name, name, documents) database.session.with(consistency: :strong) do |session| session.execute insert end end
Class
2
def from_string(string) raise Errors::InvalidObjectId.new(string) unless legal?(string) data = [] 12.times { |i| data << string[i*2, 2].to_i(16) } new data end
Class
2
def access?(query) return false if record.internal == true && !user.permissions?('ticket.agent') ticket = Ticket.lookup(id: record.ticket_id) Pundit.authorize(user, ticket, query) end
Class
2
def remove_application(user_ids) return if user_ids.nil? or user_ids.empty? SqlHelper.validate_token([user_ids]) con = ["(xtype='#{Comment::XTYPE_APPLY}')"] con << "(item_id=#{self.item_id})" user_con_a = [] user_ids.each do |user_id| user_con_a << "(user_id=#{user_id})" end ...
Base
1
def self.loginByToken(session, cookies) if username = validToken(cookies["token"]) if SUPERUSER == username if cookies['CIB_user'] and cookies['CIB_user'].strip != '' session[:username] = cookies['CIB_user'] if cookies['CIB_user_groups'] and cookies['CIB_user_groups'].strip != ''...
Compound
4
def query(query) if options[:consistency] == :eventual query.flags |= [:slave_ok] if query.respond_to? :flags mode = :read else mode = :write end reply = socket_for(mode).execute(query) reply.tap do |reply| if reply.flags.include?(:query_failure) ...
Class
2
it "returns true" do session.should be_safe end
Class
2
it "removes all matching documents" do session.should_receive(:with, :consistency => :strong). and_yield(session) session.should_receive(:execute).with do |delete| delete.flags.should eq [] delete.selector.should eq query.operation.selector end query.remove_all ...
Class
2
def primaries servers.select(&:primary?) end
Class
2
it "does not re-sync the cluster" do cluster.should_receive(:sync).never cluster.socket_for :write end
Class
2
it "doesn't try to set flags" do session.stub(socket_for: socket) expect { session.query(query) }.not_to raise_exception end
Class
2
def test_html5_data_attributes_without_hyphenation assert_equal("<div data-author_id='123' data-biz='baz' data-foo='bar'></div>\n", render("%div{:data => {:author_id => 123, :foo => 'bar', :biz => 'baz'}}", :hyphenate_data_attrs => false)) assert_equal("<div data-one_plus_one='2'></div>\n", ...
Base
1
def add_order_constraint( session, resourceA, resourceB, actionA, actionB, score, symmetrical=true, force=false, autocorrect=true ) sym = symmetrical ? "symmetrical" : "nonsymmetrical" if score != "" score = "score=" + score end command = [ PCS, "constraint", "order", actionA, resourceA, "then",...
Compound
4
def parse_memory(data, encoding = "UTF-8") raise ArgumentError unless data return if data.empty? ctx = ParserContext.memory(data, encoding) yield ctx if block_given? ctx.parse_with(self) end
Base
1
def initialize(remote_host, remote_port, local_host = nil, local_port = nil) if Thread.current[:private_address_check] && PrivateAddressCheck.resolves_to_private_address?(remote_host) raise PrivateAddressCheck::PrivateConnectionAttemptedError end initialize_without_private_address_check(remote_host...
Class
2
def within_bounding_box(sw_lat, sw_lng, ne_lat, ne_lng, lat_attr, lon_attr) spans = "#{lat_attr} BETWEEN #{sw_lat} AND #{ne_lat} AND " # handle box that spans 180 longitude if sw_lng.to_f > ne_lng.to_f spans + "(#{lon_attr} BETWEEN #{sw_lng} AND 180 OR " + "#{lon_attr} BETWEEN -180...
Base
1
def initialize(seeds, options = {}) @cluster = Cluster.new(seeds) @options = options @options[:consistency] ||= :eventual end
Class
2
def read_checksums gem Gem.load_yaml @checksums = gem.seek 'checksums.yaml.gz' do |entry| Zlib::GzipReader.wrap entry do |gz_io| YAML.load gz_io.read end end end
Base
1
def gate_process HistoryHelper.keep_last(request) @login_user = User.find_by_id(session[:login_user_id]) begin if @login_user.nil? \ or @login_user.time_zone.nil? or @login_user.time_zone.empty? unless THETIS_USER_TIMEZONE_DEFAULT.nil? or THETIS_USER_TIMEZONE_DEFAULT.empty? ...
Base
1
it "stores the database" do collection.database.should eq database end
Class
2
def set_member_and_redirect(member) set_member member Member::ActivityLog.create( cur_site: @cur_site, cur_member: member, activity_type: "login", remote_addr: remote_addr, user_agent: request.user_agent) ref = URI::decode(params[:ref] || flash[:ref] || "") ref = redirec...
Base
1
def test_full_sanitize_allows_turning_off_encoding_special_chars assert_equal '&amp;', full_sanitize('&') assert_equal '&', full_sanitize('&', encode_special_chars: false) end
Base
1
it 'is valid with valid attributes' do notification = build(:notification) expect(notification).to be_valid end
Base
1
def spec_summary entry, spec entry << "\n\n" << format_text(spec.summary, 68, 4) end
Class
2
it "instructs the cluster to reconnect" do session.stub(with: new_session) new_session.cluster.should_receive(:reconnect) session.new(new_options) end
Class
2