text:
require 'minitest_helper'

describe Fog::XenServer::Compute::Models::Host do
  let(:host_class) do
    class Fog::XenServer::Compute::Models::Host
      def self.read_identity
        instance_variable_get('@identity')
      end
    end
    Fog::XenServer::Compute::Models::Host
  end
  let(:host) { Fog::XenServer::Compute::Models::Host.new }
  let(:service) { Object.new }

  it 'should associate to a provider class' do
    host_class.provider_class.must_equal('host')
  end

  it 'should have a collection name' do
    host_class.collection_name.must_equal(:hosts)
  end

  it 'should have an unique id' do
    host_class.read_identity.must_equal(:reference)
  end

  it 'should have 39 attributes' do
    host_class.attributes.must_equal([ :reference,
                                       :address,
                                       :allowed_operations,
                                       :api_version_major,
                                       :api_version_minor,
                                       :api_version_vendor,
                                       :api_version_vendor_implementation,
                                       :bios_strings,
                                       :blobs,
                                       :capabilities,
                                       :chipset_info,
                                       :cpu_configuration,
                                       :cpu_info,
                                       :current_operations,
                                       :description,
                                       :edition,
                                       :enabled,
                                       :external_auth_configuration,
                                       :external_auth_service_name,
                                       :external_auth_type,
                                       :guest_vcpus_params,
                                       :ha_network_peers,
                                       :ha_statefiles,
                                       :hostname,
                                       :license_params,
                                       :license_server,
                                       :logging,
                                       :memory_overhead,
                                       :name,
                                       :other_config,
                                       :patches,
                                       :power_on_config,
                                       :power_on_mode,
                                       :sched_policy,
                                       :software_version,
                                       :supported_bootloaders,
                                       :suspend_image_sr,
                                       :tags,
                                       :uuid ])
  end

  it 'should have 10 associations' do
    host_class.associations.must_equal(:crashdumps => :crash_dumps,
                                       :crash_dump_sr => :storage_repositories,
                                       :host_cpus => :host_cpus,
                                       :local_cache_sr => :storage_repositories,
                                       :metrics => :hosts_metrics,
                                       :pbds => :pbds,
                                       :pcis => :pcis,
                                       :pgpus => :pgpus,
                                       :pifs => :pifs,
                                       :resident_vms => :servers)
  end

  it 'should have 49 masks' do
    host_class.masks.must_equal(:reference => :reference,
                                :address => :address,
                                :allowed_operations => :allowed_operations,
                                :api_version_major => :API_version_major,
                                :api_version_minor => :API_version_minor,
                                :api_version_vendor => :API_version_vendor,
                                :api_version_vendor_implementation => :API_version_vendor_implementation,
                                :bios_strings => :bios_strings,
                                :blobs => :blobs,
                                :capabilities => :capabilities,
                                :chipset_info => :chipset_info,
                                :cpu_configuration => :cpu_configuration,
                                :cpu_info => :cpu_info,
                                :current_operations => :current_operations,
                                :description => :description,
                                :edition => :edition,
                                :enabled => :enabled,
                                :external_auth_configuration => :external_auth_configuration,
                                :external_auth_service_name => :external_auth_service_name,
                                :external_auth_type => :external_auth_type,
                                :guest_vcpus_params => :guest_VCPUs_params,
                                :ha_network_peers => :ha_network_peers,
                                :ha_statefiles => :ha_statefiles,
                                :hostname => :hostname,
                                :license_params => :license_params,
                                :license_server => :license_server,
                                :logging => :logging,
                                :memory_overhead => :memory_overhead,
                                :name => :name,
                                :other_config => :other_config,
                                :patches => :patches,
                                :power_on_config => :power_on_config,
                                :power_on_mode => :power_on_mode,
                                :sched_policy => :sched_policy,
                                :software_version => :software_version,
                                :supported_bootloaders => :supported_bootloaders,
                                :suspend_image_sr => :suspend_image_sr,
                                :tags => :tags,
                                :uuid => :uuid,
                                :crashdumps => :crashdumps,
                                :crash_dump_sr => :crash_dump_sr,
                                :host_cpus => :host_CPUs,
                                :local_cache_sr => :local_cache_sr,
                                :metrics => :metrics,
                                :pbds => :PBDs,
                                :pcis => :PCIs,
                                :pgpus => :PGPUs,
                                :pifs => :PIFs,
                                :resident_vms => :resident_VMs)
  end

  it 'should have 13 aliases' do
    host_class.aliases.must_equal(:name_label => :name,
                                  :API_version_major => :api_version_major,
                                  :API_version_minor => :api_version_minor,
                                  :API_version_vendor => :api_version_vendor,
                                  :API_version_vendor_implementation => :api_version_vendor_implementation,
                                  :guest_VCPUs_params => :guest_vcpus_params,
                                  :name_description => :description,
                                  :host_CPUs => :host_cpus,
                                  :PBDs => :pbds,
                                  :PCIs => :pcis,
                                  :PGPUs => :pgpus,
                                  :PIFs => :pifs,
                                  :resident_VMs => :resident_vms)
  end

  it "shouldn't have default values" do
    host_class.default_values.must_equal({})
  end

  it "shouldn't require attributes before save" do
    host_class.require_before_save.must_equal([])
  end

  describe '#shutdown' do
    describe 'with auto_disable equal true' do
      before :each do
        def service.disable_host(reference); @disabled = true end
        def service.shutdown_host(reference); @halted = true end
        host.stub(:service, service) do
          host.shutdown
        end
      end

      it 'should disable the host' do
        service.instance_variable_get(:@disabled).must_equal(true)
      end

      it 'should shutdown the host' do
        service.instance_variable_get(:@halted).must_equal(true)
      end
    end

    describe 'with auto_disable equal false' do
      before :each do
        def service.shutdown_host(reference); @halted = true end
        host.stub(:service, service) do
          host.shutdown(false)
        end
      end

      it 'should not disable the host' do
        service.instance_variable_get(:@disabled).must_equal(nil)
      end

      it 'should shutdown the host' do
        service.instance_variable_get(:@halted).must_equal(true)
      end
    end
  end

  describe '#reboot' do
    describe 'with auto_disable equal true' do
      before :each do
        def service.disable_host(reference); @disabled = true end
        def service.reboot_host(reference); @rebooted = true end
        host.stub(:service, service) do
          host.reboot
        end
      end

      it 'should disable the host' do
        service.instance_variable_get(:@disabled).must_equal(true)
      end

      it 'should shutdown the host' do
        service.instance_variable_get(:@rebooted).must_equal(true)
      end
    end

    describe 'with auto_disable equal false' do
      before :each do
        def service.reboot_host(reference); @rebooted = true end
        host.stub(:service, service) do
          host.reboot(false)
        end
      end

      it 'should not disable the host' do
        service.instance_variable_get(:@disabled).must_equal(nil)
      end

      it 'should shutdown the host' do
        service.instance_variable_get(:@rebooted).must_equal(true)
      end
    end
  end
end


text:
@implementation SectionHeaderView

@end

redpajama_set_name: RedPajamaGithub


text:
package kafka.network

import com.fasterxml.jackson.databind.ObjectMapper
import kafka.network
import kafka.server.EnvelopeUtils
import kafka.utils.TestUtils
import org.apache.kafka.clients.admin.AlterConfigOp.OpType
import org.apache.kafka.common.config.types.Password
import org.apache.kafka.common.config.{ConfigResource, SaslConfigs, SslConfigs, TopicConfig}
import org.apache.kafka.common.memory.MemoryPool
import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic
import org.apache.kafka.common.message.IncrementalAlterConfigsRequestData._
import org.apache.kafka.common.message.{CreateTopicsRequestData, CreateTopicsResponseData, IncrementalAlterConfigsRequestData}
import org.apache.kafka.common.network.{ClientInformation, ListenerName}
import org.apache.kafka.common.protocol.Errors
import org.apache.kafka.common.requests.AlterConfigsRequest._
import org.apache.kafka.common.requests._
import org.apache.kafka.common.security.auth.{KafkaPrincipal, KafkaPrincipalSerde, SecurityProtocol}
import org.apache.kafka.common.utils.{SecurityUtils, Utils}
import org.apache.kafka.test
import org.junit.jupiter.api.Assertions._
import org.junit.jupiter.api._
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.EnumSource
import org.mockito.Mockito.mock

import java.io.IOException
import java.net.InetAddress
import java.nio.ByteBuffer
import java.util.Collections
import java.util.concurrent.atomic.AtomicReference
import scala.collection.{Map, Seq}
import scala.jdk.CollectionConverters._

class RequestChannelTest {
  private val requestChannelMetrics: RequestChannel.Metrics = mock(classOf[RequestChannel.Metrics])
  private val principalSerde = new KafkaPrincipalSerde() {
    override def serialize(principal: KafkaPrincipal): Array[Byte] = Utils.utf8(principal.toString)
    override def deserialize(bytes: Array[Byte]): KafkaPrincipal = SecurityUtils.parseKafkaPrincipal(Utils.utf8(bytes))
  }

  @Test
  def testAlterRequests(): Unit = {

    val sensitiveValue = "secret"
    def verifyConfig(resource: ConfigResource, entries: Seq[ConfigEntry], expectedValues: Map[String, String]): Unit = {
      val alterConfigs = request(new AlterConfigsRequest.Builder(
          Collections.singletonMap(resource, new Config(entries.asJavaCollection)), true).build())

      val loggableAlterConfigs = alterConfigs.loggableRequest.asInstanceOf[AlterConfigsRequest]
      val loggedConfig = loggableAlterConfigs.configs.get(resource)
      assertEquals(expectedValues, toMap(loggedConfig))
      val alterConfigsDesc = RequestConvertToJson.requestDesc(alterConfigs.header, alterConfigs.requestLog, alterConfigs.isForwarded).toString
      assertFalse(alterConfigsDesc.contains(sensitiveValue), s"Sensitive config logged $alterConfigsDesc")
    }

    val brokerResource = new ConfigResource(ConfigResource.Type.BROKER, "1")
    val keystorePassword = new ConfigEntry(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, sensitiveValue)
    verifyConfig(brokerResource, Seq(keystorePassword), Map(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG -> Password.HIDDEN))

    val keystoreLocation = new ConfigEntry(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, "/path/to/keystore")
    verifyConfig(brokerResource, Seq(keystoreLocation), Map(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG -> "/path/to/keystore"))
    verifyConfig(brokerResource, Seq(keystoreLocation, keystorePassword),
      Map(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG -> "/path/to/keystore", SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG -> Password.HIDDEN))

    val listenerKeyPassword = new ConfigEntry(s"listener.name.internal.${SslConfigs.SSL_KEY_PASSWORD_CONFIG}", sensitiveValue)
    verifyConfig(brokerResource, Seq(listenerKeyPassword), Map(listenerKeyPassword.name -> Password.HIDDEN))

    val listenerKeystore = new ConfigEntry(s"listener.name.internal.${SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG}", "/path/to/keystore")
    verifyConfig(brokerResource, Seq(listenerKeystore), Map(listenerKeystore.name -> "/path/to/keystore"))

    val plainJaasConfig = new ConfigEntry(s"listener.name.internal.plain.${SaslConfigs.SASL_JAAS_CONFIG}", sensitiveValue)
    verifyConfig(brokerResource, Seq(plainJaasConfig), Map(plainJaasConfig.name -> Password.HIDDEN))

    val plainLoginCallback = new ConfigEntry(s"listener.name.internal.plain.${SaslConfigs.SASL_LOGIN_CALLBACK_HANDLER_CLASS}", "test.LoginClass")
    verifyConfig(brokerResource, Seq(plainLoginCallback), Map(plainLoginCallback.name -> plainLoginCallback.value))

    val customConfig = new ConfigEntry("custom.config", sensitiveValue)
    verifyConfig(brokerResource, Seq(customConfig), Map(customConfig.name -> Password.HIDDEN))

    val topicResource = new ConfigResource(ConfigResource.Type.TOPIC, "testTopic")
    val compressionType = new ConfigEntry(TopicConfig.COMPRESSION_TYPE_CONFIG, "lz4")
    verifyConfig(topicResource, Seq(compressionType), Map(TopicConfig.COMPRESSION_TYPE_CONFIG -> "lz4"))
    verifyConfig(topicResource, Seq(customConfig), Map(customConfig.name -> Password.HIDDEN))

    // Verify empty request
    val alterConfigs = request(new AlterConfigsRequest.Builder(
        Collections.emptyMap[ConfigResource, Config], true).build())
    assertEquals(Collections.emptyMap, alterConfigs.loggableRequest.asInstanceOf[AlterConfigsRequest].configs)
  }

