text:
package paw.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ConsoleInputReader {

	private BufferedReader reader;

    public ConsoleInputReader() {
        this.reader = new BufferedReader(new InputStreamReader(System.in));
    }

    public String readLine() {
        String result = null;

        try{
            result = this.reader.readLine();
        }
        catch(IOException e) {

        }

        return result;
    }

}


text:
cask 'ilok-license-manager' do
  version '5.2.1'
  sha256 'c68fa5d23fa015237f178edc46ebec836ffff4ea389858a7732fbcd0f9646743'

  url 'https://installers.ilok.com/iloklicensemanager/LicenseSupportInstallerMac.zip'
  appcast 'https://updates.ilok.com/iloklicensemanager/LicenseSupportInstallerMacAppcast.xml'
  name 'iLok License Manager'
  homepage 'https://ilok.com/#!license-manager'

  pkg 'License Support.pkg'

  uninstall pkgutil:   [
                         'com.paceap.pkg.eden.iLokLicenseManager',
                         'com.paceap.pkg.eden.licensed',
                         'com.paceap.pkg.eden.activationexperience',
                       ],
            launchctl: [
                         'com.paceap.eden.licensed',
                         'com.paceap.eden.licensed.agent',
                       ]
end

redpajama_set_name: RedPajamaGithub


text:
from django.test import TestCase
from django.contrib.auth.models import User, Permission

class TestConnectLogout(TestCase):

    # Set up the database
    def setUp(self):
        self.user = User.objects.create(username='user', password='test')
        basic = Permission.objects.get(codename='basic_account')
        self.user.user_permissions.add(basic)
        self.user.set_password('test')
        self.user.save()

    def test_connect_success(self):
        response = self.client.post(
            '/',
            {'username': 'user', 'password': 'test'}
        )
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, '/purchase/')

    def test_connect_fail(self):
        response = self.client.post(
            '/',
            {'username': 'user', 'password': 'false'}
        )
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, '/')

    def test_wrong_information(self):
        response = self.client.post(
            '/',
            {'username': '', 'password': 'aaa'}
        )
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, '/')

    def test_user_already_connect(self):
        self.client.force_login(self.user)
        response = self.client.get('/')
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, '/purchase/')

    def test_logout_redirect(self):
        self.client.force_login(self.user)
        response = self.client.get('/logout/')
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, '/')


text:
package kodkod.ast;

import kodkod.ast.operator.Multiplicity;
import kodkod.ast.visitor.ReturnVisitor;
import kodkod.ast.visitor.VoidVisitor;

/**
 * Denotes the integer obtained by summing the values of an iteger expression ie
 * for all values of a scalar x drawn from a set e.
 * @specfield intExpr: IntExpression
 * @specfield decls: Decls
 * @specfield children = 0->decls + 1->intExpr
 * @invariant  all d: decls.children[int] | d.multiplicity = 1
 * @author Emina Torlak
 */
public final class SumExpression extends IntExpression {
	private final Decls decls;
	private final IntExpression intExpr;

	/**
	 * Constructs a sum expression
	 * @ensures this.decls' = decls && this.intExpr' = intExpr
	 * @throws IllegalArgumentException  some d: decls.children | d.multiplicty != ONE
	 */
	SumExpression(Decls decls, IntExpression intExpr) {
		for(Decl d : decls) {
			if (d.multiplicity()!=Multiplicity.ONE)
				throw new IllegalArgumentException(d + " is not a scalar declaration.");
		}
		this.decls = decls;
		this.intExpr = intExpr;
	}

	/**
	 * Returns this.decls.
	 * @return this.decls
	 */
	public final Decls decls() {
		return decls;
	}

	/**
	 * Returns this.intExpr.
	 * @return this.intExpr
	 */
	public final IntExpression intExpr() {
		return intExpr;
	}

	/**
	 * {@inheritDoc}
	 * @see kodkod.ast.IntExpression#accept(kodkod.ast.visitor.ReturnVisitor)
	 */
	@Override
	public <E, F, D, I> I accept(ReturnVisitor<E, F, D, I> visitor) {
		return visitor.visit(this);
	}

	/**
	 * {@inheritDoc}
	 * @see kodkod.ast.IntExpression#accept(kodkod.ast.visitor.VoidVisitor)
	 */
	@Override
	public void accept(VoidVisitor visitor) {
		visitor.visit(this);
	}

	/**
	 * {@inheritDoc}
	 * @see kodkod.ast.Node#toString()
	 */
	public String toString() {
		return "(sum " + decls + " | " + intExpr + ")";
	}

}


text:
export const jQuery = function(arg){
	this.arg = arg;
	this.form_submit =function(){
		console.log("form submitted");
	};

	this.order_submit = function(food){
		console.log("food submitted:" +food);
	}
	return this;

}


text:
module MobsHelper

  def render_mob_properties_by_type(mob_type)
    if mob_type == 1
      render :partial => 'mobs/form_mob'
    elsif mob_type == 2
      render :partial => 'mobs/form_npc'
    end
  end

  def mob_table_row(record, column, name = '', data_override = nil)
    unless record.send(column).blank?
      markaby do
        tr :class => cycle('odd', 'even') do
          td.item_header name.blank? ? column.humanize : name
          td.item_data   {data_override.nil? ? record.send(column) : data_override}
        end
      end
    end
  end

  def mobs_alphabetic_filter
    s_letters = 'A'..'Z'
    a_letters = Mob.mob_alphabet
    markaby do
      table :class => 'alphabet_filter', :cellpadding => 0, :cellspacing => 0  do
        tr do
          for letter in s_letters
            unless a_letters[letter].nil?
              td {link_to(letter, "/mobs/filter/#{letter}", :title => pluralize(a_letters[letter], 'Mob'))}
            else
              td {content_tag(:span, letter, :class => 'empty')}
            end
          end
        end
      end
    end
  end

  def render_mob_spell_weakness(weak_schools)
    weak_schools ||= []
    spell_ids = weak_schools.collect{|s| s.weakness_id}
    cbs = MobWeakness.spell_weaknesses.sort{|a,b|a.last<=>b.last}.inject([]) do |result, school|
      result << (check_box_tag("weak_spell[#{school.first}]", 0, spell_ids.include?(school.first), :id => "weak_spell_#{school.first}") + school.last)
    end
    cbs.insert(7, '<br/>')
    cbs.join(' ')
  end

  def render_mob_melee_weakness(weak_melles)
    cbs = []
    weak_melles ||= []
    melee_ids = weak_melles.collect{|s| s.weakness_id} || []
    MobWeakness.melee_types.sort{|a,b|a.last<=>b.last}.each do |melee|
      cbs << (check_box_tag("weak_melee[#{melee.first}]", 0, melee_ids.include?(melee.first), :id => "weak_melee_#{melee.first}") + melee.last.humanize)
    end
    cbs.join(' ')
  end

  def mob_action_links
    links = [link_to('Add mob', new_mob_path) + ' to database']
    links << (link_to('View un-approved', unapproved_mob_path) + ' mobs') if Moderator.db_moderator?(current_user)
    links.join('  |  ')
  end

end


text:
package org.apereo.portal.spring.web.servlet;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * {@link DispatcherServlet} that will NEVER touch multipart request data. Needed in uPortal so that
 * the multipart request is passed on to the portlet correctly
 */
public class NoMultipartDispatcherServlet extends DispatcherServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected HttpServletRequest checkMultipart(HttpServletRequest request)
            throws MultipartException {
        return request;
    }
}


text:
class AddDefaultValueForExternalDiffStoreToMergeRequestDiffs < ActiveRecord::Migration[6.0]
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false

  def up
    with_lock_retries do
      change_column_default :merge_request_diffs, :external_diff_store, 1
    end
  end

  def down
    with_lock_retries do
      change_column_default :merge_request_diffs, :external_diff_store, nil
    end
  end
end


text:
<form (submit)="saveParty(party)" *ngIf="party">
  Name
  <input [disabled]="!isOwner" type="text" [(ngModel)]="party.name"/>

  Description
  <input [disabled]="!isOwner" type="text" [(ngModel)]="party.description"/>

  Location
  <input [disabled]="!isOwner" type="text" [(ngModel)]="party.location"/>

  <button [disabled]="!isOwner" type="submit">Save</button>
  <button [routerLink]="['/PartiesList']">Back</button>
</form>

Your status for this party: {{party | userPartyStatus}}

    Users to invite:

{{user | displayName}}

      <button (click)="invite(user)">Invite</button>

Reply to the invitation

  <input type="button" value="I'm going!" (click)="reply('yes')"/>
  <input type="button" value="Maybe" (click)="reply('maybe')"/>
  <input type="button" value="Nah.." (click)="reply('no')"/>


text:
using namespace std;
using namespace boost;

