code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
it "returns the count" do database.stub(command: { "n" => 4 }) query.count.should eq 4 end
Class
2
def self.extract_events(post) cooked = PrettyText.cook(post.raw, topic_id: post.topic_id, user_id: post.user_id) valid_options = VALID_OPTIONS.map { |o| "data-#{o}" } valid_custom_fields = [] SiteSetting.discourse_post_event_allowed_custom_fields.split('|').each do |setting| valid_c...
Base
1
def add_to_group Log.add_info(request, params.inspect) if params[:thetisBoxSelKeeper].nil? or params[:thetisBoxSelKeeper].empty? render(:partial => 'ajax_groups', :layout => false) return end group_id = params[:thetisBoxSelKeeper].split(':').last unless group_id == '0' # '0' for ROO...
Base
1
it "returns nothing" do socket.stub(connect: false) cluster.sync_server(server).should be_empty end
Class
2
it "memoizes the database" do database = session.current_database session.current_database.should equal(database) end
Class
2
it "returns nothing" do socket.stub(connect: false) cluster.sync_server(server).should be_empty end
Class
2
it "creates an index with the provided name" do indexes.create(key, name: "custom_index_name") indexes[key]["name"].should eq "custom_index_name" end
Class
2
it 'should return nil if the key ID is invalid' do expect(jwt_validator.jwks_key(:alg, "#{jwks_kid}_invalid")).to eq(nil) end
Base
1
it "with Pathname command and params" do cl = subject.build_command_line(Pathname.new("/usr/bin/ruby"), "-v" => nil) expect(cl).to eq "/usr/bin/ruby -v" end
Base
1
it "removes the socket" do cluster.should_receive(:remove).with(dead_server) cluster.socket_for :write end
Class
2
def update_order Log.add_info(request, params.inspect) mail_account_id = params[:mail_account_id] order_ary = params[:mail_filters_order] @mail_account = MailAccount.find_by_id(mail_account_id) if @mail_account.user_id != @login_user.id render(:text => 'ERROR:' + t('msg.need_to_be_owner')...
Base
1
def get_group_users Log.add_info(request, params.inspect) begin @folder = Folder.find(params[:id]) rescue => evar Log.add_error(request, evar) end @group_id = nil if !params[:thetisBoxSelKeeper].nil? @group_id = params[:thetisBoxSelKeeper].split(':').last elsif !params[...
Base
1
it "sets the query operation's fields" do query.select(a: 1) query.operation.fields.should eq(a: 1) end
Class
2
def approve_account_if_needed if invited_user.present? && reviewable_user = ReviewableUser.find_by(target: invited_user, status: Reviewable.statuses[:pending]) reviewable_user.perform( invite.invited_by, :approve_user, send_email: false, approved_by_invite: true ) e...
Class
2
it "sets the object id's data" do Moped::BSON::ObjectId.new(bytes).data.should == bytes end
Class
2
def socket_for(mode) if options[:retain_socket] @socket ||= cluster.socket_for(mode) else cluster.socket_for(mode) end end
Class
2
def tags_for_index(model) model.tags.inject("".html_safe) do |out, tag| query = controller.send(:current_query) || "" hashtag = "##{tag}" if query.empty? query = hashtag elsif !query.include?(hashtag) query += " #{hashtag}" end out << link_to_function(tag, "crm....
Base
1
it "creates an index" do indexes.create(key, background: true) indexes[key]["background"].should eq true end
Class
2
def update_attachments_order Log.add_info(request, params.inspect) order_ary = params[:attachments_order] item = Item.find(params[:id]) item.attachments_without_content.each do |attach| class << attach def record_timestamps; false; end end attach.update_attribute(:xorder,...
Base
1
def package_index valid_http_methods :get required_parameters :project, :repository, :arch, :package # read access permission check if params[:package] == "_repository" prj = DbProject.get_by_name params[:project], use_source=false else pkg = DbPackage.get_by_project_and_name params[:...
Base
1
def each cursor = Cursor.new(session.with(retain_socket: true), operation) cursor.to_enum.tap do |enum| enum.each do |document| yield document end if block_given? end end
Class
2
def self.parse_csv_row(row, book, idxs, user) imp_id = (idxs[0].nil? or row[idxs[0]].nil?)?(nil):(row[idxs[0]].strip) SqlHelper.validate_token([imp_id]) unless imp_id.blank? org_address = Address.find_by_id(imp_id) end if org_address.nil? address = Address.new else address ...
Base
1
def add_node_attr_remote(params, request, session) if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end retval = add_node_attr( session, params["node"], params["key"], params["value"] ) # retval = 2 if removing attr which doesn't exist if retval == 0 or r...
Compound
4
def redirect_back_or_default(default, options={}) back_url = params[:back_url].to_s if back_url.present? begin uri = URI.parse(back_url) # do not redirect user to another host or to the login or register page if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{...
Class
2
def self.get_sql_like(attr_names, keyword) key = ActiveRecord::Base.connection.quote("%#{SqlHelper.escape_for_like(keyword)}%") con = [] attr_names.each do |attr_name| con << "(#{attr_name} like #{key})" end sql = con.join(' or ') sql = '(' + sql + ')' if con.length > 1 return sql ...
Base
1
def check_owner return if params[:id].nil? or params[:id].empty? or @login_user.nil? begin owner_id = Location.find(params[:id]).user_id rescue owner_id = -1 end if !@login_user.admin?(User::AUTH_LOCATION) and owner_id != @login_user.id Log.add_check(request, '[check_owner]'+req...
Base
1
it "should should be a subclass of Base" do Puppet::FileServing::Content.superclass.should equal(Puppet::FileServing::Base) end
Class
2
def initialize(image_path, colors=16, depth=8) output = `convert #{image_path} -resize 400x400 -format %c -dither None -quantize YIQ -colors #{colors} -depth #{depth} histogram:info:-` @lines = output.lines.sort.reverse.map(&:strip).reject(&:empty?) 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 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 "queries the master node" do session.should_receive(:socket_for).with(:write). and_return(socket) session.query(query) end
Class
2
def get_mail_attachments Log.add_info(request, params.inspect) email_id = params[:id] email = Email.find_by_id(email_id) if email.nil? or email.user_id != @login_user.id render(:text => '') return end download_name = "mail_attachments#{email.id}.zip" zip_file = email.zip_att...
Base
1
def initialize(session, config_classes, nodes, cluster_name) @config_classes = config_classes @nodes = nodes @cluster_name = cluster_name @session = session end
Compound
4
def self.get_my_folder(user_id) return Folder.where("(owner_id=#{user_id}) and (xtype='#{Folder::XTYPE_USER}')").first end
Base
1
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_fo...
Base
1
def update_by_ajax Log.add_info(request, params.inspect) cat_h = {:desktop => User::AUTH_DESKTOP, :user => User::AUTH_USER, :log => User::AUTH_LOG} yaml = ApplicationHelper.get_config_yaml cat_h.keys.each do |cat| next if params[cat].nil? or params[cat].empty? unless @login_user.admin...
Base
1
def self.delete_statistics_group(group_id) yaml = Research.get_config_yaml if yaml.nil? or yaml[:statistics].nil? return [] end groups = yaml[:statistics][:groups] return [] if groups.nil? ary = groups.split('|') ary.delete group_id.to_s ary.compact! ary.delete '' ...
Base
1
def update if @application.update(application_params) flash[:notice] = I18n.t(:notice, scope: i18n_scope(:update)) respond_to do |format| format.html { redirect_to oauth_application_url(@application) } format.json { render json: @application } end else ...
Class
2
def split_header self.fields = unfolded_header.split(CRLF) end
Base
1
def column_content(column, item) value = column.value_object(item) if value.is_a?(Array) value.collect {|v| column_value(column, item, v)}.compact.join(', ').html_safe else column_value(column, item, value) end end
Base
1
def match_resource(env) path = env[PATH_INFO] origin = env[HTTP_ORIGIN] origin_matched = false all_resources.each do |r| if r.allow_origin?(origin, env) origin_matched = true if found = r.match_resource(path, env) return [found, ni...
Base
1
it "with dofollowify disabled, links should be nofollowed" do @blog.dofollowify = false @blog.save expect(nofollowify_links('<a href="http://myblog.net">my blog</a>')). to eq('<a href="http://myblog.net" rel="nofollow">my blog</a>') end
Base
1
def get_acls(session, cib_dom=nil) unless cib_dom cib_dom = get_cib_dom(session) return {} unless cib_dom end acls = { 'role' => {}, 'group' => {}, 'user' => {}, 'target' => {} } cib_dom.elements.each('/cib/configuration/acls/*') { |e| type = e.name[4..-1] if e.name == 'acl_r...
Compound
4
def set_cluster_conf(params, request, session) if not allowed_for_local_cluster(session, Permissions::FULL) return 403, 'Permission denied' end if params[:cluster_conf] != nil and params[:cluster_conf].strip != "" Cfgsync::ClusterConf.backup() Cfgsync::ClusterConf.from_text(params[:cluster_conf]).save...
Compound
4
def html_message key = keys.last.to_s.gsub('_', ' ').gsub(/\b('?[a-z])/) { $1.capitalize } %(<span class="translation_missing" title="translation missing: #{keys.join('.')}">#{key}</span>)
Base
1
def cluster_enable(params, request, session) if params[:name] code, response = send_request_with_token( session, params[:name], 'cluster_enable', true ) else if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end success = enable_cluster(ses...
Compound
4
def group_link(uniqueid, data) notification = t( "notifications.group.#{data[:type]}", name: data[:user], group_name: data[:group] ) link = "/groups/#{data[:group_id]}" notification_link(uniqueid, link, notification) end
Base
1
def RelaxNG string_or_io RelaxNG.new(string_or_io) end
Base
1
def socket_for(mode) sync unless primaries.any? || (secondaries.any? && mode == :read) server = nil while primaries.any? || (secondaries.any? && mode == :read) if mode == :write || secondaries.empty? server = primaries.sample else server = secondaries.sample ...
Class
2
it "returns a new session" do session.with(new_options).should_not eql session end
Class
2
it "stores the collection name" do collection.name.should eq :users end
Class
2
it "should choose :rest when a server is specified" do @request.stubs(:protocol).returns "puppet" @request.expects(:server).returns "foo" @object.select_terminus(@request).should == :rest end
Class
2
def secondaries servers.select(&:secondary?) end
Class
2
def load_file(filename) Gem.load_yaml yaml_errors = [ArgumentError] yaml_errors << Psych::SyntaxError if defined?(Psych::SyntaxError) return {} unless filename and File.exist? filename begin content = YAML.load(File.read(filename)) unless content.kind_of? Hash warn "Failed t...
Base
1
it "limits the query" do session.should_receive(:query) do |query| query.limit.should eq(-1) reply end session.simple_query(query) end
Class
2
def test_new_attribute_interpolation assert_equal("<a href='12'>bar</a>\n", render('%a(href="1#{1 + 1}") bar')) assert_equal("<a href='2: 2, 3: 3'>bar</a>\n", render(%q{%a(href='2: #{1 + 1}, 3: #{foo}') bar}, :locals => {:foo => 3})) assert_equal(%Q{<a href='1\#{1 + 1}'>bar</a>\n}, render('%a(href="1\#{1 ...
Base
1
it 'does not log in with incorrect two factor' do post "/session/email-login/#{email_token.token}", params: { second_factor_token: "0000", second_factor_method: UserSecondFactor.methods[:totp] } expect(response.status).to eq(200) ...
Class
2
def get_cluster_tokens(params, request, session) # pcsd runs as root thus always returns hacluster's tokens if not allowed_for_local_cluster(session, Permissions::FULL) return 403, "Permission denied" end on, off = get_nodes nodes = on + off nodes.uniq! return [200, JSON.generate(get_tokens_of_nodes(n...
Compound
4
it "removes the stored credentials" do cluster.logout :admin cluster.auth.should be_empty end
Class
2
def create_fixed_clamp_code(nbits, signed) if nbits == 1 && signed == :signed raise "signed bitfield must have more than one bit" end if signed == :signed max = (1 << (nbits - 1)) - 1 min = -(max + 1) else min = 0 max = (1 << nbits...
Class
2
def deliver!(mail) envelope_from = mail.return_path || mail.sender || mail.from_addrs.first return_path = "-f \"#{envelope_from.to_s.gsub('"', '\"')}\"" if envelope_from arguments = [settings[:arguments], return_path].compact.join(" ") Sendmail.call(settings[:location], arguments, mail.des...
Class
2
def primaries servers.select(&:primary?) end
Class
2
def one_time_password otp_username = $redis.get "otp_#{params[:token]}" if otp_username && user = User.find_by_username(otp_username) log_on_user(user) $redis.del "otp_#{params[:token]}" return redirect_to path("/") else @error = I18n.t('user_api_key.invalid_token') end r...
Class
2
it "with params as empty Hash" do cl = subject.build_command_line("true", {}) expect(cl).to eq "true" end
Base
1
def get_pacemaker_version() begin stdout, stderror, retval = run_cmd( PCSAuth.getSuperuserSession, PACEMAKERD, "-$" ) rescue stdout = [] end if retval == 0 match = /(\d+)\.(\d+)\.(\d+)/.match(stdout.join()) if match return match[1..3].collect { | x | x.to_i } end end retu...
Compound
4
it "returns the database from the options" do session.current_database.should eq(database) end
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 "returns the living socket" do cluster.socket_for(:write).should eq socket end
Class
2
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 next now = Time.new.to_i counter = @mutex.synchronize do last_timestamp, @last_timestamp = @last_timestamp, now if last_timestamp == now @counter += 1 else @counter = 0 end end generate(now...
Class
2
def initialize(attribute = nil, direction = nil) @attribute = attribute @direction = direction || :asc end
Base
1
it "returns the database from the options" do session.current_database.should eq(database) end
Class
2
def extract_tar_gz io, destination_dir, pattern = "*" # :nodoc: open_tar_gz io do |tar| tar.each do |entry| next unless File.fnmatch pattern, entry.full_name, File::FNM_DOTMATCH destination = install_location entry.full_name, destination_dir FileUtils.rm_rf destination mkd...
Base
1
def self.publish_unread(post) return unless post.topic.regular? # TODO at high scale we are going to have to defer this, # perhaps cut down to users that are around in the last 7 days as well group_ids = if post.post_type == Post.types[:whisper] [Group::AUTO_GROUPS[:staff]] else...
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 execute...
Class
2
def team_organize Log.add_info(request, params.inspect) team_id = params[:team_id] unless team_id.nil? or team_id.empty? begin @team = Team.find(team_id) rescue @team = nil ensure if @team.nil? flash[:notice] = t('msg.already_deleted', :name => Team.mod...
Base
1
def simple_query(query) query.limit = -1 query(query).documents.first end
Class
2
def opposite_direction direction.to_sym == :asc ? :desc : :asc end
Base
1
def logout(database) auth.delete(database.to_s) end
Class
2
def accepted_ally_link(uniqueid, data) notification = t( 'notifications.ally.accepted', name: data[:user] ) link = "/profile?uid=#{data[:uid]}" notification_link(uniqueid, link, notification) end
Base
1
def is_a_copy?(folder_obj_cache=nil) return false if self.source_id.nil? # Exclude those created from system templates. src_item = Item.find_by_id(self.source_id) if src_item.nil? return true else return !src_item.in_system_folder?(folder_obj_cache) end end
Base
1
it "stores the collection" do query.collection.should eq collection end
Class
2
it "returns the index with the provided key" do indexes[name: 1]["name"].should eq "name_1" end
Class
2
def name FIELD_NAME_MAP[@name.to_s.downcase] || @name end
Base
1
def test_should_not_fall_for_xss_image_hack_with_uppercase_tags assert_sanitized %(<IMG """><SCRIPT>alert("XSS")</SCRIPT>">), "<img>\"&gt;" end
Base
1
def test_destroy subnet = Subnet.first subnet.hosts.clear subnet.interfaces.clear subnet.domains.clear delete :destroy, {:id => subnet}, set_session_user assert_redirected_to subnets_url assert !Subnet.exists?(subnet.id) end
Class
2
def send_nodes_request_with_token(session, nodes, request, post=false, data={}, remote=true, raw_data=nil) out = "" code = 0 $logger.info("SNRWT: " + request) # If we're removing nodes, we don't send this to one of the nodes we're # removing, unless we're removing all nodes if request == "/remove_nodes" ...
Compound
4
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 select_terminus(request) # We rely on the request's parsing of the URI. # Short-circuit to :file if it's a fully-qualified path or specifies a 'file' protocol. return PROTOCOL_MAP["file"] if Puppet::Util.absolute_path?(request.key) return PROTOCOL_MAP["file"] if request.protocol == "file" # ...
Class
2
it "returns the result of the block" do session.with(new_options) { false }.should eq false end
Class
2
def each cursor = Cursor.new(session.with(retain_socket: true), operation) cursor.to_enum.tap do |enum| enum.each do |document| yield document end if block_given? end end
Class
2
def file_list io # :nodoc: header = String.new read_until_dashes io do |line| header << line end YAML.load header end
Base
1
def enable_cluster(session) stdout, stderror, retval = run_cmd(session, PCS, "cluster", "enable") return false if retval != 0 return true end
Compound
4
it 'should return an x5c key' do expect(jwt_validator.jwks_key(:x5c, jwks_kid).length).to eq(1) end
Base
1
def get_avail_resource_agents(params, request, session) if not allowed_for_local_cluster(session, Permissions::READ) return 403, 'Permission denied' end agents = getResourceAgents(session) return JSON.generate(agents) end
Compound
4
def sync_server(server) [].tap do |hosts| socket = server.socket if socket.connect info = socket.simple_query Protocol::Command.new(:admin, ismaster: 1) if info["ismaster"] server.primary = true end if info["secondary"] server....
Class
2
def self.count_ack_users(item_id) SqlHelper.validate_token([item_id]) return Comment.where("(item_id=#{item_id}) and (xtype='#{Comment::XTYPE_DIST_ACK}')").count end
Base
1
it "raises a QueryFailure exception" do expect { session.query(query) }.to raise_exception(Moped::Errors::QueryFailure) end
Class
2
it "yields all documents in the cursor" do cursor = Moped::Cursor.allocate cursor.stub(:to_enum).and_return([1, 2].to_enum) Moped::Cursor.stub(new: cursor) query.to_a.should eq [1, 2] end
Class
2
def allowed_for_local_cluster(session, action) pcs_config = PCSConfig.new(Cfgsync::PcsdSettings.from_file('{}').text()) return pcs_config.permissions_local.allows?( session[:username], session[:usergroups], action ) end
Compound
4