  @Test
  def testIncrementalAlterRequests(): Unit = {

    def incrementalAlterConfigs(resource: ConfigResource,
                                entries: Map[String, String], op: OpType): IncrementalAlterConfigsRequest = {
      val data = new IncrementalAlterConfigsRequestData()
      val alterableConfigs = new AlterableConfigCollection()
      entries.foreach { case (name, value) =>
        alterableConfigs.add(new AlterableConfig().setName(name).setValue(value).setConfigOperation(op.id))
      }
      data.resources.add(new AlterConfigsResource()
        .setResourceName(resource.name).setResourceType(resource.`type`.id)
        .setConfigs(alterableConfigs))
      new IncrementalAlterConfigsRequest.Builder(data).build()
    }

    val sensitiveValue = "secret"
    def verifyConfig(resource: ConfigResource,
                     op: OpType,
                     entries: Map[String, String],
                     expectedValues: Map[String, String]): Unit = {
      val alterConfigs = request(incrementalAlterConfigs(resource, entries, op))
      val loggableAlterConfigs = alterConfigs.loggableRequest.asInstanceOf[IncrementalAlterConfigsRequest]
      val loggedConfig = loggableAlterConfigs.data.resources.find(resource.`type`.id, resource.name).configs
      assertEquals(expectedValues, toMap(loggedConfig))
      val alterConfigsDesc = RequestConvertToJson.requestDesc(alterConfigs.header, alterConfigs.requestLog, alterConfigs.isForwarded).toString
      assertFalse(alterConfigsDesc.contains(sensitiveValue), s"Sensitive config logged $alterConfigsDesc")
    }

    val brokerResource = new ConfigResource(ConfigResource.Type.BROKER, "1")
    val keystorePassword = Map(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG -> sensitiveValue)
    verifyConfig(brokerResource, OpType.SET, keystorePassword, Map(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG -> Password.HIDDEN))

    val keystoreLocation = Map(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG -> "/path/to/keystore")
    verifyConfig(brokerResource, OpType.SET, keystoreLocation, keystoreLocation)
    verifyConfig(brokerResource, OpType.SET, keystoreLocation ++ keystorePassword,
      Map(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG -> "/path/to/keystore", SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG -> Password.HIDDEN))

    val listenerKeyPassword = Map(s"listener.name.internal.${SslConfigs.SSL_KEY_PASSWORD_CONFIG}" -> sensitiveValue)
    verifyConfig(brokerResource, OpType.SET, listenerKeyPassword,
      Map(s"listener.name.internal.${SslConfigs.SSL_KEY_PASSWORD_CONFIG}" -> Password.HIDDEN))

    val listenerKeystore = Map(s"listener.name.internal.${SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG}" -> "/path/to/keystore")
    verifyConfig(brokerResource, OpType.SET, listenerKeystore, listenerKeystore)

    val plainJaasConfig = Map(s"listener.name.internal.plain.${SaslConfigs.SASL_JAAS_CONFIG}" -> sensitiveValue)
    verifyConfig(brokerResource, OpType.SET, plainJaasConfig,
      Map(s"listener.name.internal.plain.${SaslConfigs.SASL_JAAS_CONFIG}" -> Password.HIDDEN))

    val plainLoginCallback = Map(s"listener.name.internal.plain.${SaslConfigs.SASL_LOGIN_CALLBACK_HANDLER_CLASS}" -> "test.LoginClass")
    verifyConfig(brokerResource, OpType.SET, plainLoginCallback, plainLoginCallback)

    val sslProtocols = Map(SslConfigs.SSL_ENABLED_PROTOCOLS_CONFIG -> "TLSv1.1")
    verifyConfig(brokerResource, OpType.APPEND, sslProtocols, Map(SslConfigs.SSL_ENABLED_PROTOCOLS_CONFIG -> "TLSv1.1"))
    verifyConfig(brokerResource, OpType.SUBTRACT, sslProtocols, Map(SslConfigs.SSL_ENABLED_PROTOCOLS_CONFIG -> "TLSv1.1"))
    val cipherSuites = Map(SslConfigs.SSL_CIPHER_SUITES_CONFIG -> null)
    verifyConfig(brokerResource, OpType.DELETE, cipherSuites, cipherSuites)

    val customConfig = Map("custom.config" -> sensitiveValue)
    verifyConfig(brokerResource, OpType.SET, customConfig, Map("custom.config" -> Password.HIDDEN))

    val topicResource = new ConfigResource(ConfigResource.Type.TOPIC, "testTopic")
    val compressionType = Map(TopicConfig.COMPRESSION_TYPE_CONFIG -> "lz4")
    verifyConfig(topicResource, OpType.SET, compressionType, compressionType)
    verifyConfig(topicResource, OpType.SET, customConfig, Map("custom.config" -> Password.HIDDEN))
  }

  @Test
  def testNonAlterRequestsNotTransformed(): Unit = {
    val metadataRequest = request(new MetadataRequest.Builder(List("topic").asJava, true).build())
    assertSame(metadataRequest.body[MetadataRequest], metadataRequest.loggableRequest)
  }

  @Test
  def testJsonRequests(): Unit = {
    val sensitiveValue = "secret"
    val resource = new ConfigResource(ConfigResource.Type.BROKER, "1")
    val keystorePassword = new ConfigEntry(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, sensitiveValue)
    val entries = Seq(keystorePassword)

    val alterConfigs = request(new AlterConfigsRequest.Builder(Collections.singletonMap(resource,
      new Config(entries.asJavaCollection)), true).build())

    assertTrue(isValidJson(RequestConvertToJson.request(alterConfigs.loggableRequest).toString))
  }

  @ParameterizedTest
  @EnumSource(value=classOf[Errors], names=Array("NONE", "CLUSTER_AUTHORIZATION_FAILED", "NOT_CONTROLLER"))
  def testBuildEnvelopeResponse(error: Errors): Unit = {
    val topic = "foo"
    val createTopicRequest = buildCreateTopicRequest(topic)
    val unwrapped = buildUnwrappedEnvelopeRequest(createTopicRequest)

    val createTopicResponse = buildCreateTopicResponse(topic, error)
    val envelopeResponse = buildEnvelopeResponse(unwrapped, createTopicResponse)

    error match {
      case Errors.NOT_CONTROLLER =>
        assertEquals(Errors.NOT_CONTROLLER, envelopeResponse.error)
        assertNull(envelopeResponse.responseData)
      case _ =>
        assertEquals(Errors.NONE, envelopeResponse.error)
        val unwrappedResponse = AbstractResponse.parseResponse(envelopeResponse.responseData, unwrapped.header)
        assertEquals(createTopicResponse.data, unwrappedResponse.data)
    }
  }

  private def buildCreateTopicRequest(topic: String): CreateTopicsRequest = {
    val requestData = new CreateTopicsRequestData()
    requestData.topics.add(new CreatableTopic()
      .setName(topic)
      .setReplicationFactor(-1)
      .setNumPartitions(-1)
    )
    new CreateTopicsRequest.Builder(requestData).build()
  }

  private def buildCreateTopicResponse(
    topic: String,
    error: Errors,
  ): CreateTopicsResponse = {
    val responseData = new CreateTopicsResponseData()
    responseData.topics.add(new CreateTopicsResponseData.CreatableTopicResult()
      .setName(topic)
      .setErrorCode(error.code)
    )
    new CreateTopicsResponse(responseData)
  }

  private def buildUnwrappedEnvelopeRequest(request: AbstractRequest): RequestChannel.Request = {
    val wrappedRequest = TestUtils.buildEnvelopeRequest(
      request,
      principalSerde,
      requestChannelMetrics,
      System.nanoTime()
    )

    val unwrappedRequest = new AtomicReference[RequestChannel.Request]()

    EnvelopeUtils.handleEnvelopeRequest(
      wrappedRequest,
      requestChannelMetrics,
      request => unwrappedRequest.set(request)
    )

    unwrappedRequest.get()
  }

  private def isValidJson(str: String): Boolean = {
    try {
      val mapper = new ObjectMapper
      mapper.readTree(str)
      true
    } catch {
      case _: IOException => false
    }
  }

  def request(req: AbstractRequest): RequestChannel.Request = {
    val buffer = req.serializeWithHeader(new RequestHeader(req.apiKey, req.version, "client-id", 1))
    val requestContext = newRequestContext(buffer)
    new network.RequestChannel.Request(processor = 1,
      requestContext,
      startTimeNanos = 0,
      mock(classOf[MemoryPool]),
      buffer,
      mock(classOf[RequestChannel.Metrics])
    )
  }

  private def newRequestContext(buffer: ByteBuffer): RequestContext = {
    new RequestContext(
      RequestHeader.parse(buffer),
      "connection-id",
      InetAddress.getLoopbackAddress,
      new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "user"),
      ListenerName.forSecurityProtocol(SecurityProtocol.PLAINTEXT),
      SecurityProtocol.PLAINTEXT,
      new ClientInformation("name", "version"),
      false)
  }

  private def toMap(config: Config): Map[String, String] = {
    config.entries.asScala.map(e => e.name -> e.value).toMap
  }

  private def toMap(config: IncrementalAlterConfigsRequestData.AlterableConfigCollection): Map[String, String] = {
    config.asScala.map(e => e.name -> e.value).toMap
  }

  private def buildEnvelopeResponse(
    unwrapped: RequestChannel.Request,
    response: AbstractResponse
  ): EnvelopeResponse = {
    assertTrue(unwrapped.envelope.isDefined)
    val envelope = unwrapped.envelope.get

    val send = unwrapped.buildResponseSend(response)
    val sendBytes = test.TestUtils.toBuffer(send)

    // We need to read the size field before `parseResponse` below
    val size = sendBytes.getInt
    assertEquals(size, sendBytes.remaining())
    val envelopeResponse = AbstractResponse.parseResponse(sendBytes, envelope.header)

    assertTrue(envelopeResponse.isInstanceOf[EnvelopeResponse])
    envelopeResponse.asInstanceOf[EnvelopeResponse]
  }
}