namespace impala {

// BufferedBlockMgr::Block methods.
BufferedBlockMgr::Block::Block(BufferedBlockMgr* block_mgr)
  : buffer_desc_(NULL),
    block_mgr_(block_mgr),
    write_range_(NULL),
    valid_data_len_(0),
    unpinned_blocks_it_(block_mgr->unpinned_blocks_.end()) {
}

Status BufferedBlockMgr::Block::Pin() {
  RETURN_IF_ERROR(block_mgr_->PinBlock(this));
  DCHECK(Validate()) << endl << DebugString();
  return Status::OK;
}

Status BufferedBlockMgr::Block::Unpin() {
  RETURN_IF_ERROR(block_mgr_->UnpinBlock(this));
  DCHECK(Validate()) << endl << DebugString();
  return Status::OK;
}

Status BufferedBlockMgr::Block::Delete() {
  RETURN_IF_ERROR(block_mgr_->DeleteBlock(this));
  DCHECK(Validate()) << endl << DebugString();
  return Status::OK;
}

void BufferedBlockMgr::Block::Init() {
  // No locks are taken because the block is new or has previously been deleted.
  is_pinned_ = false;
  in_write_ = false;
  is_deleted_ = false;
  valid_data_len_ = 0;
}

bool BufferedBlockMgr::Block::Validate() const {
  if (is_deleted_ && (is_pinned_ || (!in_write_ && buffer_desc_ != NULL))) {
    LOG (WARNING) << "Deleted block in use - " << DebugString();
    return false;
  }

  if (buffer_desc_ == NULL && (is_pinned_ || in_write_)) {
    LOG (WARNING) << "Block without buffer in use - " << DebugString();
    return false;
  }

  if (buffer_desc_ == NULL &&
      (unpinned_blocks_it_ != block_mgr_->unpinned_blocks_.end())) {
    LOG (WARNING) << "Unpersisted block without buffer - " << DebugString();
    return false;
  }

  if (buffer_desc_ != NULL && (buffer_desc_->block != this)) {
    LOG (WARNING) << "Block buffer inconsistency - " << DebugString();
    return false;
  }

  return true;
}

string BufferedBlockMgr::Block::DebugString() const {
  stringstream ss;
  ss << "Block: " << this
     << " Buffer Desc: " << buffer_desc_
     << " Deleted: " << is_deleted_
     << " Pinned: " << is_pinned_
     << " Write Issued: " << in_write_;

  return ss.str();
}

// BufferedBlockMgr methods.
BufferedBlockMgr* BufferedBlockMgr::Create(RuntimeState* state, MemTracker* parent,
      RuntimeProfile* profile, int64_t mem_limit, int64_t block_size,
      int initial_num_buffers) {
  BufferedBlockMgr* block_mgr = new BufferedBlockMgr(state, parent, mem_limit,
      block_size, initial_num_buffers);

  // Initialize the tmp files and the initial file to use.
  int num_tmp_devices = TmpFileMgr::num_tmp_devices();
  block_mgr->tmp_files_.reserve(num_tmp_devices);
  for (int i = 0; i < num_tmp_devices; ++i) {
    TmpFileMgr::File* tmp_file;
    TmpFileMgr::GetFile(i, state->query_id(), state->fragment_instance_id(), &tmp_file);
    block_mgr->tmp_files_.push_back(tmp_file);
  }
  block_mgr->next_block_index_ = rand() % num_tmp_devices;
  block_mgr->InitCounters(profile);
  return block_mgr;
}

Status BufferedBlockMgr::GetFreeBlock(Block** block) {
  {
    lock_guard<mutex> lock(lock_);
    if (is_cancelled_) return Status::CANCELLED;
  }

  Block* new_block = GetUnusedBlock();
  bool in_mem;
  RETURN_IF_ERROR(FindBufferForBlock(new_block, &in_mem));
  DCHECK(!in_mem);

  *block = new_block;
  return Status::OK;
}

Status BufferedBlockMgr::TryExpand(Block** block, bool* expanded) {
  lock_guard<mutex> lock(lock_);
  if (is_cancelled_) return Status::CANCELLED;

  *expanded = false;
  uint8_t* buffer = buffer_pool_->TryAllocate(block_size_);
  if (buffer == NULL) return Status::OK;
  // The number of unallocated buffers has decreased. Call WriteUnpinnedBlocks()
  // to check if the number of free buffers is below the threshold and write any
  // unpinned blocks if necessary.
  RETURN_IF_ERROR(WriteUnpinnedBlocks());

  BufferDescriptor* buffer_desc = obj_pool_.Add(new BufferDescriptor(buffer));
  all_buffers_.push_back(buffer_desc);
  Block* new_block = GetUnusedBlock();
  buffer_desc->block = new_block;
  new_block->buffer_desc_ = buffer_desc;
  new_block->is_pinned_ = true;
  *block = new_block;
  *expanded = true;
  mem_used_counter_->Update(block_size_);
  return Status::OK;
}

void BufferedBlockMgr::Close() {
  DiskIoMgr::RequestContext* unregister_context = NULL;
  {
    lock_guard<mutex> lock(lock_);
    is_cancelled_ = true;
    unregister_context = io_request_context_;
    io_request_context_ = NULL;
  }

  // Relinquish the lock before unregistering since WriteComplete() may be called
  // on UnregisterContext() for outstanding writes. UnregisterContext() is called
  // before any resources are cleaned up to ensure that memory buffers remain valid
  // for any in-progress writes.
  if (unregister_context != NULL) {
    io_mgr_->UnregisterContext(unregister_context);
  }

  {
    lock_guard<mutex> lock(lock_);
    DCHECK(io_request_context_ == NULL);
    // Delete tmp files.
    BOOST_FOREACH(TmpFileMgr::File& file, tmp_files_) {
      file.Remove();
    }
    tmp_files_.clear();

    // Free memory resources.
    if (buffer_pool_ != NULL) {
      buffer_pool_->FreeAll();
      buffer_pool_.reset();
      DCHECK_EQ(mem_tracker_->consumption(), 0);
      mem_tracker_->UnregisterFromParent();
      mem_tracker_.reset();
    }
  }
}

BufferedBlockMgr::BufferedBlockMgr(RuntimeState* state, MemTracker* parent,
    int64_t mem_limit, int64_t block_size, int initial_num_buffers)
  : block_size_(block_size),
    block_write_threshold_(TmpFileMgr::num_tmp_devices()),
    num_outstanding_writes_(0),
    io_mgr_(state->io_mgr()),
    is_cancelled_(false),
    state_(state) {
  // Create a new mem_tracker and allocate buffers.
  mem_tracker_.reset(new MemTracker(mem_limit, "Block Manager", parent));
  buffer_pool_.reset(new MemPool(mem_tracker_.get(), block_size));
  for (int i = 0; i < initial_num_buffers; ++i) {
    uint8_t* buffer = buffer_pool_->TryAllocate(block_size_);
    if (buffer == NULL) break;
    BufferDescriptor* buffer_desc = obj_pool_.Add(new BufferDescriptor(buffer));
    free_buffers_.Enqueue(buffer_desc);
    all_buffers_.push_back(buffer_desc);
  }

  state->io_mgr()->RegisterContext(NULL, &io_request_context_);
}

Status BufferedBlockMgr::PinBlock(Block* block) {
  bool in_mem;
  RETURN_IF_ERROR(FindBufferForBlock(block, &in_mem));

  if (!in_mem) {
    // Read the block from disk if it was not in memory.
    DCHECK_NOTNULL(block->write_range_);
    SCOPED_TIMER(disk_read_timer_);
    // Create a ScanRange to perform the read.
    DiskIoMgr::ScanRange* scan_range = obj_pool_.Add(new DiskIoMgr::ScanRange());
    scan_range->Reset(block->write_range_->file(), block->write_range_->len(),
        block->write_range_->offset(), block->write_range_->disk_id(), false, block);
    vector<DiskIoMgr::ScanRange*> ranges(1, scan_range);
    RETURN_IF_ERROR(io_mgr_->AddScanRanges(io_request_context_, ranges, true));

    // Read from the io mgr buffer into the block's assigned buffer.
    int64_t offset = 0;
    DiskIoMgr::BufferDescriptor* io_mgr_buffer;
    do {
      RETURN_IF_ERROR(scan_range->GetNext(&io_mgr_buffer));
      memcpy(block->buffer() + offset, io_mgr_buffer->buffer(), io_mgr_buffer->len());
      offset += io_mgr_buffer->len();
      io_mgr_buffer->Return();
    } while (!io_mgr_buffer->eosr());
    DCHECK_EQ(offset, block->write_range_->len());
  }

  return Status::OK;
}

Status BufferedBlockMgr::UnpinBlock(Block* block) {
  lock_guard<mutex> unpinned_lock(lock_);
  if (is_cancelled_) return Status::CANCELLED;
  DCHECK(block->is_pinned_) << "Unpin for unpinned block.";
  DCHECK(!block->is_deleted_) << "Unpin for deleted block.";
  DCHECK(Validate()) << endl << DebugString();
  // Add 'block' to the list of unpinned blocks and set is_pinned_ to false.
  // Cache its position in the list for later removal.
  block->is_pinned_ = false;
  DCHECK(block->unpinned_blocks_it_ == unpinned_blocks_.end())
      << " Unpin for block in unpinned list";
  if (!block->in_write_) {
    block->unpinned_blocks_it_ = unpinned_blocks_.insert(unpinned_blocks_.end(), block);
  }
  RETURN_IF_ERROR(WriteUnpinnedBlocks());
  DCHECK(Validate()) << endl << DebugString();
  return Status::OK;
}

Status BufferedBlockMgr::WriteUnpinnedBlocks() {
  // Assumes block manager lock is already taken.
  while (!unpinned_blocks_.empty() &&
      (num_outstanding_writes_ + free_buffers_.size() +
          (mem_tracker_->SpareCapacity() / block_size_)) < block_write_threshold_) {
    // Pop a block from the back of the list (LIFO)
    Block* block_to_write = unpinned_blocks_.back();
    unpinned_blocks_.pop_back();
    block_to_write->unpinned_blocks_it_ = unpinned_blocks_.end();

    if (block_to_write->write_range_ == NULL) {
      // First time the block is being persisted. Find the next physical file in
      // round-robin order and create a write range for it.
      TmpFileMgr::File& tmp_file = tmp_files_[next_block_index_];
      next_block_index_ = (next_block_index_ + 1) % tmp_files_.size();
      int64_t file_offset;
      RETURN_IF_ERROR(tmp_file.AllocateSpace(block_size_, &file_offset));
      // Assign a valid disk id to the write range if the tmp file was not assigned one.
      int disk_id = tmp_file.disk_id();
      if (disk_id < 0) {
        static unsigned int next_disk_id = 0;
        disk_id = (++next_disk_id) % io_mgr_->num_disks();
      }
      disk_id %= io_mgr_->num_disks();
      DiskIoMgr::WriteRange::WriteDoneCallback callback =
          bind(mem_fn(&BufferedBlockMgr::WriteComplete), this, block_to_write, _1);
      block_to_write->write_range_ = obj_pool_.Add(new DiskIoMgr::WriteRange(
          tmp_file.path(), file_offset, disk_id, callback));
    }

    block_to_write->write_range_->SetData(block_to_write->buffer(),
        block_to_write->valid_data_len_);

    // Issue write through DiskIoMgr.
    RETURN_IF_ERROR(
        io_mgr_->AddWriteRange(io_request_context_, block_to_write->write_range_));
    block_to_write->in_write_ = true;
    DCHECK(block_to_write->Validate()) << endl << block_to_write->DebugString();
    ++num_outstanding_writes_;
    outstanding_writes_counter_->Update(1);
    writes_issued_counter_->Update(1);
  }
  DCHECK(Validate()) << endl << DebugString();
  return Status::OK;
}

void BufferedBlockMgr::WriteComplete(Block* block, const Status& write_status) {
  outstanding_writes_counter_->Update(-1);
  lock_guard<mutex> lock(lock_);
  DCHECK(Validate()) << endl << DebugString();
  --num_outstanding_writes_;
  DCHECK(block->in_write_) << "WriteComplete() for block not in write."
                           << endl << block->DebugString();
  block->in_write_ = false;
  if (is_cancelled_) return;
  // Check for an error. Set cancelled and wake up waiting threads if an error occurred.
  if (!write_status.ok()) {
    state_->LogError(write_status);
    is_cancelled_ = true;
    buffer_available_cv_.notify_all();
    return;
  }

  // If the block was re-pinned when it was in the IOMgr queue, don't free it.
  if (block->is_pinned_) {
    // The number of outstanding writes has decreased but the number of free buffers
    // hasn't.
    WriteUnpinnedBlocks();
    DCHECK(Validate()) << endl << DebugString();
    return;
  }
  free_buffers_.Enqueue(block->buffer_desc_);
  if (block->is_deleted_) ReturnUnusedBlock(block);
  DCHECK(Validate()) << endl << DebugString();
  buffer_available_cv_.notify_one();
}

Status BufferedBlockMgr::DeleteBlock(Block* block) {
  lock_guard<mutex> lock(lock_);
  if (is_cancelled_) return Status::CANCELLED;
  // For now, only pinned blocks can be deleted.
  DCHECK(block->is_pinned_);

  block->is_deleted_ = true;
  block->is_pinned_ = false;

  // If a write is still pending, return. Cleanup will be done in WriteComplete().
  if (block->in_write_) return Status::OK;

  free_buffers_.Enqueue(block->buffer_desc_);
  ReturnUnusedBlock(block);
  DCHECK(Validate()) << endl << DebugString();
  buffer_available_cv_.notify_one();
  return Status::OK;
}

void BufferedBlockMgr::ReturnUnusedBlock(Block* block) {
  // Assumes the lock is already taken.
  DCHECK(block->is_deleted_);
  block->buffer_desc_->block = NULL;
  block->buffer_desc_ = NULL;
  unused_blocks_.Enqueue(block);
  block->Init();
}

Status BufferedBlockMgr::FindBufferForBlock(Block* block, bool* in_mem) {
  unique_lock<mutex> l(lock_);
  if (is_cancelled_) return Status::CANCELLED;
  DCHECK(!block->is_pinned_ && !block->is_deleted_) << "GetBufferForBlock() "
                                                    << endl << block->DebugString();
  DCHECK(Validate()) << endl << DebugString();
  *in_mem = false;
  if (block->buffer_desc_ != NULL) {
    // The block is in memory. It may be in 3 states
    // 1) In the unpinned list. The buffer will not be in the free list.
    // 2) Or, in_write_ = true. The buffer will not be in the free list.
    // 3) Or, the buffer is free, but hasn't yet been reassigned to a different block.
    DCHECK((block->unpinned_blocks_it_ != unpinned_blocks_.end()) ||
        free_buffers_.Contains(block->buffer_desc_) || block->in_write_);
    if (block->unpinned_blocks_it_ != unpinned_blocks_.end()) {
      unpinned_blocks_.erase(block->unpinned_blocks_it_);
      block->unpinned_blocks_it_ = unpinned_blocks_.end();
      DCHECK(!free_buffers_.Contains(block->buffer_desc_));
    } else if (!block->in_write_) {
      free_buffers_.Remove(block->buffer_desc_);
    } else {
      DCHECK(block->in_write_ && !free_buffers_.Contains(block->buffer_desc_));
    }

    buffered_pin_counter_->Update(1);
    *in_mem = true;
  } else {
    // At this point, we know the block is not associated with any buffer.
    // Get a free buffer from the front of the queue and assign it to the block.
    // Wait if there are no free buffers available.
    while (free_buffers_.empty()) {
      SCOPED_TIMER(buffer_wait_timer_);
      // The mem tracker capacity may have reduced since the last time
      // WriteUnpinnedBlocks() was called. Call it again before waiting.
      RETURN_IF_ERROR(WriteUnpinnedBlocks());
      buffer_available_cv_.wait(l);
      if (is_cancelled_) return Status::CANCELLED;
    }
    BufferDescriptor* buffer = free_buffers_.Dequeue();
    // Check if the buffer was assigned to a different block
    if (buffer->block != NULL) {
      DCHECK(buffer->block->Validate()) << endl << buffer->block->DebugString();
      buffer->block->buffer_desc_ = NULL;
    }

    buffer->block = block;
    block->buffer_desc_ = buffer;
  }

  DCHECK_NOTNULL(block->buffer_desc_);
  block->is_pinned_ = true;
  DCHECK(block->Validate()) << endl << block->DebugString();
  // The number of free buffers has decreased. Write unpinned blocks if the number
  // of free buffers below the threshold is reached.
  RETURN_IF_ERROR(WriteUnpinnedBlocks());
  DCHECK(Validate()) << endl << DebugString();
  return Status::OK;
}

BufferedBlockMgr::Block* BufferedBlockMgr::GetUnusedBlock() {
  Block* new_block;
  if (unused_blocks_.empty()) {
    new_block = obj_pool_.Add(new Block(this));
    new_block->Init();
    created_block_counter_->Update(1);
  } else {
    new_block = unused_blocks_.Dequeue();
    recycled_blocks_counter_->Update(1);
  }

  DCHECK_NOTNULL(new_block);
  DCHECK(new_block->Validate()) << endl << new_block->DebugString();
  return new_block;
}

bool BufferedBlockMgr::Validate() const {
  int num_free_buffers = 0;
  BOOST_FOREACH(BufferDescriptor* buffer, all_buffers_) {
    bool is_free = free_buffers_.Contains(buffer);
    num_free_buffers += is_free;
    if (buffer->block == NULL && !is_free) {
      LOG(WARNING) << "Buffer with no block not in free list." << endl << DebugString();
      return false;
    }

    if (buffer->block != NULL) {
      if (!buffer->block->Validate()) {
        LOG (WARNING) << "buffer->block inconsistent."
                      << endl << buffer->block->DebugString();
        return false;
      }

      if (is_free && (buffer->block->is_pinned_ || buffer->block->in_write_ ||
          buffer->block->unpinned_blocks_it_ != unpinned_blocks_.end())) {
        LOG (WARNING) << "Block with buffer in free list and"
                      << " is_pinned_ = " << buffer->block->is_pinned_
                      << " in_write_ = " << buffer->block->in_write_
                      << " Unpinned_blocks_.Contains = "
                      << (buffer->block->unpinned_blocks_it_ != unpinned_blocks_.end())
                      << endl << buffer->block->DebugString();
        return false;
      }
    }
  }

  if (free_buffers_.size() != num_free_buffers) {
    LOG (WARNING) << "free_buffer_list_ inconsistency."
                  << " num_free_buffers = " << num_free_buffers
                  << " free_buffer_list_.size() = " << free_buffers_.size()
                  << endl << DebugString();
    return false;
  }

  BOOST_FOREACH(Block* block, unpinned_blocks_) {
    if (block->unpinned_blocks_it_ == unpinned_blocks_.end()) {
      LOG (WARNING) << "Block in unpinned list with no pointer to list "
                    << endl << block->DebugString();
    }
    if (!block->Validate()) {
      LOG (WARNING) << "Block inconsistent in unpinned list."
                    << endl << block->DebugString();
      return false;
    }

    if (block->in_write_ || free_buffers_.Contains(block->buffer_desc_)) {
      LOG (WARNING) << "Block in unpinned list with"
                    << " in_write_ = " << block->in_write_
                    << " free_buffers_.Contains = "
                    << free_buffers_.Contains(block->buffer_desc_)
                    << endl << block->DebugString();
      return false;
    }
  }

  // Check if we're writing blocks when the number of free buffers falls below
  // threshold. We don't write blocks after cancellation.
  if (!is_cancelled_ && !unpinned_blocks_.empty() &&
      (free_buffers_.size() + num_outstanding_writes_ < block_write_threshold_)) {
    LOG (WARNING) << "Missed writing unpinned blocks";
    return false;
  }
  return true;
}

string BufferedBlockMgr::DebugString() const {
  stringstream ss;
  ss << " Num writes outstanding " << outstanding_writes_counter_->value()
     << " Num free buffers " << free_buffers_.size()
     << " Block write threshold " << block_write_threshold_;

  return ss.str();
}

void BufferedBlockMgr::InitCounters(RuntimeProfile* profile) {
  mem_limit_counter_ = ADD_COUNTER(profile, "MemoryLimit", TCounterType::BYTES);
  mem_limit_counter_->Set(mem_tracker_->limit());
  mem_used_counter_ = ADD_COUNTER(profile, "MemoryUsed", TCounterType::BYTES);
  mem_used_counter_->Set(static_cast<int64_t>(all_buffers_.size()) * block_size_);
  block_size_counter_ = ADD_COUNTER(profile, "BlockSize", TCounterType::BYTES);
  block_size_counter_->Set(block_size_);
  created_block_counter_ = ADD_COUNTER(profile, "BlocksCreated", TCounterType::UNIT);
  recycled_blocks_counter_ = ADD_COUNTER(profile, "BlocksRecycled", TCounterType::UNIT);
  writes_issued_counter_ = ADD_COUNTER(profile, "BlockWritesIssued", TCounterType::UNIT);
  outstanding_writes_counter_ =
      ADD_COUNTER(profile, "BlockWritesOutstanding", TCounterType::UNIT);
  buffered_pin_counter_ = ADD_COUNTER(profile, "BufferedPins", TCounterType::UNIT);
  disk_read_timer_ = ADD_TIMER(profile, "TotalReadBlockTime");
  buffer_wait_timer_ = ADD_TIMER(profile, "TotalBufferWaitTime");
}

} // namespace impala


