code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
def valid?(user, password) return false if user.blank? if PasswordHash.legacy?(user.password, password) update_password(user, password) return true end PasswordHash.verified?(user.password, password) end
Class
2
def self.get_team_folder(team_id) SqlHelper.validate_token([team_id]) begin return Folder.where("(owner_id=#{team_id}) and (xtype='#{Folder::XTYPE_TEAM}')").first rescue => evar Log.add_error(nil, evar) return nil end end
Base
1
def edit_page # Saved contents of Login User begin @research = Research.where("user_id=#{@login_user.id}").first rescue end if @research.nil? @research = Research.new else # Already accepted? if [email protected]? and @research.status != 0 render(:action => 'show_receipt') return end end # Specifying page @page = '01' unless params[:page].nil? or params[:page].empty? @page = params[:page] end end
Base
1
def self.update_for(user_id, fiscal_year, num) SqlHelper.validate_token([user_id, fiscal_year]) if num <= 0 con = [] con << "(user_id=#{user_id})" con << "(year=#{fiscal_year})" PaidHoliday.destroy_all(con.join(' and ')) return end paid_holiday = PaidHoliday.get_for(user_id, fiscal_year) if paid_holiday.nil? paid_holiday = PaidHoliday.new paid_holiday.user_id = user_id paid_holiday.year = fiscal_year paid_holiday.num = num paid_holiday.save! else paid_holiday.update_attribute(:num, num) end end
Base
1
def check_import(mode, address_names) #, address_emails err_msgs = [] # Existing Addresss unless self.id.nil? or self.id == 0 or self.id == '' if mode == 'add' err_msgs << I18n.t('address.import.dont_specify_id') else begin org_address = Address.find(self.id) rescue end if org_address.nil? err_msgs << I18n.t('address.import.not_found') end end end # Requierd if self.name.nil? or self.name.empty? err_msgs << Address.human_attribute_name('name') + I18n.t('msg.is_required') end # Groups unless self.groups.nil? or self.groups.empty? if (/^|([0-9]+|)+$/ =~ self.groups) == 0 self.get_groups_a.each do |group_id| group = Group.find_by_id(group_id) if group.nil? err_msgs << I18n.t('address.import.not_valid_groups') + ': '+group_id.to_s break end end else err_msgs << I18n.t('address.import.invalid_groups_format') end end # Teams unless self.teams.nil? or self.teams.empty? if (/^|([0-9]+|)+$/ =~ self.teams) == 0 self.get_teams_a.each do |team_id| team = Team.find_by_id(team_id) if team.nil? err_msgs << I18n.t('address.import.not_valid_teams') + ': '+team_id.to_s break end end else err_msgs << I18n.t('address.import.invalid_teams_format') end end return err_msgs end
Base
1
it "updates all records matching selector with change" do query.should_receive(:update).with(change, [:multi]) query.update_all change end
Class
2
it "stores the list of seeds" do cluster.seeds.should eq ["127.0.0.1:27017", "127.0.0.1:27018"] end
Class
2
def filename_extension File.extname(@name.to_s.downcase).sub(/^\./, '').to_sym end
Base
1
it "sets the :database option" do session.use :admin session.options[:database].should eq(:admin) 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 initialize(session, query_operation) @session = session @query_op = query_operation.dup @get_more_op = Protocol::GetMore.new( @query_op.database, @query_op.collection, 0, @query_op.limit ) @kill_cursor_op = Protocol::KillCursors.new([0]) end
Class
2
def verify_signature(string, signature) if signature.nil? fail InvalidSignature, "missing \"signature\" param" elsif signature != generate_signature(string) fail InvalidSignature, "provided signature does not match the calculated signature" end end
Base
1
def get_corosync_version() begin stdout, stderror, retval = run_cmd( PCSAuth.getSuperuserSession, COROSYNC, "-v" ) rescue stdout = [] end if retval == 0 match = /version\D+(\d+)\.(\d+)\.(\d+)/.match(stdout.join()) if match return match[1..3].collect { | x | x.to_i } end end return nil end
Compound
4
def build_gem_lines(conservative_versioning) @deps.map do |d| name = d.name.dump requirement = if conservative_versioning ", \"#{conservative_version(@definition.specs[d.name][0])}\"" else ", #{d.requirement.as_list.map(&:dump).join(", ")}" end if d.groups != Array(:default) group = d.groups.size == 1 ? ", :group => #{d.groups.first.inspect}" : ", :groups => #{d.groups.inspect}" end source = ", :source => \"#{d.source}\"" unless d.source.nil? git = ", :git => \"#{d.git}\"" unless d.git.nil? branch = ", :branch => \"#{d.branch}\"" unless d.branch.nil? %(gem #{name}#{requirement}#{group}#{source}#{git}#{branch}) end.join("\n")
Base
1
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 more? @get_more_op.cursor_id != 0 end
Class
2
def update_folders_order Log.add_info(request, params.inspect) order_ary = params[:folders_order] folders = MailFolder.get_childs(params[:id], false, false) # folders must be ordered by xorder ASC. folders.sort! { |id_a, id_b| idx_a = order_ary.index(id_a) idx_b = order_ary.index(id_b) if idx_a.nil? or idx_b.nil? idx_a = folders.index(id_a) idx_b = folders.index(id_b) end idx_a - idx_b } idx = 1 folders.each do |folder_id| begin folder = MailFolder.find(folder_id) next if folder.user_id != @login_user.id folder.update_attribute(:xorder, idx) if folder.xtype == MailFolder::XTYPE_ACCOUNT_ROOT mail_account = MailAccount.find_by_id(folder.mail_account_id) unless mail_account.nil? mail_account.update_attribute(:xorder, idx) end end idx += 1 rescue => evar Log.add_error(request, evar) end end render(:text => '') end
Base
1
def __bson_load__(io) new io.read(12).unpack('C*') end
Class
2
def execute(op) mode = options[:consistency] == :eventual ? :read : :write socket = socket_for(mode) if safe? last_error = Protocol::Command.new( "admin", { getlasterror: 1 }.merge(safety) ) socket.execute(op, last_error).documents.first.tap do |result| raise Errors::OperationFailure.new( op, result ) if result["err"] || result["errmsg"] end else socket.execute(op) end end
Class
2
it "should return :file if the URI protocol is set to 'file'" do @request.expects(:protocol).returns "file" @object.select_terminus(@request).should == :file end
Class
2
def params super rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e raise BadRequest, "Invalid query parameters: #{e.message}" end
Base
1
it "does not automatically approve users if must_approve_users is true" do SiteSetting.must_approve_users = true invite = Fabricate(:invite, email: '[email protected]') user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'test') expect(user.approved).to eq(false) end
Class
2
def category_preferences_export return enum_for(:category_preferences_export) unless block_given? CategoryUser .where(user_id: @current_user.id) .select(:category_id, :notification_level, :last_seen_at) .each do |cu| yield [ cu.category_id, piped_category_name(cu.category_id), NotificationLevels.all[cu.notification_level], cu.last_seen_at ] end end
Class
2
def selected_ids return @selected_ids if @selected_ids ids = default_ids_hash #types NOT ignored - get ids that are selected hash_keys.each do |col| ids[col] = Array(taxonomy.send(col)) end #types that ARE ignored - get ALL ids for object Array(taxonomy.ignore_types).each do |taxonomy_type| ids["#{taxonomy_type.tableize.singularize}_ids"] = taxonomy_type.constantize.pluck(:id) end ids["#{opposite_taxonomy_type}_ids"] = Array(taxonomy.send("#{opposite_taxonomy_type}_ids")) @selected_ids = ids end
Class
2
def set_resource_utilization(params, reqest, session) unless allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end unless params[:resource_id] and params[:name] return 400, 'resource_id and name are required' end res_id = params[:resource_id] name = params[:name] value = params[:value] || '' _, stderr, retval = run_cmd( session, PCS, 'resource', 'utilization', res_id, "#{name}=#{value}" ) if retval != 0 return [400, "Unable to set utilization '#{name}=#{value}' for " + "resource '#{res_id}': #{stderr.join('')}" ] end return 200 end
Compound
4
def clean_text(text) text.gsub(/[\u0000-\u0008\u000b-\u000c\u000e-\u001F\u007f]/, ".".freeze) end
Base
1
def deliver!(mail) if ::File.respond_to?(:makedirs) ::File.makedirs settings[:location] else ::FileUtils.mkdir_p settings[:location] end mail.destinations.uniq.each do |to| ::File.open(::File.join(settings[:location], to), 'a') { |f| "#{f.write(mail.encoded)}\r\n\r\n" } end end
Base
1
it "allows you to create an account and redeems the invite successfully even if must_approve_users is enabled" do SiteSetting.must_approve_users = true login_with_sso_and_invite expect(response.status).to eq(302) expect(response).to redirect_to("/") expect(invite.reload.redeemed?).to eq(true) user = User.find_by_email("[email protected]") expect(user.active).to eq(true) end
Class
2
def check_owner return if params[:id].nil? or params[:id].empty? or @login_user.nil? begin owner_id = Workflow.find(params[:id]).user_id rescue owner_id = -1 end if !@login_user.admin?(User::AUTH_WORKFLOW) and owner_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
it "queries a slave node" do session.should_receive(:socket_for).with(:read). and_return(socket) session.query(query) end
Class
2
it "stores whether the connection is direct" do cluster.direct.should be_true end
Class
2
it 'returns all campaigns belonging to the inbox to administrators' do # create a random campaign create(:campaign, account: account) get "/api/v1/accounts/#{account.id}/inboxes/#{inbox.id}/campaigns", headers: administrator.create_new_auth_token, as: :json expect(response).to have_http_status(:success) body = JSON.parse(response.body, symbolize_names: true) expect(body.first[:id]).to eq(campaign.display_id) expect(body.length).to eq(1) end
Base
1
it "initializes with the strings bytes" do Moped::BSON::ObjectId.should_receive(:new).with(bytes) Moped::BSON::ObjectId.from_string "4e4d66343b39b68407000001" end
Class
2
def reset_users Log.add_info(request, params.inspect) count = 0 unless params[:check_user].nil? params[:check_user].each do |user_id, value| if value == '1' begin Research.destroy_all('user_id=' + user_id.to_s) count += 1 rescue => evar Log.add_error(request, evar) end end end end if count > 0 flash[:notice] = t('msg.status_of')+ count.to_s + t('user.status_reset') end redirect_to(:controller => 'researches', :action => 'users') rescue => evar Log.add_error(request, evar) render(:text => evar.to_s) end
Base
1
def download(url, remote_headers = {}) headers = remote_headers. reverse_merge('User-Agent' => "CarrierWave/#{CarrierWave::VERSION}") begin file = OpenURI.open_uri(process_uri(url.to_s), headers) rescue StandardError => e raise CarrierWave::DownloadError, "could not download file: #{e.message}" end CarrierWave::Downloader::RemoteFile.new(file) end
Base
1
it "raises an exception" do expect { session.current_database }.to raise_exception end
Class
2
def request(args = {}) { :ip => '10.1.1.1', :node => 'host.domain.com', :key => 'key', :authenticated => true }.each do |k,v| args[k] ||= v end ['test', :find, args[:key], args] end
Class
2
def get_attachment Log.add_info(request, params.inspect) attach = Attachment.find(params[:id]) if attach.nil? redirect_to(THETIS_RELATIVE_URL_ROOT + '/404.html') return end parent_item = attach.item || ((attach.comment.nil?) ? nil : attach.comment.item) if parent_item.nil? or !parent_item.check_user_auth(@login_user, 'r', true) Log.add_check(request, '[Item.check_user_auth]'+request.to_s) redirect_to(:controller => 'frames', :action => 'http_error', :id => '401') return end attach_name = 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) } attach_name = CGI::escape(attach_name) unless ie_ver.nil? end begin attach_location = attach.location rescue attach_location = Attachment::LOCATION_DB # for lower versions end if attach_location == Attachment::LOCATION_DIR filepath = AttachmentsHelper.get_path(attach) send_file(filepath, :filename => attach_name, :stream => true, :disposition => 'attachment') else send_data(attach.content, :type => (attach.content_type || 'application/octet-stream')+';charset=UTF-8', :disposition => 'attachment;filename="'+attach_name+'"') end end
Base
1
it "returns false" do session.should_not be_safe end
Class
2
def list Log.add_info(request, params.inspect) con = [] @group_id = nil if !params[:thetisBoxSelKeeper].nil? @group_id = params[:thetisBoxSelKeeper].split(':').last elsif !params[:group_id].blank? @group_id = params[:group_id] end unless @group_id.nil? if @group_id == '0' con << "((groups like '%|0|%') or (groups is null))" else con << ApplicationHelper.get_sql_like([:groups], "|#{@group_id}|") end end where = '' unless con.empty? where = ' where ' + con.join(' and ') end order_by = nil @sort_col = params[:sort_col] @sort_type = params[:sort_type] if @sort_col.blank? or @sort_type.blank? @sort_col = 'id' @sort_type = 'ASC' end SqlHelper.validate_token([@sort_col, @sort_type]) order_by = ' order by ' + @sort_col + ' ' + @sort_type sql = 'select distinct Equipment.* from equipment Equipment' sql << where + order_by @equipment_pages, @equipment, @total_num = paginate_by_sql(Equipment, sql, 20) end
Base
1
it "delegates to #with" do session.should_receive(:with).with(new_options).and_return(new_session) session.new(new_options) end
Class
2
def remote_remove_nodes(params, request, session) if not allowed_for_local_cluster(session, Permissions::FULL) return 403, 'Permission denied' end count = 0 out = "" node_list = [] options = [] while params["nodename-" + count.to_s] node_list << params["nodename-" + count.to_s] count = count + 1 end options << "--force" if params["force"] cur_node = get_current_node_name() if i = node_list.index(cur_node) node_list.push(node_list.delete_at(i)) end # stop the nodes at once in order to: # - prevent resources from moving pointlessly # - get possible quorum loss warning stop_params = node_list + options stdout, stderr, retval = run_cmd( session, PCS, "cluster", "stop", *stop_params ) if retval != 0 return [400, stderr.join] end node_list.each {|node| retval, output = remove_node(session, node, true) out = out + output.join("\n") } config = PCSConfig.new(Cfgsync::PcsdSettings.from_file('{}').text()) if config.get_nodes($cluster_name) == nil or config.get_nodes($cluster_name).length == 0 return [200,"No More Nodes"] end return out end
Compound
4
def login(database, username, password) auth[database.to_s] = [username, password] end
Class
2
def group 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 @group_id = params[:id] group_users = Group.get_users(params[:id]) @user_schedule_hash = {} unless group_users.nil? @holidays = Schedule.get_holidays group_users.each do |user| @user_schedule_hash[user.id.to_s] = Schedule.get_somebody_week(@login_user, user.id, @date, @holidays) end end params[:display] = params[:action] + '_' + params[:id] end
Base
1
def calculated_media_type @calculated_media_type ||= calculated_content_type.split("/").first end
Base
1
def login(username, password) session.cluster.login(name, username, password) end
Class
2
it "sets the object id's data" do Moped::BSON::ObjectId.new(bytes).data.should == bytes end
Class
2
def update_config Log.add_info(request, params.inspect) yaml = ApplicationHelper.get_config_yaml unless params[:timecard].nil? or params[:timecard].empty? yaml[:timecard] = Hash.new if yaml[:timecard].nil? params[:timecard].each do |key, val| yaml[:timecard][key] = val end ApplicationHelper.save_config_yaml(yaml) end @yaml_timecard = yaml[:timecard] @yaml_timecard = Hash.new if @yaml_timecard.nil? flash[:notice] = t('msg.update_success') render(:action => 'configure') end
Base
1
def unfolded_header @unfolded_header ||= unfold(raw_source) end
Base
1
def add_node_attr(session, node, key, value) stdout, stderr, retval = run_cmd( session, PCS, "property", "set", "--node", node, key.to_s + '=' + value.to_s ) return retval end
Compound
4
def create @application = Doorkeeper.config.application_model.new(application_params) if @application.save flash[:notice] = I18n.t(:notice, scope: %i[doorkeeper flash applications create]) flash[:application_secret] = @application.plaintext_secret respond_to do |format| format.html { redirect_to oauth_application_url(@application) } format.json { render json: @application } end else respond_to do |format| format.html { render :new } format.json do errors = @application.errors.full_messages render json: { errors: errors }, status: :unprocessable_entity end end end end
Class
2
it 'should write the public key to disk if its the first time its been seen' do @plugin.stubs(:lookup_config_option).with('learn_public_keys').returns('1') @plugin.stubs(:lookup_config_option).with('publickey_dir').returns('ssh/pkd') File.stubs(:directory?).with('ssh/pkd').returns(true) File.stubs(:exists?).with('ssh/pkd/rspec_pub.pem').returns(false) file = mock File.expects(:open).with('ssh/pkd/rspec_pub.pem', 'w').yields(file) file.expects(:puts).with('ssh-rsa abcd') @plugin.send(:write_key_to_disk, 'ssh-rsa abcd', 'rspec') end
Class
2
def supplied_file_content_types @supplied_file_content_types ||= MIME::Types.type_for(@name).collect(&:content_type) end
Base
1
def empty Log.add_info(request, params.inspect) @folder_id = params[:id] mail_account_id = params[:mail_account_id] SqlHelper.validate_token([mail_account_id]) trash_folder = MailFolder.get_for(@login_user, mail_account_id, MailFolder::XTYPE_TRASH) mail_folder = MailFolder.find(@folder_id) emails = MailFolder.get_mails(mail_folder.id, @login_user) || [] if mail_folder.id == trash_folder.id \ or mail_folder.get_parents(false).include?(trash_folder.id.to_s) emails.each do |email| email.destroy end flash[:notice] = t('msg.delete_success') else emails.each do |email| email.update_attribute(:mail_folder_id, trash_folder.id) end flash[:notice] = t('msg.moved_to_trash') end get_mails end
Base
1
def self.destroy(host) client = host.gsub("..",".") dir = File.join(Puppet[:reportdir], client) if File.exists?(dir) Dir.entries(dir).each do |file| next if ['.','..'].include?(file) file = File.join(dir, file) File.unlink(file) if File.file?(file) end Dir.rmdir(dir) end end
Base
1
it "creates a new cursor" do cursor = mock(Moped::Cursor, next: nil) Moped::Cursor.should_receive(:new). with(session, query.operation).and_return(cursor) query.each end
Class
2
def self.save_value(user_id, category, key, value) SqlHelper.validate_token([user_id, category, key]) con = [] con << "(user_id=#{user_id})" con << "(category='#{category}')" con << "(xkey='#{key}')" setting = Setting.where(con.join(' and ')).first if value.nil? unless setting.nil? setting.destroy end else if setting.nil? setting = Setting.new setting.user_id = user_id setting.category = category setting.xkey = key setting.xvalue = value setting.save! else setting.update_attribute(:xvalue, value) end end end
Base
1
def query(operation) reply = session.query operation @get_more_op.limit -= reply.count if limited? @get_more_op.cursor_id = reply.cursor_id @kill_cursor_op.cursor_ids = [reply.cursor_id] reply.documents end
Class
2
def new @item = Item.new if params[:folder_id].nil? or params[:folder_id].empty? my_folder = @login_user.get_my_folder if my_folder.nil? @item.folder_id = 0 else @item.folder_id = my_folder.id end else @item.folder_id = params[:folder_id].to_i end @item.xtype= Item::XTYPE_INFO @item.layout = 'C' render(:action => 'edit') end
Base
1
it "stores the database" do collection.database.should eq database end
Class
2
def nofollowify_links(string) if this_blog.dofollowify string else string.gsub(/<a(.*?)>/i, '<a\1 rel="nofollow">') end end
Base
1
def self.find_by_sql_with_limit(sql, offset, limit) sql = sanitize_sql(sql) add_limit!(sql, {:limit => limit, :offset => offset}) find_by_sql(sql) end
Base
1
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", render("%div{:data => {:one_plus_one => 1+1}}", :hyphenate_data_attrs => false)) assert_equal("<div data-foo='Here&#x0027;s a \"quoteful\" string.'></div>\n", render(%{%div{:data => {:foo => %{Here's a "quoteful" string.}}}},
Base
1
def private_message_reset_new topic_query = TopicQuery.new(current_user, limit: false) if params[:topic_ids].present? unless Array === params[:topic_ids] raise Discourse::InvalidParameters.new( "Expecting topic_ids to contain a list of topic ids" ) end topic_scope = topic_query .private_messages_for(current_user, :all) .where("topics.id IN (?)", params[:topic_ids].map(&:to_i)) else params.require(:inbox) inbox = params[:inbox].to_s filter = private_message_filter(topic_query, inbox) topic_scope = topic_query.filter_private_message_new(current_user, filter) end topic_ids = TopicsBulkAction.new( current_user, topic_scope.distinct(false).pluck(:id), type: "dismiss_topics" ).perform! render json: success_json.merge(topic_ids: topic_ids) end
Class
2
it "raises an OperationFailure exception" do session.stub(socket_for: socket) socket.stub(execute: reply) expect { session.execute(operation) }.to raise_exception(Moped::Errors::OperationFailure) end
Class
2
it "has an empty list of secondaries" do cluster.secondaries.should be_empty end
Class
2
def run_auth_requests(session, nodes_to_send, nodes_to_auth, username, password, force=false, local=true) data = {} nodes_to_auth.each_with_index { |node, index| data["node-#{index}"] = node } data['username'] = username data['password'] = password data['bidirectional'] = 1 if not local data['force'] = 1 if force auth_responses = {} threads = [] nodes_to_send.each { |node| threads << Thread.new { code, response = send_request(session, node, 'auth', true, data) if 200 == code token = response.strip if '' == token auth_responses[node] = {'status' => 'bad_password'} else auth_responses[node] = {'status' => 'ok', 'token' => token} end else auth_responses[node] = {'status' => 'noresponse'} end } } threads.each { |t| t.join } return auth_responses end
Compound
4
def skip_node?(node) node.text? || node.cdata? end
Base
1
def test_jail_instances_should_have_limited_methods expected = ["class", "inspect", "method_missing", "methods", "respond_to?", "respond_to_missing?", "to_jail", "to_s", "instance_variable_get"] expected.delete('respond_to_missing?') if RUBY_VERSION > '1.9.3' # respond_to_missing? is private in rubies above 1.9.3 objects.each do |object| assert_equal expected.sort, reject_pretty_methods(object.to_jail.methods.map(&:to_s).sort) end end
Class
2
it "upserts the record matching selector with change" do query.should_receive(:update).with(change, [:upsert]) query.upsert change end
Class
2
def self.load_current_node(session, crm_dom=nil) node = ClusterEntity::Node.new node.corosync = corosync_running? node.corosync_enabled = corosync_enabled? node.pacemaker = pacemaker_running? node.pacemaker_enabled = pacemaker_enabled? node.cman = cman_running? node.pcsd_enabled = pcsd_enabled? node_online = (node.corosync and node.pacemaker) node.status = node_online ? 'online' : 'offline' node.uptime = get_node_uptime node.id = get_local_node_id if node_online and crm_dom node_el = crm_dom.elements["//node[@id='#{node.id}']"] if node_el and node_el.attributes['standby'] == 'true' node.status = 'standby' else node.status = 'online' end node.quorum = !!crm_dom.elements['//current_dc[@with_quorum="true"]'] else node.status = 'offline' end return node end
Compound
4
def remove_constraint_rule(session, rule_id) stdout, stderror, retval = run_cmd( session, PCS, "constraint", "rule", "remove", rule_id ) $logger.info stdout return retval end
Compound
4
it 'does not log in with incorrect backup code' do post "/session/email-login/#{email_token.token}", params: { second_factor_token: "0000", second_factor_method: UserSecondFactor.methods[:backup_codes] } expect(response.status).to eq(200) expect(CGI.unescapeHTML(response.body)).to include(I18n.t( "login.invalid_second_factor_code" )) end
Class
2
def write_key_to_disk(key, identity) # Writing is disabled. Don't bother checking any other states. return unless lookup_config_option('learn_public_keys') =~ /^1|y/ publickey_dir = lookup_config_option('publickey_dir') unless publickey_dir Log.info("Public key sent with request but no publickey_dir defined in configuration. Not writing key to disk.") return end if File.directory?(publickey_dir) if File.exists?(old_keyfile = File.join(publickey_dir, "#{identity}_pub.pem")) old_key = File.read(old_keyfile).chomp unless old_key == key unless lookup_config_option('overwrite_stored_keys', 'n') =~ /^1|y/ Log.warn("Public key sent from '%s' does not match the stored key. Not overwriting." % identity) else Log.warn("Public key sent from '%s' does not match the stored key. Overwriting." % identity) File.open(File.join(publickey_dir, "#{identity}_pub.pem"), 'w') { |f| f.puts key } end end else Log.debug("Discovered a new public key for '%s'. Writing to '%s'" % [identity, publickey_dir]) File.open(File.join(publickey_dir, "#{identity}_pub.pem"), 'w') { |f| f.puts key } end else raise("Cannot write public key to '%s'. Directory does not exist." % publickey_dir) end end
Class
2
def show if params[:action] == 'show' Log.add_info(request, params.inspect) end @mail_filter = MailFilter.find_by_id(params[:id]) if @mail_filter.nil? render(:text => 'ERROR:' + t('msg.already_deleted', :name => MailFilter.model_name.human)) return else if @mail_filter.mail_account.user_id != @login_user.id render(:text => 'ERROR:' + t('msg.need_to_be_owner')) return end end render(:action => 'show', :layout => (!request.xhr?)) end
Base
1
it "raises no exception" do lambda do cluster.sync_server server end.should_not raise_exception end
Class
2
def drop command dropDatabase: 1 end
Class
2
it "queries the master node" do session.should_receive(:socket_for).with(:write). and_return(socket) session.query(query) end
Class
2
def self.search_by_host(key, operator, value) conditions = "hosts.name #{operator} '#{value_to_sql(operator, value)}'" direct = Puppetclass.all(:conditions => conditions, :joins => :hosts, :select => 'puppetclasses.id').map(&:id).uniq hostgroup = Hostgroup.joins(:hosts).where(conditions).first indirect = HostgroupClass.where(:hostgroup_id => hostgroup.path_ids).pluck(:puppetclass_id).uniq return { :conditions => "1=0" } if direct.blank? && indirect.blank? puppet_classes = (direct + indirect).uniq { :conditions => "puppetclasses.id IN(#{puppet_classes.join(',')})" } end
Base
1
def get_data_center_from_api_key(api_key) # Return an empty string for invalid API keys so Gibbon hits the main endpoint data_center = "" if api_key && api_key["-"] # Add a period since the data_center is a subdomain and it keeps things dry data_center = "#{api_key.split('-').last}." end data_center end
Base
1
def stub_bad_jwks stub_request(:get, 'https://samples.auth0.com/.well-known/jwks-bad.json') .to_return( status: 404 ) end
Base
1
def config_restore(params, request, session) if params[:name] code, response = send_request_with_token( session, params[:name], 'config_restore', true, {:tarball => params[:tarball]} ) else if not allowed_for_local_cluster(session, Permissions::FULL) return 403, 'Permission denied' end $logger.info "Restore node configuration" if params[:tarball] != nil and params[:tarball] != "" out = "" errout = "" status = Open4::popen4(PCS, "config", "restore", "--local") { |pid, stdin, stdout, stderr| stdin.print(params[:tarball]) stdin.close() out = stdout.readlines() errout = stderr.readlines() } retval = status.exitstatus if retval == 0 $logger.info "Restore successful" return "Succeeded" else $logger.info "Error during restore: #{errout.join(' ').strip()}" return errout.length > 0 ? errout.join(' ').strip() : "Error" end else $logger.info "Error: Invalid tarball" return "Error: Invalid tarball" end end end
Compound
4
def limited? @query_op.limit > 0 end
Class
2
def set_auth_users Log.add_info(request, params.inspect) @folder = Folder.find(params[:id]) if Folder.check_user_auth(@folder.id, @login_user, 'w', true) read_users = [] write_users = [] users_auth = params[:users_auth] unless users_auth.nil? users_auth.each do |auth_param| user_id = auth_param.split(':').first auths = auth_param.split(':').last.split('+') if auths.include?('r') read_users << user_id end if auths.include?('w') write_users << user_id end end end user_id = @folder.get_my_folder_owner if !user_id.nil? and (!read_users.include?(user_id.to_s) or !write_users.include?(user_id.to_s)) flash[:notice] = 'ERROR:' + t('folder.my_folder_without_auth_owner') else @folder.set_read_users read_users @folder.set_write_users write_users @folder.save flash[:notice] = t('msg.register_success') end else flash[:notice] = 'ERROR:' + t('folder.need_auth_to_modify') end @group_id = params[:group_id] if @group_id.nil? or @group_id.empty? @users = [] else @users = Group.get_users(@group_id) end render(:partial => 'ajax_auth_users', :layout => false) rescue => evar Log.add_error(request, evar) render(:partial => 'ajax_auth_users', :layout => false) end
Base
1
def private_message_reset_new topic_query = TopicQuery.new(current_user) if params[:topic_ids].present? unless Array === params[:topic_ids] raise Discourse::InvalidParameters.new( "Expecting topic_ids to contain a list of topic ids" ) end topic_scope = topic_query .private_messages_for(current_user, :all) .where("topics.id IN (?)", params[:topic_ids].map(&:to_i)) else params.require(:inbox) inbox = params[:inbox].to_s filter = private_message_filter(topic_query, inbox) topic_query.options[:limit] = false topic_scope = topic_query.filter_private_message_new(current_user, filter) end topic_ids = TopicsBulkAction.new( current_user, topic_scope.pluck(:id), type: "dismiss_topics" ).perform! render json: success_json.merge(topic_ids: topic_ids) end
Class
2
it "passes the initial directory" do expect(File.cleanpath('C/../../D')).to eq "../D" end
Base
1
it "sets the current database" do session.should_receive(:set_current_database).with(:admin) session.use :admin end
Class
2
it "executes a simple query" do session.should_receive(:simple_query).with(query.operation) query.one end
Class
2
it "creates a new cursor" do cursor = mock(Moped::Cursor, next: nil) Moped::Cursor.should_receive(:new). with(session, query.operation).and_return(cursor) query.each end
Class
2
it "returns the result of the block" do session.with(new_options) { false }.should eq false end
Class
2
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
it 'is possible to return errors in jsonapi format' do get '/' expect(last_response.body).to eq('{"error":"rain!"}') end
Base
1
def get_sync_capabilities(params, request, session) return JSON.generate({ 'syncable_configs' => Cfgsync::get_cfg_classes_by_name().keys, }) end
Compound
4
def self.search_by_user(key, operator, value) key_name = key.sub(/^.*\./,'') users = User.all(:conditions => "#{key_name} #{operator} '#{value_to_sql(operator, value)}'") hosts = users.map(&:hosts).flatten opts = hosts.empty? ? "= 'nil'" : "IN (#{hosts.map(&:id).join(',')})" return {:conditions => " hosts.id #{opts} " } end
Base
1
def need_ring1_address?() out, errout, retval = run_cmd(PCSAuth.getSuperuserSession, COROSYNC_CMAPCTL) if retval != 0 return false else udpu_transport = false rrp = false out.each { |line| # support both corosync-objctl and corosync-cmapctl format if /^\s*totem\.transport(\s+.*)?=\s*udpu$/.match(line) udpu_transport = true elsif /^\s*totem\.rrp_mode(\s+.*)?=\s*(passive|active)$/.match(line) rrp = true end } # on rhel6 ring1 address is required regardless of transport # it has to be added to cluster.conf in order to set up ring1 # in corosync by cman return ((ISRHEL6 and rrp) or (rrp and udpu_transport)) end end
Compound
4
def mapped_content_type Paperclip.options[:content_type_mappings][filename_extension] end
Base
1
def remove_application(users) return if users.nil? or users.empty? array = ["(xtype='#{Comment::XTYPE_APPLY}')"] array << "(item_id=#{self.item_id})" user_con_a = [] users.each do |user_id| user_con_a << "(user_id=#{user_id})" end array << '(' + user_con_a.join(' or ') + ')' Comment.destroy_all(array.join(' and ')) end
Base
1
def get_cib(params, request, session) if not allowed_for_local_cluster(session, Permissions::READ) return 403, 'Permission denied' end cib, stderr, retval = run_cmd(session, CIBADMIN, "-Ql") if retval != 0 if not pacemaker_running? return [400, '{"pacemaker_not_running":true}'] end return [500, "Unable to get CIB: " + cib.to_s + stderr.to_s] else return [200, cib] end end
Compound
4
def seed # Authorisation is disabled usually when run from a rake db:* task User.current = FactoryGirl.build(:user, :admin => true) load File.expand_path('../../../../db/seeds.rb', __FILE__) end
Class
2
def get_folder_items Log.add_info(request, params.inspect) unless params[:thetisBoxSelKeeper].nil? or params[:thetisBoxSelKeeper].empty? @folder_id = params[:thetisBoxSelKeeper].split(':').last end begin if Folder.check_user_auth(@folder_id, @login_user, 'r', true) @items = Folder.get_items(@login_user, @folder_id) end rescue => evar Log.add_error(request, evar) end submit_url = url_for(:controller => 'schedules', :action => 'get_folder_items') render(:partial => 'common/select_items', :layout => false, :locals => {:target_attr => :id, :submit_url => submit_url}) end
Base
1