text:
require 'spec_helper'

# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator.  If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails.  There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec.  Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.

describe EventsController do
  include Devise::TestHelpers

  before do
    user = User.new name: 'Test User', email: 'example@example.com', password: 'changeme', password_confirmation: 'changeme'#, confirmed_at: 1.minute.ago
    user.skip_confirmation!
    user.save
    sign_in user

    @event = Event.create(name: 'weekly event', start_time: Time.utc(2014, 1, 3, 0).in_time_zone)
  end
  it "can retrieve an event" do
    Connectors::Meetup.stub(:events) { [double(name: 'weekly event', time: DateTime.new(2014,1,2,19,0,0,'-5'))] }
    get :show, id: @event.id, format: :json
    event = assigns[:event]
    event.name.should == 'weekly event'
    response.body.should == EventSerializer.new(event).to_json
  end

end


text:
'use strict';
const spawnpoint = require('..');
//const expect = require('unexpected');

describe('spawnpoint.isSecure', () => {
	if(typeof(process.getuid) === 'function' && process.getuid() === 0){
		it('Should error when run as root', () => {
		});
	}else{
		it('Should run successfully', () => {
			const app = new spawnpoint();
			app.isSecure();
			// TODO: handle user testing
		});
	}
});


text:
package xyz.brassgoggledcoders.moarcarts.mods.neotech.entities;

import net.minecraft.world.World;
import xyz.brassgoggledcoders.moarcarts.mods.neotech.items.ItemMinecartRFStorage;

public class EntityMinecartAdvancedRFStorage extends EntityMinecartBasicRFStorage
{
	public EntityMinecartAdvancedRFStorage(World world)
	{
		super(world, ItemMinecartRFStorage.StorageType.ADVANCED);
	}

	@Override
	public int getMetadata()
	{
		return ItemMinecartRFStorage.StorageType.ADVANCED.ordinal();
	}
}


text:
http://bioinf.spbau.ru/spades

## General design

Short reads aligner, using de Bruijn graphs for read assembly and
conflict resolution. SPAdes standalone was designed for use with
Illimuna and other short-read technology. It has since been expanded to
include the ability to align long-reads such as long produced by PacBio
SMRT systems (hybridSPAdes) and Illunia TruSeq (TruSPAdes). SPAdes was
designed with small, bacterial genomes in mind and has models for
chimeric read correction, rearrangements, and other assembler-intriduced
artifacting.

High level view of SPAdes assembly:

1. Assembly graph construction with multisized de Bruijn graphs (dBG)
and bulge resolution

2. Integration of Pair-end data with dBG-derived paths to determine
genomic distance

3. Paired assembly graph

4. Contig reconstruction

## Algorithm

1 Assembly graph construction