text:
package com.github.cxfplus.com.sun.xml.bind.v2.model.impl;

import java.util.Iterator;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.namespace.QName;

import com.github.cxfplus.com.sun.xml.bind.v2.model.annotation.Locatable;
import com.github.cxfplus.com.sun.xml.bind.v2.model.core.EnumConstant;
import com.github.cxfplus.com.sun.xml.bind.v2.model.core.EnumLeafInfo;
import com.github.cxfplus.com.sun.xml.bind.v2.model.core.NonElement;
import com.github.cxfplus.com.sun.xml.bind.v2.model.core.Element;
import com.github.cxfplus.com.sun.xml.bind.v2.model.core.ClassInfo;
import com.github.cxfplus.com.sun.xml.bind.v2.runtime.Location;

/**
 * {@link EnumLeafInfo} implementation.
 *
 * @author Kohsuke Kawaguchi
 */
class EnumLeafInfoImpl<T,C,F,M> extends TypeInfoImpl<T,C,F,M>
        implements EnumLeafInfo<T,C>, Element<T,C>, Iterable<EnumConstantImpl<T,C,F,M>> {

    /**
     * The enum class whose information this object represents.
     */
    /*package*/ final C clazz;

    NonElement<T,C> baseType;

    private final T type;

    /**
     * Can be null for anonymous types.
     */
    private final QName typeName;

    /**
     * All the {@link EnumConstantImpl}s are linked in this list.
     */
    private EnumConstantImpl<T,C,F,M> firstConstant;

    /**
     * If this enum is also bound to an element, that tag name.
     * Or else null.
     */
    private QName elementName;

    /**
     * @param clazz
     * @param type
     *      clazz and type should both point to the enum class
     *      that this {@link EnumLeafInfo} represents.
     *      Because of the type parameterization we have to take them separately.
     */
    public EnumLeafInfoImpl(ModelBuilder<T,C,F,M> builder,
                            Locatable upstream, C clazz, T type ) {
        super(builder,upstream);
        this.clazz = clazz;
        this.type = type;

        elementName = parseElementName(clazz);

        // compute the type name
        // TODO: I guess it must be allowed for enums to have @XmlElement
        typeName = parseTypeName(clazz);

        // locate the base type.
        // this can be done eagerly because there shouldn't be no cycle.
        XmlEnum xe = builder.reader.getClassAnnotation(XmlEnum.class, clazz, this);
        if(xe!=null) {
            T base = builder.reader.getClassValue(xe, "value");
            baseType = builder.getTypeInfo(base,this);
        } else {
            baseType = builder.getTypeInfo(builder.nav.ref(String.class),this);
        }
    }

    /**
     * Build {@link EnumConstant}s and discover/report any error in it.
     */
    protected void calcConstants() {
        EnumConstantImpl<T,C,F,M> last = null;
        F[] constants = nav().getEnumConstants(clazz);
        for( int i=constants.length-1; i>=0; i-- ) {
            F constant = constants[i];
            String name = nav().getFieldName(constant);
            XmlEnumValue xev = builder.reader.getFieldAnnotation(XmlEnumValue.class, constant, this);

            String literal;
            if(xev==null)   literal = name;
            else            literal = xev.value();

            last = createEnumConstant(name,literal,constant,last);
        }
        this.firstConstant = last;
    }

    protected EnumConstantImpl<T,C,F,M> createEnumConstant(String name, String literal, F constant, EnumConstantImpl<T,C,F,M> last) {
        return new EnumConstantImpl<T,C,F,M>(this, name, literal, last);
    }

    public T getType() {
        return type;
    }

    /**
     * Leaf-type cannot be referenced from IDREF.
     *
     * @deprecated
     *      why are you calling a method whose return value is always known?
     */
    public final boolean canBeReferencedByIDREF() {
        return false;
    }

    public QName getTypeName() {
        return typeName;
    }

    public C getClazz() {
        return clazz;
    }

    public NonElement<T,C> getBaseType() {
        return baseType;
    }

    public boolean isSimpleType() {
        return true;
    }

    public Location getLocation() {
        return nav().getClassLocation(clazz);
    }

    public Iterable<? extends EnumConstantImpl<T,C,F,M>> getConstants() {
        if(firstConstant==null)
            calcConstants();
        return this;
    }

    public void link() {
        // make sure we've computed constants
        getConstants();
        super.link();
    }

    /**
     * No substitution.
     *
     * @deprecated if you are invoking this method directly, there's something wrong.
     */
    public Element<T, C> getSubstitutionHead() {
        return null;
    }

    public QName getElementName() {
        return elementName;
    }

    public boolean isElement() {
        return elementName!=null;
    }

    public Element<T,C> asElement() {
        if(isElement())
            return this;
        else
            return null;
    }

    /**
     * When a bean binds to an element, it's always through {@link XmlRootElement},
     * so this method always return null.
     *
     * @deprecated
     *      you shouldn't be invoking this method on {@link ClassInfoImpl}.
     */
    public ClassInfo<T,C> getScope() {
        return null;
    }

    public Iterator<EnumConstantImpl<T,C,F,M>> iterator() {
        return new Iterator<EnumConstantImpl<T,C,F,M>>() {
            private EnumConstantImpl<T,C,F,M> next = firstConstant;
            public boolean hasNext() {
                return next!=null;
            }

            public EnumConstantImpl<T,C,F,M> next() {
                EnumConstantImpl<T,C,F,M> r = next;
                next = next.next;
                return r;
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }
}


text:
td,a,a:link,a:visited {
	color:#000000;text-decoration:none;font-size:9pt
}

a:hover{
	color:#000000;
	font-size:9pt;
	text-decoration:underline;
}

input,select {
	font-size:9pt;
	color:#000000;
}

body {
	color:#000000;
	font-size:9pt;
	scrollbar-track-color:#eeeeee;
	scrollbar-shadow-color:buttonface;
	scrollbar-highlight-color:buttonface;
	scrollbar-3dlight-color:buttonhighlight;
	scrollbar-darkshadow-color:buttonshadow
}

.input {
	font-size:9pt;
	border-top:#cdcdcd 1px solid;
	border-left:#cdcdcd 1px solid;
	border-right:#eeeeee 1px solid;
	border-bottom:#eeeeee 1px solid;
	height:18px;color:#000000;
	padding-top:1px;
	letter-spacing:0px;
	padding-right:0px;
	padding-left:0px;
	width:90%;
}

.admintb td{ padding-right:6px; }

.btn {
	font-size:9pt;
	border-top:#cdcdcd 1px solid;
	border-left:#cdcdcd 1px solid;
	border-right:#737373 1px solid;
	border-bottom:#737373 1px solid;
	height:18px;
	color:#000000;
	padding-top:1px;
	letter-spacing:0px;
	padding-right:0px;
	padding-left:0px;
}

.textarea {
	font-size:9pt;
	border-top:#cdcdcd 1px solid;
	border-left:#cdcdcd 1px solid;
	border-right:#eeeeee 1px solid;
	border-bottom:#eeeeee 1px solid;
	color:#000000;
	padding-top:1px;
	letter-spacing:0px;
	padding-right:0px;
	padding-left:0px;
	width:90%;
}


text:
{-# LANGUAGE TypeOperators     #-}
{-# LANGUAGE DataKinds         #-}
{-# LANGUAGE NoImplicitPrelude #-}
module WishlistSimple where

import Prelude hiding (log)

import Control.Monad.Reader
import Data.IORef
import Data.Proxy
import Servant.API
import Servant.Server
import Network.Wai.Handler.Warp

import Wishlist.Types.Simple
import Wishlist.Utils

-- part #1: the service API
type API =
       "wishes" :> Get '[JSON] Wishlist
  :<|> "wishes" :> Capture "shop" Shop :> Get '[JSON] Wishlist
  :<|> "wishes" :> ReqBody '[JSON] Wish :> Post '[JSON] ()

-- part #2: a service for the above API
service :: Service API
service = getAllWishes :<|> getShopWishes :<|> postNewWish

getAllWishes :: Controller Wishlist
getAllWishes = log "getAllWishes" $ do
  store <- ask
  liftIO (readIORef store)

getShopWishes :: Shop -> Controller Wishlist
getShopWishes shop = log "getShopWishes" $ do
  wishlist <- getAllWishes
  return $ filter (\wish -> getShop wish == shop) wishlist

postNewWish :: Wish -> Controller ()
postNewWish wish = logWith "postNewWish " wish $ do
  store <- ask
  liftIO $ do
    wishlist <- readIORef store
    writeIORef store (wish:wishlist)

-- part #3: run the server
main :: IO ()
main = do
  putStrLn "Starting wishlist service on port 8080..."
  store <- newIORef []
  run 8080 $ serve (Proxy :: Proxy API) (enter (toHandler store) service)


text:
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.vr180.common.crypto;

import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPairGenerator;
import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.Mac;

/**
 * The default implementation of CryptoProvider using Android default provider
 */
public class DefaultCipherProvider implements CryptoProvider {

  @Override
  public KeyPairGenerator getKeyPairGenerator() throws GeneralSecurityException {
    return KeyPairGenerator.getInstance(CryptoUtilities.ASYMMETRIC_KEY_TYPE);
  }

  @Override
  public KeyAgreement getKeyAgreement() throws GeneralSecurityException {
    return KeyAgreement.getInstance(CryptoUtilities.KEY_AGREEMENT_ALGORITHM);
  }

  @Override
  public KeyFactory getKeyFactory() throws GeneralSecurityException {
    return KeyFactory.getInstance(CryptoUtilities.ASYMMETRIC_KEY_TYPE);
  }

  @Override
  public Mac getMac() throws GeneralSecurityException {
    return Mac.getInstance(CryptoUtilities.HMAC_ALGORITHM);
  }

  @Override
  public Cipher getCipher() throws GeneralSecurityException {
    return Cipher.getInstance(CryptoUtilities.ENCRYPTION_TRANSFORMATION);
  }
}


text:
"""Checks names of global exports from a library."""

from __future__ import print_function

import os.path
import re
import subprocess
import sys

PROG = 'check_symbol_exports'

def command_output(cmd, directory):
    """Runs a command in a directory and returns its standard output stream.

    Captures the standard error stream.

    Raises a RuntimeError if the command fails to launch or otherwise fails.
    """
    p = subprocess.Popen(cmd,
                         cwd=directory,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         universal_newlines=True)
    (stdout, _) = p.communicate()
    if p.returncode != 0:
        raise RuntimeError('Failed to run %s in %s' % (cmd, directory))
    return stdout

def check_library(library):
    """Scans the given library file for global exports.  If all such
    exports are namespaced or begin with spv (in either C or C++ styles)
    then return 0.  Otherwise emit a message and return 1."""

    # The pattern for a global symbol record
    symbol_pattern = re.compile(r'^[0-aA-Fa-f]+ g *F \.text.*[0-9A-Fa-f]+ +(.*)')

    # Ok patterns are as follows, assuming Itanium name mangling:
    #   spv[A-Z]          :  extern "C" symbol starting with spv
    #   _ZN               :  something in a namespace
    #   _Z[0-9]+spv[A-Z_] :  C++ symbol starting with spv[A-Z_]
    symbol_ok_pattern = re.compile(r'^(spv[A-Z]|_ZN|_Z[0-9]+spv[A-Z_])')

    # In addition, the following pattern whitelists global functions that are added
    # by the protobuf compiler:
    #   - AddDescriptors_spvtoolsfuzz_2eproto()
    #   - InitDefaults_spvtoolsfuzz_2eproto()
    symbol_whitelist_pattern = re.compile(r'_Z[0-9]+(InitDefaults|AddDescriptors)_spvtoolsfuzz_2eprotov')

    seen = set()
    result = 0
    for line in command_output(['objdump', '-t', library], '.').split('\n'):
        match = symbol_pattern.search(line)
        if match:
            symbol = match.group(1)
            if symbol not in seen:
                seen.add(symbol)
                #print("look at '{}'".format(symbol))
                if not (symbol_whitelist_pattern.match(symbol) or symbol_ok_pattern.match(symbol)):
                    print('{}: error: Unescaped exported symbol: {}'.format(PROG, symbol))
                    result = 1
    return result

def main():
    import argparse
    parser = argparse.ArgumentParser(description='Check global names exported from a library')
    parser.add_argument('library', help='The static library to examine')
    args = parser.parse_args()

    if not os.path.isfile(args.library):
        print('{}: error: {} does not exist'.format(PROG, args.library))
        sys.exit(1)

    if os.name == 'posix':
        status = check_library(args.library)
        sys.exit(status)
    else:
        print('Passing test since not on Posix')
        sys.exit(0)

if __name__ == '__main__':
    main()


text:
<!DOCTYPE html>

		<meta charset="utf-8" />

		<link href="asset/css/bootstrap.css" rel="stylesheet" />
		<link rel="stylesheet" href="asset/css/dexter.min.css" />
		<link rel="stylesheet" href="asset/css/font-awesome.min.css" />

		<link rel="stylesheet" href="asset/css/prettify.css" />

 Checker Code

					incompleteArrayFill

 Description

Array 'buffer' is filled incompletely.

 Severity

					Minor

 Detector / Bug Pattern

Array 'buffer' is filled incompletely.

 More Information

Array 'buffer' is filled incompletely.

 Bad Code

struct Foo
{
	int fooId;
	char arr[ ];
}
fooList[] =
{ {1, {'a', 'b'}},
  {2, {'c', 'd'}}
};

int main()
{
  for (int i = 0; i < 2; i++)
    printf("%d %c\n", fooList[i].fooId, fooList[i].arr[0]);
}

 Good Code

struct Foo
{
	int fooId;
	char arr[2]; // this line modified
}
fooList[] =
{ {1, {'a', 'b'}},
  {2, {'c', 'd'}}
};
//Only the last member of a C struct can be flexible as in arr[].

 CWE ID

				0

 Code Review Asset

					N/A

 URLs

					http://stackoverflow.com/questions/4862914/array-initialization-c-c


text:
.post { /* stylelint-disable */

}


text:
typedef NS_ENUM(NSInteger, ARDirection) {
    ARUp = 1,
    ARDown = -1
};

@interface ARCrossfadingImageView ()
@property (nonatomic) UIImageView *topView;
@property (nonatomic) ARDirection dir;
@end

@implementation ARCrossfadingImageView

- (instancetype)init
{
    self = [super init];
    if (self) {
        _topView = [[UIImageView alloc] initWithFrame:self.bounds];
        _currentIndex = NSNotFound;
        self.contentMode = UIViewContentModeScaleAspectFill;
        [self insertSubview:_topView atIndex:0];
    }
    return self;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    _topView.frame = self.bounds;
}

- (void)setBounds:(CGRect)bounds
{
    [super setBounds:bounds];
    _topView.frame = bounds;
}

- (void)setImages:(NSArray *)images
{
    _images = images;
    self.currentIndex = 0;
    self.dir = ARUp;
}

- (void)setDir:(ARDirection)dir
{
    if (_dir == dir) {
        return;
    }
    _dir = dir;
    [self setTop];
}

- (void)setTop
{
    switch (self.dir) {
        case ARUp:
            if (self.currentIndex == self.images.count - 1) {
                if (self.shouldLoopImages) {
                    self.topView.image = [self.images firstObject];
                } else {
                    self.topView.image = nil;
                }
            } else {
                self.topView.image = self.images[self.currentIndex + 1];
            }
            break;
        case ARDown:
            if (self.currentIndex == 0) {
                if (self.shouldLoopImages) {
                    self.topView.image = [self.images lastObject];
                } else {
                    self.topView.image = nil;
                }
            } else {
                self.topView.image = self.images[self.currentIndex - 1];
            }
    }
}

- (void)setCurrentIndex:(NSInteger)currentIndex
{
    NSInteger imageCount = self.images.count;
    if (currentIndex == self.currentIndex || imageCount == 0) {
        return;
    }
    if (currentIndex < 0 || currentIndex >= imageCount) {
        ARErrorLog(@"Index %@ out of bounds in crossfading image view %@ with %@ images",
                   @(currentIndex), self, @(imageCount));
        return;
    }
    _currentIndex = currentIndex;

    self.image = self.images[_currentIndex];
    self.topView.alpha = 0;
    [self setTop];
}

- (void)setContentMode:(UIViewContentMode)contentMode
{
    [super setContentMode:contentMode];
    [_topView setContentMode:contentMode];
}

- (void)up:(CGFloat)t
{
    if (!self.shouldLoopImages && self.currentIndex == self.images.count - 1) {
        return;
    }
    self.dir = ARUp;
    t = fmaxf(fminf(1.f, t), 0.f);
    self.topView.alpha = t;
}

- (void)down:(CGFloat)t
{
    if (!self.shouldLoopImages && self.currentIndex == 0) {
        return;
    }
    self.dir = ARDown;
    t = fmaxf(fminf(1.f, t), 0.f);
    self.topView.alpha = t;
}

@end


text:
import * as React from 'react';
import {
  Grid,
  Row,
  Col,
  Label,
  Button,
  FormControl,
  Form,
  FormGroup,
} from 'react-bootstrap';
import * as FontAwesome from 'react-fontawesome';
import styled from 'styled-components';
import aggToField from 'utils/aggs/aggToField';
import MultiCrumb from 'components/MultiCrumb';
import AutoSuggester from './AutoSuggester';

const CrumbsBarStyleWrappper = styled.div`
  .crumbs-bar {
    padding: 10px 30px;
    border: solid white 1px;
    background-color: #f2f2f2;
    color: black;
    margin-bottom: 1em;

    .container {
      background: #d9deea;
      border: 0px;
      margin-top: 5px;
      color: #394149;
    }

    i {
      font-style: normal;
      margin-right: 3px;
      text-transform: capitalize;
    }

    span.label.label-default {
      padding: 7px !important;
      border-radius: 2px !important;
    }

    input.form-control {
      border: 0px;
      box-shadow:none;
      margin-right: 10px;
      height:100%;
      width:100%;
      clear: both;
    }
    input.rbt-input-hint {
      opacity: 0;
    }

    span.label {
      background: none;
      padding: 5px;
      font-size: 12px;
      border-radius: 4px;
      margin-right: 5px;
      text-transform: capitalize;

      span.fa-remove {
        color: #fff !important;
        opacity: 0.5;
        margin-left: 5px !important;
      }

      span.fa-remove:hover {
        opacity: 1;
      }

      b {
        padding-right: 5px;
      }

      b:last-of-type {
        padding-right: 0px;
      }
    }
  }
  .right-align {
    text-align: right;
  }

  div.row > div {
    padding-left: 0px;
  }

  .searchInput {
    padding-bottom: 10px;
  }
`;

import { AggCallback, SearchParams } from '../Types';
import { isEmpty } from 'ramda';
import { MAX_WINDOW_SIZE } from '../../../utils/constants';
import { PulseLoader } from 'react-spinners';

//
interface CrumbsBarProps {
  searchParams: SearchParams;
  removeFilter: AggCallback;
  addSearchTerm: (term: string) => void;
  removeSearchTerm: (term: string, bool?) => void;
  page: number;
  recordsTotal: number;
  pagesTotal: number;
  pageSize: number;
  update: { page: (n: number) => void };
  onReset: () => void;
  loading: boolean;
}
interface CrumbsBarState {
  searchTerm: string;
}

const Crumb = ({ category, value, onClick }) => {
  return (

      {category}: {value}
      <FontAwesome
        className="remove"
        name="remove"
        style={{ cursor: 'pointer', color: '#cc1111', margin: '0 0 0 3px' }}
        onClick={onClick}
      />

  );
};

export default class CrumbsBar extends React.Component<
  CrumbsBarProps,
  CrumbsBarState
> {
  *mkCrumbs(searchParams: SearchParams, removeFilter) {
    if (!isEmpty(searchParams.q)) {
      yield (
        <MultiCrumb
          key="Search"
          category="search"
          values={searchParams.q}
          onClick={term => this.props.removeSearchTerm(term)}
        />
      );
    }
    for (const key in searchParams.aggFilters) {
      const agg = searchParams.aggFilters[key];
      const cat = aggToField(agg.field);
      yield (
        <MultiCrumb
          category={cat}
          values={agg.values}
          onClick={val => removeFilter(agg.field, val)}
          key={cat + agg.values.join()}
        />
      );
    }
    for (const key in searchParams.crowdAggFilters) {
      const agg = searchParams.crowdAggFilters[key];
      const cat = aggToField(agg.field);
      yield (
        <MultiCrumb
          category={cat}
          values={agg.values}
          onClick={val => removeFilter(agg.field, val, true)}
          key={cat + agg.values.join('')}
        />
      );
    }
    const totalLength =
      searchParams.q.length +
      searchParams.crowdAggFilters.length +
      searchParams.aggFilters.length;
    if (totalLength > 0) {
      yield (
        <Button
          bsSize="small"
          key="reset"
          onClick={this.props.onReset}
          style={{ marginLeft: '10px' }}
        >
          Reset
        </Button>
      );
    }
  }

  localSearchChange = e => {
    this.setState({ searchTerm: e.target.value });
  };
  clearPrimarySearch = () => {
    this.props.removeSearchTerm('', true);
  };
  onSubmit = e => {
    //console.log('hi');
    e.preventDefault();
    this.props.addSearchTerm(this.state.searchTerm);
    this.setState({ searchTerm: '' });
  };

  inputSearchChange = val => {
    this.setState({searchTerm:val})
  }

  clickSearchChange = val => {
    this.setState({searchTerm:val[0]})
  }
  render() {
    return (
      <CrumbsBarStyleWrappper>
        <Grid className="crumbs-bar">
          <Row>
            <Col xs={12} md={9}>
              <Form inline className="searchInput" onSubmit={this.onSubmit}>
                <FormGroup>
                  Search Within:

                  <FormControl

                    componentClass={AutoSuggester}
                    onInputChange={this.inputSearchChange}
                    onChange={this.clickSearchChange}
                    id='searcher'
                    placeholder='search...'
                    params = {val=>{return val}}
                    autocomplete='off'/>

                </FormGroup>

                <Button type="submit">
                  <FontAwesome name="search" />
                </Button>
              </Form>

            </Col>
            <Col xsHidden md={3}>

                {this.props.page > 0 && !this.props.loading ? (
                  <FontAwesome
                    className="arrow-left"
                    name="arrow-left"
                    style={{ cursor: 'pointer', margin: '5px' }}
                    onClick={() => this.props.update.page(this.props.page - 1)}
                  />
                ) : <FontAwesome
                  className="arrow-left"
                  name="arrow-left"
                  style={{ margin: '5px', color: 'gray' }}
                /> }
                page{' '}

                  {this.props.loading ?
<PulseLoader color="#cccccc" size={8} />

                    : `${Math.min(this.props.page + 1, this.props.pagesTotal)}/${this.props.pagesTotal}`}{' '}

                {this.props.page + 1 < this.props.pagesTotal && !this.props.loading ? (
                  <FontAwesome
                    className="arrow-right"
                    name="arrow-right"
                    style={{ cursor: 'pointer', margin: '5px' }}
                    onClick={() => this.props.update.page(this.props.page + 1)}
                  />
                ) : <FontAwesome
                  className="arrow-right"
                  name="arrow-right"
                  style={{ margin: '5px', color: 'gray' }}
                />}

                  {this.props.recordsTotal} results

                  {this.props.recordsTotal > MAX_WINDOW_SIZE ? `(showing first ${MAX_WINDOW_SIZE})` : null}

            </Col>
          </Row>
          {/* <Row>
          <Col md={10}>
          </Col>
          <Col md={2}>

              <DropdownButton title={this.props.pageSize+" Rows"} >
                <MenuItem eventKey="1">5 Rows</MenuItem>
                <MenuItem eventKey="2">10 Rows</MenuItem>
                <MenuItem eventKey="3">20 Rows</MenuItem>
                <MenuItem eventKey="4">25 Rows</MenuItem>
                <MenuItem eventKey="5">50 Rows</MenuItem>
                <MenuItem eventKey="5">100 Rows</MenuItem>
              </DropdownButton>

          </Col>
        </Row> */}
          <Row>
            <Col md={12} style={{ padding: '10px 0px' }}>
              Filters:
              {Array.from(
                this.mkCrumbs(this.props.searchParams, this.props.removeFilter),
              )}
            </Col>
          </Row>
        </Grid>
      </CrumbsBarStyleWrappper>
    );
  }
}


text:
#pragma once
#include <aws/waf-regional/WAFRegional_EXPORTS.h>
#include <aws/waf-regional/WAFRegionalRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace WAFRegional
{
namespace Model
{

  /**
   */
  class AWS_WAFREGIONAL_API DeleteRegexPatternSetRequest : public WAFRegionalRequest
  {
  public:
    DeleteRegexPatternSetRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DeleteRegexPatternSet"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The RegexPatternSetId of the RegexPatternSet that you
     * want to delete. RegexPatternSetId is returned by
     * CreateRegexPatternSet and by ListRegexPatternSets.

     */
    inline const Aws::String& GetRegexPatternSetId() const{ return m_regexPatternSetId; }

    /**
     *
The RegexPatternSetId of the RegexPatternSet that you
     * want to delete. RegexPatternSetId is returned by
     * CreateRegexPatternSet and by ListRegexPatternSets.

     */
    inline bool RegexPatternSetIdHasBeenSet() const { return m_regexPatternSetIdHasBeenSet; }

    /**
     *
The RegexPatternSetId of the RegexPatternSet that you
     * want to delete. RegexPatternSetId is returned by
     * CreateRegexPatternSet and by ListRegexPatternSets.

     */
    inline void SetRegexPatternSetId(const Aws::String& value) { m_regexPatternSetIdHasBeenSet = true; m_regexPatternSetId = value; }

    /**
     *
The RegexPatternSetId of the RegexPatternSet that you
     * want to delete. RegexPatternSetId is returned by
     * CreateRegexPatternSet and by ListRegexPatternSets.

     */
    inline void SetRegexPatternSetId(Aws::String&& value) { m_regexPatternSetIdHasBeenSet = true; m_regexPatternSetId = std::move(value); }

    /**
     *
The RegexPatternSetId of the RegexPatternSet that you
     * want to delete. RegexPatternSetId is returned by
     * CreateRegexPatternSet and by ListRegexPatternSets.

     */
    inline void SetRegexPatternSetId(const char* value) { m_regexPatternSetIdHasBeenSet = true; m_regexPatternSetId.assign(value); }

    /**
     *
The RegexPatternSetId of the RegexPatternSet that you
     * want to delete. RegexPatternSetId is returned by
     * CreateRegexPatternSet and by ListRegexPatternSets.

     */
    inline DeleteRegexPatternSetRequest& WithRegexPatternSetId(const Aws::String& value) { SetRegexPatternSetId(value); return *this;}

    /**
     *
The RegexPatternSetId of the RegexPatternSet that you
     * want to delete. RegexPatternSetId is returned by
     * CreateRegexPatternSet and by ListRegexPatternSets.

     */
    inline DeleteRegexPatternSetRequest& WithRegexPatternSetId(Aws::String&& value) { SetRegexPatternSetId(std::move(value)); return *this;}

    /**
     *
The RegexPatternSetId of the RegexPatternSet that you
     * want to delete. RegexPatternSetId is returned by
     * CreateRegexPatternSet and by ListRegexPatternSets.

     */
    inline DeleteRegexPatternSetRequest& WithRegexPatternSetId(const char* value) { SetRegexPatternSetId(value); return *this;}

    /**
     *
The value returned by the most recent call to GetChangeToken.

     */
    inline const Aws::String& GetChangeToken() const{ return m_changeToken; }

    /**
     *
The value returned by the most recent call to GetChangeToken.

     */
    inline bool ChangeTokenHasBeenSet() const { return m_changeTokenHasBeenSet; }

    /**
     *
The value returned by the most recent call to GetChangeToken.

     */
    inline void SetChangeToken(const Aws::String& value) { m_changeTokenHasBeenSet = true; m_changeToken = value; }

    /**
     *
The value returned by the most recent call to GetChangeToken.

     */
    inline void SetChangeToken(Aws::String&& value) { m_changeTokenHasBeenSet = true; m_changeToken = std::move(value); }

    /**
     *
The value returned by the most recent call to GetChangeToken.

     */
    inline void SetChangeToken(const char* value) { m_changeTokenHasBeenSet = true; m_changeToken.assign(value); }

    /**
     *
The value returned by the most recent call to GetChangeToken.

     */
    inline DeleteRegexPatternSetRequest& WithChangeToken(const Aws::String& value) { SetChangeToken(value); return *this;}

    /**
     *
The value returned by the most recent call to GetChangeToken.

     */
    inline DeleteRegexPatternSetRequest& WithChangeToken(Aws::String&& value) { SetChangeToken(std::move(value)); return *this;}

    /**
     *
The value returned by the most recent call to GetChangeToken.

     */
    inline DeleteRegexPatternSetRequest& WithChangeToken(const char* value) { SetChangeToken(value); return *this;}

  private:

    Aws::String m_regexPatternSetId;
    bool m_regexPatternSetIdHasBeenSet;

    Aws::String m_changeToken;
    bool m_changeTokenHasBeenSet;
  };

} // namespace Model
} // namespace WAFRegional
} // namespace Aws


text:
"""Defines some "system features", especially the :class:`SiteConfig` model.
See :doc:`/specs/system`.

"""

from lino import ad, _
from django.utils.translation import gettext
from etgen.html import E, join_elems

class Plugin(ad.Plugin):
    "See :doc:`/dev/plugins`."

    verbose_name = _("System")

    needs_plugins = ['lino.modlib.printing']

    def setup_config_menu(self, site, user_type, m):
        system = m.add_menu(self.app_label, self.verbose_name)
        system.add_instance_action(site.site_config)

    def on_site_startup(self, site):
        super(Plugin, self).on_site_startup(site)

        from lino.modlib.system.mixins import Lockable

        if len(list(Lockable.get_lockables())):
            def welcome_messages(ar):
                locked_rows = list(Lockable.get_lockable_rows(ar.get_user()))
                if locked_rows:
                    chunks = [
                        gettext("You have a dangling edit lock on"), " "]
                    chunks += join_elems(
                        [ar.obj2html(obj) for obj in locked_rows], ", ")
                    chunks.append('.')
                    yield E.div(*chunks)

            site.add_welcome_handler(welcome_messages)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace ProjectManagement
{
    public partial class ExprertsRegisterForm : Form
    {
        PmContext context = new PmContext();
        EXPERT expert;
        public ExprertsRegisterForm()
        {
            InitializeComponent();
        }

        private void CreateExpertBtn_Click(object sender, EventArgs e)
        {

            if (!IsValidInput(ExpertNameTextBox) || !IsValidInput(ExpertMiddleNameTextBox) || !IsValidInput(ExpertLastNameTextBox))
            {
                return;
            }

            expert = new EXPERT();
            expert.EXPERT_NAME = ExpertNameTextBox.Text;
            expert.EXPERT_SURNAME = ExpertMiddleNameTextBox.Text;
            expert.EXPERT_LASTNAME = ExpertLastNameTextBox.Text;
            if (OutsideExpert.Checked == true)
            {
                expert.EXPERT_TYPE = "E";
            }
            else if (InsideExpert.Checked == true)
            {
                expert.EXPERT_TYPE = "I";
            }
            else if (OutsideExpert.Checked == false && InsideExpert.Checked == false)
            {
                MessageBox.Show("Изберете тип на експерта!");
                return;
            }

            context.EXPERTS.Add(expert);
            context.SaveChanges();
            MessageBox.Show("Експертът е регистриран успешно.");

            ExpertNameTextBox.Clear();
            ExpertMiddleNameTextBox.Clear();
            ExpertLastNameTextBox.Clear();
            InsideExpert.Checked = false;
            OutsideExpert.Checked = false;

            //if form is open from Create Tast Form:
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name.Equals("CreatingTaskForm"))
                {
                    CreatingTaskForm form = Application.OpenForms.OfType<CreatingTaskForm>().FirstOrDefault();
                    if (form != null)
                    {
                        form.PopulateExpertCb();
                        var cb = (ComboBox)form.Controls.Find("ExpertsCb", true).FirstOrDefault();
                        cb.SelectedValue = expert.EXPRET_ID;
                        this.Close();
                    }
                }
                else if (f.Name.Equals("TaskDetailsForm"))
                {
                    TaskDetailsForm form = Application.OpenForms.OfType<TaskDetailsForm>().FirstOrDefault();
                    if (form != null)
                    {
                        form.PopulateExpertCb();
                        var cb = (ComboBox)form.Controls.Find("ExpertsCb", true).FirstOrDefault();
                        cb.SelectedValue = expert.EXPRET_ID;
                        this.Close();
                    }
                }
            }
        }

        private bool IsValidInput(TextBox tb)
        {
            string tbName = "";
            switch (tb.Name)
            {
                case "ExpertNameTextBox": tbName = "име"; break;
                case "ExpertMiddleNameTextBox": tbName = "презиме"; break;
                case "ExpertLastNameTextBox": tbName = "фамилия"; break;
                default:
                    break;
            }

            if (tb.Text == "")
            {
                MessageBox.Show($"Моля, попълнете полето {tbName}!");
                return false;
            }
            return true;
        }

        private void CloseBtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonClear_Click(object sender, EventArgs e)
        {
            ExpertNameTextBox.Clear();
            ExpertMiddleNameTextBox.Clear();
            ExpertLastNameTextBox.Clear();
            OutsideExpert.Checked = false;
            InsideExpert.Checked = false;
        }
    }
}


text:
package com.wegas.core.persistence;

import com.wegas.test.TestHelper;
import com.wegas.test.arquillian.AbstractArquillianTestMinimal;
import org.junit.Assert;
import org.junit.Test;

/**
 *
 * @author maxence
 */
public class DatabaseTest extends AbstractArquillianTestMinimal {

    @Test
    public void testIndexes() {
        Assert.assertEquals("Some indexes are missing. Please create them with JPA and LiquiBase See log for details", 0, TestHelper.getMissingIndexesCount());
    }
}


text:
package com.example.achuan.bombtest.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;
import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by codeest on 2016/8/2.
 * 功能:MVP Fragment基类
 */
public abstract class BaseFragment<T extends BasePresenter> extends SupportFragment implements BaseView{

    protected T mPresenter;
    private boolean isInited = false;//记录是否已经初始化完毕

    //当碎片和活动建立关联的时候调用
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }
    //为碎片创建视图(加载布局)时调用
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(getLayoutId(),container,false);
        mPresenter=createPresenter();//创建操作者实例
        return view;
    }
    //确保与碎片相关联的活动一定已经创建完毕的时候调用
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if(mPresenter!=null){
            mPresenter.attachView(this);//添加关联(presenter和fragment)
        }
        ButterKnife.bind(this, view);//初始化加载布局控件
        //如果是视图第一次创建,而且没有被挡住,才初始化事件和数据
        if (savedInstanceState == null) {
            if (!isHidden()) {
                isInited = true;//已经初始化过一次了
                initEventAndData();
            }
        }
    }
    //碎片隐藏状态改变时调用该方法(用来确保非隐藏状态时完成初始化)
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!isInited && !hidden) {
            isInited = true;
            initEventAndData();
        }
    }
    //当与碎片关联的视图被移除的时候调用
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(mPresenter!=null){
            mPresenter.detachView();//取消关联(presenter和fragment)
        }
    }

    protected abstract T createPresenter();//创建操作者实例
    protected abstract int getLayoutId();//添加布局文件
    protected abstract void initEventAndData();//初始化事件及数据
}


