text:
package org.cloudfoundry.logcache.v1;

import org.cloudfoundry.AbstractIntegrationTest;
import org.cloudfoundry.ApplicationUtils;
import org.cloudfoundry.CloudFoundryVersion;
import org.cloudfoundry.IfCloudFoundryVersion;
import org.junit.Test;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

import java.math.BigInteger;
import java.time.Duration;
import java.util.Random;
import java.util.function.Predicate;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.within;
import static org.cloudfoundry.util.DelayUtils.exponentialBackOff;

@IfCloudFoundryVersion(greaterThanOrEqualTo = CloudFoundryVersion.PCF_2_9)
public class LogCacheTest extends AbstractIntegrationTest implements InitializingBean {

    @Autowired
    LogCacheClient logCacheClient;

    @Autowired
    Random random;

    @Autowired
    private Mono<ApplicationUtils.ApplicationMetadata> testLogCacheApp;

    private ApplicationUtils.ApplicationMetadata testLogCacheAppMetadata;

    @Autowired
    private TestLogCacheEndpoints testLogCacheEndpoints;

    @Override
    public void afterPropertiesSet() {
        this.testLogCacheAppMetadata = this.testLogCacheApp.block();
    }

    @Test
    public void info() {
        this.logCacheClient.info(InfoRequest.builder().build())
            .as(StepVerifier::create)
            .assertNext(response -> {
                assertThat(response).isNotNull();
                assertThat(response.getVersion())
                    .isNotBlank();
                assertThat(response.vmUptime())
                    .isNotNull()
                    .isGreaterThan(1);
            })
            .expectComplete()
            .verify(Duration.ofMinutes(5));
    }

    @Test
    public void meta() {
        this.logCacheClient.meta(MetaRequest.builder().build())
            .as(StepVerifier::create)
            .assertNext(response -> {
                assertThat(response).isNotNull();
                assertThat(response.getMeta())
                    .containsKey(this.testLogCacheAppMetadata.applicationId);
            })
            .expectComplete()
            .verify(Duration.ofMinutes(5));
    }

    @Test
    public void readCounter() {
        final String name = this.nameFactory.getName("counter-");
        final int delta = this.random.nextInt(1000);

        this.testLogCacheEndpoints.counter(name, delta)
            .then(read(EnvelopeType.COUNTER, envelope -> hasCounter(envelope) && name.equals(envelope.getCounter().getName())))
            .as(StepVerifier::create)
            .assertNext(response -> assertCounter(response, name, delta))
            .expectComplete()
            .verify(Duration.ofMinutes(5));
    }

    @Test
    public void readEvent() {
        final String title = this.nameFactory.getName("event-");
        final String body = "This is the body. " + new BigInteger(1024, this.random).toString(32);

        this.testLogCacheEndpoints.event(title, body)
            .then(read(EnvelopeType.EVENT, this::hasEvent))
            .as(StepVerifier::create)
            .assertNext(response -> assertEvent(response, title, body))
            .expectComplete()
            .verify(Duration.ofMinutes(5));
    }

    @Test
    public void readGauge() {
        final String gaugeName = this.nameFactory.getName("gauge-");
        final Double value = this.random.nextDouble() % 100;

        this.testLogCacheEndpoints.gauge(gaugeName, value)
            .then(read(EnvelopeType.GAUGE, envelope -> hasGauge(envelope) && envelope.getGauge().getMetrics().containsKey(gaugeName)))
            .as(StepVerifier::create)
            .assertNext(response -> assertGauge(response, gaugeName, value))
            .expectComplete()
            .verify(Duration.ofMinutes(5));
    }

    @Test
    public void readLogs() {
        final String logMessage = this.nameFactory.getName("log-");

        this.testLogCacheEndpoints.log(logMessage)
            .then(read(EnvelopeType.LOG, envelope -> hasLog(envelope) && logMessage.equals(envelope.getLog().getPayloadAsText())))
            .as(StepVerifier::create)
            .expectNextCount(1)
            .expectComplete()
            .verify(Duration.ofMinutes(5));
    }

    private void assertCounter(Envelope envelope, String name, int delta) {
        assertThat(envelope.getCounter().getName()).isEqualTo(name);
        assertThat(envelope.getCounter().getDelta()).isEqualTo(delta);
        assertThat(envelope.getCounter().getTotal()).isEqualTo(delta);
    }

    private void assertEnvelope(Envelope envelope) {
        assertThat(envelope).isNotNull();
        assertThat(envelope.getInstanceId()).isEqualTo("0");
        assertThat(envelope.getSourceId()).isEqualTo(this.testLogCacheAppMetadata.applicationId);
        assertThat(envelope.getTimestamp()).isGreaterThan(0);
    }

    private void assertEvent(Envelope envelope, String title, String body) {
        assertThat(envelope.getEvent().getBody()).isEqualTo(body);
        assertThat(envelope.getEvent().getTitle()).isEqualTo(title);
    }

    private void assertGauge(Envelope envelope, String gaugeName, Double value) {
        assertThat(envelope.getGauge().getMetrics().get(gaugeName).getValue())
            .isCloseTo(value, within(0.001));
    }

    private void assertResponse(ReadResponse readResponse) {
        assertThat(readResponse).isNotNull();
        assertThat(readResponse.getEnvelopes()).isNotNull();
        assertThat(readResponse.getEnvelopes().getBatch()).isNotNull();
    }

    private boolean hasCounter(Envelope envelope) {
        return envelope.getCounter() != null;
    }

    private boolean hasEvent(Envelope envelope) {
        return envelope.getEvent() != null;
    }

    private boolean hasGauge(Envelope envelope) {
        return envelope.getGauge() != null;
    }

    private boolean hasLog(Envelope envelope) {
        return envelope.getLog() != null;
    }

    private Mono<Envelope> read(EnvelopeType envelopeType, Predicate<Envelope> filter) {
        return this.logCacheClient.read(ReadRequest.builder()
            .sourceId(this.testLogCacheAppMetadata.applicationId)
            .envelopeType(envelopeType)
            .limit(1000)
            .build())
            .doOnNext(this::assertResponse)
            .flatMap(response -> Mono.justOrEmpty(response.getEnvelopes().getBatch().stream().filter(filter).findFirst()))
            .repeatWhenEmpty(exponentialBackOff(Duration.ofSeconds(1), Duration.ofSeconds(5), Duration.ofMinutes(1)))
            .doOnNext(this::assertEnvelope);
    }

}


text:
package netty.napsters.client;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

import com.alibaba.fastjson.JSON;

import netty.file.SharedFile;

public class Response {
	private List<SharedFile> sharedFiles = new ArrayList<>();
	private String shareFileFlag = "";
	private String unshareFlag = "";
	private String fileShareIp = "";

	private boolean setFlag = false;

	public String sendListCommond(String string) {

		return string;
	}

	public void setSharedFiles(String response) {

		synchronized (sharedFiles) {

			this.sharedFiles = JSON.parseArray(response, SharedFile.class);

		}
	}

	public List<SharedFile> getSharedFiles() {

		synchronized (sharedFiles) {

			return this.sharedFiles;

		}

	}

	/**
	 * Share a new file to Napster server.
	 *
	 * @param sharedFile
	 *            the file to share
	 * @return whether the share operation is successful
	 */
	public String sendADDCommond(String commond) {
		setFlag = true;
		return commond;
	}