SPAdes derives its assembly graph construction model ("bulge
corremoval") from two previously published methods. dBG assemblers make
use of kmers to split reads for assembly, however kmer size is typically
a user-provided constraint and chosing the "wrong" size can result in
poor assemblies. SPAdes utilizes multisized de Bruijn graph which
integrate pairs of k-bimers over a predefined range of kmer sizes,
producing assembly graph DB\*(*Reads,k*). Graph bulges are resolved by
random mixing of DB\*(*Reads,k*), DB\*(*Reads,k'*),..., and chosing the
least tangled combination of split-paths.

2 Integration of k-bimer genomic distances

During Stage 1, genomic context of paired reads is not explicity
accounted for. Stage 2 begins by assuming read-pairs are at an estimated
genomic distance ≈ d0 and are linked within DB\*(*Reads,k*) by
*bireads*. Bireads decomposied by the *B-transformation* into k-bimers,
whose *biedges* are the genomic distance. The *H transform* maps the
biedges onto an assembly graph, and these values are sorted into a
histogram of estimated distances. The *A transform* uses the histogram
data to improve estimated distance. And finally, the *E transform* the
improved histogram back into to corrected/adjusted k-bimers.

For any given DB\*(*Reads,k*), the initial set of bireads, *B*ireads, is
transformed it into a set of adjusted k-bimers by the transform
E(A(H(B(Bireads)))

[Stage 2](/assets/spades_stage2.jpeg)

3 Paired de Bruijn graphs (PDBGs)

SPAdes makes use of a theoretical model, Paired de Bruijn graphs
(PDBGs), to resolve repeats and other sequence chimeras that are larger
than twice the read-size. Standard dBGs do not make use of mate-pair
information to "unwind" the graph for contig assembly. SPAdes integrated
mate-pair information in order to decrease the computation required and
the error introduced during repeat-resolution. For example: if 6 hubs
(uniqe kmers), K1, K2, etc, are interconnected with mutliple cycles
present (eg K1,K2,K3,K1,K5,K4,K6,K2), kmer distance computed in Stage 2
allows for the construction of PDBGs that remove ambiguity by only
selecting hubs which position fits the computed distance.

4 Contig reconstruction

PDBGs are unwound to reconstruct the sequence. Disjoint sets are
assigned to different contigs.


text:
package com.ibm.watson.assistant.v1.model;

import com.ibm.cloud.sdk.core.service.model.GenericModel;
import java.util.ArrayList;
import java.util.List;

/**
 * An object defining the message input, intents, and entities to be sent to the Watson Assistant
 * service if the user selects the corresponding disambiguation option.
 */
public class DialogSuggestionValue extends GenericModel {

  protected MessageInput input;
  protected List<RuntimeIntent> intents;
  protected List<RuntimeEntity> entities;

  /** Builder. */
  public static class Builder {
    private MessageInput input;
    private List<RuntimeIntent> intents;
    private List<RuntimeEntity> entities;

    private Builder(DialogSuggestionValue dialogSuggestionValue) {
      this.input = dialogSuggestionValue.input;
      this.intents = dialogSuggestionValue.intents;
      this.entities = dialogSuggestionValue.entities;
    }

    /** Instantiates a new builder. */
    public Builder() {}

    /**
     * Builds a DialogSuggestionValue.
     *
     * @return the new DialogSuggestionValue instance
     */
    public DialogSuggestionValue build() {
      return new DialogSuggestionValue(this);
    }

    /**
     * Adds an intents to intents.
     *
     * @param intents the new intents
     * @return the DialogSuggestionValue builder
     */
    public Builder addIntents(RuntimeIntent intents) {
      com.ibm.cloud.sdk.core.util.Validator.notNull(intents, "intents cannot be null");
      if (this.intents == null) {
        this.intents = new ArrayList<RuntimeIntent>();
      }
      this.intents.add(intents);
      return this;
    }

    /**
     * Adds an entities to entities.
     *
     * @param entities the new entities
     * @return the DialogSuggestionValue builder
     */
    public Builder addEntities(RuntimeEntity entities) {
      com.ibm.cloud.sdk.core.util.Validator.notNull(entities, "entities cannot be null");
      if (this.entities == null) {
        this.entities = new ArrayList<RuntimeEntity>();
      }
      this.entities.add(entities);
      return this;
    }

    /**
     * Set the input.
     *
     * @param input the input
     * @return the DialogSuggestionValue builder
     */
    public Builder input(MessageInput input) {
      this.input = input;
      return this;
    }

    /**
     * Set the intents. Existing intents will be replaced.
     *
     * @param intents the intents
     * @return the DialogSuggestionValue builder
     */
    public Builder intents(List<RuntimeIntent> intents) {
      this.intents = intents;
      return this;
    }

    /**
     * Set the entities. Existing entities will be replaced.
     *
     * @param entities the entities
     * @return the DialogSuggestionValue builder
     */
    public Builder entities(List<RuntimeEntity> entities) {
      this.entities = entities;
      return this;
    }
  }

  protected DialogSuggestionValue() {}

  protected DialogSuggestionValue(Builder builder) {
    input = builder.input;
    intents = builder.intents;
    entities = builder.entities;
  }

  /**
   * New builder.
   *
   * @return a DialogSuggestionValue builder
   */
  public Builder newBuilder() {
    return new Builder(this);
  }

  /**
   * Gets the input.
   *
   *
An input object that includes the input text.
   *
   * @return the input
   */
  public MessageInput input() {
    return input;
  }

  /**
   * Gets the intents.
   *
   *
An array of intents to be sent along with the user input.
   *
   * @return the intents
   */
  public List<RuntimeIntent> intents() {
    return intents;
  }

  /**
   * Gets the entities.
   *
   *
An array of entities to be sent along with the user input.
   *
   * @return the entities
   */
  public List<RuntimeEntity> entities() {
    return entities;
  }
}


text:
package betterwithmods.common.blocks;

import betterwithmods.common.BWMBlocks;
import betterwithmods.util.DirUtils;
import net.minecraft.block.Block;
import net.minecraft.block.material.EnumPushReaction;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EnumCreatureAttribute;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;

import javax.annotation.Nullable;
import java.util.List;
import java.util.Random;

public class BlockInvisibleLight extends BWMBlock {
    public static final PropertyBool SUNLIGHT = PropertyBool.create("sunlight");

    public BlockInvisibleLight() {
        super(Material.AIR);
        this.setLightLevel(1.0F);
        this.setTickRandomly(true);
        this.setDefaultState(this.blockState.getBaseState().withProperty(SUNLIGHT, false).withProperty(DirUtils.FACING, EnumFacing.UP));
    }

    @Override
    public EnumBlockRenderType getRenderType(IBlockState state) {
        return EnumBlockRenderType.INVISIBLE;
    }

    @Override
    public int tickRate(World world) {
        return 6;
    }

    @Override
    public boolean isOpaqueCube(IBlockState state) {
        return false;
    }

    @Override
    public boolean isFullCube(IBlockState state) {
        return false;
    }

    @Override
    public EnumPushReaction getMobilityFlag(IBlockState state) {
        return EnumPushReaction.DESTROY;
    }

    @Override
    public void onBlockAdded(World world, BlockPos pos, IBlockState state) {
        super.onBlockAdded(world, pos, state);
        world.scheduleUpdate(pos, this, 5);
    }

    @Override
    public int quantityDropped(Random rand) {
        return 0;
    }

    @Override
    @Nullable
    public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) {
        return NULL_AABB;
    }

    @Override
    public boolean canCollideCheck(IBlockState state, boolean playerActivated) {
        return false;
    }

    @Override
    public boolean isReplaceable(IBlockAccess worldIn, BlockPos pos) {
        return true;
    }

    @Override
    public void dropBlockAsItemWithChance(World world, BlockPos pos, IBlockState state, float f, int fortune) {
    }

    @Override
    public void neighborChanged(IBlockState state, World world, BlockPos pos, Block block, BlockPos other) {
        if (world.getBlockState(pos).getBlock() == BWMBlocks.LIGHT_SOURCE)
            world.setBlockToAir(pos);
    }

    @Override
    public void onEntityCollidedWithBlock(World world, BlockPos pos, IBlockState state, Entity entity) {
        if (!world.isRemote) {
            if (world.getBlockState(pos).getValue(SUNLIGHT)) {
                if (entity instanceof EntityLiving) {
                    EntityLiving living = (EntityLiving) entity;
                    if (living.getCreatureAttribute() == EnumCreatureAttribute.UNDEAD) {
                        living.setFire(4);
                    }
                }
            }
        }
    }

    @Override
    public void updateTick(World world, BlockPos pos, IBlockState state, Random rand) {
        if (!hasClearViewToLens(world, pos)) {
            world.setBlockToAir(pos);
        } else
            world.scheduleUpdate(pos, this, 5);
    }

    public EnumFacing getFacing(IBlockAccess world, BlockPos pos) {
        return world.getBlockState(pos).getValue(DirUtils.FACING);
    }

    public EnumFacing getFacing(IBlockState state) {
        return state.getValue(DirUtils.FACING);
    }

    public IBlockState setFacingInBlock(IBlockState state, EnumFacing facing) {
        return state.withProperty(DirUtils.FACING, facing);
    }

    private boolean hasClearViewToLens(World world, BlockPos pos) {
        boolean clear = true;
        EnumFacing face = getFacing(world.getBlockState(pos));
        for (int i = 1; i < 32; i++)//64 default, try to get some lag solved
        {
            BlockPos bPos = pos.offset(face, i);
            int x = bPos.getX();
            int y = bPos.getY();
            int z = bPos.getZ();
            List<Entity> entity = world.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(x, y, z, x + 1, y + 1, z + 1));
            if (entity.size() > 0)
                clear = false;
            else if (world.getBlockState(bPos).getBlock() == BWMBlocks.LIGHT_SOURCE)
                clear = false;
            else if (world.getBlockState(bPos).getBlock() == BWMBlocks.LENS) {
                BlockLens lens = (BlockLens) world.getBlockState(bPos).getBlock();
                return lens.getFacing(world, bPos) == DirUtils.getOpposite(getFacing(world, bPos));
            } else if (!world.isAirBlock(bPos))
                clear = false;
            if (!clear)
                break;
        }
        return clear;
    }

    @Override
    public IBlockState getStateFromMeta(int meta) {
        boolean sun = false;
        if (meta > 7) {
            sun = true;
            meta -= 8;
        }
        return this.getDefaultState().withProperty(SUNLIGHT, sun).withProperty(DirUtils.FACING, EnumFacing.getFront(meta));
    }

    @Override
    public int getMetaFromState(IBlockState state) {
        int meta = state.getValue(SUNLIGHT) ? 8 : 0;
        return meta + state.getValue(DirUtils.FACING).getIndex();
    }

    @Override
    protected BlockStateContainer createBlockState() {
        return new BlockStateContainer(this, DirUtils.FACING, SUNLIGHT);
    }
}


text:
extern crate vault;
extern crate libc;
extern crate rustc_serialize;

use std::collections::HashMap;
use std::env;
use std::error::Error;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::mem;
use std::path::Path;
use std::ptr;
use std::raw::Slice;
use std::string::String;
use std::sync::{Mutex};

use rustc_serialize::base64::FromBase64;

use libc::{c_int, size_t};

use rustc_serialize::json;
use rustc_serialize::json::DecodeResult;

use postgres_extension::*;
use vault::http::client::{Vault, AzureVault};

pg_module!(version: 90400);

lazy_static! {
    static ref CACHE: Mutex<HashMap<&'static str, VaultAuth>> =
        Mutex::new(HashMap::new());
}

#[derive(RustcEncodable, RustcDecodable, Debug, Clone, PartialEq)]
pub struct VaultAuth {
  pub vault_name: String,
  pub client_id: String,
  pub secret: String
}

#[pg_export]
pub fn encrypt(pg_key_name: *mut Text, pg_data: *mut Bytea) -> *mut Bytea {
    log_to_file(format!("ENTERING ENCRYPT...\n"));
    read_vault_creds();
    let lock = CACHE.lock().unwrap();
    let auth = lock.get("auth").unwrap();
    log_key_and_data(pg_key_name, pg_data);

    let key_name = string_from_pg_text(pg_key_name);
    let data_bytes = bytes_from_pg_bytes(pg_data);

    let mut client: AzureVault = Vault::new(&auth.vault_name[..], &auth.client_id[..], &auth.secret[..]);
    let encrypt_result = client.encrypt(&key_name[..], data_bytes);
    let encrypted_string = match encrypt_result {
        Ok(bits) => bits,
        Err(why) => {
            log_to_file(format!("Encrypt Error: {:?}...\n", why));
            panic!("failed to encrypt with key: {} {}\n", key_name, Error::description(&why));
        }
    };

    let un_base64 = encrypted_string[..].from_base64();
    log_to_file(format!("encrypted string: {:?}\n", encrypted_string));
    let mut into_bytes =  un_base64.unwrap();
    let mut mut_encrypted = &mut into_bytes[..];
    let pg_result = build_pg_data(mut_encrypted);

    // log_to_file(format!("string: {}\n", key_name));
    // log_to_file(format!("raw_bytes: {:?}\n", data_bytes));
    unsafe {
        log_to_file(format!("upper pg_result: {:?}\n", (*pg_result)));
    };

    log_to_file(format!("EXITING ENCRYPT...\n"));

    return pg_result;
}

#[pg_export]
pub fn decrypt(pg_key_name: *mut Text, pg_data: *mut Bytea) -> *mut Bytea {
    log_to_file(format!("ENTERING DECRYPT...\n"));
    read_vault_creds();
    let lock = CACHE.lock().unwrap();
    let auth = lock.get("auth").unwrap();
    log_key_and_data(pg_key_name, pg_data);

    let key_name = string_from_pg_text(pg_key_name);
    let data_bytes = bytes_from_pg_bytes(pg_data);

    let mut client: AzureVault = Vault::new(&auth.vault_name[..], &auth.client_id[..], &auth.secret[..]);

    log_to_file(format!("callin decrypt\n"));
    let decrypt_result = client.decrypt(&key_name[..], data_bytes);
    let decrypted_string = match decrypt_result {
        Ok(bits) => {
            log_to_file(format!("got some bits...\n"));
            bits
        },
        Err(why) => {
            log_to_file(format!("Decrypt Error: {:?}...\n", why));
            panic!("failed to decrypt with key: {} {}", key_name, Error::description(&why));
        }
    };

    let un_base64 = decrypted_string[..].from_base64();
    let mut into_bytes = un_base64.unwrap();
    log_to_file(format!("decrypted string: {:?}\n", String::from_utf8(into_bytes.clone())));
    let mut mut_decrypted = &mut into_bytes[..];
    let pg_result = build_pg_data(mut_decrypted);

    // log_to_file(format!("string: {}\n", key_name));
    // log_to_file(format!("raw_bytes: {:?}\n", data_bytes));
    // unsafe {
    //     log_to_file(format!("upper pg_result: {:?}\n", (*pg_result)));
    // };

    log_to_file(format!("EXITING DECRYPT...\n"));

    return pg_result;
}

fn build_pg_data(bytes: &mut [u8]) -> *mut Bytea{
    let pg_bytes = unsafe {
        let total_len = bytes.len() + 4;
        let pg_bytes = pg_malloc(total_len as size_t) as *mut Bytea;
        ptr::write_bytes(pg_bytes, 0, total_len as usize);
        (*pg_bytes).p.len = (total_len as u32) << 2;
        ptr::copy(bytes.as_mut_ptr(), (*pg_bytes).p.data.as_mut_ptr(), bytes.len());

        log_to_file(format!("the pg_bytes data... {:?}\n", (*pg_bytes)));
        log_to_file(format!("the bytes data... {:?}\n", bytes.len()));
        pg_bytes
    };

    return pg_bytes;
}

fn log_key_and_data(pg_key_name: *mut Text, pg_data: *mut Bytea) {
    unsafe {
        log_to_file(format!("the key data... {:?}\n", (*pg_key_name)));
        log_to_file(format!("the msg data... {:?}\n", (*pg_data)));
    };
}

fn read_vault_creds() {
    let mut path_buf = env::current_dir().unwrap();
    path_buf.push("vault");
    path_buf.set_extension("json");
    let path = path_buf.as_path();
    let display = path.display();

    // Locking block where cache is used to not require reopening the file
    let auth = {
        log_to_file(format!("Locking...\n"));
        let lock_result = CACHE.lock();
        let cache = lock_result.unwrap();
        log_to_file(format!("Unwrapped...\n"));
        let result = cache.get("auth").clone();
        match result {
            Some(auth) => {
                log_to_file(format!("auth: {:?}...\n", auth));
                auth.clone()
            },
            None => {
                log_to_file(format!("no auth...\n"));
                // log_to_file(format!("I'm starting...\n"));
                // Open the path in read-only mode, returns `io::Result<File>`
                let mut file = match File::open(&path) {
                    // The `description` method of `io::Error` returns a string that
                    // describes the error
                    Err(why) => {
                        log_to_file(format!("couldn't open {}: {}\n", display, why));
                        panic!("couldn't open {}: {}", display, why)
                    },
                    Ok(file) => file,
                };

                let mut file_string = String::new();
                // Read the file contents into a string, returns `io::Result<usize>`
                match file.read_to_string(&mut file_string) {
                    Err(why) => {
                        log_to_file(format!("couldn't read {}: {}\n", display, why));
                        panic!("couldn't read {}: {}", display, why)
                    },
                    Ok(_) => print!("{} contains:\n{}", display, file_string),
                };

                // log_to_file(format!("json read 1: {}", s));
                // log_to_file(format!("I'm decoding...\n"));
                let auth_result: DecodeResult<VaultAuth> = json::decode(&file_string[..]);
                match auth_result {
                    Ok(auth) => {
                        auth
                    },
                    Err(why) => {
                        // log_to_file(format!("json read 2: {}\n", s));
                        log_to_file(format!("error: {:?}\n", why));
                        log_to_file(format!("bad format for vault.json: {}\n", why));
                        panic!("bad format for vault.json: {}", why)
                    }
                }
            }
        }
    };
    log_to_file(format!("Locking again...\n"));
    let lock_result = CACHE.lock();
    let mut cache = lock_result.unwrap();
    log_to_file(format!("Inserting auth...\n"));
    cache.insert("auth", auth.clone());
}

fn string_from_pg_text(pg_text: *mut Text) -> String{
    log_to_file(format!("String from pg_text...\n"));
    let string = unsafe {
        log_to_file(format!("pg_text org size: {:?}...\n", (*pg_text).p.len));
        let total_len = ((*pg_text).p.len as u32 >> 2) & 0x3FFFFFFF;
        let data_size = total_len - 4; // subtract the 4 byte header
        log_to_file(format!("pg_text shrunk size: {:?}...\n", data_size));
        let ptr = (*pg_text).p.data.as_mut_ptr();
        String::from_raw_parts(ptr, data_size as usize, data_size as usize)
    };
    return string;
}

fn bytes_from_pg_bytes<'a>(pg_bytes: *mut Bytea) -> &'a [u8]{
    log_to_file(format!("Bytes from pg_bytes...\n"));
    let some_bytes: &[u8] = unsafe {
        log_to_file(format!("pg_bytes org size: {:?}...\n", (*pg_bytes).p.len));
        let total_len = ((*pg_bytes).p.len as u32 >> 2) & 0x3FFFFFFF;
        let data_size = total_len - 4; // subtract the 4 byte header
        log_to_file(format!("pg_bytes shrunk size: {:?}...\n", data_size));
        let ptr = (*pg_bytes).p.data.as_mut_ptr();
        let raw_bytes: Slice<u8> = Slice {
            data: ptr,
            len: data_size as usize
        };
        log_to_file(format!("pg_bytes got the raw...\n"));
        mem::transmute(raw_bytes)
    };
    log_to_file(format!("pg_bytes transmuted, len: {}...\n", some_bytes.len()));
    return some_bytes;
}

fn log_to_file(text: String){
    let path = Path::new("test.txt");
    let display = path.display();

    // Open a file in write-only mode, returns `io::Result<File>`
    let mut file = match OpenOptions::new().write(true).create(true).append(true).open("test.txt") {
        Err(why) => panic!("couldn't create {}: {}",
                           display,
                           Error::description(&why)),
        Ok(file) => file,
    };

    // Write the `LOREM_IPSUM` string to `file`, returns `io::Result<()>`
    match file.write_all(text.as_bytes()) {
        Err(why) => {
            panic!("couldn't write to {}: {}", display,
                                               Error::description(&why))
        },
        Ok(_) => println!("successfully wrote to {}", display),
    }
}


text:
package br.gov.siscomex.portalunico.duimp_api.model;

import java.util.List;

import javax.validation.Valid;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import com.fasterxml.jackson.annotation.JsonProperty;

import io.swagger.annotations.ApiModelProperty;

@XmlAccessorType(XmlAccessType.FIELD)
 @XmlType(name = "RespostaApiErro", propOrder =
    { "message", "identificacao", "errors"
})

@XmlRootElement(name="RespostaApiErro")
public class RespostaApiErro  {

  @XmlElement(name="message")
  @ApiModelProperty(example = "Mensagem de exemplo.", value = "Mensagem de resposta do resultado da operação.")
 /**
   * Mensagem de resposta do resultado da operação.
  **/
  private String message = null;

  @XmlElement(name="identificacao")
  @ApiModelProperty(value = "")
  @Valid
  private IdentificacaoDuimpRespostaApi identificacao = null;

  @XmlElement(name="errors")
  @ApiModelProperty(value = "Conjunto de erros de validação dos campos. Devolvido apenas para erros HTTP 422.
 Esta é uma lista opcional e fornece o detalhamento de todos os erros que deram origem ao erro 422
 Quando houver mais de um erro, essa lista será preenchida com cada um dos erros
 Exemplo: A lista detalhada dos problemas encontrados em um item, quando for gerado um erro 422 ao validar a inclusão de um item.")
  @Valid
 /**
   * Conjunto de erros de validação dos campos. Devolvido apenas para erros HTTP 422.
 Esta é uma lista opcional e fornece o detalhamento de todos os erros que deram origem ao erro 422
 Quando houver mais de um erro, essa lista será preenchida com cada um dos erros
 Exemplo: A lista detalhada dos problemas encontrados em um item, quando for gerado um erro 422 ao validar a inclusão de um item.
  **/
  private List<DuimpApiMessageCover> errors = null;
 /**
   * Mensagem de resposta do resultado da operação.
   * @return message
  **/
  @JsonProperty("message")
  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public RespostaApiErro message(String message) {
    this.message = message;
    return this;
  }

 /**
   * Get identificacao
   * @return identificacao
  **/
  @JsonProperty("identificacao")
  public IdentificacaoDuimpRespostaApi getIdentificacao() {
    return identificacao;
  }

  public void setIdentificacao(IdentificacaoDuimpRespostaApi identificacao) {
    this.identificacao = identificacao;
  }

  public RespostaApiErro identificacao(IdentificacaoDuimpRespostaApi identificacao) {
    this.identificacao = identificacao;
    return this;
  }

 /**
   * Conjunto de erros de validação dos campos. Devolvido apenas para erros HTTP 422. <br> Esta é uma lista opcional e fornece o detalhamento de todos os erros que deram origem ao erro 422<br> Quando houver mais de um erro, essa lista será preenchida com cada um dos erros<br> <b>Exemplo:</b> A lista detalhada dos problemas encontrados em um item, quando for gerado um erro 422 ao validar a inclusão de um item.
   * @return errors
  **/
  @JsonProperty("errors")
  public List<DuimpApiMessageCover> getErrors() {
    return errors;
  }

  public void setErrors(List<DuimpApiMessageCover> errors) {
    this.errors = errors;
  }

  public RespostaApiErro errors(List<DuimpApiMessageCover> errors) {
    this.errors = errors;
    return this;
  }

  public RespostaApiErro addErrorsItem(DuimpApiMessageCover errorsItem) {
    this.errors.add(errorsItem);
    return this;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class RespostaApiErro {\n");

    sb.append("    message: ").append(toIndentedString(message)).append("\n");
    sb.append("    identificacao: ").append(toIndentedString(identificacao)).append("\n");
    sb.append("    errors: ").append(toIndentedString(errors)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private static String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
namespace SharpStore
{
    using System.Collections.Generic;
    using System.IO;
    using SimpleHttpServer;
    using SimpleHttpServer.Enums;
    using SimpleHttpServer.Models;

    public class SharpStore
    {
        public static void Main()
        {
            var routes = new List<Route>()
            {
                new Route
                {
                    Name = "Home Directory",
                    Method = RequestMethod.GET,
                    UrlRegex = "^/home$",
                    Callable = (request) =>
                    {
                        return new HttpResponse
                        {
                            StatusCode = ResponseStatusCode.OK,
                            ContentAsUTF8 = File.ReadAllText("../../content/home.html")
                        };
                    }
                },
                new Route
                {
                    Name = "Carousel CSS",
                    Method = RequestMethod.GET,
                    UrlRegex = "^/content/css/carousel.css$",
                    Callable = (request) =>
                    {
                        var response = new HttpResponse
                        {
                            StatusCode = ResponseStatusCode.OK,
                            ContentAsUTF8 = File.ReadAllText("../../content/css/carousel.css")
                        };

                        response.Header.ContentType = "text/css";
                        return response;
                    }
                },
                new Route
                {
                    Name = "Bootstrap JS",
                    Method = RequestMethod.GET,
                    UrlRegex = "^/bootstrap/js/bootstrap.min.js$",
                    Callable = (request) =>
                    {
                        var response = new HttpResponse
                        {
                            StatusCode = ResponseStatusCode.OK,
                            ContentAsUTF8 = File.ReadAllText("../../content/bootstrap/js/bootstrap.min.js")
                        };

                        response.Header.ContentType = "application/x-javascript";
                        return response;
                    }
                },
                new Route
                {
                    Name = "Bootstrap CSS",
                    Method = RequestMethod.GET,
                    UrlRegex = "^/bootstrap/css/bootstrap.min.css$",
                    Callable = (request) =>
                    {
                        var response = new HttpResponse
                        {
                            StatusCode = ResponseStatusCode.OK,
                            ContentAsUTF8 = File.ReadAllText("../../content/bootstrap/css/bootstrap.min.css")
                        };

                        response.Header.ContentType = "text/css";
                        return response;
                    }
                },
                new Route
                {
                    Name = "About Directory",
                    Method = RequestMethod.GET,
                    UrlRegex = "^/about$",
                    Callable = (request) =>
                    {
                        return new HttpResponse
                        {
                            StatusCode = ResponseStatusCode.OK,
                            ContentAsUTF8 = File.ReadAllText("../../content/about.html")
                        };
                    }
                },
                new Route
                {
                    Name = "Products Directory",
                    Method = RequestMethod.GET,
                    UrlRegex = "^/products$",
                    Callable = request =>
                    {
                        return new HttpResponse
                        {
                            StatusCode = ResponseStatusCode.OK,
                            ContentAsUTF8 = File.ReadAllText("../../content/products.html")
                        };
                    }
                }
            };

            var server = new HttpServer(8081, routes);
            server.Listen();
        }
    }
}


text:
#ifndef SESSION_H
#define SESSION_H

#include <iostream>
#include <memory>
#include <map>
#include <vector>

#include "Internal.h"
#include "Struct.h"
#include "Tree.h"
#include "Sysrepo.h"
#include "Connection.h"
#include "Session.h"

extern "C" {
#include "sysrepo.h"
}

using namespace std;

class Session
{

public:
    Session(S_Connection conn, sr_datastore_t datastore = (sr_datastore_t) DS_RUNNING, \
            const sr_sess_options_t opts = SESS_DEFAULT, const char *user_name = NULL);
    Session(sr_session_ctx_t *sess, sr_sess_options_t opts = SESS_DEFAULT);
    void session_stop();
    void session_switch_ds(sr_datastore_t ds);
    S_Error get_last_error();
    S_Errors get_last_errors();
    S_Schemas list_schemas();
    S_Schema_Content get_schema(const char *module_name, const char *revision,\
                               const char *submodule_name, sr_schema_format_t format);
    S_Val get_item(const char *xpath);
    S_Vals get_items(const char *xpath);
    S_Iter_Value get_items_iter(const char *xpath);
    S_Val get_item_next(S_Iter_Value iter);
    S_Tree get_subtree(const char *xpath, sr_get_subtree_options_t opts = GET_SUBTREE_DEFAULT);
    S_Trees get_subtrees(const char *xpath, sr_get_subtree_options_t opts = GET_SUBTREE_DEFAULT);

    void set_item(const char *xpath, S_Val value = NULL, const sr_edit_options_t opts = EDIT_DEFAULT);
    void delete_item(const char *xpath, const sr_edit_options_t opts = EDIT_DEFAULT);
    void move_item(const char *xpath, const sr_move_position_t position, const char *relative_item = NULL);
    void refresh();
    void validate();
    void commit();
    void lock_datastore();
    void unlock_datastore();
    void lock_module(const char *module_name);
    void unlock_module(const char *module_name);
    void discard_changes();
    void copy_config(const char *module_name, sr_datastore_t src_datastore, sr_datastore_t dst_datastore);
    void set_options(const sr_sess_options_t opts);
    ~Session();
    sr_session_ctx_t *get() {return _sess;};

private:
    sr_session_ctx_t *_sess;
    sr_datastore_t _datastore;
    sr_sess_options_t _opts;
    S_Connection _conn;
};

class Callback
{
public:
    Callback();
    virtual ~Callback();

    virtual void module_change(S_Session session, const char *module_name, sr_notif_event_t event, void *private_ctx) {return;};
    virtual void subtree_change(S_Session session, const char *xpath, sr_notif_event_t event, void *private_ctx) {return;};
    virtual void module_install(const char *module_name, const char *revision, sr_module_state_t state, void *private_ctx) {return;};
    virtual void feature_enable(const char *module_name, const char *feature_name, bool enabled, void *private_ctx) {return;};
    virtual void rpc(const char *xpath, S_Vals input, S_Vals_Holder output, void *private_ctx) {return;};
    virtual void rpc_tree(const char *xpath, S_Trees input, S_Trees_Holder output, void *private_ctx) {return;};
    virtual void dp_get_items(const char *xpath, S_Vals_Holder vals, void *private_ctx) {return;};
    virtual void event_notif(const char *xpath, S_Vals vals, void *private_ctx) {return;};
    virtual void event_notif_tree(const char *xpath, S_Trees trees, void *private_ctx) {return;};
    Callback *get() {return this;};

    std::map<const char *, void*> private_ctx;
};

class Subscribe
{

public:
    Subscribe(S_Session sess);

    void module_change_subscribe(const char *module_name, S_Callback callback, void *private_ctx = NULL, uint32_t priority = 0, sr_subscr_options_t opts = SUBSCR_DEFAULT);
    void subtree_change_subscribe(const char *xpath, S_Callback callback, void *private_ctx = NULL, uint32_t priority = 0, sr_subscr_options_t opts = SUBSCR_DEFAULT);
    void module_install_subscribe(S_Callback callback, void *private_ctx = NULL, sr_subscr_options_t opts = SUBSCR_DEFAULT);
    void feature_enable_subscribe(S_Callback callback, void *private_ctx = NULL, sr_subscr_options_t opts = SUBSCR_DEFAULT);
    void rpc_subscribe(const char *xpath, S_Callback callback, void *private_ctx = NULL, sr_subscr_options_t opts = SUBSCR_DEFAULT);
    void event_notif_subscribe_tree(const char *xpath, S_Callback callback, void *private_ctx = NULL, sr_subscr_options_t opts = SUBSCR_DEFAULT);
    void event_notif_subscribe(const char *xpath, S_Callback callback, void *private_ctx = NULL, sr_subscr_options_t opts = SUBSCR_DEFAULT);
    void rpc_subscribe_tree(const char *xpath, S_Callback callback, void *private_ctx = NULL, sr_subscr_options_t opts = SUBSCR_DEFAULT);
    void dp_get_items_subscribe(const char *xpath, S_Callback callback, void *private_ctx = NULL, sr_subscr_options_t opts = SUBSCR_DEFAULT);
    std::vector<S_Callback > cb_list;

    void unsubscribe();
    S_Iter_Change get_changes_iter(const char *xpath);
    S_Change get_change_next(S_Iter_Change iter);
    S_Vals rpc_send(const char *xpath, S_Vals input);
    S_Trees rpc_send_tree(const char *xpath, S_Trees input);
    ~Subscribe();

    // SWIG specific
    sr_subscription_ctx_t *swig_sub;
    S_Session swig_sess;
    std::vector<void*> wrap_cb_l;
    void additional_cleanup(void *private_ctx) {return;};

private:
    sr_subscription_ctx_t *_sub;
    S_Session _sess;
};

#endif


text:
package org.librairy.modeler.lda.optimizers;

import org.librairy.boot.model.domain.resources.Resource;
import org.librairy.boot.storage.generator.URIGenerator;
import org.librairy.modeler.lda.cache.IterationsCache;
import org.librairy.modeler.lda.models.Corpus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;

/**
 * Created on 01/09/16:
 *
 * @author cbadenes
 */
@Component
//@Conditional(BasicOptimizerCondition.class)
public class BasicOptimizer implements LDAOptimizer{

    @Autowired
    IterationsCache iterationsCache;

    @Override
    public String getId() {
        return "basic";
    }

    @Override
    public LDAParameters getParametersFor(Corpus corpus) {

        String domainUri = URIGenerator.fromId(Resource.Type.DOMAIN, corpus.getId());

        LDAParameters parameters = new LDAParameters();
        Integer numTopics = Double.valueOf(2*Math.sqrt(corpus.getSize()/2)).intValue();
        parameters.setK(numTopics != 0? numTopics : 2);
        parameters.setBeta(-1.0);
        parameters.setAlpha(-1.0);
        parameters.setIterations(iterationsCache.getIterations(domainUri));
        return parameters;
    }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<ns2:persons_common xmlns:ns2="http://collectionspace.org/services/person">
  <personTermGroupList>
    <personTermGroup>
      <termName>John Wayne</termName>
      <termPrefForLang>false</termPrefForLang>
      <termDisplayName>John Wayne May 26, 1907-June 11, 1979</termDisplayName>
      <foreName>John</foreName>
      <middleName/>
      <surName>Wayne</surName>
      <initials>JW</initials>
      <nameAdditions>The Duke</nameAdditions>
      <salutation>Mr.</salutation>
      <title/>
    </personTermGroup>
  </personTermGroupList>
  <birthDateGroup>
      <dateEarliestSingleQualifier/>
      <scalarValuesComputed>true</scalarValuesComputed>
      <dateLatestDay/>
      <dateLatestYear/>
      <dateAssociation/>
      <dateEarliestSingleEra/>
      <dateDisplayDate>May 26, 1907</dateDisplayDate>
      <dateEarliestSingleCertainty/>
      <dateLatestEra/>
      <dateEarliestSingleQualifierValue/>
      <dateLatestCertainty/>
      <dateEarliestSingleYear/>
      <dateLatestQualifier/>
      <dateLatestQualifierValue/>
      <dateEarliestSingleQualifierUnit/>
      <datePeriod/>
      <dateEarliestScalarValue/>
      <dateLatestMonth/>
      <dateNote/>
      <dateLatestScalarValue/>
      <dateLatestQualifierUnit/>
      <dateEarliestSingleDay/>
      <dateEarliestSingleMonth/>
  </birthDateGroup>
  <birthPlace>urn:cspace:org.collectionspace.demo:location:name(Museum):item:name(IA_Winterset)'Winterset, Iowa'</birthPlace>
  <deathDateGroup>
      <dateEarliestSingleQualifier/>
      <scalarValuesComputed>true</scalarValuesComputed>
      <dateLatestDay/>
      <dateLatestYear/>
      <dateAssociation/>
      <dateEarliestSingleEra/>
      <dateDisplayDate>June 11, 1979</dateDisplayDate>
      <dateEarliestSingleCertainty/>
      <dateLatestEra/>
      <dateEarliestSingleQualifierValue/>
      <dateLatestCertainty/>
      <dateEarliestSingleYear/>
      <dateLatestQualifier/>
      <dateLatestQualifierValue/>
      <dateEarliestSingleQualifierUnit/>
      <datePeriod/>
      <dateEarliestScalarValue/>
      <dateLatestMonth/>
      <dateNote/>
      <dateLatestScalarValue/>
      <dateLatestQualifierUnit/>
      <dateEarliestSingleDay/>
      <dateEarliestSingleMonth/>
  </deathDateGroup>
  <deathPlace/>
  <bioNote>born Marion Robert Morrison and better known by his stage name John Wayne, was an
    American film actor, director and producer. He epitomized rugged masculinity and has become an
    enduring American icon. He is famous for his distinctive voice, walk and height. He was also
    known for his conservative political views and his support in the 1950s for anti-communist
    positions. </bioNote>
  <nameNote>Screen name</nameNote>
</ns2:persons_common>


text:
package org.apache.juddi.v3.client.mapping;

import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class URLLocalizerDefaultImpl implements URLLocalizer {

	URL baseUrl;

	public URLLocalizerDefaultImpl() {
		super();
	}
	public URLLocalizerDefaultImpl(URL baseUrl) {
		super();
		this.baseUrl = baseUrl;
	}

	private Log log = LogFactory.getLog(this.getClass());

	public String rewrite (URL urlIn) {
		return rewriteURL(urlIn).toExternalForm();
	}

	public String rewriteToWSDLURL (URL urlIn) {
		URL url = rewriteURL(urlIn);
		return url.toExternalForm() + "?wsdl";
	}

	public URL rewriteURL(URL urlIn) {
		URL url = null;
		if (baseUrl!=null && url == null) {
			try {
				url = new URL(baseUrl.getProtocol(),
							baseUrl.getHost(),
							baseUrl.getPort(),
							urlIn.getPath());
			} catch (MalformedURLException e) {
				log.error(e.getMessage(),e);
			}
		} else {
			url = urlIn;
		}
		return url;
	}

	public void setBaseUrl(URL baseUrl) {
		this.baseUrl = baseUrl;
	}

}


text:
import { object, array, string, boolean, number, ref, ObjectSchema } from 'yup'

import { userInputsToObject, userInputsToArray } from 'client/models/Helper'
import {
  UserInputType,
  T,
  INPUT_TYPES,
  USER_INPUT_TYPES,
} from 'client/constants'
import {
  Field,
  arrayToOptions,
  sentenceCase,
  getObjectSchemaFromFields,
} from 'client/utils'

const {
  password: uiPassword,
  list: uiList,
  listMultiple: uiListMultiple,
  number: uiNumber,
  numberFloat: uiNumberFloat,
  range: uiRange,
  rangeFloat: uiRangeFloat,
  boolean: uiBoolean,
} = USER_INPUT_TYPES

const { array: _array, fixed: _fixed, ...userInputTypes } = USER_INPUT_TYPES

/** @type {UserInputType[]} User inputs types */
const valuesOfUITypes = Object.values(userInputTypes)

/** @type {Field} Type field */
const TYPE = {
  name: 'type',
  label: T.Type,
  type: INPUT_TYPES.SELECT,
  values: arrayToOptions(valuesOfUITypes, {
    addEmpty: false,
    getText: (type) => sentenceCase(type),
  }),
  validation: string()
    .trim()
    .required()
    .oneOf(valuesOfUITypes)
    .default(() => valuesOfUITypes[0]),
  grid: { sm: 6, md: 4 },
}

/** @type {Field} Name field */
const NAME = {
  name: 'name',
  label: T.Name,
  type: INPUT_TYPES.TEXT,
  validation: string()
    .trim()
    .required()
    .default(() => undefined),
  grid: { sm: 6, md: 4 },
}

/** @type {Field} Description field */
const DESCRIPTION = {
  name: 'description',
  label: T.Description,
  type: INPUT_TYPES.TEXT,
  validation: string()
    .trim()
    .notRequired()
    .default(() => undefined),
  grid: { sm: 6, md: 4 },
}

/** @type {Field} Options field */
const OPTIONS = {
  name: 'options',
  label: T.Options,
  tooltip: [T.PressKeysToAddAValue, ['ENTER']],
  dependOf: TYPE.name,
  type: INPUT_TYPES.AUTOCOMPLETE,
  multiple: true,
  htmlType: (type) =>
    ![uiList, uiListMultiple].includes(type) && INPUT_TYPES.HIDDEN,
  validation: array(string().trim())
    .default(() => [])
    .when(TYPE.name, (type, schema) =>
      [uiList, uiListMultiple].includes(type)
        ? schema.required().min(1)
        : schema.strip().notRequired()
    ),
  fieldProps: {
    freeSolo: true,
    placeholder: 'optA,optB,optC',
  },
  grid: { md: 8 },
}

/** @type {{ MIN: Field, MAX: Field }} Range fields */
const { MIN, MAX } = (() => {
  const validation = number()
    .positive()
    .default(() => undefined)
    .when(TYPE.name, (type, schema) =>
      [uiRange, uiRangeFloat].includes(type)
        ? schema.required()
        : schema.strip().notRequired()
    )

  const common = {
    dependOf: TYPE.name,
    type: INPUT_TYPES.TEXT,
    htmlType: (type) =>
      [uiRange, uiRangeFloat].includes(type) ? 'number' : INPUT_TYPES.HIDDEN,
    grid: { sm: 6, md: 4 },
    fieldProps: (type) => ({ step: type === uiRangeFloat ? 0.01 : 1 }),
  }

  return {
    MIN: {
      ...common,
      name: 'min',
      label: T.Min,
      validation: validation.lessThan(ref('max')),
    },
    MAX: {
      ...common,
      name: 'max',
      label: T.Max,
      validation: validation.moreThan(ref('min')),
    },
  }
})()

/** @type {Field} Default value field */
const DEFAULT_VALUE = {
  name: 'default',
  label: T.DefaultValue,
  dependOf: [TYPE.name, OPTIONS.name],
  type: ([type] = []) =>
    [uiBoolean, uiList, uiListMultiple].includes(type)
      ? INPUT_TYPES.SELECT
      : INPUT_TYPES.TEXT,
  htmlType: ([type] = []) =>
    ({
      [uiNumber]: 'number',
      [uiNumberFloat]: 'number',
      [uiPassword]: INPUT_TYPES.HIDDEN,
    }[type]),
  multiple: ([type] = []) => type === uiListMultiple,
  values: ([type, options = []] = []) =>
    type === uiBoolean
      ? arrayToOptions(['NO', 'YES'])
      : arrayToOptions(options),
  validation: string()
    .trim()
    .default(() => undefined)
    .when(
      [TYPE.name, OPTIONS.name],
      (type, options = [], schema) =>
        ({
          [uiList]: schema.oneOf(options).notRequired(),
          [uiListMultiple]: schema.includesInOptions(options),
          [uiRange]: number().min(ref(MIN.name)).max(ref(MAX.name)).integer(),
          [uiRangeFloat]: number().min(ref(MIN.name)).max(ref(MAX.name)),
          [uiPassword]: schema.strip().notRequired(),
        }[type] ?? schema)
    ),
  grid: { sm: 6, md: 4 },
}

/** @type {Field} Mandatory field */
const MANDATORY = {
  name: 'mandatory',
  label: T.Mandatory,
  type: INPUT_TYPES.SWITCH,
  validation: boolean().default(() => false),
  grid: { md: 12 },
}

/** @type {Field[]} List of User Inputs fields */
export const USER_INPUT_FIELDS = [
  TYPE,
  NAME,
  DESCRIPTION,
  DEFAULT_VALUE,
  OPTIONS,
  MIN,
  MAX,
  MANDATORY,
]

/** @type {ObjectSchema} User Input object schema */
export const USER_INPUT_SCHEMA = getObjectSchemaFromFields(USER_INPUT_FIELDS)

/** @type {ObjectSchema} User Inputs schema */
export const USER_INPUTS_SCHEMA = object({
  USER_INPUTS: array(USER_INPUT_SCHEMA)
    .ensure()
    .afterSubmit((userInputs, { context }) => {
      const capacityInputs = userInputsToArray(context?.general?.MODIFICATION, {
        filterCapacityInputs: false,
      }).map(({ name, ...userInput }) => ({
        name,
        ...userInput,
        // set default value from MEMORY, CPU and VCPU fields
        default: context.general?.[name],
        ...(['MEMORY', 'CPU'].includes(name) && { mandatory: true }),
      }))

      return userInputsToObject([...capacityInputs, ...userInputs])
    }),
  INPUTS_ORDER: string()
    .trim()
    .afterSubmit((_inputsOrder_, { context }) => {
      const userInputs = context?.extra?.USER_INPUTS

      return userInputs
        ?.filter(({ name }) => !['MEMORY', 'CPU', 'VCPU'].includes(name))
        ?.map(({ name }) => String(name).toUpperCase())
        .join(',')
    }),
})


text:
"use strict";
var chai = require("chai");
var sinon = require("sinon");
var sinonChai = require("sinon-chai");
var expect = chai.expect;
chai.use(sinonChai);

var proxyquire = require("proxyquire");
var aMockResponse = require('../../../glue').aMockResponse;

var requiredModule = {
    '../../model/user': {login:sinon.stub()}
};

var login = proxyquire('../../../main/routes/operations/login', requiredModule);

describe('login', function() {
    var dummyCollection = {};
    var dummyConnection = {
        collection: sinon.stub().returns(dummyCollection)
    };
    var dummyUsername = {};
    var dummyPassword = {};

    var request = {
        params: {},
        connection: dummyConnection,
        cookies: {},
        body: {
            username: dummyUsername,
            password: dummyPassword
        }
    };
    var response = aMockResponse();
    var next = sinon.spy();

    it('should break the router chain', function() {
        login(request, response, next);

        expect( next ).not.to.have.been.called ;
    });

    describe('if no user is present on the cookie', function() {
        it('should call authenticationProvider.secureLogin with req.collection, req.body.username, req.body.password and a callback', function() {
            login(request, response, next);

            expect ( requiredModule['../../model/user'].login ).to.have.been.calledWith( dummyCollection, dummyUsername, dummyPassword );
        });

        describe('if secureLogin returns an error', function() {
            var anError = {some: 'error'};
            var requiredModule = {
                '../../model/user': {login:sinon.stub().callsArgWith(3, anError, {})}
            };

            var login = proxyquire('../../../main/routes/operations/login', requiredModule);

            it('should set the response status to 403', function() {
                login(request, response, next);

                expect( response.status ).to.have.been.calledWith( 403 );
            });

            it('should send the error in the response', function() {
                login(request, response, next);

                expect( response.send ).to.have.been.calledWith( anError );
            });

        });

        describe('if secureLogin returns data', function() {
            var someData = {some: 'data'};
            var requiredModule = {
                '../../model/user': {login:sinon.stub().callsArgWith(3, null, someData)}
            };

            var login = proxyquire('../../../main/routes/operations/login', requiredModule);

            it('should send the data in the response', function() {
                login(request, response, next);

                expect( response.send ).to.have.been.calledWith(someData);
            });

            it('if (request.rememberMe)', function() {
                var requestWithRememberMe = request;
                requestWithRememberMe.body.rememberMe = true;

                login(request, response, next);

                expect( response.cookie ).to.have.been.calledWith('user', someData, { maxAge: 900000 });
            });

        });

    });

    describe('if there is a user on the cookie', function() {
        it('should send the user back on the response', function() {
            var request = {
                cookies: {
                    user: 'some user'
                }
            };

            var login = proxyquire('../../../main/routes/operations/login', requiredModule);

            login(request, response, next);

            expect( response.send).to.have.been.calledWith( 'some user' );

        })

    });

});


text:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>asdasd</title>
</head>
<body aurelia-app>
    <script src="jspm_packages/system.js"></script>
    <script src="config.js"></script>
    <script> System.import('aurelia-bootstrapper')</script>
</body>
</html>


text:
require 'sinatra'

get '/' do
  200
end

get '/:status_code?' do
  code = params[:status_code].to_i

  # Add any addtional code here

  code
end


text:
'use strict';

var myApp = angular.module('my-app', [
  'ngMaterial',
  'ngSanitize',
  'ui.router',
  'main',
  'welcome',
  'my-disasters.my-disasters',
  'weather',
  'my-app.my-map',
  'angular-jwt',
  'angular-storage',
  'btford.socket-io',
  'angular-notification-icons',
  'jkAngularCarousel'
]);

myApp.factory('socket', function (socketFactory) {
  return socketFactory({
    ioSocket: io.connect('http://localhost:3300')
  });
});

myApp.controller('AppCtrl',AppCtrl);

myApp.config(function($locationProvider,$mdThemingProvider,$stateProvider,$urlRouterProvider) {
    var mycolor = $mdThemingProvider.extendPalette('indigo');
    $mdThemingProvider.definePalette('mycolor', mycolor);

    $mdThemingProvider.theme('default')
    .primaryPalette('indigo',{'default': '800'})
    .accentPalette('indigo', {'default': '600'});

    $stateProvider
      .state("main",{
        url: "/main",
        templateUrl: "main/app.html",
        redirectTo: 'main.weather.list',
        data: {
          requiresLogin: true
        }
      })
      .state("main.disasters",{
        url: "/disasters",
        templateUrl: "templates/disasters.html",
        data: {
          requiresLogin: true
        }
      })
      .state("welcome",{
          url: "/welcome",
          templateUrl: "home/index.html"
        }
      );

    $urlRouterProvider.otherwise("/welcome");
});

myApp.run(function($rootScope, $state, store, jwtHelper) {
  $rootScope.$on('$stateChangeStart', function(e, to,params) {
    if (to.redirectTo){
      e.preventDefault();
      $state.go(to.redirectTo, params, {location: 'replace'})
    }
    if (to.data && to.data.requiresLogin){
      if (!store.get('jwt') || jwtHelper.isTokenExpired(store.get('jwt'))) {
        e.preventDefault();
        $state.go("welcome",{},{reload: true});
      }
    }
  });
});

function AppCtrl () {

}


text:
layout:      page
title:       Artof Comments - Disqus Support for Joomla 2.5/3.0
description: ArtofComments is a Joomla 2.5/3.0 plugin that provides Disqus comment support for Joomla articles. What sets ArtofComments apart is the tight integration with Joomla forms. Comments are enabled within the edit form for an article or category - no need to remember dozens of category or article id's.
date:        2013-01-19 10:00:00
image:
  feature: abstract-7.jpg
  credit: dargadgetz
  creditlink: http://www.dargadgetz.com/ios-7-abstract-wallpaper-pack-for-iphone-5-and-ipod-touch-retina/
comments: false
reading_time: false
---
**DOWNLOAD VERSION 1.1 NOW**
Joomla 2.5/3.0 --- [ZIP Format][0]
Last updated {{ page.date | date: "%B %d, %Y" }} ![Compatible with Joomla 2.5](/images/software/joomla/compat_25.png) ![Compatible with Joomla 3.0](/images/software/joomla/compat_30.png)

**ArtofComments** is a Joomla 2.5/3.0 plugin that provides Disqus comment support for Joomla articles.

What sets ArtofComments apart is the tight integration with Joomla forms. Comments are enabled within the edit form for an article or category - no need to remember dozens of category or article id's.

[![Screenshot](/images/software/artofcomments/artofcomments_display.jpg)][1]

## Features

* Enable or disable comments for any category - right in the edit form.
* Enable or disable comments for single articles - right in the article edit form.
* Support Disqus developer mode to test comments on local testing sites.

## Requirements

* Joomla 2.5 or 3.0
* **PHP 5.3+**

## Packing List

All extensions are automatically installed from the one package.

* The ArtofComments content plugin.
* English language files.

## License and Support

This extension is free to download and use on any number of Joomla web sites. It is released as Open Source under the GNU General Public License and the MIT license.

The full source code can be found on [Github][2].

No official support is provided.  However, usage difficulties can be reported on the [ArtofComments issue tracker][3].

If you find any this extension useful, please consider paying us forward (not paying us back) by supporting one of our nominated charities [Kiva.org][4] or [World Hope Australia][5] and help fight world poverty! Let us know if you do.

## Installation & Upgrading

Download the single extension package from the Art of Joomla project site.

Install the single package using the Joomla installer. Log into the Joomla 2.5 or 3.0 Administrator. Select _Extensions -\> Install/Uninstall_ from the menu. Click _Browse_ and select the extension package you downloaded. Click _Upload & Install File_ (alternatively use the other installation methods available if desired).

To upgrade ArtofComments just download the latest version and install over the top of the old version.  Do not uninstall ArtofComments as you may loose plugin settings.

## Using ArtofComments

### Turn on the ArtofComments Content Plugin

In order for ArtofComments to connect to Disqus, in the Joomla Administrator go to _Extensions -\> Plugin Manager_. In the search filter type "ArtofComments" and click _Go_ or press enter/return.  You should see the plugin named "Content - ArtofComments" in the filtered list.

Click the name of the to edit the settings.

Enter the "shortname" you would have configured on the Disqus site.

Turn on the Developer Mode if you are testing a local copy of your site. Make sure this is turned off on a production site.

Enable the plugin and save.

### Enabling and Disabling Comments

When the ArtofComments plugin is enabled, there are two ways to enable, or disable, comments.

The first way is to edit an article category. Under the Basic Parameters you will see a new option called "Enable Comments". Change this setting to "Yes" to allow Disqus comments to be added to each article in the category.

[![Screenshot](/images/software/artofcomments/artofcomments_category.jpg)][6]

The second way is to edit a single article. Under the Article Options you will also see a new option called "Enable Comments". Change this setting to "Yes" to explicitly allow Disqus comments, or "No" to disallow them (even if comments are enabled in the category the article is in).

[![Screenshot](/images/software/artofcomments/artofcomments_article.jpg)][7]

[0]: http://www.theartofjoomla.com/downloads/artof-comments/artof-comments-1-1/artofcomments-1-1-zip.raw
[1]: /images/software/artofcomments/artofcomments_display.jpg
[2]: https://github.com/eddieajau/artof-comments/ "Github repository for ArtofComments"
[3]: https://github.com/eddieajau/artof-comments/issues
[4]: http://www.kiva.org/team/joomla
[5]: http://worldhope.org.au
[6]: /images/software/artofcomments/artofcomments_category.jpg
[7]: /images/software/artofcomments/artofcomments_article.jpg


text:
<?php

declare(strict_types=1);

namespace Comely\IO\Session\ComelySession;

use Comely\IO\Session\Exception\ComelySessionException;

/**
 * Class Bag
 * @package Comely\IO\Session\ComelySession
 */
class Bag
{
    /** @var array */
    private $props;
    /** @var array */
    private $bags;

    /**
     * Bag constructor.
     */
    public function __construct()
    {
        $this->props = [];
        $this->bags = [];
    }

    /**
     * @param string $name
     * @return Bag
     */
    public function bag(string $name): Bag
    {
        $name = strtolower($name);
        return $this->bags[$name] ?? $this->bags[$name] = new Bag;
    }

    /**
     * @param string $key
     * @param $value
     * @return Bag
     * @throws ComelySessionException
     */
    public function set(string $key, $value): self
    {
        $valueType = gettype($value);
        switch ($valueType) {
            case "boolean":
            case "integer":
            case "double":
            case "string":
            case "array":
            case "NULL":
                $this->props[strtolower($key)] = $value;
                break;
            default:
                throw new ComelySessionException(sprintf('Data type "%s" cannot be stored', $valueType));
        }

        return $this;
    }

    /**
     * @param string $prop
     * @return mixed|null
     */
    public function get(string $prop)
    {
        return $this->props[strtolower($prop)] ?? null;
    }

    /**
     * Checks if 1 or all the keys exist in Bag
     * @param string[] ...$props
     * @return bool
     */
    public function has(string ...$props): bool
    {
        foreach ($props as $prop) {
            if (!array_key_exists(strtolower($prop), $this->props)) {
                return false;
            }
        }

        return true;
    }

    /**
     * @param string $bag
     * @return bool
     */
    public function hasBag(string $bag): bool
    {
        return isset($this->bags[strtolower($bag)]);
    }

    /**
     * @param string $key
     * @return Bag
     */
    public function delete(string $key): self
    {
        $key = strtolower($key);
        unset($this->props[$key], $this->bags[$key]);
        return $this;
    }
}


text:
QR Workshop is a free, open source and portable application that allows you to generate QR codes of your choice.

## This project has been abandoned in 2014 and will not receive any updates.

Since this project is using DevExpress controls, if you do not have a valid license you will need to replace any DevExpress controls with the stock ones or you will not be able to compile/run the project properly.


text:
    <?php $this->load->view('admin/admin_dashboard_navbar_view'); ?>

                        <?php echo $common_header; ?>

                             <a href="<?php echo base_url(); ?>admin">Dashboard

                             <?php echo $common_header; ?>

 <?php echo $common_header; ?>

                    <form name='add_project_cat_form' id='add_project_cat_form' enctype="multipart/form-data"
                          class="form-horizontal form-widgets" role="form" method="POST" action="">

                                    <fieldset>
                                        <?php if (validation_errors()) { ?>

                                                        ×
                                                        <?php echo validation_errors(); ?>

                                        <?php } ?>

                                            Skill Category Name:

                                                <input type="text" class="form-control" name="skill_category_name"
                                                       id="skill_category_name" value="<?php echo $single_skill_cat['skill_category_name']; ?>"
                                                       placeholder="Write Skill Category Name" required/>

                                            Is Active:

                                                    <input type="checkbox" id="is_active"
                                                           name="is_active" value="1" <?php echo ($single_skill_cat['is_active']== 1 ? 'checked' : '');?> />

                                    </fieldset>

                            <button id="update" name="update" type="submit" data-role="button"
                                    class="btn btn-submit btn-success">Update
                            </button>
                            <a class="btn btn-danger" href="<?php echo base_url(); ?>admin/add/company/skill/category"
                               role="button">Cancel

                    </form>


text:
<!DOCTYPE html>

    <title>{{title}}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="../bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" media="screen">
    <link href="../css/style.css" rel="stylesheet" media="screen">
    <link href="../css/nupic.css" rel="stylesheet" media="screen">

{{title}}


text:
namespace EDDiscovery.UserControls
{
    partial class UserControlExtPanel
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.SuspendLayout();
            //
            // UserControlExtPanel
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Name = "UserControlExtPanel";
            this.Size = new System.Drawing.Size(496, 224);
            this.ResumeLayout(false);

        }

        #endregion
    }
}


text:
require "docushin/route"
require "docushin/engine"
require "docushin/version"
require "docushin/route_set"

module Docushin
  mattr_accessor :path_regexp
  @@path_regexp = nil

  mattr_accessor :data_fields
  @@data_fields = [:description]

  def self.setup
    yield self
  end
end


text:
class AccessorsArePreserved {
    private Integer someInt = 1;

    // get header
    public Integer getSomeInt() {
        // get body 1
        System.out.println("Some text");
        // get body 2
        return someInt;
    } // get footer

    // set header
    public void setSomeInt(Integer state) {
        // set body 1
        someInt = state;
        // set body 2
        System.out.println("Some text");
    } // set footer
}

class AccessorsAreRemoved {
    private Integer someInt = 1;

    // get header
    public Integer getSomeInt() {
        // get body
        return someInt;
    } // get footer

    // set header
    public void setSomeInt(Integer state) {
        // set body
        someInt = state;
    } // set footer
}


text:
/*
 * vim:ts=4:sw=4:expandtab
 *
 * i3 - an improved dynamic tiling window manager
 * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
 *
 */
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <limits.h>
#include <stdlib.h>
#include <math.h>

#include <xcb/xcb.h>
#include <xcb/xcb_aux.h>

#include "libi3.h"

/*
 * Try to get the contents of the given atom (for example I3_SOCKET_PATH) from
 * the X11 root window and return NULL if it doesn't work.
 *
 * If the provided XCB connection is NULL, a new connection will be
 * established.
 *
 * The memory for the contents is dynamically allocated and has to be
 * free()d by the caller.
 *
 */
char *root_atom_contents(const char *atomname, xcb_connection_t *provided_conn, int screen) {
    xcb_intern_atom_cookie_t atom_cookie;
    xcb_intern_atom_reply_t *atom_reply;
    char *content;
    size_t content_max_words = 256;
    xcb_connection_t *conn = provided_conn;

    if (provided_conn == NULL &&
        ((conn = xcb_connect(NULL, &screen)) == NULL ||
         xcb_connection_has_error(conn)))
        return NULL;

    atom_cookie = xcb_intern_atom(conn, 0, strlen(atomname), atomname);

    xcb_screen_t *root_screen = xcb_aux_get_screen(conn, screen);
    xcb_window_t root = root_screen->root;

    atom_reply = xcb_intern_atom_reply(conn, atom_cookie, NULL);
    if (atom_reply == NULL)
        return NULL;

    xcb_get_property_cookie_t prop_cookie;
    xcb_get_property_reply_t *prop_reply;
    prop_cookie = xcb_get_property_unchecked(conn, false, root, atom_reply->atom,
                                             XCB_GET_PROPERTY_TYPE_ANY, 0, content_max_words);
    prop_reply = xcb_get_property_reply(conn, prop_cookie, NULL);
    if (prop_reply == NULL) {
        free(atom_reply);
        return NULL;
    }
    if (xcb_get_property_value_length(prop_reply) > 0 && prop_reply->bytes_after > 0) {
        /* We received an incomplete value. Ask again but with a properly
         * adjusted size. */
        content_max_words += ceil(prop_reply->bytes_after / 4.0);
        /* Repeat the request, with adjusted size */
        free(prop_reply);
        prop_cookie = xcb_get_property_unchecked(conn, false, root, atom_reply->atom,
                                                 XCB_GET_PROPERTY_TYPE_ANY, 0, content_max_words);
        prop_reply = xcb_get_property_reply(conn, prop_cookie, NULL);
        if (prop_reply == NULL) {
            free(atom_reply);
            return NULL;
        }
    }
    if (xcb_get_property_value_length(prop_reply) == 0) {
        free(atom_reply);
        free(prop_reply);
        return NULL;
    }
    if (prop_reply->type == XCB_ATOM_CARDINAL) {
        /* We treat a CARDINAL as a >= 32-bit unsigned int. The only CARDINAL
         * we query is I3_PID, which is 32-bit. */
        if (asprintf(&content, "%u", *((unsigned int *)xcb_get_property_value(prop_reply))) == -1) {
            free(atom_reply);
            free(prop_reply);
            return NULL;
        }
    } else {
        if (asprintf(&content, "%.*s", xcb_get_property_value_length(prop_reply),
                     (char *)xcb_get_property_value(prop_reply)) == -1) {
            free(atom_reply);
            free(prop_reply);
            return NULL;
        }
    }
    if (provided_conn == NULL)
        xcb_disconnect(conn);
    free(atom_reply);
    free(prop_reply);
    return content;
}