text:
package eCommerce.dominio;

public class Estado extends EntidadeDominio{

	private String nome;
	private Pais pais;
	private Boolean ativo=true;

	public Boolean getAtivo() {
		return ativo;
	}

	public void setAtivo(Boolean ativo) {
		this.ativo = ativo;
	}

	public Pais getPais() {
		return pais;
	}

	public void setPais(Pais pais) {
		this.pais = pais;
	}

	public String getNome() {
		return nome;
	}

	public void setNome(String nome) {
		this.nome = nome;
	}

}


text:
layout: page
title: Stanley Electronics Seminar
date: 2016-05-24
author: Gabriel Gibbs
tags: weekly links, java
status: published
summary: Praesent nec pellentesque lectus. Ut a aliquet nulla.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 06/19/2019
  endDate: 06/23/2019
  ctyhocn: FSTTXHX
  groupCode: SES
published: true
---
Nullam suscipit blandit odio sed tincidunt. Sed dolor mi, blandit ac tristique nec, gravida eu urna. Morbi congue ex in nisi posuere accumsan. Maecenas eu pharetra elit. Nullam cursus euismod sem, ut sagittis sapien pellentesque sit amet. Morbi vitae orci aliquam nibh volutpat accumsan. Nunc ut turpis in dolor condimentum malesuada at vestibulum ex.