	public void setShareFile(String response) {

		synchronized (shareFileFlag) {
			while (!setFlag) {
				try {
					shareFileFlag.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (response.equals("ADD OK")) {
				this.shareFileFlag = "true";
			} else {
				this.shareFileFlag = "false";
			}
			setFlag = false;
			shareFileFlag.notifyAll();
		}

	}

	public String shareNewFile() {

		// Receive response from server
		synchronized (shareFileFlag) {
			while (setFlag) {
				try {
					shareFileFlag.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			shareFileFlag.notifyAll();
			return this.shareFileFlag;

		}

	}

	/**
	 * Unshare a file from Napster server.
	 *
	 * @param fileName
	 *            the file name of the file
	 * @param checksum
	 *            the checksum of the file
	 * @return whether the unshare operation is successful
	 */
	public String sendUnshareFileCommond(String fileName, String checksum) {

		String Commond = "DELETE " + JSON.toJSON(((Supplier<Map<String, String>>) (() -> {
			Map<String, String> map = new HashMap<String, String>();
			map.put("fileName", fileName);
			map.put("checksum", checksum);
			return Collections.unmodifiableMap(map);
		})).get());
		setFlag = true;
		return Commond+"\r\n";

	}

	public void setUnshareFile(String response) {

		synchronized (unshareFlag) {
			while (!setFlag) {
				try {
					unshareFlag.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (response.equals("DELETE OK")) {
				this.unshareFlag = "ture";
			} else {
				this.unshareFlag = "false";
			}
			setFlag = false;
			unshareFlag.notifyAll();

		}

	}

	public String unshareFile() {

		synchronized (unshareFlag) {
			while (setFlag) {
				try {
					unshareFlag.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			unshareFlag.notifyAll();

			return this.unshareFlag;
		}

	}

	/**
	 * Get the IP of the sharer who share a specific file
	 *
	 * @param checksum
	 *            the checksum of the file
	 * @return the IP of the sharer or N/a if the file is not available
	 */
	public String sendRequestCommond(String commond) {
		setFlag = true;
		return commond;
	}

	public void setFileShareIp(String response) {

		synchronized (fileShareIp) {
			while (!setFlag) {
				try {
					fileShareIp.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (!response.equals("ERROR")) {

				this.fileShareIp = response;
			} else {
				this.fileShareIp = "N/a";
			}
			setFlag = false;
			fileShareIp.notifyAll();
		}
	}

	public String getFileSharerIp() {

		synchronized (fileShareIp) {
			while (setFlag) {
				try {
					fileShareIp.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			fileShareIp.notifyAll();
			return this.fileShareIp;
		}

	}
}

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from 'react';
import { Text } from 'react-native';

import styles from '../../styles/styles';
import InPageImage from '../inPageImage';
import AnimalText from '../animalText';
import AnimalTemplate from '../animalTemplate';

const IMAGES = [
  require('../../images/animals/plamenakRuzovy/01.jpg'),
  require('../../images/animals/plamenakRuzovy/02.jpg'),
  require('../../images/animals/plamenakRuzovy/03.jpg'),
];

const THUMBNAILS = [
  require('../../images/animals/plamenakRuzovy/01-thumb.jpg'),
  require('../../images/animals/plamenakRuzovy/02-thumb.jpg'),
  require('../../images/animals/plamenakRuzovy/03-thumb.jpg'),
];

var AnimalDetail = React.createClass({
  render() {
    return (
      <AnimalTemplate firstIndex={[2]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}>
        <AnimalText>
          Ahoj kamarádi,
        </AnimalText>
        <AnimalText>
          my jsme plameňáci růžoví a patříme k velkým ptákům. Máme velmi dlouhý a tenký krk. I naše prsty na nohou jsou dlouhé a tenké, ale navíc jsou ještě spojeny plovací blánou. Na těle, křídlech i na krku máme měkká peříčka, která jsou bílá až světle růžová. A že jste nás viděli už tmavě růžové, třeba ve filmu Madagaskar? Inu, i to se může stát. Naše peří mění barvu podle toho, co zrovna jíme. Máme rádi plankton, vodní korýše a měkkýše či červíky. Čím víc pak sníme červených dobrot, které obsahují pigmenty karotenoidy, tím růžovější jsme. Nicméně zkuste se podívat, jak vlastně jíme. Zobák nám slouží jako cedník, bláto vyteče a pochutiny zůstanou. Nabírat a filtrovat vodu dokážeme až 20krát za minutu! A když máme doloveno, zůstanou po nás v mělkých jezerech či lagunách stopy. Určitě nějaké najdete i vy.
        </AnimalText>
        <InPageImage indexes={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
        <AnimalText>
          Pokud se zaposloucháte, můžete slyšet, jak si povídáme. Zní to podobně jako husí kejhání. My na sebe rádi voláme, jsme totiž velmi společenští, naše kolonie mohou mít až 200 000 jedinců. Můžete zkusit poznat samečky, kteří jsou větší, samičky, které jsou menší a ptáčata, která mají jen málo bílých peříček.
        </AnimalText>
        <AnimalText>
          Veselé je, když chceme vzlétnout. Musíme se pořádně rozběhnout, abychom nabrali rychlost. Dlouhý krk máme natažený dopředu a nohy dozadu. Jsme jako opeřená letadla. I Márty se tomu smál. A  když si chceme odpočinout, stoupneme si na jednu nohu a hlavu schováme pod křídlo. Chráníme si velký červený zobák, který má černou špičku a velmi citlivou kůži. Také dobře vidíme, ale necítíme skoro nic. A oko máme větší než mozek.
        </AnimalText>
        <InPageImage indexes={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
        <AnimalText>
          Zkuste si na nás taky někdy zahrát, stačí, když si stoupnete na jednu nohu a schováte si hlavu pod rameno. Kdo to umí lépe?
        </AnimalText>
        <AnimalText>
          Tak zase příště, kamarádi.
        </AnimalText>
      </AnimalTemplate>
    );
  }
});

module.exports = AnimalDetail;


text:
export default {

  replace: true,

  props: {
    id: {
      type: String
    },
    prop: {
      type: String
    },
    color: {
      type: String
    },
    name: {
      type: String
    },
    customClass: {
      type: String
    },
    groups: {
      type: String
    }
  },

  data: function data() {
    return {
      type: ''
    };
  },

  mounted() {
    this.$parent.$emit('c3-chart-element-mounted', this.type, this.prop, this.options)
  },

  methods: {
    optionExists: function(option) {
      return (undefined !== option && null !== option && '' !== option) ? true : false
    },
  },

  computed: {
    options: function() {
      var _options = {}

      if (this.optionExists(this.color)) {
        _options.color = this.color
      }

      if (this.optionExists(this.name)) {
        _options.name = this.name
      }

      if (this.optionExists(this.customClass)) {
        _options.customClass = this.customClass
      }

      if (this.optionExists(this.groups)) {
        _options.groups = this.groups
      }

      return _options
    }
  },
}


text:
Adds support for media links:

## Media links

Allows to embed audio/video links to popular website:

```````````````````````````````` example
![Video1](https://www.youtube.com/watch?v=mswPy5bt3TQ)

![Video2](https://vimeo.com/8607834)
.

````````````````````````````````


text:
@interface AppDelegate : NSObject <NSApplicationDelegate>
{
@private
    IBOutlet NSWindow *window;
    IBOutlet ViViewOSX *renderView;

    vi::common::kernel *kernel;
    vi::scene::camera *camera;
    vi::scene::scene *scene;
    vi::graphic::rendererOSX *renderer;

    vi::scene::baseParticleEffect effect;
    vi::scene::particleEmitter *emitter;
}

@end


text:
package gr.iti.mklab.reveal.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

/**
 * A basic RabbitMQ Publisher
 *
 * @author kandreadou
 */
public class RabbitMQPublisher {

    private Channel channel;
    private Connection connection;
    private String exchangeName;

    public RabbitMQPublisher(String host, String collection) {
        try {
            this.exchangeName = collection;
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(host);
            // Do we need the methods below? port probably 5672, user "guest"
            // setPort, setUsername, setPassword
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(collection, "topic");
        } catch (IOException ioe) {
            System.out.println(ioe);
        }
    }

    public void publish(String message) {
        try {
            System.out.println("RABBITMQ publish: "+message);
            channel.basicPublish(exchangeName, "test-rooting", null, message.getBytes());
        } catch (IOException ioe) {
            System.out.println(ioe);
        }
    }

    public void close() {
        try {
            channel.close();
            connection.close();
        } catch (Exception e) {
            //ignore
        }
    }
}


text:
#include "config.h"
#if ENABLE(INSPECTOR)
#include "InjectedScriptManager.h"

#include "BindingState.h"
#include "DOMWindow.h"
#include "InjectedScriptHost.h"
#include "ScriptObject.h"
#include "V8Binding.h"
#include "V8DOMWindow.h"
#include "V8InjectedScriptHost.h"
#include "V8RecursionScope.h"
#include <wtf/RefPtr.h>

namespace WebCore {

static void WeakReferenceCallback(v8::Persistent<v8::Value> object, void* parameter)
{
    InjectedScriptHost* nativeObject = static_cast<InjectedScriptHost*>(parameter);
    nativeObject->deref();
    object.Dispose();
}

static v8::Local<v8::Object> createInjectedScriptHostV8Wrapper(InjectedScriptHost* host)
{
    v8::Local<v8::Function> function = V8InjectedScriptHost::GetTemplate()->GetFunction();
    if (function.IsEmpty()) {
        // Return if allocation failed.
        return v8::Local<v8::Object>();
    }
    v8::Local<v8::Object> instance = V8ObjectConstructor::newInstance(function);
    if (instance.IsEmpty()) {
        // Avoid setting the wrapper if allocation failed.
        return v8::Local<v8::Object>();
    }
    V8DOMWrapper::setDOMWrapper(instance, &V8InjectedScriptHost::info, host);
    // Create a weak reference to the v8 wrapper of InspectorBackend to deref
    // InspectorBackend when the wrapper is garbage collected.
    host->ref();
    v8::Persistent<v8::Object> weakHandle = v8::Persistent<v8::Object>::New(instance);
    weakHandle.MakeWeak(host, &WeakReferenceCallback);
    return instance;
}

ScriptObject InjectedScriptManager::createInjectedScript(const String& scriptSource, ScriptState* inspectedScriptState, int id)
{
    v8::HandleScope scope;

    v8::Local<v8::Context> inspectedContext = inspectedScriptState->context();
    v8::Context::Scope contextScope(inspectedContext);

    // Call custom code to create InjectedScripHost wrapper specific for the context
    // instead of calling toV8() that would create the
    // wrapper in the current context.
    // FIXME: make it possible to use generic bindings factory for InjectedScriptHost.
    v8::Local<v8::Object> scriptHostWrapper = createInjectedScriptHostV8Wrapper(m_injectedScriptHost.get());
    if (scriptHostWrapper.IsEmpty())
        return ScriptObject();

    v8::Local<v8::Object> windowGlobal = inspectedContext->Global();

    // Inject javascript into the context. The compiled script is supposed to evaluate into
    // a single anonymous function(it's anonymous to avoid cluttering the global object with
    // inspector's stuff) the function is called a few lines below with InjectedScriptHost wrapper,
    // injected script id and explicit reference to the inspected global object. The function is expected
    // to create and configure InjectedScript instance that is going to be used by the inspector.
    v8::Local<v8::Script> script = v8::Script::Compile(v8String(scriptSource));
    V8RecursionScope::MicrotaskSuppression recursionScope;
    v8::Local<v8::Value> v = script->Run();
    ASSERT(!v.IsEmpty());
    ASSERT(v->IsFunction());

    v8::Handle<v8::Value> args[] = {
      scriptHostWrapper,
      windowGlobal,
      v8::Number::New(id),
    };
    v8::Local<v8::Value> injectedScriptValue = v8::Function::Cast(*v)->Call(windowGlobal, 3, args);
    return ScriptObject(inspectedScriptState, v8::Handle<v8::Object>::Cast(injectedScriptValue));
}

bool InjectedScriptManager::canAccessInspectedWindow(ScriptState* scriptState)
{
    v8::HandleScope handleScope;
    v8::Local<v8::Context> context = scriptState->context();
    v8::Local<v8::Object> global = context->Global();
    if (global.IsEmpty())
        return false;
    v8::Handle<v8::Object> holder = V8DOMWrapper::lookupDOMWrapper(V8DOMWindow::GetTemplate(), global);
    if (holder.IsEmpty())
        return false;
    Frame* frame = V8DOMWindow::toNative(holder)->frame();

    v8::Context::Scope contextScope(context);
    return BindingSecurity::shouldAllowAccessToFrame(BindingState::instance(), frame, DoNotReportSecurityError);
}

} // namespace WebCore

#endif // ENABLE(INSPECTOR)


text:
#include <algorithm>

#include <boost/algorithm/string/join.hpp>

#include <aws/core/client/AWSError.h>
#include <aws/core/utils/Outcome.h>
#include <aws/firehose/model/PutRecordBatchRequest.h>
#include <aws/firehose/model/PutRecordBatchResult.h>

#include <osquery/flags.h>
#include <osquery/registry.h>

#include "osquery/logger/plugins/aws_firehose.h"

namespace osquery {

REGISTER(FirehoseLoggerPlugin, "logger", "aws_firehose");

FLAG(uint64,
     aws_firehose_period,
     10,
     "Seconds between flushing logs to Firehose (default 10)");

FLAG(string, aws_firehose_stream, "", "Name of Firehose stream for logging")

Status FirehoseLoggerPlugin::setUp() {
  initAwsSdk();

  forwarder_ = std::make_shared<FirehoseLogForwarder>(
      "aws_firehose", FLAGS_aws_firehose_period, 500);
  Status s = forwarder_->setUp();
  if (!s.ok()) {
    LOG(ERROR) << "Error initializing Firehose logger: " << s.getMessage();
    return s;
  }

  Dispatcher::addService(forwarder_);
  return Status(0);
}

Status FirehoseLoggerPlugin::logString(const std::string& s) {
  return forwarder_->logString(s);
}

Status FirehoseLoggerPlugin::logStatus(const std::vector<StatusLogLine>& log) {
  return forwarder_->logStatus(log);
}

void FirehoseLoggerPlugin::init(const std::string& name,
                                const std::vector<StatusLogLine>& log) {
  logStatus(log);
}

Status FirehoseLogForwarder::internalSetup() {
  if (FLAGS_aws_firehose_stream.empty()) {
    return Status(1,
                  "Stream name must be specified with --aws_firehose_stream");
  }

  // Make sure we can connect to designated stream
  VLOG(1) << "Firehose logging initialized with stream: "
          << FLAGS_aws_firehose_stream;
  return Status(0);
}

FirehoseLogForwarder::Outcome FirehoseLogForwarder::internalSend(
    const Batch& batch) {
  Aws::Firehose::Model::PutRecordBatchRequest request;
  request.WithDeliveryStreamName(FLAGS_aws_firehose_stream)
      .WithRecords(std::move(batch));
  return client_->PutRecordBatch(request);
}

void FirehoseLogForwarder::initializeRecord(
    Record& record, Aws::Utils::ByteBuffer& buffer) const {
  record.SetData(buffer);
}

size_t FirehoseLogForwarder::getMaxBytesPerRecord() const {
  return 1000000U;
}

size_t FirehoseLogForwarder::getMaxRecordsPerBatch() const {
  return 500U;
}

size_t FirehoseLogForwarder::getMaxBytesPerBatch() const {
  return 4000000U;
}

size_t FirehoseLogForwarder::getMaxRetryCount() const {
  return 100U;
}

size_t FirehoseLogForwarder::getInitialRetryDelay() const {
  return 3000U;
}

bool FirehoseLogForwarder::appendNewlineSeparators() const {
  return true;
}

size_t FirehoseLogForwarder::getFailedRecordCount(Outcome& outcome) const {
  return static_cast<size_t>(outcome.GetResult().GetFailedPutCount());
}

FirehoseLogForwarder::Result FirehoseLogForwarder::getResult(
    Outcome& outcome) const {
  return outcome.GetResult().GetRequestResponses();
}
}


text: this is index page


text:
using UnityEngine;

public class LoopAudioSource : MonoBehaviour {

	public float startLoopTime;
	public float endLoopTime;

	private AudioSource source;

	void Start() {
		this.source = this.gameObject.GetComponent<AudioSource>();
	}

	void FixedUpdate() {
		if(source.time >= endLoopTime){
			source.time = startLoopTime;
		}
	}
}


text:
package io.github.yuokada.embulk.input.randomj;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.embulk.config.ConfigDiff;
import org.embulk.config.ConfigSource;
import org.embulk.config.TaskReport;
import org.embulk.config.TaskSource;
import org.embulk.spi.Column;
import org.embulk.spi.ColumnConfig;
import org.embulk.spi.Exec;
import org.embulk.spi.InputPlugin;
import org.embulk.spi.PageBuilder;
import org.embulk.spi.PageOutput;
import org.embulk.spi.Schema;
import org.embulk.spi.SchemaConfig;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;

public class RandomjInputPlugin
        implements InputPlugin
{
    @Override
    public ConfigDiff transaction(ConfigSource config,
            InputPlugin.Control control)
    {
        PluginTask task = config.loadConfig(PluginTask.class);

        Schema schema = task.getSchema().toSchema();
        int taskCount = task.getThreads();  // number of run() method calls

        return resume(task.dump(), schema, taskCount, control);
    }

    @Override
    public ConfigDiff resume(TaskSource taskSource,
            Schema schema, int taskCount,
            InputPlugin.Control control)
    {
        control.run(taskSource, schema, taskCount);
        return Exec.newConfigDiff();
    }

    @Override
    public void cleanup(TaskSource taskSource,
            Schema schema, int taskCount,
            List<TaskReport> successTaskReports)
    {
        // throw new UnsupportedOperationException("randomj input plugin does not support cleanup"); // NOSONAR
    }

    @Override
    public TaskReport run(TaskSource taskSource,
            Schema schema, int taskIndex,
            PageOutput output)
    {
        PluginTask task = taskSource.loadTask(PluginTask.class);
        Integer rows = task.getRows();
        final HashMap<Column, Map<String, Integer>> columnOptions = getColumnOptions(task);
        final HashMap<Column, List<JsonNode>> columnSchemas = getColumnSchemas(task);
        try (PageBuilder pagebuilder =
                new PageBuilder(Exec.getBufferAllocator(), schema, output)) {
            IntStream.rangeClosed(
                    taskIndex * rows + 1,
                    taskIndex * rows + rows
            ).boxed().forEach(rowNumber -> {
                RandomjColumnVisitor visitor = new RandomjColumnVisitor(pagebuilder, task, rowNumber, columnOptions, columnSchemas);
                schema.visitColumns(visitor);
                pagebuilder.addRecord();
            });
            pagebuilder.finish();
        }

        TaskReport taskReport = Exec.newTaskReport();
        taskReport.set("columns", schema.size());
        taskReport.set("rows", rows);
        return taskReport;
    }

    HashMap<Column, Map<String, Integer>> getColumnOptions(PluginTask task)
    {
        SchemaConfig schemaConfig = task.getSchema();
        Schema schema = schemaConfig.toSchema();
        HashMap<Column, Map<String, Integer>> lengthMap = new HashMap<>();
        for (Column column : schema.getColumns()) {
            HashMap<String, Integer> miniMap = new HashMap<>();
            ColumnConfig c = schemaConfig.getColumn(column.getIndex());

            miniMap.put("pk_offset", c.getOption().get(Integer.class, "pk_offset", null));
            miniMap.put("length", c.getOption().get(Integer.class, "length", 0));
            miniMap.put("null_rate", c.getOption().get(Integer.class, "null_rate", 0));
            miniMap.put("max_value", c.getOption().get(Integer.class, "max_value", null));
            miniMap.put("min_value", c.getOption().get(Integer.class, "min_value", null));
            // For datetime
            miniMap.put("start_date", c.getOption().get(Integer.class, "start_date", null));
            miniMap.put("end_date", c.getOption().get(Integer.class, "end_date", null));
            lengthMap.put(column, miniMap);
        }
        return lengthMap;
    }

    HashMap<Column, List<JsonNode>> getColumnSchemas(PluginTask task)
    {
        SchemaConfig schemaConfig = task.getSchema();
        Schema schema = schemaConfig.toSchema();
        HashMap<Column, List<JsonNode>> schemaMap = new HashMap<>();
        for (Column column : schema.getColumns()) {
            String schemaString = schemaConfig
                    .getColumn(column.getIndex())
                    .getOption().get(String.class, "schema", "");
            if (!schemaString.isEmpty()) {
                try {
                    List<JsonNode> jsonNodes = new ObjectMapper().readValue(schemaString, new TypeReference<List<JsonNode>>() {});
                    schemaMap.put(column, jsonNodes);
                }
                catch (IOException e) {
                    e.printStackTrace(); // NOSONAR
                }
            }
        }
        return schemaMap;
    }

    @Override
    public ConfigDiff guess(ConfigSource config)
    {
        return Exec.newConfigDiff();
    }
}


text:
C.A.V.A.
====================

**C**onsole-based **A**udio **V**isualizer for **A**LSA

by [Karl Stavestrand](mailto:karl@stavestrand.no)

![spectrum](https://cloud.githubusercontent.com/assets/5231746/7368413/7d7ca93e-ed9f-11e4-842f-61c54fc03dbe.gif "spectrum")

thanks to [anko](https://github.com/anko) for the gif, here is the [recipe]( http://unix.stackexchange.com/questions/113695/gif-screencastng-the-unix-way).

[Demo video](http://youtu.be/vA4RyatP064) (old)

**Table of Contents**  *generated with [DocToc](https://github.com/thlorenz/doctoc)*

- [C.A.V.A. ](#cava)
  - [Updates](#updates)
  - [What it is](#what-it-is)
  - [Build requirements](#build-requirements)
  - [Getting started](#getting-started)
    - [Installing](#installing)
    - [Uninstalling](#uninstalling)
  - [Capturing audio](#capturing-audio)
    - [From loopback device](#from-loopback-device)
      - [PulseAudio (easy)](#pulseaudio-easy)
      - [ALSA (hard)](#alsa-hard)
    - [From mpd's fifo output](#from-mpds-fifo-output)
  - [Running via ssh](#running-via-ssh)
  - [Font notes](#font-notes)
    - [In ttys](#in-ttys)
    - [In terminal emulators](#in-terminal-emulators)
  - [Latency notes](#latency-notes)
  - [Usage](#usage)
    - [Controls](#controls)
  - [Configuration](#configuration)
    - [Example file:](#example-file)
    - [Sections:](#sections)
      - [[general]](#general)
      - [[input]](#input)
      - [[output]](#output)
      - [[color]](#color)
      - [[smoothing]](#smoothing)
      - [[eq]](#eq)

Updates
-------

7/16/2015 - 0.3.2 - added legacy ouput mode 'noncurses', for people experiencing issues with ncurses

7/15/2015 - 0.3.1 - added config file

7/12/2015 - 0.3.0 - Modular source code

5/23/2015 - 0.2.0 - Switched to ncurses

4/23/2015 - Fixed terminal window resizing, added smoothing

4/19/2015 - Added Monstercat style FFT easing (by [CelestialWalrus)](https://github.com/CelestialWalrus).

9/22/2014 - Added support for mpd FIFO input.

What it is
----------

C.A.V.A. is a bar spectrum analyzer for audio using ALSA for input. Its frequency range is limited to 50-10,000Hz. I know that the human ear can hear from 20 up to 20,000 Hz (and probably "sense" even higher frequencies), but the frequencies between 50-10,000Hz seem to me to be the most distinguishable. (I believe telephones used to be limited to as low as 8kHz.)

This program is not intended for scientific use.

This is my first published code. I am not a professional programmer so the source code is probably, by all conventions, a complete mess. Please excuse all the typos as I am both dyslexic and foreign.

Any tips or comments would be much appreciated.

Build requirements
------------------

* [ALSA dev files](http://alsa-project.org/)
* [FFTW](http://www.fftw.org/)
* [ncursesw dev files](http://www.gnu.org/software/ncurses/) (bundled in ncurses in arch)

This can be installed easily in all major distros:

Debian/Raspbian:

    apt-get install libfftw3-dev libasound2-dev libncursesw5-dev

ArchLinux:

    pacman -S base-devel fftw ncurses

openSUSE:

    zypper install alsa-devel ncurses-devel fftw3-devel

Getting started
---------------

    make

You can use the following for compilation options, value in *italic style* is the default value:

| Name | Value | Description |
| ---- | ----- | ----------- |
| `debug` | *0* or 1 | Debugging message switch |

For example, turning on debugging messages:

    make debug=1

### Installing manually

Install `cava` to default `/usr/local`:

    make install

Or you can change `PREFIX`, for example:

    make PREFIX=$HOME/.local install

### Uninstalling

    make uninstall

Or:

    make PREFIX=$HOME/.local uninstall

### openSUSE

On openSUSE you need to add jubalh's home repository to install cava via zypper. For example for Tumbleweed do:

    zypper ar -f http://download.opensuse.org/repositories/home:/jubalh/openSUSE_Tumbleweed/home:jubalh.repo
	zypper in cava

If you use 13.2 or 13.1 just replace *openSUSE_Tumbleweed* with *openSUSE_13.2*, adjust it to your version.

Capturing audio
---------------

### From loopback device

If you want to capture audio straight fom the output (not just mic or line-in), you must create an ALSA loopback interface, then output the audio simultaneously to both the loopback and your normal interface.

To create a loopback interface simply run:

`sudo modprobe snd_aloop`

Hopefully your `aplay -l` should now contain a loopback interface.

To make it presistent across boot add the line `snd-aloop` to "/etc/modules". To keep it form beeing loaded as the first soundcard add the line `options snd-aloop index=1` to "/etc/modprobe.d/alsa-base.conf", this will load it at '1' which is what cava uses as default. You can replace '1' with whatever makes most senes in your audio setup, but then cava must be specified to use that index. Simply pass the -d argument or alter the config file with the loopback interface index.

Playing the audio through your Loopback interface makes it possible for cava to to capture it, but there will be no sound in your speakers. :(

Not to worry! There are (at least) two ways of sending the audio output to the loopback *and* your actual audio interface at the same time:

#### PulseAudio (easy)

First create the loopback device as explained in the section above.

To `/etc/pulse/default.pa`, add the line `load-module module-combine-sink` (in PulseAudio versions <1.0, the module was only called `module-combine`). Then restart PulseAudio. For some reason, I had to turn off realtime scheduling for this to work on a Raspberry Pi (set `realtime-scheduling = no` in `/etc/pulse/daemon.conf`).

PulseAudio setup can also be done in paprefs (Debian: `sudo apt-get install paprefs && paprefs`): In the far right tab check the box "Simultaneous Output".

An extra Output should appear in your sound options called "Simultaneous output to..." Note that when using this method if you turn down the volume on the Simultaneous output, this will effect the visualizer. To avoid this, select the actual output, turn down the volume, then select the Simultaneous output again.

#### ALSA (hard)

First create the loopback device as explained in the section above.

Look at the inculded example file `example_files/etc/asound.conf`. I was able to make this work on my laptop (an Asus UX31 running Elementary OS). I had no luck with the ALSA method on my Rasberry PI (Rasbian) with an USB DAC. The PulseAudio method however works perfectly on my PI.

Read more about the ALSA method [here](http://stackoverflow.com/questions/12984089/capture-playback-on-play-only-sound-card-with-alsa).

### From mpd's fifo output

Add these lines in mpd:

    audio_output {
        type                    "fifo"
        name                    "my_fifo"
        path                    "/tmp/mpd.fifo"
        format                  "44100:16:2"
    }

Run cava with `./cava -i fifo`.

The path of the fifo can be specified with `-p`.

I had some trouble with sync (the visualizer was ahead of the sound). Reducing the ALSA buffer in mpd fixed it:

    audio_output {
            type            "alsa"
            name            "My ALSA"
            buffer_time     "50000"   # (50ms); default is 500000 microseconds (0.5s)
    }

Running via ssh
---------------

To run via ssh to an external monitor, redirect output to `/dev/console`:

     ~# ./cava [options] > /dev/console

exit with ctrl+z then run 'bg' to keep it running after you log out.

(You must be root to redirect to console. Simple sudo is not enough: Run `sudo su` first.)

Font notes
----------

Since the graphics are simply based on characters, performance is dependent on the terminal font.

### In ttys

If you run this in a TTY the program will change the font to the included `cava.psf` (actually a slightly modified "unifont").

In console fonts it seems that only 256 Unicode characters are supported, probably because they are bitmap fonts. I could not find a font with Unicode characters 2581-2587 (the 1/8 - 7/8 blocks used on the top of each bar to increase resolution).

So in `cava.psf`, the characters 1-7 are actually replaced by Unicode characters 2581-2587. When cava exits, it changes the font back. If cava exits abnormally and you notice that 1-7 are replaced by partial blocks, just change the font with `setfont`.

Actually, `setfont` is supposed to return the default font, but this usually isn't set. I haven't found another way to get the current font. So cava sets the font to "Lat2-Fixed16" when interrupted. All major distros should have it. It will revert to your default font at reboot.

### In terminal emulators

In terminal emulators like `xterm`, the font settings is chosen in the software and cannot be changed by an application. So find your terminal settings and try out different fonts and settings. Also character spacing affects the look of the bar spectrum.

Cava also disables the terminal cursor, and turns it back on on exit, but in case it terminates unexpectedly, run `setterm -cursor on` to get it back.e

Tip: Cava will look much nicer in small font sizes. Use a second terminal emulator for cava and set the font size to 1. Warning, can cause high CPU usage and latency if the terminal window is too large!

Latency notes
-------------

If you see latency issues (sound before image) in a terminal emulator, try increasing the font size. This will reduce the number of characters that have to be shown.

If your audio device has a huge buffer, you might experience that cava is actually faster then the audio you hear. This reduces the experience of the visualization. To fix this, you try decreasing the buffer settings in your audio playing software.

Usage
-----

    Usage : cava [options]
    Visualize audio input in terminal.

    Options:
        -b 1..(console columns/2-1) or 200  number of bars in the spectrum (default 25 + fills up the console), program will automatically adjust if there are too many frequency bands)
        -i 'input method'           method used for listnening to audio, supports: 'alsa' and 'fifo'
        -o 'output method'          method used for outputting processed data, supports: 'ncurses', 'noncurses' and 'circle'
        -d 'alsa device'            name of alsa capture device (default 'hw:Loopback,1')
        -p 'fifo path'              path to fifo (default '/tmp/mpd.fifo')
        -c foreground color         suported colors: red, green, yellow, magenta, cyan, white, blue, black (default: cyan)
        -C background color         supported colors: same as above (default: no change)
        -s sensitivity              sensitivity percentage, 0% - no response, 50% - half, 100% - normal, etc...
        -f framerate                FPS limit, if you are experiencing high CPU usage, try redcing this (default: 60)
        -m mode                 set mode (normal, scientific, waves)
        -h                  print the usage
        -v                  print version

Exit with ctrl+c.

If cava quits unexpectedly or is force killed, echo must be turned on manually with `stty -echo`.

### Controls

| Key | Description |
| --- | ----------- |
| m | Swtich between smoothing modes |
| up / down| increase/decrease sensitivity |
| r | Reload configuration |
| q or CTRL-C| Quit C.A.V.A. |

Configuration
-------------

Configuration file is located in `$XDG_CONFIG_HOME/cava/config` or `$HOME/.config/cava/config`.

### Example file:

    [general]
    mode=normal
    framerate=60
    sensitivity=100
    bars=0

    [input]
    method=fifo
    source=/tmp/mpd.fifo

    [output]
    method=terminal

    [color]
    background=white
    foreground=blue

    [smoothing]
    integral=0.7
    monstercat=1
    gravity=1
    ignore=0

    [eq]
    ; naming of keys doesn't matter
    1=0.5
    2=0.6
    3=0.7
    4=0.3
    5=0.2

### Sections:

#### [general]

* `mode` defines smoothing mode, can be `normal`, `scientific` or `waves`. Default: `normal`.
* `framerate` is framerate (FPS). Default: `60`. Accepts only non-negative values.
* `sensitivity` is sensitivity %. Default: `100`. Accepts only non-negative values.
* `bars` defines the amount of bars. `0` sets it to auto. Default: `0`. Accepts only non-negative values.

#### [input]

* `method` may be `alsa` or `fifo`.
* `source` is the ALSA path or FIFO path.

#### [output]

* `method` may be `terminal` or `circle`. Default: `terminal`.

#### [color]

* `background` is the background color.
* `foreground` is the foreground (bars) color.

#### [smoothing]

* `integral` sets the multiplier for the integral smoothing calculations. Default: `0.7`. Another example: `0.5`. Accepts only non-negative values.
* `monstercat` disables or enables the so-called "Monstercat smoothing". Default: `1`. Accepts only `0` or `1`.
* `gravity` sets the gravity multiplier. Default: `1`. Accepts only non-negative values.
* `ignore` zeroes bars with height lower than this setting's value. Default: `0`. Accepts only non-negative values.

#### [eq]

This one is tricky. You can have as much keys as you want. More keys = more precision.

**How it works:**

1. Cava takes values from this section in the order of appearance (naming of the keys doesn't really matter) and puts them into an array.
2. Visualization is divided into `x` sections (where x is the amount of values) and all bars in each of these sections are multiplied by the corresponding value from that array.

**Examples:**

    [eq]
    1=0
    2=1
    3=0
    4=1
    5=0

![3_138](https://cloud.githubusercontent.com/assets/6376571/8670183/a54a851e-29e8-11e5-9eff-346bf6ed91e0.png)

    [eq]
    1=2
    2=2
    3=1
    4=1
    5=0.5

![3_139](https://cloud.githubusercontent.com/assets/6376571/8670181/9db0ef50-29e8-11e5-81bc-3e2bb9892da0.png)


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends MY_Controller {

    function __construct() {
        parent::__construct();
//cargo librerias,helpers necesarios en constructor.
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->load->helper('security');
        $this->load->library('session');
        $this->load->helper('url');
    }

    public function profile() {
//Es el perfil de usuario
//solo permitido SI esta logeuado
        if (!$this->isAuthorized()) {
            $data["error"] = 1;
            $data["error_message"] = "Que haces por acá Picaron?.";
            $this->load->view('home_layout', $data);
            return; //andate de esta funcion
        } else {
            $this->load->model('user_model');
            $data["log"] = 1;
            $data["error"] = 0;
            $res = false;

            if (($this->uri->segment(3) === null) || $this->uri->segment(3) === "" || $this->uri->segment(3) === "me" || $this->uri->segment(3) === $this->session->userdata('nick')) {
                $data["profile"] = "me";
                $res = $this->user_model->selectByNick($this->session->userdata('nick'));
            } else if ($this->uri->segment(3) !== "" || ($this->uri->segment(3) !== null)) {
                $data["profile"] = "alien";
                $res = $this->user_model->selectByNick("" . $this->uri->segment(3) . "");
            }
            if ($res !== false) {
                if ($res->thumbUrl === "") {
                    $res->thumbUrl = base_url() . ALT_PROFILE_PIC;
                } else {
                    $res->thumbUrl = base_url() . USER_THUMB_IMAGE_UPLOAD . $res->thumbUrl;
                }
                $data["user_data"] = $res;
                //aca habria que pedir videos
                $this->load->view('user_layout', $data);
                return; //andate de esta funcion
            } else {
                show_404();
                return;
            }
        }
    }

    /**
     * Desloguea al usuario conectado
     */
    public function logOut() {
        $this->session->sess_destroy();
        redirect('/', 'refresh');
    }

    public function uploadThumb() {
        if (!$this->isAuthorized()) {
            $data["error"] = 1;
            $data["error_message"] = "Que haces por acá Picaron?.";
            $this->load->view('home_layout', $data);
            return; //andate de esta funcion
        }
        $data["log"] = 1;

//save file
        $this->load->helper('MY_upload');
        $filename = "thumb.png";
        $uploadResult = upload_user_thumb($this->session->userdata('nick'), $filename, "user_thumb");
        if ($uploadResult["error"] === false) {
//save on DB
            $this->load->model('user_model');
            $res = $this->user_model->edit($this->session->userdata('userId'), "", "", "", "", $this->session->userdata('nick') . "/" . $filename);
        }
        echo json_encode($uploadResult);
        return;
    }

    /**
     * Editar datos de usuario
     */
    public function editInfo() {
        if (!$this->isAuthorized()) {
            $data["error"] = 1;
            $data["error_message"] = "Que haces por acá Picaron?.";
            $this->load->view('home_layout', $data);
            return; //andate de esta funcion
        }
        $this->load->model('user_model');
        $data["log"] = 1;
//valido la data del form
        $this->form_validation->set_rules('name', 'name', 'trim|required');
        $this->form_validation->set_rules('lastname', 'lastname', 'trim|required');
        $this->form_validation->set_rules('birthday', 'birthday', 'trim|required');
        $this->form_validation->set_rules('gender', 'gender', 'trim|required');
        if ($this->form_validation->run() == FALSE) {
            $data["error"] = 1;
            $data["error_message"] = "Asegurese que escribió correctamente.";
            redirect(base_url() . 'user/profile/me', 'refresh');
        } else {
            $name = $this->input->post('name');
            $lastname = $this->input->post('lastname');
            $birthday = $this->input->post('birthday');
            $gender = $this->input->post('gender');
            if ($this->user_model->edit($this->session->userdata('userId'), $name, $lastname, $birthday, $gender, "")) {
//muestra alguna pagina todavia no sabemos cual
                $data["error"] = 0;
                redirect(base_url() . 'user/profile/me', 'refresh');
                return;
            }

            //NO SE HICIERON CAMBIOS
            $data["error"] = 0;
            redirect(base_url() . 'user/profile/me', 'refresh');
            return;
        }
    }

    /**
     * Muestra el loginForm
     */
    public function loginForm() {
        $data["error"] = 0;
        $this->load->view('login_layout', $data);
    }

    /**
     * Muestra el loginForm
     */
    public function changePassForm() {
        $data["error"] = 0;
        $this->load->view('change_password_layout', $data);
    }

    /**
     * Muestra el loginForm
     */
    public function registerForm() {
        $data["error"] = 0;
        $this->load->view('register_layout', $data);
    }

    /**
     * user login
     */
    public function doLogin() {
        $this->load->model('user_model');
        $user = "";
//solo permitido si NO esta logeuado
        if ($this->isAuthorized()) {
            $data["error"] = 1;
            $data["error_message"] = "Que haces por acá Picaron?.";
            $this->load->view('home_layout', $data);
            return; //andate de esta funcion
        }
//valido la data del form
        $this->form_validation->set_rules('email', 'email', 'trim|required|valid_email');
        $this->form_validation->set_rules('password', 'password', 'trim|required');
        if ($this->form_validation->run() == FALSE) {
            $data["error"] = 1;
            $data["error_message"] = "Asegurese que escribió correctamente.";
            $this->load->view('login_layout', $data);
        } else {
            $email = $this->input->post('email');
            $password = do_hash($this->input->post('password'), 'md5');
            $user = $this->user_model->authorize($email, $password);

            if (!$user) {

                $data["error"] = 1;
                $data["error_message"] = "Email o contraseña invalidos.";
                $this->load->view('login_layout', $data);

            } else if (strtotime($user->banned_until) >= strtotime(date('Y-m-d'))) {

                $data["error"] = 1;
                $data["error_message"] = "Cuenta Baneada hasta el día " . date('d/m/Y', strtotime($user->banned_until));
                $this->load->view('login_layout', $data);

            } else {

                $session = array(
                    'userId' => $user->id,
                    'email' => $user->email,
                    'nick' => $user->nick,
                    'logged_in' => TRUE
                );
                $this->session->set_userdata($session); //guarda en session
                $data["log"] = 1;
//mando a homepage
                redirect('/', 'refresh');
                return;
            }
        }
    }

    public function mailForgotPassword() {
        $this->load->helper("email_content");
        $this->load->library("email");
        $this->load->model('user_model');
        $mail = $this->input->post("email");
        if (isset($mail) && $mail !== "") {
            $mailExists = $this->user_model->emailExists($mail);
            if ($mailExists) {
                $valCode = valCode();
                $to = $mail;
                $this->user_model->updateValidationCode($mail, $valCode);
                $mailContent = forgotPasswordMail($valCode, $mail);
                $data["error"] = 0;
                $data["error_message"] = "Email enviado correctamente";
                $this->load->view('forgot_layout', $data);
                return;
            }
            $data["error"] = 1;
            $data["error_message"] = "Email no encontrado";
            $this->load->view('forgot_layout', $data);
            return;
        }
        show_404();
    }

    public function forgotPassword() {
        $this->load->view('forgot_layout');
    }

    public function validateNewPassword() {
        $this->load->model('user_model');
        $this->form_validation->set_rules('forgot_token', 'forgot_token', 'required');
        $this->form_validation->set_rules('password', 'password', 'trim|required|matches[passconf]|min_length[5]|max_length[12]');
        $this->form_validation->set_rules('passconf', 'password Confirmation', 'trim|required');

        if ($this->form_validation->run() == TRUE) {
            $newPassword = do_hash($this->input->post('password'), 'md5');
            $code = $this->input->post('forgot_token');
            if ($this->user_model->changePasswordByCode($code, $newPassword)) {
                $data["error"] = 0;
                $data["token"] = 'No-token';
                $data["error_message"] = "Contraseña cambiada con exito, ya puedes iniciar sesión.";
                $this->load->view('change_password_forgot_layout', $data);
                return;
            } else {
                $data["error"] = 1;
                $data["token"] = 'No-token';
                $data["error_message"] = "No existe el token.";
                $this->load->view('change_password_forgot_layout', $data);
                return;
            }
        } else {
            $data["error"] = 1;
            $data["token"] = 'No-token';
            $data["error_message"] = "Posible falta de datos.";
            $this->load->view('change_password_forgot_layout', $data);
            return;
        }
        show_404();
    }

    public function changeForgottenPassword($token) {
        if (isset($token) && $token !== "") {
            $data["token"] = $token;
            $this->load->view('change_password_forgot_layout', $data);
            return;
        }show_404();
    }

    public function validate($code) {
        if ($code !== NULL && $code !== "") {
            $this->load->model('user_model');
            $res = $this->user_model->validate($code);
            if ($res) {
                redirect('/?vd=1', 'refresh');
                return;
            }
            show_404();
            return;
        }
    }

    /**
     * Persiste un user en la BD
     */
    public function register() {
        $this->load->model('user_model');
        $this->load->library("email");
        $this->load->helper("email_content");
//control
//solo permitido si NO esta logeuado
        if ($this->isAuthorized()) {
            $data["error"] = 1;
            $data["error_message"] = "Que haces por acá Picaron?.";
            $this->load->view('register_layout', $data);
            exit; //andate de esta funcion
        }
//valido la data del form
        $this->form_validation->set_rules('email', 'email', 'trim|required|valid_email');
        $this->form_validation->set_rules('name', 'name', 'trim|required|min_length[4]|max_length[30]|alpha');
        $this->form_validation->set_rules('nick', 'nick', 'trim|required|min_length[4]|max_length[20]');
        $this->form_validation->set_rules('password', 'password', 'trim|required|min_length[4]|max_length[60]|matches[passwordConf]');
        $this->form_validation->set_rules('passwordConf', 'passwordConf', 'trim|required|min_length[4]|max_length[60]');
        $this->form_validation->set_rules('lastname', 'lastname', 'trim|required|min_length[4]|max_length[30]|alpha');
        $this->form_validation->set_rules('birthday', 'birthday', 'trim|required');
        $this->form_validation->set_rules('gender', 'gender', 'trim|required');
//$this->form_validation->set_rules('thumbUrl', 'thumbUrl', 'required');
        if ($this->form_validation->run() == FALSE) {
            $data["error"] = 1;
            $data["error_message"] = "Asegurese que escribió correctamente.";
            $this->load->view('register_layout', $data);
        } else {
            $email = $this->input->post('email');
            $name = $this->input->post('name');
            $nick = $this->input->post('nick');
            $password = do_hash($this->input->post('password'), 'md5');
            $lastname = $this->input->post('lastname');
            $birthday = $this->input->post('birthday');
            $gender = $this->input->post('gender');
            $thumbUrl = "";
//inserta y redirige a algun lado todavia no sabemos
            $valCode = valCode();
            if ($this->user_model->emailExists($email)) {
                $data["error"] = 1;
                $data["error_message"] = "Email en uso.";
                $this->load->view('register_layout', $data);
            } else {
                if ($this->user_model->push($email, $nick, $name, $password, $lastname, $birthday, $gender, $thumbUrl, $valCode)) {
                    $mailContent = validationMail($name, $valCode, $email);
                    if ($mailContent) {
                        $data["error"] = 0;
                        redirect('/?ms=1', 'refresh');
                        return;
                    }

                    $data["error"] = 0;
                    redirect('/?confirmation_sent=false', 'refresh');
                    return;
                }
                $data["error"] = 1;
                $data["error_message"] = "Ha ocurrido un error inesperado.";
                $this->load->view('register_layout', $data);
            }
        }
    }

//ajaxalyzed json borghes was here
    public function followChannelAX() {
        $this->load->helper("email_content");
        $this->load->library("email");
        $this->load->model("channel_model");
        $this->load->model("user_model");
        if (!$this->isAuthorized()) {
            $data["error"] = 1;
            $data["error_message"] = "No tienes autorización";
            $this->load->view('home_layout', $data);
            exit; //andate de esta funcion
        }
        $this->load->model('user_model');
        $data["log"] = 1;
        $channelId = $this->input->post('channel');

        $userId = $this->session->userdata('userId');

        if ($this->user_model->followChannel($userId, $channelId)) {

//Envio de Email al dueño del canal NO ANDA
//Falta el mail
// newFollowMail($userId, $channelId);
            //Envio de Email al dueño del canal NO ANDA
            //Falta el mail
            newFollowMail($userId, $channelId);

            echo json_encode(array('result' => 'true', 'html' => ''));
            return;
        } else {
            echo json_encode(array('result' => 'false', 'html' => ''));
            return;
        }
    }

    public function unfollowChannelAX() {
        $this->load->model("channel_model");
        $this->load->model("user_model");
        if (!$this->isAuthorized()) {
            $data["error"] = 1;
            $data["error_message"] = "No tienes autorización";
            $this->load->view('home_layout', $data);
            exit; //andate de esta funcion
        }
        $this->load->model('user_model');
        $data["log"] = 1;
        $channelId = $this->input->post('channel');

        $userId = $this->session->userdata('userId');

        if ($this->user_model->unfollowChannel($userId, $channelId)) {
            echo json_encode(array('result' => 'true', 'html' => ''));
            return;
        } else {
            echo json_encode(array('result' => 'false', 'html' => ''));
            return;
        }
    }

    public function changePassword() {
        if (!$this->isAuthorized()) {
            $data["error"] = 1;
            $data["error_message"] = "Debes estar logueado";
            $this->load->view('login_layout', $data);
            return; //andate de esta funcion
        }$this->load->model('user_model');
        $this->form_validation->set_rules('oldPassword', 'Old Password', 'trim|required');
        $this->form_validation->set_rules('password', 'password', 'trim|required|matches[passconf]|min_length[5]|max_length[12]');
        $this->form_validation->set_rules('passconf', 'password Confirmation', 'trim|required');
        if ($this->form_validation->run() == FALSE) {
            $data["error"] = 1;
            $data["error_message"] = "Verifique los campos ingresados.";
            $this->load->view('change_password_layout', $data);
        } else {
            $newPassword = do_hash($this->input->post('password'), 'md5');
            $oldPassword = do_hash($this->input->post('oldPassword'), 'md5');
//inserta y redirige a algun lado todavia no sabemos
            if ($this->user_model->changePassword($this->session->userdata('userId'), $newPassword, $oldPassword)) {
//muestra alguna pagina todavia no sabemos cual
//estaria bueno mostrar un mensaje indicando que se csmbio el password correctamente, y mandar el mail
                redirect('/', 'refresh');
                return;
            }
            $data["error"] = 1;
            $data["error_message"] = "Debes intentar con tu contraseña real.";
            $this->load->view('change_password_layout', $data);
        }
    }

    /*
     * Verifica si esta usado el mail (AJAX)
     * return: bool
     */

    public function isEmailAvailable() {
        $this->form_validation->set_rules('email', 'email', 'trim|required|valid_email');
        if ($this->form_validation->run() != FALSE) {
            $email = $this->input->post('email');
            $this->load->model('user_model');
            $res = $this->user_model->isEmailAvailable($email);
            echo json_encode(array('result' => $res));
            return;
        }
        echo json_encode(array('result' => 'error'));
        return;
    }

    public function isNickAvailable() {
        $nick = $this->input->post('nick');
        $this->load->model('user_model');
        $res = $this->user_model->isNickAvailable($nick);
        echo json_encode(array('result' => $res));
        return;
    }

}


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

use app\models\general\GeneralLabel;

/* @var $this yii\web\View */
/* @var $searchModel frontend\models\RefUniversitiInstitusiEBiasiswaSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = GeneralLabel::universiti_institusi_ebiasiswa;
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a(GeneralLabel::createTitle.' '.GeneralLabel::universiti_institusi_ebiasiswa, ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            // 'id',
            [
                'attribute' => 'ref_universiti_institusi_kategori_e_biasiswa_id',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::ref_universiti_institusi_kategori_e_biasiswa_id,
                ],
                'value' => 'refUniversitiInstitusiKategoriEBiasiswa.desc',
            ],
            [
                'attribute' => 'desc',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::desc,
                ]
            ],
            // 'aktif',
            [
                'attribute' => 'aktif',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::aktif,
                ],
                'value' => function ($model) {
                    return $model->aktif == 1 ? GeneralLabel::yes : GeneralLabel::no;
                },
            ],
            // 'created_by',
            // 'updated_by',
            // 'created',
            // 'updated',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
var autobahn = require('autobahn');
var wsuri = "wss://api.poloniex.com";
var connection = new autobahn.Connection({
  url: wsuri,
  realm: "realm1"
});

connection.onopen = function (session) {
	function marketEvent (args,kwargs) {
		console.log(args);
	}
	function tickerEvent (args,kwargs) {
		console.log(args);
	}
	function trollboxEvent (args,kwargs) {
		console.log(args);
	}
	session.subscribe('BTC_XMR', marketEvent);
	session.subscribe('ticker', tickerEvent);
	session.subscribe('trollbox', trollboxEvent);
}

connection.onclose = function () {
  console.log("Websocket connection closed");
}

connection.open();


text:
package proguard.gui.splash;

import java.awt.*;

/**
 * This interface represents a Color that varies with time.
 *
 * @author Eric Lafortune
 */
interface VariableColor
{
    /**
     * Returns the Color for the given time.
     */
    public Color getColor(long time);
}


text:
//@@author A0114395E
package seedu.todoapp.logic.parser;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.joestelmach.natty.DateGroup;

/**
 * Parses loose user input for dates into proper date format
 */
public class NattyParser {
    private static NattyParser instance = null;
    private static final String EMPTY_VALUE = "-";
    private static final int TIMEZONE_IDX = 4;
    // Exists only to defeat instantiation.
    protected NattyParser() {
    }

    // Returns the singleton instance
    public static NattyParser getInstance() {
        if (instance == null) {
            instance = new NattyParser();
        }
        return instance;
    }

    /**
     * Parses, analyses and converts 'rich text' into a timestamp
     *
     * @param String - e.g. 'Tomorrow'
     * @return String - Timestamp
     */
    public String parseNLPDate(String argsString) {
        if (argsString.trim().equals(EMPTY_VALUE)) {
            return EMPTY_VALUE;
        }
        com.joestelmach.natty.Parser nParser = new com.joestelmach.natty.Parser();
        List<DateGroup> groups = nParser.parse(argsString);
        String output = "";
        for (DateGroup group : groups) {
            List<String> dateRepArr = this.getDateFromString(group);
            output = String.join(" ", dateRepArr);
        }
        return output;
    }

    /*
     * Helper function for parsing NLP date
     * @param Takes in a dategroup object parsed from Natty Library
     * @return List<String> excluding timezone
     */
    private List<String> getDateFromString(DateGroup group) {
        List<String> outputArr = new ArrayList<>(Arrays.asList(group.getDates().get(0).toString().split(" ")));
        // Remove time-zone string
        outputArr.remove(TIMEZONE_IDX);
        return outputArr;
    }
}


text:
package io.github.repir.Strategy.Tools;
import io.github.htools.lib.Log;

/**
 * Represents an occurrence of a ProximityOperator in a Document.
 * @author Jeroen Vuurens
 */
public class ProximityOccurrence implements Comparable<ProximityOccurrence> {
   public final int pos;
   public final int span;

  public ProximityOccurrence(int pos, int span) {
      this.pos = pos;
      this.span = span;
  }

   @Override
   public int compareTo(ProximityOccurrence o) {
      return (span < o.span) ? -1 : (span > o.span) ? 1 : pos - o.pos;
   }

   public String toString() {
      return "(" + pos + "," + span + ")";
   }

}


text:
using System;
using System.IO;
using System.Text;

namespace Autofac.Extras.Common.IO
{
    /// <summary>
    /// IO 流操作
    /// </summary>
    public class StreamUtil
    {
        /// <summary>
        /// 写入数据。
        /// </summary>
        /// <param name="path">路径及文件名</param>
        /// <param name="append">ture:追加,false:覆盖</param>
        /// <param name="encoding">要使用的字符编码</param>
        /// <param name="data">要写入的数据</param>
        public static void WriteData(string path, bool append, Encoding encoding, string data)
        {
            String directoryName = Path.GetDirectoryName(path);

            // 若路径不存在则创建
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }

            StreamWriter writer = new StreamWriter(path, append, encoding);

            writer.Write(data);
            writer.Flush();
            writer.Close();
            writer.Dispose();
        }

        /// <summary>
        /// 读取数据。
        /// </summary>
        /// <param name="path">路径及文件名</param>
        /// <returns>文件中的数据</returns>
        public static string ReadData(string path)
        {
            if (!File.Exists(path))
            {
                return string.Empty;
            }

            StreamReader reader = new StreamReader(path);
            string line = string.Empty; // 文件的每一行
            StringBuilder ctx = new StringBuilder(); // 完整文件内容

            while ((line = reader.ReadLine()) != null)
            {
                ctx.AppendLine(line);
            }

            reader.Close();
            reader.Dispose();

            return ctx.ToString();
        }

        /// <summary>
        /// 从指定行开始读取数据并返回总行数。
        /// </summary>
        /// <param name="path">路径及文件名</param>
        /// <param name="startRow">开始行号</param>
        /// <param name="rowCount">总行数</param>
        /// <returns>文件中的数据</returns>
        public static string ReadData(string path, int startRow, out int rowCount)
        {
            rowCount = 0; // 总行数

            // 若文件不存在则返回空
            if (!File.Exists(path))
            {
                return string.Empty;
            }

            StreamReader reader = new StreamReader(path);
            string line = string.Empty; // 文件的每一行
            StringBuilder ctx = new StringBuilder(); // 完整文件内容

            while ((line = reader.ReadLine()) != null)
            {
                if (++rowCount < startRow)
                {
                    continue;
                }

                ctx.AppendLine(line);
            }

            reader.Close();
            reader.Dispose();

            return ctx.ToString();
        }

        public static byte[] ReadBytes(Stream stream)
        {
            byte[] buffer = new byte[ 2 * 1024 ];

            using (MemoryStream memoryStream = new MemoryStream())
            {
                int part;

                while ((part = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    memoryStream.Write(buffer, 0, part);
                }

                return memoryStream.ToArray();
            }
        }
    }
}


text:
import test from 'ava';
import sinon from 'sinon';

import React from 'react';
import { shallow } from 'enzyme';

import Form from '../Form';

import Field from '../Field/Field';
import Message from '../Message/Message';

const props = {
  legend: 'test form',
  fields: [
    {
      type: 'text',
      name: 'test',
      label: 'test field',
      value: 'value1',
      placeholder: 'Write something',
      required: true,
      error: false,
    },
    {
      type: 'select',
      name: 'test2',
      label: 'test field',
      value: 'value2',
      placeholder: 'Select something',
      options: [{
        text: 'something',
        value: 'something',
      }],
      required: false,
      error: false,
    },
    {
      type: 'password',
      name: 'password-field1',
      label: 'password-label',
      value: 'abc',
      required: false,
    },
    {
      type: 'password',
      name: 'password-field2',
      label: 'password-label',
      value: 'abc',
      required: false,
      confirm: 'password-field1',
    },
  ],
  submitText: 'submit test',
  messages: {
    email: 'Not a valid email',
    tel: 'Not a valid phone number.',
    required: 'This field is required.',
    confirm: 'The value must match [label]',
  },
  sending: false,
  error: {},
  onSubmit: sinon.spy(),
};

test.afterEach(() => props.onSubmit.reset());

test('Form renders as a form element', (t) => {
  const wrapper = shallow(<Form {...props} />);

  t.is(wrapper.type(), 'form');
});

test('Form renders a legend with text that matches props', (t) => {
  const wrapper = shallow(<Form {...props} />);

  t.is(wrapper.find('legend').length, 1);
  t.is(wrapper.find('legend').first().text(), props.legend);
});

test('Form does not render any legend if it is omitted from props', (t) => {
  const noLegend = { ...props };
  delete noLegend.legend;

  const wrapper = shallow(<Form {...noLegend} />);

  t.is(wrapper.find('legend').length, 0);
});

test('Form renders an error message if error.message is set in props', (t) => {
  const wrapperNoError = shallow(<Form {...props} />);

  const errorProps = {
    ...props,
    error: {
      message: 'there was an error',
    },
  };

  t.is(wrapperNoError.find(Message).length, 0);

  const wrapperError = shallow(<Form {...errorProps} />);

  t.is(wrapperError.find(Message).length, 1);
});

test('Form renders the same ammount of fields as specified in props', (t) => {
  const wrapper = shallow(<Form {...props} />);

  t.is(wrapper.find(Field).length, props.fields.length);
});

test('Form calls props.onSubmit when the form is submitted', (t) => {
  const wrapper = shallow(<Form {...props} />);

  wrapper.simulate('submit');

  t.true(props.onSubmit.calledOnce);
});

test('Form does not call props.onSubmit if props.sending is true', (t) => {
  const wrapper = shallow(<Form {...props} />);
  const component = wrapper.instance();

  wrapper.setProps({ sending: true });
  wrapper.update();

  component.onSubmit();

  t.true(props.onSubmit.notCalled);
});

test('Form does not call props.onSubmit if there is an error in state.error', (t) => {
  const wrapper = shallow(
    <Form
      url={'/success'}
      fields={[
        {
          type: 'text',
          name: 'name',
          value: '',
          required: true,
        },
      ]}
    />
  );
  const component = wrapper.instance();

  component.onSubmit();

  t.true(props.onSubmit.notCalled);
});

test('Form:onSubmit calls preventDefault and stopPropagation if event is passed', (t) => {
  const wrapper = shallow(<Form {...props} />);
  const component = wrapper.instance();

  const event = {
    preventDefault: sinon.spy(),
    stopPropagation: sinon.spy(),
  };

  component.onSubmit(event);

  t.true(event.preventDefault.calledOnce);
  t.true(event.stopPropagation.calledOnce);
});

test('Form calls props.onSubmit with data if not props.sending and no state.error', (t) => {
  const wrapper = shallow(<Form {...props} />);
  const component = wrapper.instance();

  component.onSubmit();

  t.true(props.onSubmit.calledWith({
    [props.fields[0].name]: props.fields[0].value,
    [props.fields[1].name]: props.fields[1].value,
    [props.fields[2].name]: props.fields[2].value,
    [props.fields[3].name]: props.fields[3].value,
  }));
});

test('Form:setError updates state.errors', (t) => {
  const wrapper = shallow(<Form {...props} />);
  const component = wrapper.instance();

  const errorMessage = 'some message';

  component.setError({ select: false });

  t.is(wrapper.state('error').select, undefined);

  component.setError({ select: errorMessage });

  t.is(wrapper.state('error').select, errorMessage);
});

test('Form:setFieldStatus updates values in state.form', (t) => {
  const wrapper = shallow(<Form {...props} />);
  const component = wrapper.instance();

  const name = props.fields[0].name;
  const value = 'some value';

  t.is(wrapper.state('form')[name].value, props.fields[0].value);

  component.setFieldStatus(name, value, false);

  t.is(wrapper.state('form')[name].value, value);
});

test('Form:setFieldStatus updates errors and validity in state.errors and state.form on error', (t) => {
  const wrapper = shallow(<Form {...props} />);
  const component = wrapper.instance();

  const name = props.fields[0].name;
  const value = 'some value';
  const errorMessage = 'some error message';

  component.setFieldStatus(name, value, false);

  t.falsy(wrapper.state('error')[name]);
  t.true(wrapper.state('form')[name].valid);

  component.setFieldStatus(name, '', errorMessage);

  t.is(wrapper.state('error')[name], errorMessage);
  t.false(wrapper.state('form')[name].valid);
});

test('Form:reset calls preventDefault and stopPropagation if event is passed', (t) => {
  const wrapper = shallow(<Form {...props} />);
  const component = wrapper.instance();

  const event = {
    preventDefault: sinon.spy(),
    stopPropagation: sinon.spy(),
  };

  component.reset(event);

  t.true(event.preventDefault.calledOnce);
  t.true(event.stopPropagation.calledOnce);
});

test('Form:reset resets all form values', (t) => {
  const wrapper = shallow(<Form {...props} />);
  const component = wrapper.instance();

  t.is(wrapper.state('form').test.value, props.fields[0].value);
  t.is(wrapper.state('form').test2.value, props.fields[1].value);

  component.reset();

  t.is(wrapper.state('form').test.value, '');
  t.is(wrapper.state('form').test2.value, '');
});

test('Form:validate returns false and calls Form:setFieldStatus with error if required field has no value', (t) => {
  const field = {
    name: 'text-field',
    label: 'text-label',
    value: ' ',
    required: true,
  };

  const messages = {
    required: 'EEEEEE',
  };

  const wrapper = shallow(<Form {...{ ...props, fields: [field], messages }} />);
  const component = wrapper.instance();
  sinon.spy(component, 'setFieldStatus');

  const { name, label, value, required } = field;

  t.false(component.validate(name, label, value, required));
  t.true(component.setFieldStatus.calledWith(name, value, messages.required));
});

test('Form:validate returns true and calls Form:setFieldStatus without error if value is not required', (t) => {
  const field = {
    name: 'text-field',
    label: 'text-label',
    value: '',
    required: false,
  };

  const wrapper = shallow(<Form {...{ ...props, fields: [field] }} />);
  const component = wrapper.instance();
  sinon.spy(component, 'setFieldStatus');

  const { name, label, value, required } = field;

  t.true(component.validate(name, label, value, required));
  t.true(component.setFieldStatus.calledWith(name, value, false));
});

test('Form:validate returns false and calls Form:setFieldStatus with error if value does not match constraints', (t) => {
  const field = {
    name: 'email',
    label: 'text-label',
    value: 'asdsa',
    required: false,
    constraints: [
      '^([^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-',
      '\\x5d\\x7f-\\xff]+|\\x22([^\\x0d\\x22\\x5c\\x80-\\xff]|\\x5c[\\x00-',
      '\\x7f])*\\x22)(\\x2e([^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\',
      'x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+|\\x22([^\\x0d\\x22\\x5c\\x80-',
      '\\xff]|\\x5c[\\x00-\\x7f])*\\x22))*\\x40([^\\x00-\\x20\\x22\\x28\\x',
      '29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+|\\x5b([^',
      '\\x0d\\x5b-\\x5d\\x80-\\xff]|\\x5c[\\x00-\\x7f])*\\x5d)(\\x2e([^\\x',
      '00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d',
      '\\x7f-\\xff]+|\\x5b([^\\x0d\\x5b-\\x5d\\x80-\\xff]|\\x5c[\\x00-\\x7',
      'f])*\\x5d))*$',
    ].join(''),
  };

  const messages = {
    email: 'EEEEEE',
  };

  const wrapper = shallow(<Form {...{ ...props, fields: [field], messages }} />);
  const component = wrapper.instance();
  sinon.spy(component, 'setFieldStatus');

  const { name, label, value, required, constraints } = field;

  t.false(component.validate(name, label, value, required, constraints));
  t.true(component.setFieldStatus.calledWith(name, value, messages.email));
});

test('Form:validate returns true and calls Form:setFieldStatus without error if value matches constraints', (t) => {
  const field = {
    name: 'email',
    label: 'text-label',
    value: 'an@email.com',
    required: false,
    constraints: [
      '^([^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-',
      '\\x5d\\x7f-\\xff]+|\\x22([^\\x0d\\x22\\x5c\\x80-\\xff]|\\x5c[\\x00-',
      '\\x7f])*\\x22)(\\x2e([^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\',
      'x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+|\\x22([^\\x0d\\x22\\x5c\\x80-',
      '\\xff]|\\x5c[\\x00-\\x7f])*\\x22))*\\x40([^\\x00-\\x20\\x22\\x28\\x',
      '29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+|\\x5b([^',
      '\\x0d\\x5b-\\x5d\\x80-\\xff]|\\x5c[\\x00-\\x7f])*\\x5d)(\\x2e([^\\x',
      '00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d',
      '\\x7f-\\xff]+|\\x5b([^\\x0d\\x5b-\\x5d\\x80-\\xff]|\\x5c[\\x00-\\x7',
      'f])*\\x5d))*$',
    ].join(''),
  };

  const messages = {
    email: 'EEEEEE',
  };

  const wrapper = shallow(<Form {...{ ...props, fields: [field], messages }} />);
  const component = wrapper.instance();
  sinon.spy(component, 'setFieldStatus');

  const { name, label, value, required, constraints } = field;

  t.true(component.validate(name, label, value, required, constraints));
  t.true(component.setFieldStatus.calledWith(name, value, false));
});

test('Form:validate returns false and calls Form:setFieldStatus with error if value does not match the confirm-field value', (t) => {
  const fields = [
    {
      name: 'text',
      value: 'abcd',
      confirm: 'text2',
    },
    {
      name: 'text2',
      value: 'abc',
    },
  ];

  const messages = {
    confirm: 'EEEEEE',
  };

  const wrapper = shallow(<Form {...{ ...props, fields, messages }} />);
  const component = wrapper.instance();
  sinon.spy(component, 'setFieldStatus');

  const { name, label, value, required, constraints, confirm } = fields[0];

  t.false(component.validate(name, label, value, required, constraints, confirm));
  t.true(component.setFieldStatus.calledWith(name, value, messages.confirm));
});

test('Form:validate returns true and calls Form:setFieldStatus without error if value matches confirm-field value', (t) => {
  const fields = [
    {
      name: 'text',
      value: 'abcd',
      confirm: 'text2',
    },
    {
      name: 'text2',
      value: 'abcd',
    },
  ];

  const wrapper = shallow(<Form {...{ ...props, fields }} />);
  const component = wrapper.instance();
  sinon.spy(component, 'setFieldStatus');

  const { name, label, value, required, constraints, confirm } = fields[0];

  t.true(component.validate(name, label, value, required, constraints, confirm));
  t.true(component.setFieldStatus.calledWith(name, value, false));
});


text:
#region License
// /*
// See license included in this library folder.
// */
#endregion

using System.Collections.Generic;
using Sqloogle.Libs.NLog.Config;
using Sqloogle.Libs.NLog.LayoutRenderers;
using Sqloogle.Libs.NLog.Layouts;

namespace Sqloogle.Libs.NLog.Targets
{
    ///
    ///     Sends log messages to the remote instance of NLog Viewer.
    ///
    /// <seealso href="http://nlog-project.org/wiki/NLogViewer_target">Documentation on NLog Wiki</seealso>
    /// <example>
    ///

    ///         To set up the target in the configuration file,
    ///         use the following syntax:
    ///

    ///
    ///

    ///         This assumes just one target and a single rule. More configuration
    ///         options are described here.
    ///

    ///

    ///         To set up the log target programmatically use code like this:
    ///

    ///
    ///

    ///         NOTE: If your receiver application is ever likely to be off-line, don't use TCP protocol
    ///         or you'll get TCP timeouts and your application will crawl.
    ///         Either switch to UDP transport or use AsyncWrapper target
    ///         so that your application threads will not be blocked by the timing-out connection attempts.
    ///

    /// </example>
    [Target("NLogViewer")]
    public class NLogViewerTarget : NetworkTarget
    {
        private readonly Log4JXmlEventLayout layout = new Log4JXmlEventLayout();

        ///
        ///     Initializes a new instance of the <see cref="NLogViewerTarget" /> class.
        ///
        /// <remarks>
        ///     The default value of the layout is: ${longdate}|${level:uppercase=true}|${logger}|${message}
        /// </remarks>
        public NLogViewerTarget()
        {
            Parameters = new List<NLogViewerParameterInfo>();
            Renderer.Parameters = Parameters;
            NewLine = false;
        }

        ///
        ///     Gets or sets a value indicating whether to include NLog-specific extensions to log4j schema.
        ///
        /// <docgen category='Payload Options' order='10' />
        public bool IncludeNLogData
        {
            get { return Renderer.IncludeNLogData; }
            set { Renderer.IncludeNLogData = value; }
        }

        ///
        ///     Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain.
        ///
        /// <docgen category='Payload Options' order='10' />
        public string AppInfo
        {
            get { return Renderer.AppInfo; }
            set { Renderer.AppInfo = value; }
        }

#if !NET_CF
        ///
        ///     Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network.
        ///
        /// <docgen category='Payload Options' order='10' />
        public bool IncludeCallSite
        {
            get { return Renderer.IncludeCallSite; }
            set { Renderer.IncludeCallSite = value; }
        }

#if !SILVERLIGHT
        ///
        ///     Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network.
        ///
        /// <docgen category='Payload Options' order='10' />
        public bool IncludeSourceInfo
        {
            get { return Renderer.IncludeSourceInfo; }
            set { Renderer.IncludeSourceInfo = value; }
        }
#endif

#endif

        ///
        ///     Gets or sets a value indicating whether to include <see cref="MappedDiagnosticsContext" /> dictionary contents.
        ///
        /// <docgen category='Payload Options' order='10' />
        public bool IncludeMdc
        {
            get { return Renderer.IncludeMdc; }
            set { Renderer.IncludeMdc = value; }
        }

        ///
        ///     Gets or sets a value indicating whether to include <see cref="NestedDiagnosticsContext" /> stack contents.
        ///
        /// <docgen category='Payload Options' order='10' />
        public bool IncludeNdc
        {
            get { return Renderer.IncludeNdc; }
            set { Renderer.IncludeNdc = value; }
        }

        ///
        ///     Gets or sets the NDC item separator.
        ///
        /// <docgen category='Payload Options' order='10' />
        public string NdcItemSeparator
        {
            get { return Renderer.NdcItemSeparator; }
            set { Renderer.NdcItemSeparator = value; }
        }

        ///
        ///     Gets the collection of parameters. Each parameter contains a mapping
        ///     between NLog layout and a named parameter.
        ///
        /// <docgen category='Payload Options' order='10' />
        [ArrayParameter(typeof (NLogViewerParameterInfo), "parameter")]
        public IList<NLogViewerParameterInfo> Parameters { get; private set; }

        ///
        ///     Gets the layout renderer which produces Log4j-compatible XML events.
        ///
        public Log4JXmlEventLayoutRenderer Renderer
        {
            get { return layout.Renderer; }
        }

        ///
        ///     Gets or sets the instance of <see cref="Log4JXmlEventLayout" /> that is used to format log messages.
        ///
        /// <docgen category='Layout Options' order='10' />
        public override Layout Layout
        {
            get { return layout; }

            set { }
        }
    }
}


text:
package org.zaproxy.addon.paramdigger;

public interface GuesserProgressListener {

    void updateProgress(int scanId, String displayName, int paramsTried, int totalParams);

    void completed(int scanId, String displayName, boolean successfully);
}


text:
//: typeinfo/PetCount2.java
import typeinfo.pets.*;

public class PetCount2 {
  public static void main(String[] args) {
    PetCount.countPets(Pets.creator);
  }
} /* (Execute to see output) *///:~


text:
namespace platf {

//
// Allocates a single object on general heap
//
struct SingleAlloc {
    template <class Type, class... Args>
    E4_NODISCARD static Type*
    alloc_class(Args&&... args) {
        return new Type(std::forward<Args>(args)...);
    }

    template<class T>
    static void free(T* p) {
        if (p) { delete p; }
    }
};

//
// Allocates array on general heap
//
struct ArrayAlloc {
    template<class T>
    E4_NODISCARD static T*
    alloc(::size_t sz) {
        return new T[sz];
    }

    template<class T>
    static void free(T* p) {
        if (p) { delete[] p; }
    }
};

} // ns platf


text:
package org.uma.jmetal.operator.crossover.impl;

import org.uma.jmetal.operator.crossover.CrossoverOperator;
import org.uma.jmetal.solution.integersolution.IntegerSolution;
import org.uma.jmetal.util.JMetalException;
import org.uma.jmetal.util.bounds.Bounds;
import org.uma.jmetal.util.pseudorandom.JMetalRandom;
import org.uma.jmetal.util.pseudorandom.RandomGenerator;

import java.util.ArrayList;
import java.util.List;

/**
 * This class allows to apply a SBX crossover operator using two parent solutions (Integer encoding)
 *
 * @author Antonio J. Nebro <antonio@lcc.uma.es>
 */
@SuppressWarnings("serial")
public class IntegerSBXCrossover implements CrossoverOperator<IntegerSolution> {
  /** EPS defines the minimum difference allowed between real values */
  private static final double EPS = 1.0e-14;

  private double distributionIndex ;
  private double crossoverProbability  ;

  private RandomGenerator<Double> randomGenerator ;

  /** Constructor */
  public IntegerSBXCrossover(double crossoverProbability, double distributionIndex) {
	  this(crossoverProbability, distributionIndex, () -> JMetalRandom.getInstance().nextDouble());
  }

  /** Constructor */
  public IntegerSBXCrossover(double crossoverProbability, double distributionIndex, RandomGenerator<Double> randomGenerator) {
    if (crossoverProbability < 0) {
      throw new JMetalException("Crossover probability is negative: " + crossoverProbability) ;
    } else if (distributionIndex < 0) {
      throw new JMetalException("Distribution index is negative: " + distributionIndex);
    }

    this.crossoverProbability = crossoverProbability ;
    this.distributionIndex = distributionIndex ;
    this.randomGenerator = randomGenerator ;
  }

  /* Getters */
  @Override
  public double getCrossoverProbability() {
    return crossoverProbability;
  }

  public double getDistributionIndex() {
    return distributionIndex;
  }

  /* Setters */
  public void setDistributionIndex(double distributionIndex) {
    this.distributionIndex = distributionIndex;
  }

  public void setCrossoverProbability(double crossoverProbability) {
    this.crossoverProbability = crossoverProbability;
  }

  /** Execute() method */
  @Override
  public List<IntegerSolution> execute(List<IntegerSolution> solutions) {
    if (null == solutions) {
      throw new JMetalException("Null parameter") ;
    } else if (solutions.size() != 2) {
      throw new JMetalException("There must be two parents instead of " + solutions.size()) ;
    }

    return doCrossover(crossoverProbability, solutions.get(0), solutions.get(1)) ;
  }

  /** doCrossover method */
  public List<IntegerSolution> doCrossover(
          double probability, IntegerSolution parent1, IntegerSolution parent2) {
    List<IntegerSolution> offspring = new ArrayList<IntegerSolution>(2);

    offspring.add((IntegerSolution) parent1.copy()) ;
    offspring.add((IntegerSolution) parent2.copy()) ;

    int i;
    double rand;
    double y1, y2, yL, yu;
    double c1, c2;
    double alpha, beta, betaq;
    int valueX1, valueX2;

    if (randomGenerator.getRandomValue() <= probability) {
      for (i = 0; i < parent1.getNumberOfVariables(); i++) {
        valueX1 = parent1.getVariable(i);
        valueX2 = parent2.getVariable(i);
        if (randomGenerator.getRandomValue() <= 0.5) {
          if (Math.abs(valueX1 - valueX2) > EPS) {

            if (valueX1 < valueX2) {
              y1 = valueX1;
              y2 = valueX2;
            } else {
              y1 = valueX2;
              y2 = valueX1;
            }

            Bounds<Integer> bounds = parent1.getBounds(i);
            yL = bounds.getLowerBound();
            yu = bounds.getUpperBound();
            rand = randomGenerator.getRandomValue();
            beta = 1.0 + (2.0 * (y1 - yL) / (y2 - y1));
            alpha = 2.0 - Math.pow(beta, -(distributionIndex + 1.0));

            if (rand <= (1.0 / alpha)) {
              betaq = Math.pow((rand * alpha), (1.0 / (distributionIndex + 1.0)));
            } else {
              betaq = Math
                .pow(1.0 / (2.0 - rand * alpha), 1.0 / (distributionIndex + 1.0));
            }

            c1 = 0.5 * ((y1 + y2) - betaq * (y2 - y1));
            beta = 1.0 + (2.0 * (yu - y2) / (y2 - y1));
            alpha = 2.0 - Math.pow(beta, -(distributionIndex + 1.0));

            if (rand <= (1.0 / alpha)) {
              betaq = Math.pow((rand * alpha), (1.0 / (distributionIndex + 1.0)));
            } else {
              betaq = Math
                .pow(1.0 / (2.0 - rand * alpha), 1.0 / (distributionIndex + 1.0));
            }

            c2 = 0.5 * (y1 + y2 + betaq * (y2 - y1));

            if (c1 < yL) {
              c1 = yL;
            }

            if (c2 < yL) {
              c2 = yL;
            }

            if (c1 > yu) {
              c1 = yu;
            }

            if (c2 > yu) {
              c2 = yu;
            }

            if (randomGenerator.getRandomValue() <= 0.5) {
              offspring.get(0).setVariable(i, (int)c2);
              offspring.get(1).setVariable(i, (int)c1);
            } else {
              offspring.get(0).setVariable(i, (int)c1);
              offspring.get(1).setVariable(i, (int)c2);
            }
          } else {
            offspring.get(0).setVariable(i, valueX1);
            offspring.get(1).setVariable(i, valueX2);
          }
        } else {
          offspring.get(0).setVariable(i, valueX2);
          offspring.get(1).setVariable(i, valueX1);
        }
      }
    }

    return offspring;
  }

  public int getNumberOfRequiredParents() {
    return 2 ;
  }

  public int getNumberOfGeneratedChildren() {
    return 2 ;
  }
}


text:
package org.apache.camel.processor;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;

/**
 * @version
 */
public class FilterNotMatchedTest extends ContextTestSupport {

    public void testSendMatchingMessage() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(1);
        mock.message(0).exchangeProperty(Exchange.FILTER_MATCHED).isEqualTo(true);

        getMockEndpoint("mock:end").message(0).exchangeProperty(Exchange.FILTER_MATCHED).isNotNull();
        getMockEndpoint("mock:end").message(0).exchangeProperty(Exchange.FILTER_MATCHED).isEqualTo(true);

        template.sendBodyAndHeader("direct:start", "<matched/>", "foo", "bar");

        assertMockEndpointsSatisfied();
    }

    public void testSendNotMatchingMessage() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(0);

        getMockEndpoint("mock:end").message(0).exchangeProperty(Exchange.FILTER_MATCHED).isNotNull();
        getMockEndpoint("mock:end").message(0).exchangeProperty(Exchange.FILTER_MATCHED).isEqualTo(false);

        template.sendBodyAndHeader("direct:start", "<notMatched/>", "foo", "notMatchedHeaderValue");

        assertMockEndpointsSatisfied();
    }

    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            public void configure() {
                from("direct:start")
                    .filter(header("foo").isEqualTo("bar"))
                        .to("mock:result")
                    .end()
                    .to("mock:end");
            }
        };
    }

}


text:
package com.github.bjoern2.codegen;

import java.util.List;

import org.apache.commons.lang3.ObjectUtils;

public class JavaTypeImpl implements JavaType {

	private String name;
	private List<JavaType> generics;
	private int arrays;

	public JavaTypeImpl() {
		super();
	}

	public JavaTypeImpl(String name) {
		super();
		this.name = name;
	}

	public JavaTypeImpl(String name, List<JavaType> generics) {
		super();
		this.name = name;
		this.generics = generics;
	}

	public JavaTypeImpl(String name, int arrays) {
		super();
		this.name = name;
		this.arrays = arrays;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public List<JavaType> getGenerics() {
		return generics;
	}

	@Override
	public void setGenerics(List<JavaType> generics) {
		this.generics = generics;
	}

	@Override
	public void write(int tabs, Generator writer) {
		writer.tab(tabs).write(name);
		if ((generics != null) && (!generics.isEmpty())) {
			writer.write("<");
			for (JavaType t : generics) {
				t.write(tabs, writer);
			}
			writer.write(">");
		}

		if (arrays > 0) {
			for (int i = 0; i < arrays; i++) {
				writer.write("[]");
			}
		}

	}

	@Override
	public void setArray(int count) {
		this.arrays = count;
	}

	public static JavaTypeImpl _void() {
		return new JavaTypeImpl("void");
	}

	public static JavaTypeImpl _int() {
		return new JavaTypeImpl("int");
	}

	public static JavaTypeImpl _long() {
		return new JavaTypeImpl("long");
	}

	public static JavaTypeImpl _String() {
		return new JavaTypeImpl("String");
	}

	@Override
	public int getArray() {
		return arrays;
	}

	@Override
	public JavaTypeImpl clone() {
		return ObjectUtils.clone(this);
	}

}


text:
from django import forms

from organizations.models import Organization, get_user_model

class UserRegistrationForm(forms.ModelForm):
    """Form class for completing a user's registration and activating the
    User."""
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    password = forms.CharField(max_length=30, widget=forms.PasswordInput)
    password_confirm = forms.CharField(max_length=30,
            widget=forms.PasswordInput)

    def __init__(self, *args, **kwargs):
        super(UserRegistrationForm, self).__init__(*args, **kwargs)
        self.initial['username'] = ''

    class Meta:
        model = get_user_model()
        exclude = ('is_staff', 'is_superuser', 'is_active', 'last_login',
                'date_joined', 'groups', 'user_permissions')

class OrganizationRegistrationForm(forms.ModelForm):
    """Form class for creating new organizations owned by new users."""
    email = forms.EmailField()

    class Meta:
        model = Organization
        exclude = ('is_active', 'users')

    def save(self, *args, **kwargs):
        self.instance.is_active = False
        super(OrganizationRegistrationForm, self).save(*args, **kwargs)