* Aenean condimentum ante ut turpis tempor, at viverra magna ullamcorper
* Sed tempor metus sit amet odio fringilla, sed elementum lacus pretium
* Nam laoreet eros quis quam vulputate, in convallis mauris varius.

Vivamus eu est a arcu egestas facilisis. Ut molestie, ex quis fringilla rhoncus, nulla quam euismod odio, at maximus massa lorem id diam. Mauris id velit ullamcorper, ullamcorper libero ac, elementum dolor. Maecenas eu ligula vitae libero aliquam pellentesque. Nunc maximus, sapien vitae tincidunt egestas, tellus risus porta ex, vel euismod dui dolor sagittis urna. Vivamus interdum tincidunt varius. Vivamus molestie mi id risus bibendum fringilla. Mauris laoreet nibh ullamcorper tristique fermentum. Nullam dictum mattis imperdiet. Morbi semper dui augue, sed mollis sem luctus ac. Ut sollicitudin nulla auctor, laoreet risus malesuada, dictum mauris. Ut id sapien quis magna faucibus vulputate id et nunc.
Quisque malesuada condimentum nisl in posuere. Curabitur elementum egestas accumsan. Phasellus ultricies sodales consequat. Nullam lobortis turpis ligula, sit amet lacinia magna sollicitudin sit amet. Etiam pretium turpis a condimentum cursus. Donec vulputate ex magna, non lacinia ex maximus scelerisque. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis ac enim volutpat, auctor nisi eu, pretium orci. Suspendisse eros odio, feugiat in magna vitae, ultricies eleifend ligula. Aliquam eu mi sed justo elementum vulputate eget sed mi.


text:
package com.hazelcast.internal.util.counters;

import java.util.concurrent.atomic.AtomicLongFieldUpdater;

import static java.util.concurrent.atomic.AtomicLongFieldUpdater.newUpdater;

/**
 * A {@link Counter} that is thread-safe; so can be incremented by multiple threads concurrently.
 *
 * The MwCounter is not meant for a huge amount of contention. In that case it would be better to create a counter
 * on the {@link java.util.concurrent.atomic.LongAdder}.
 *
 * This counter does not provide padding to prevent false sharing.
 */
public final class MwCounter implements Counter {

    private static final AtomicLongFieldUpdater<MwCounter> COUNTER = newUpdater(MwCounter.class, "value");

    private volatile long value;

    private MwCounter(long initialValue) {
        this.value = initialValue;
    }

    @Override
    public void set(long newValue) {
        COUNTER.set(this, newValue);
    }

    @Override
    public long getAndSet(long newValue) {
        return COUNTER.getAndSet(this, newValue);
    }

    @Override
    public long get() {
        return value;
    }

    @Override
    public long inc() {
        return COUNTER.incrementAndGet(this);
    }

    @Override
    public long inc(long amount) {
        return COUNTER.addAndGet(this, amount);
    }

    @Override
    public String toString() {
        return "Counter{"
                + "value=" + value
                + '}';
    }

    /**
     * Creates a new MwCounter with 0 as its initial value.
     *
     * @return the new MwCounter, set to 0.
     */
    public static MwCounter newMwCounter() {
        return newMwCounter(0);
    }

    /**
     * Creates a new MwCounter with the given initial value.
     *
     * @param initialValue the initial value of the counter.
     * @return the new MwCounter, set to the given initial value.
     */
    public static MwCounter newMwCounter(long initialValue) {
        return new MwCounter(initialValue);
    }
}


text:
<?php

namespace Croogo\Translate\Event;

use Cake\Event\EventListenerInterface;
use Croogo\Translate\Translations;

/**
 * TranslateEventHandler
 *
 * @package  Croogo.Translate.Event
 * @author   Rachman Chavik <rchavik@gmail.com>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class TranslateEventHandler implements EventListenerInterface
{

    public function implementedEvents()
    {
        return [
            'Croogo.bootstrapComplete' => [
                'callable' => 'onCroogoBootstrapComplete',
            ],
        ];
    }

    public function onCroogoBootstrapComplete($event)
    {
        Translations::translateModels();
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title><?php
if(array_key_exists('header', $this->data)) {
	echo $this->data['header'];
} else {
	echo 'simpleSAMLphp';
}
?></title>

	<link rel="stylesheet" type="text/css" href="/<?php echo $this->data['baseurlpath']; ?>resources/default.css" />
	<meta name="robots" content="noindex, nofollow" />

<?php
if(array_key_exists('head', $this->data)) {
	echo '<!-- head -->' . $this->data['head'] . '<!-- /head -->';
}
?>
</head>
<body class="body-embed">


text:
package nl.nn.adapterframework.webcontrol.action;

import nl.nn.adapterframework.util.AppConstants;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * This handler adjusts the way the configuration is shown (original or loaded).
 * @version $Id$
 * @author  Peter Leeuwenburgh
 */

public final class ConfigHandler extends ActionBase {

	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String adapterName = null;
		String receiverName = null;
		// Initialize action
		initAction(request);

		if (null == ibisManager) {
			return (mapping.findForward("noconfig"));
		}
		String action = request.getParameter("action");
		if (null == action)
			action = mapping.getParameter();

		if (action.equals("showoriginalconfig")) {
			AppConstants.getInstance().put("showConfiguration.original", "true");
		} else {
			AppConstants.getInstance().put("showConfiguration.original", "false");
		}

		// Report any errors we have discovered back to the original form
		if (!errors.isEmpty()) {
			saveErrors(request, errors);
		} // Forward control to the specified success URI
		log.debug("forward to success");
		return (mapping.findForward("success"));
	}
}


text:
<?php

namespace wcmf\lib\io;

use wcmf\lib\core\IllegalArgumentException;
use wcmf\lib\core\ObjectFactory;
use wcmf\lib\io\IOException;

/**
 * FileUtil provides basic support for file functionality like HTTP file upload.
 *
 * @author ingo herwig <ingo@wemove.com>
 */
class FileUtil {

  /**
   * Copy an uploaded file to a given destination (only if the mime type matches the given one).
   * @param $mediaFile An associative array with the following keys: 'name', 'type', 'tmp_name' (typically a $_FILES entry)
   * @param $destName The destination file name
   * @param $mimeTypes An array holding the allowed mime types, null if arbitrary (default: _null_)
   * @param $override Boolean whether an existing file should be overridden, if false an unique id will be placed in the filename to prevent overriding (default: _true_)
   * @return The filename of the uploaded file
   */
  public static function uploadFile($mediaFile, $destName, $mimeTypes=null, $override=true) {
    $message = ObjectFactory::getInstance('message');

    // check if the file was uploaded
    if (!is_uploaded_file($mediaFile['tmp_name'])) {
      $msg = $message->getText("Possible file upload attack: filename %0%.", [$mediaFile['name']]);
      throw new IOException($msg);
    }

    // check mime type
    if ($mimeTypes != null && !in_array($mediaFile['type'], $mimeTypes)) {
      throw new IOException($message->getText("File '%0%' has wrong mime type: %1%. Allowed types: %2%.",
        [$mediaFile['name'], $mediaFile['type'], join(", ", $mimeTypes)]));
    }

    // check if we need a new name
    if ($override == false && file_exists($destName)) {
      $pieces = preg_split('/\./', self::basename($destName));
      $extension = array_pop($pieces);
      $name = join('.', $pieces);
      $destName = dirname($destName)."/".$name.uniqid(mt_rand(0, 99)).".".$extension;
    }
    $result = move_uploaded_file($mediaFile['tmp_name'], $destName);
    if ($result === false) {
      throw new IOException($message->getText("Failed to move %0% to %1%.", [$mediaFile['tmp_name'], $destName]));
    }
    return self::basename($destName);
  }

  /**
   * Get the mime type of the given file
   * @param $file The file
   * @return String
   */
  public static function getMimeType($file) {
    $defaultType = 'application/octet-stream';

    // try to determine from file content, if the file exists
    if (self::fileExists($file)) {
      if (class_exists('\FileInfo')) {
        // use FileInfo extension
        $fileInfo = new finfo(FILEINFO_MIME);
        $fileType = $fileInfo->file(file_get_contents($file));
      }
      else {
        // try detect image mime type
        $imageInfo = @getimagesize($file);
        $fileType = isset($imageInfo['mime']) ? $imageInfo['mime'] : '';
      }
      return (is_string($fileType) && !empty($fileType)) ? $fileType : $defaultType;
    }

    // fall back to file extension
    $pieces = preg_split('/\./', self::basename($file));
    $extension = strtolower(array_pop($pieces));
    return isset(self::MIME_TYPE_MAP[$extension]) ? self::MIME_TYPE_MAP[$extension] : $defaultType;
  }

  /**
   * Write unicode to file.
   * @param $fp File Handle
   * @param $str String to write
   */
  public static function fputsUnicode($fp, $str) {
    fputs($fp, utf8_encode($str));
  }

  /*
   * Get the files in a directory that match a pattern
   * @param $directory The directory to search in
   * @param $pattern The pattern (regexp) to match (default: _/./_)
   * @param $prependDirectoryName Boolean whether to prepend the directory name to each file (default: _false_)
   * @param $recursive Boolean whether to recurse into subdirectories (default: _false_)
   * @return An array containing the filenames sorted by modification date
   */
  public static function getFiles($directory, $pattern='/./', $prependDirectoryName=false, $recursive=false) {
    if (strrpos($directory, '/') != strlen($directory)-1) {
      $directory .= '/';
    }
    if (!is_dir($directory)) {
      $message = ObjectFactory::getInstance('message');
      throw new IllegalArgumentException($message->getText("The directory '%0%' does not exist.", [$directory]));
    }
    $result = [];
    $d = dir($directory);
    $d->rewind();
    while(false !== ($file = $d->read())) {
      if($file != '.' && $file != '..') {
        if ($recursive && is_dir($directory.$file)) {
          $files = self::getFiles($directory.$file, $pattern, $prependDirectoryName, $recursive);
          $result = array_merge($result, $files);
        }
        else if(is_file($directory.$file) && preg_match($pattern, $file)) {
          $sortkey = filectime($directory.$file).',';
          if ($prependDirectoryName) {
            $file = $directory.$file;
          }
          $sortkey .= $file;
          $result[$sortkey] = $file;
        }
      }
    }
    $d->close();
    krsort($result);
    return array_values($result);
  }

  /*
   * Get the directories in a directory that match a pattern
   * @param $directory The directory to search in
   * @param $pattern The pattern (regexp) to match (default: _/./_)
   * @param $prependDirectoryName Boolean whether to prepend the directory name to each directory (default: _false_)
   * @param $recursive Boolean whether to recurse into subdirectories (default: _false_)
   * @return An array containing the directory names
   */
  public static function getDirectories($directory, $pattern='/./', $prependDirectoryName=false, $recursive=false) {
    if (strrpos($directory, '/') != strlen($directory)-1) {
      $directory .= '/';
    }
    if (!is_dir($directory)) {
      $message = ObjectFactory::getInstance('message');
      throw new IllegalArgumentException($message->getText("The directory '%0%' does not exist.", [$directory]));
    }

    $result = [];
    $d = dir($directory);
    $d->rewind();
    // iterate over all files
    while(false !== ($file = $d->read())) {
      // exclude this and parent directory
      if($file != '.' && $file != '..') {
        // include directories only
        if (is_dir($directory.$file)) {
          // recurse
          if ($recursive) {
            $dirs = self::getDirectories($directory.$file, $pattern, $prependDirectoryName, $recursive);
            $result = array_merge($result, $dirs);
          }
          if(preg_match($pattern, $file)) {
            if ($prependDirectoryName) {
              $file = $directory.$file;
            }
            $result[] = $file;
          }
        }
      }
    }
    $d->close();
    return $result;
  }

  /**
   * Recursive copy for files/directories.
   * @param $source The name of the source directory/file
   * @param $dest The name of the destination directory/file
   */
  public static function copyRec($source, $dest) {
    if (is_file($source)) {
      $perms = fileperms($source);
      return copy($source, $dest) && chmod($dest, $perms);
    }
    if (!is_dir($source)) {
      $message = ObjectFactory::getInstance('message');
      throw new IllegalArgumentException($message->getText("Cannot copy %0% (it's neither a file nor a directory).", [$source]));
    }
    self::copyRecDir($source, $dest);
  }

  /**
   * Recursive copy for directories.
   * @param $source The name of the source directory
   * @param $dest The name of the destination directory
   */
  public static function copyRecDir($source, $dest) {
    if (!is_dir($dest)) {
      self::mkdirRec($dest);
    }
    $dir = opendir($source);
    while ($file = readdir($dir)) {
      if ($file == "." || $file == "..") {
        continue;
      }
      self::copyRec("$source/$file", "$dest/$file");
    }
    closedir($dir);
  }

  /**
   * Recursive directory creation.
   * @param $dirname The name of the directory
   * @param $perm The permission for the new directories (default: 0775)
   */
  public static function mkdirRec($dirname, $perm=0775) {
    if (!is_dir($dirname)) {
      @mkdir($dirname, $perm, true);
    }
  }

  /**
   * Empty a directory.
   * @param $dirname The name of the directory
   */
  public static function emptyDir($dirname) {
    if (is_dir($dirname)) {
      $files = self::getFiles($dirname, '/./', true, true);
      foreach ($files as $file) {
        @unlink($file);
      }
      $dirs = self::getDirectories($dirname, '/./', true, true);
      foreach ($dirs as $dir) {
        @rmdir($dir);
      }
    }
  }

  /**
   * Realpath function that also works for non existing paths
   * code from http://www.php.net/manual/en/function.realpath.php
   * @param $path
   * @return String
   */
  public static function realpath($path) {
    if (file_exists($path)) {
      return str_replace("\\", "/", realpath($path));
    }
    $path = str_replace("\\", "/", $path);
    $parts = array_filter(explode("/", $path), 'strlen');
    $absolutes = [];
    foreach ($parts as $part) {
      if ('.' == $part) {
        continue;
      }
      if ('..' == $part) {
        array_pop($absolutes);
      }
      else {
        $absolutes[] = $part;
      }
    }
    $result = implode("/", $absolutes);
    if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') {
      $result = '/'.$result;
    }
    return $result;
  }

  /**
   * Get a sanitized filename
   * code from: http://stackoverflow.com/questions/2021624/string-sanitizer-for-filename#2021729
   * @param $file
   * @return String
   */
  public static function sanitizeFilename($file) {
    $file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).])", '', $file);
    $file = preg_replace("([\.]{2,})", '', $file);
    return $file;
  }

  /**
   * Fix the name of an existing file to be used with php file functions
   * @param $file
   * @return String or null, if the file does not exist
   */
  public static function fixFilename($file) {
    if (file_exists($file)) {
      return $file;
    }
    else {
      $file = iconv('utf-8', 'cp1252', $file);
      if (file_exists($file)) {
        return $file;
      }
    }
    return null;
  }

  /**
   * Url encode a file path
   * @param $file
   * @return String
   */
  public static function urlencodeFilename($file) {
    $parts = explode('/', $file);
    $result = [];
    foreach ($parts as $part) {
      $result[] = rawurlencode($part);
    }
    return join('/', $result);
  }

  /**
   * Check if the given file exists
   * @param $file
   * @return Boolean
   */
  public static function fileExists($file) {
    return self::fixFilename($file) !== null;
  }

  /**
   * Get the trailing name component of a path (locale independent)
   * @param $file
   * @return String
   */
  public static function basename($file) {
    $parts = explode('/', $file);
    return end($parts);
  }

  private const MIME_TYPE_MAP = [
    'txt' => 'text/plain',
    'htm' => 'text/html',
    'html' => 'text/html',
    'php' => 'text/html',
    'css' => 'text/css',
    'js' => 'application/javascript',
    'json' => 'application/json',
    'xml' => 'application/xml',
    'swf' => 'application/x-shockwave-flash',
    'flv' => 'video/x-flv',

    // images
    'png' => 'image/png',
    'jpe' => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'jpg' => 'image/jpeg',
    'gif' => 'image/gif',
    'bmp' => 'image/bmp',
    'ico' => 'image/vnd.microsoft.icon',
    'tiff' => 'image/tiff',
    'tif' => 'image/tiff',
    'svg' => 'image/svg+xml',
    'svgz' => 'image/svg+xml',

    // archives
    'zip' => 'application/zip',
    'rar' => 'application/x-rar-compressed',
    'exe' => 'application/x-msdownload',
    'msi' => 'application/x-msdownload',
    'cab' => 'application/vnd.ms-cab-compressed',

    // audio/video
    'mp3' => 'audio/mpeg',
    'qt' => 'video/quicktime',
    'mov' => 'video/quicktime',

    // adobe
    'pdf' => 'application/pdf',
    'psd' => 'image/vnd.adobe.photoshop',
    'ai' => 'application/postscript',
    'eps' => 'application/postscript',
    'ps' => 'application/postscript',

    // ms office
    'doc' => 'application/msword',
    'rtf' => 'application/rtf',
    'xls' => 'application/vnd.ms-excel',
    'ppt' => 'application/vnd.ms-powerpoint',

    // open office
    'odt' => 'application/vnd.oasis.opendocument.text',
    'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  ];
}
?>


text:
title: Ron Kind, Wisconsin Congressperson
name: Ron Kind
avatar: /ui/img/avatars/Ron_Kind.jpg
party: democrat
state: wisconsin
type: congressperson
lasthall: 2017-05-31
phone: 202-225-5506
never:
twitter: RepRonKind
---


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/extensions/extension_messages.h"
#include "chrome/renderer/extensions/chrome_v8_context.h"
#include "chrome/renderer/extensions/chrome_v8_extension.h"
#include "chrome/renderer/extensions/content_watcher.h"
#include "chrome/renderer/extensions/dispatcher.h"
#include "content/public/renderer/render_view.h"
#include "content/public/renderer/render_view_visitor.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebElement.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "third_party/WebKit/public/web/WebView.h"

namespace extensions {

namespace {

class MutationHandler : public ChromeV8Extension {
 public:
  explicit MutationHandler(Dispatcher* dispatcher,
                           ChromeV8Context* context,
                           base::WeakPtr<ContentWatcher> content_watcher)
      : ChromeV8Extension(dispatcher, context),
        content_watcher_(content_watcher) {
    RouteFunction("FrameMutated",
                  base::Bind(&MutationHandler::FrameMutated,
                             base::Unretained(this)));
  }

 private:
  void FrameMutated(const v8::FunctionCallbackInfo<v8::Value>& args) {
    if (content_watcher_.get()) {
      content_watcher_->ScanAndNotify(
          WebKit::WebFrame::frameForContext(context()->v8_context()));
    }
  }

  base::WeakPtr<ContentWatcher> content_watcher_;
};

}  // namespace

ContentWatcher::ContentWatcher(Dispatcher* dispatcher)
    : weak_ptr_factory_(this),
      dispatcher_(dispatcher) {}
ContentWatcher::~ContentWatcher() {}

scoped_ptr<NativeHandler> ContentWatcher::MakeNatives(
    ChromeV8Context* context) {
  return scoped_ptr<NativeHandler>(new MutationHandler(
      dispatcher_, context, weak_ptr_factory_.GetWeakPtr()));
}

void ContentWatcher::OnWatchPages(
    const std::vector<std::string>& new_css_selectors) {
  if (new_css_selectors == css_selectors_)
    return;

  css_selectors_ = new_css_selectors;

  for (std::map<WebKit::WebFrame*,
                std::vector<base::StringPiece> >::iterator
           it = matching_selectors_.begin();
       it != matching_selectors_.end(); ++it) {
    WebKit::WebFrame* frame = it->first;
    if (!css_selectors_.empty())
      EnsureWatchingMutations(frame);

    // Make sure to replace the contents of it->second because it contains
    // dangling StringPieces that referred into the old css_selectors_ content.
    it->second = FindMatchingSelectors(frame);
  }

  // For each top-level frame, inform the browser about its new matching set of
  // selectors.
  struct NotifyVisitor : public content::RenderViewVisitor {
    explicit NotifyVisitor(ContentWatcher* watcher) : watcher_(watcher) {}
    virtual bool Visit(content::RenderView* view) OVERRIDE {
      watcher_->NotifyBrowserOfChange(view->GetWebView()->mainFrame());
      return true;  // Continue visiting.
    }
    ContentWatcher* watcher_;
  };
  NotifyVisitor visitor(this);
  content::RenderView::ForEach(&visitor);
}

void ContentWatcher::DidCreateDocumentElement(WebKit::WebFrame* frame) {
  // Make sure the frame is represented in the matching_selectors_ map.
  matching_selectors_[frame];

  if (!css_selectors_.empty()) {
    EnsureWatchingMutations(frame);
  }
}

void ContentWatcher::EnsureWatchingMutations(WebKit::WebFrame* frame) {
  v8::HandleScope scope(v8::Isolate::GetCurrent());
  v8::Context::Scope context_scope(frame->mainWorldScriptContext());
  if (ModuleSystem* module_system = GetModuleSystem(frame)) {
    ModuleSystem::NativesEnabledScope scope(module_system);
    module_system->Require("contentWatcher");
  }
}

ModuleSystem* ContentWatcher::GetModuleSystem(WebKit::WebFrame* frame) const {
  ChromeV8Context* v8_context =
      dispatcher_->v8_context_set().GetByV8Context(
          frame->mainWorldScriptContext());

  if (!v8_context)
    return NULL;
  return v8_context->module_system();
}

void ContentWatcher::ScanAndNotify(WebKit::WebFrame* frame) {
  std::vector<base::StringPiece> new_matches = FindMatchingSelectors(frame);
  std::vector<base::StringPiece>& old_matches = matching_selectors_[frame];
  if (new_matches == old_matches)
    return;

  using std::swap;
  swap(old_matches, new_matches);
  NotifyBrowserOfChange(frame);
}

std::vector<base::StringPiece> ContentWatcher::FindMatchingSelectors(
    WebKit::WebFrame* frame) const {
  std::vector<base::StringPiece> result;
  WebKit::WebDocument document = frame->document();
  for (size_t i = 0; i < css_selectors_.size(); ++i) {
    WebKit::WebExceptionCode exception = 0;
    if (!document.querySelector(WebKit::WebString::fromUTF8(css_selectors_[i]),
                                exception).isNull())
      result.push_back(css_selectors_[i]);
    DCHECK_EQ(0, exception)
        << "We should already have checked that the selectors are valid.";
  }
  return result;
}

void ContentWatcher::NotifyBrowserOfChange(
    WebKit::WebFrame* changed_frame) const {
  WebKit::WebFrame* const top_frame = changed_frame->top();
  const WebKit::WebSecurityOrigin top_origin =
      top_frame->document().securityOrigin();
  // Want to aggregate matched selectors from all frames where an
  // extension with access to top_origin could run on the frame.
  if (!top_origin.canAccess(changed_frame->document().securityOrigin())) {
    // If the changed frame can't be accessed by the top frame, then
    // no change in it could affect the set of selectors we'd send back.
    return;
  }

  std::set<base::StringPiece> transitive_selectors;
  for (WebKit::WebFrame* frame = top_frame; frame;
       frame = frame->traverseNext(/*wrap=*/false)) {
    if (top_origin.canAccess(frame->document().securityOrigin())) {
      std::map<WebKit::WebFrame*,
               std::vector<base::StringPiece> >::const_iterator
          frame_selectors = matching_selectors_.find(frame);
      if (frame_selectors != matching_selectors_.end()) {
        transitive_selectors.insert(frame_selectors->second.begin(),
                                    frame_selectors->second.end());
      }
    }
  }
  std::vector<std::string> selector_strings;
  for (std::set<base::StringPiece>::const_iterator
           it = transitive_selectors.begin();
       it != transitive_selectors.end(); ++it)
    selector_strings.push_back(it->as_string());
  content::RenderView* view =
      content::RenderView::FromWebView(top_frame->view());
  view->Send(new ExtensionHostMsg_OnWatchedPageChange(
      view->GetRoutingID(), selector_strings));
}

}  // namespace extensions