text:
// Gervill4Beads - integrate Gervill with the Beads library
// Copyright (c) 2015, David H. Hovemeyer <david.hovemeyer@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package io.github.daveho.gervill4beads;

import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.Map;

import javax.sound.midi.MidiMessage;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.Synthesizer;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioFormat.Encoding;
import javax.sound.sampled.AudioInputStream;

import net.beadsproject.beads.core.AudioContext;
import net.beadsproject.beads.core.Bead;
import net.beadsproject.beads.core.UGen;

/**
 * A UGen that generates audio using the
 * Gervill
 * software synthesizer.
 *
 * @author David Hovemeyer
 */
public class GervillUGen extends UGen {
	private Synthesizer synth;
	private Receiver synthRecv;
	private AudioInputStream synthAis;
	private ByteBuffer byteBuffer;
	private FloatBuffer floatBuffer;

	/**
	 * Constructor.
	 *
	 * @param context  the AudioContext
	 * @param info     info, used when opening an audio input stream from the synthesizer
	 * @throws MidiUnavailableException
	 */
	public GervillUGen(AudioContext context, Map<String, Object> info) throws MidiUnavailableException {
		super(context, 2);

		// Use reflection to instantiate a SoftSynthesizer object.
		// We definitely do NOT want to do this via MidiSystem, since
		//   (1) we won't necessarily get a SoftSynthesizer, and
		//   (2) it won't allow multiple SoftSynthesizers to be open
		//       at the same time
		try {
			Class<?> synthCls = Class.forName("com.sun.media.sound.SoftSynthesizer");
			Object synthObj = synthCls.newInstance();
			this.synth = (Synthesizer) synthObj;
		} catch (ClassNotFoundException e) {
			throw new MidiUnavailableException("Could not find SoftSynthesizer class: " + e.toString());
		} catch (Throwable e) {
			throw new MidiUnavailableException("Could not create SoftSynthesizer object: " + e.toString());
		}

		// Get the synthesizer's MIDI Receiver
		synthRecv = synth.getReceiver();

		// Use the Beads AudioContext's sample rate
		float sampleRate = context.getSampleRate();

		// Create an AudioFormat with same sample rate as AudioContext's,
		// using PCM_FLOAT encoding, 32 bits per sample.  This makes
		// calculateBuffer very simple: we just pull floats from Gervill
		// and copy them into the buffer for each output channel.
		int sampleSize = 32;
		AudioFormat fmt = new AudioFormat(Encoding.PCM_FLOAT, sampleRate, sampleSize, 2, ((2*sampleSize)+7)/8, sampleRate, true);

		// The AudioSynthesizer/SoftSynthesizer types aren't exported.
		// So, cheat and use reflection to call openStream.  There literally
		// doesn't seem to be any other way of getting an AudioInputStream
		// from a Synthesizer in Java!
		try {
			Method openStream = synth.getClass().getMethod("openStream", new Class[]{AudioFormat.class, Map.class});
			this.synthAis = (AudioInputStream) openStream.invoke(synth, fmt, info);
		} catch (Throwable e) {
			throw new MidiUnavailableException("Could not get openStream method for Synthesizer: " + e.toString());
		}

		// Use a ByteBuffer (with a FloatBuffer view) to store audio data
		// produce by Gervill.  This is a simple and efficient mechanism
		// for grabbing the data.
		byteBuffer = ByteBuffer.allocate(fmt.getFrameSize() * bufferSize);
		floatBuffer = byteBuffer.asFloatBuffer();
	}

	/**
	 * Get the Gervill SoftSynthesizer.
	 *
	 * @return the Gervill SoftSynthesizer
	 */
	public Synthesizer getSynth() {
		return synth;
	}

	/**
	 * Get the SoftSynthesizer's midi Receiver.
	 *
	 * @return the SoftSynthesizer's midi Receiver
	 */
	public Receiver getSynthRecv() {
		return synthRecv;
	}

	@Override
	protected void messageReceived(Bead message) {
		if (Midi.hasMidiMessage(message)) {
			MidiMessage msg = Midi.getMidiMessage(message);
			long timestamp = Midi.getMidiTimestamp(message);
//			System.out.printf("GervillUGen: received midi message (status=%d,ts=%d)!\n", msg.getStatus(), timestamp);
			synthRecv.send(msg, timestamp);
		}
	}

	@Override
	public void calculateBuffer() {
		try {
			synthAis.read(byteBuffer.array());
			for (int i = 0; i < bufferSize; i++) {
				bufOut[0][i] = floatBuffer.get(i*2);
				bufOut[1][i] = floatBuffer.get(i*2 + 1);
			}
		} catch (IOException e) {
			throw new RuntimeException("IOException reading data from Gervill synth", e);
		}
	}
}


text:
#include "core/html/HTMLCollection.h"

#include "core/HTMLNames.h"
#include "core/dom/ClassCollection.h"
#include "core/dom/ElementTraversal.h"
#include "core/dom/NodeRareData.h"
#include "core/html/DocumentNameCollection.h"
#include "core/html/HTMLDataListOptionsCollection.h"
#include "core/html/HTMLElement.h"
#include "core/html/HTMLFormControlElement.h"
#include "core/html/HTMLObjectElement.h"
#include "core/html/HTMLOptionElement.h"
#include "core/html/HTMLOptionsCollection.h"
#include "core/html/HTMLTagCollection.h"
#include "core/html/WindowNameCollection.h"
#include "wtf/HashSet.h"

namespace blink {

using namespace HTMLNames;

static bool shouldTypeOnlyIncludeDirectChildren(CollectionType type) {
  switch (type) {
    case ClassCollectionType:
    case TagCollectionType:
    case HTMLTagCollectionType:
    case DocAll:
    case DocAnchors:
    case DocApplets:
    case DocEmbeds:
    case DocForms:
    case DocImages:
    case DocLinks:
    case DocScripts:
    case DocumentNamedItems:
    case MapAreas:
    case TableRows:
    case SelectOptions:
    case SelectedOptions:
    case DataListOptions:
    case WindowNamedItems:
    case FormControls:
      return false;
    case NodeChildren:
    case TRCells:
    case TSectionRows:
    case TableTBodies:
      return true;
    case NameNodeListType:
    case RadioNodeListType:
    case RadioImgNodeListType:
    case LabelsNodeListType:
      break;
  }
  NOTREACHED();
  return false;
}

static NodeListRootType rootTypeFromCollectionType(const ContainerNode& owner,
                                                   CollectionType type) {
  switch (type) {
    case DocImages:
    case DocApplets:
    case DocEmbeds:
    case DocForms:
    case DocLinks:
    case DocAnchors:
    case DocScripts:
    case DocAll:
    case WindowNamedItems:
    case DocumentNamedItems:
      return NodeListRootType::TreeScope;
    case ClassCollectionType:
    case TagCollectionType:
    case HTMLTagCollectionType:
    case NodeChildren:
    case TableTBodies:
    case TSectionRows:
    case TableRows:
    case TRCells:
    case SelectOptions:
    case SelectedOptions:
    case DataListOptions:
    case MapAreas:
      return NodeListRootType::Node;
    case FormControls:
      if (isHTMLFieldSetElement(owner))
        return NodeListRootType::Node;
      DCHECK(isHTMLFormElement(owner));
      return NodeListRootType::TreeScope;
    case NameNodeListType:
    case RadioNodeListType:
    case RadioImgNodeListType:
    case LabelsNodeListType:
      break;
  }
  NOTREACHED();
  return NodeListRootType::Node;
}

static NodeListInvalidationType invalidationTypeExcludingIdAndNameAttributes(
    CollectionType type) {
  switch (type) {
    case TagCollectionType:
    case HTMLTagCollectionType:
    case DocImages:
    case DocEmbeds:
    case DocForms:
    case DocScripts:
    case DocAll:
    case NodeChildren:
    case TableTBodies:
    case TSectionRows:
    case TableRows:
    case TRCells:
    case SelectOptions:
    case MapAreas:
      return DoNotInvalidateOnAttributeChanges;
    case DocApplets:
    case SelectedOptions:
    case DataListOptions:
      // FIXME: We can do better some day.
      return InvalidateOnAnyAttrChange;
    case DocAnchors:
      return InvalidateOnNameAttrChange;
    case DocLinks:
      return InvalidateOnHRefAttrChange;
    case WindowNamedItems:
      return InvalidateOnIdNameAttrChange;
    case DocumentNamedItems:
      return InvalidateOnIdNameAttrChange;
    case FormControls:
      return InvalidateForFormControls;
    case ClassCollectionType:
      return InvalidateOnClassAttrChange;
    case NameNodeListType:
    case RadioNodeListType:
    case RadioImgNodeListType:
    case LabelsNodeListType:
      break;
  }
  NOTREACHED();
  return DoNotInvalidateOnAttributeChanges;
}

HTMLCollection::HTMLCollection(ContainerNode& ownerNode,
                               CollectionType type,
                               ItemAfterOverrideType itemAfterOverrideType)
    : LiveNodeListBase(ownerNode,
                       rootTypeFromCollectionType(ownerNode, type),
                       invalidationTypeExcludingIdAndNameAttributes(type),
                       type),
      m_overridesItemAfter(itemAfterOverrideType == OverridesItemAfter),
      m_shouldOnlyIncludeDirectChildren(
          shouldTypeOnlyIncludeDirectChildren(type)) {
  // Keep this in the child class because |registerNodeList| requires wrapper
  // tracing and potentially calls virtual methods which is not allowed in a
  // base class constructor.
  document().registerNodeList(this);
}

HTMLCollection* HTMLCollection::create(ContainerNode& base,
                                       CollectionType type) {
  return new HTMLCollection(base, type, DoesNotOverrideItemAfter);
}

HTMLCollection::~HTMLCollection() {}

void HTMLCollection::invalidateCache(Document* oldDocument) const {
  m_collectionItemsCache.invalidate();
  invalidateIdNameCacheMaps(oldDocument);
}

unsigned HTMLCollection::length() const {
  return m_collectionItemsCache.nodeCount(*this);
}

Element* HTMLCollection::item(unsigned offset) const {
  return m_collectionItemsCache.nodeAt(*this, offset);
}

static inline bool isMatchingHTMLElement(const HTMLCollection& htmlCollection,
                                         const HTMLElement& element) {
  switch (htmlCollection.type()) {
    case DocImages:
      return element.hasTagName(imgTag);
    case DocScripts:
      return element.hasTagName(scriptTag);
    case DocForms:
      return element.hasTagName(formTag);
    case DocumentNamedItems:
      return toDocumentNameCollection(htmlCollection).elementMatches(element);
    case TableTBodies:
      return element.hasTagName(tbodyTag);
    case TRCells:
      return element.hasTagName(tdTag) || element.hasTagName(thTag);
    case TSectionRows:
      return element.hasTagName(trTag);
    case SelectOptions:
      return toHTMLOptionsCollection(htmlCollection).elementMatches(element);
    case SelectedOptions:
      return isHTMLOptionElement(element) &&
             toHTMLOptionElement(element).selected();
    case DataListOptions:
      return toHTMLDataListOptionsCollection(htmlCollection)
          .elementMatches(element);
    case MapAreas:
      return element.hasTagName(areaTag);
    case DocApplets:
      return isHTMLObjectElement(element) &&
             toHTMLObjectElement(element).containsJavaApplet();
    case DocEmbeds:
      return element.hasTagName(embedTag);
    case DocLinks:
      return (element.hasTagName(aTag) || element.hasTagName(areaTag)) &&
             element.fastHasAttribute(hrefAttr);
    case DocAnchors:
      return element.hasTagName(aTag) && element.fastHasAttribute(nameAttr);
    case FormControls:
      DCHECK(isHTMLFieldSetElement(htmlCollection.ownerNode()));
      return isHTMLObjectElement(element) || isHTMLFormControlElement(element);
    case ClassCollectionType:
    case TagCollectionType:
    case HTMLTagCollectionType:
    case DocAll:
    case NodeChildren:
    case TableRows:
    case WindowNamedItems:
    case NameNodeListType:
    case RadioNodeListType:
    case RadioImgNodeListType:
    case LabelsNodeListType:
      NOTREACHED();
  }
  return false;
}

inline bool HTMLCollection::elementMatches(const Element& element) const {
  // These collections apply to any kind of Elements, not just HTMLElements.
  switch (type()) {
    case DocAll:
    case NodeChildren:
      return true;
    case ClassCollectionType:
      return toClassCollection(*this).elementMatches(element);
    case TagCollectionType:
      return toTagCollection(*this).elementMatches(element);
    case HTMLTagCollectionType:
      return toHTMLTagCollection(*this).elementMatches(element);
    case WindowNamedItems:
      return toWindowNameCollection(*this).elementMatches(element);
    default:
      break;
  }

  // The following only applies to HTMLElements.
  return element.isHTMLElement() &&
         isMatchingHTMLElement(*this, toHTMLElement(element));
}

namespace {

template <class HTMLCollectionType>
class IsMatch {
  STACK_ALLOCATED();

 public:
  IsMatch(const HTMLCollectionType& list) : m_list(&list) {}

  bool operator()(const Element& element) const {
    return m_list->elementMatches(element);
  }

 private:
  Member<const HTMLCollectionType> m_list;
};

}  // namespace

template <class HTMLCollectionType>
static inline IsMatch<HTMLCollectionType> makeIsMatch(
    const HTMLCollectionType& list) {
  return IsMatch<HTMLCollectionType>(list);
}

Element* HTMLCollection::virtualItemAfter(Element*) const {
  NOTREACHED();
  return nullptr;
}

// https://html.spec.whatwg.org/multipage/infrastructure.html#all-named-elements
// The document.all collection returns only certain types of elements by name,
// although it returns any type of element by id.
static inline bool nameShouldBeVisibleInDocumentAll(
    const HTMLElement& element) {
  return element.hasTagName(aTag) || element.hasTagName(appletTag) ||
         element.hasTagName(buttonTag) || element.hasTagName(embedTag) ||
         element.hasTagName(formTag) || element.hasTagName(frameTag) ||
         element.hasTagName(framesetTag) || element.hasTagName(iframeTag) ||
         element.hasTagName(imgTag) || element.hasTagName(inputTag) ||
         element.hasTagName(mapTag) || element.hasTagName(metaTag) ||
         element.hasTagName(objectTag) || element.hasTagName(selectTag) ||
         element.hasTagName(textareaTag);
}

Element* HTMLCollection::traverseToFirst() const {
  switch (type()) {
    case HTMLTagCollectionType:
      return ElementTraversal::firstWithin(
          rootNode(), makeIsMatch(toHTMLTagCollection(*this)));
    case ClassCollectionType:
      return ElementTraversal::firstWithin(
          rootNode(), makeIsMatch(toClassCollection(*this)));
    default:
      if (overridesItemAfter())
        return virtualItemAfter(0);
      if (shouldOnlyIncludeDirectChildren())
        return ElementTraversal::firstChild(rootNode(), makeIsMatch(*this));
      return ElementTraversal::firstWithin(rootNode(), makeIsMatch(*this));
  }
}

Element* HTMLCollection::traverseToLast() const {
  DCHECK(canTraverseBackward());
  if (shouldOnlyIncludeDirectChildren())
    return ElementTraversal::lastChild(rootNode(), makeIsMatch(*this));
  return ElementTraversal::lastWithin(rootNode(), makeIsMatch(*this));
}

Element* HTMLCollection::traverseForwardToOffset(
    unsigned offset,
    Element& currentElement,
    unsigned& currentOffset) const {
  DCHECK_LT(currentOffset, offset);
  switch (type()) {
    case HTMLTagCollectionType:
      return traverseMatchingElementsForwardToOffset(
          currentElement, &rootNode(), offset, currentOffset,
          makeIsMatch(toHTMLTagCollection(*this)));
    case ClassCollectionType:
      return traverseMatchingElementsForwardToOffset(
          currentElement, &rootNode(), offset, currentOffset,
          makeIsMatch(toClassCollection(*this)));
    default:
      if (overridesItemAfter()) {
        for (Element* next = virtualItemAfter(&currentElement); next;
             next = virtualItemAfter(next)) {
          if (++currentOffset == offset)
            return next;
        }
        return nullptr;
      }
      if (shouldOnlyIncludeDirectChildren()) {
        IsMatch<HTMLCollection> isMatch(*this);
        for (Element* next =
                 ElementTraversal::nextSibling(currentElement, isMatch);
             next; next = ElementTraversal::nextSibling(*next, isMatch)) {
          if (++currentOffset == offset)
            return next;
        }
        return nullptr;
      }
      return traverseMatchingElementsForwardToOffset(
          currentElement, &rootNode(), offset, currentOffset,
          makeIsMatch(*this));
  }
}

Element* HTMLCollection::traverseBackwardToOffset(
    unsigned offset,
    Element& currentElement,
    unsigned& currentOffset) const {
  DCHECK_GT(currentOffset, offset);
  DCHECK(canTraverseBackward());
  if (shouldOnlyIncludeDirectChildren()) {
    IsMatch<HTMLCollection> isMatch(*this);
    for (Element* previous =
             ElementTraversal::previousSibling(currentElement, isMatch);
         previous;
         previous = ElementTraversal::previousSibling(*previous, isMatch)) {
      if (--currentOffset == offset)
        return previous;
    }
    return nullptr;
  }
  return traverseMatchingElementsBackwardToOffset(
      currentElement, &rootNode(), offset, currentOffset, makeIsMatch(*this));
}

Element* HTMLCollection::namedItem(const AtomicString& name) const {
  // http://msdn.microsoft.com/workshop/author/dhtml/reference/methods/nameditem.asp
  // This method first searches for an object with a matching id
  // attribute. If a match is not found, the method then searches for an
  // object with a matching name attribute, but only on those elements
  // that are allowed a name attribute.
  updateIdNameCache();

  const NamedItemCache& cache = namedItemCache();
  HeapVector<Member<Element>>* idResults = cache.getElementsById(name);
  if (idResults && !idResults->isEmpty())
    return idResults->front();

  HeapVector<Member<Element>>* nameResults = cache.getElementsByName(name);
  if (nameResults && !nameResults->isEmpty())
    return nameResults->front();

  return nullptr;
}

bool HTMLCollection::namedPropertyQuery(const AtomicString& name,
                                        ExceptionState&) {
  return namedItem(name);
}

void HTMLCollection::supportedPropertyNames(Vector<String>& names) {
  // As per the specification (https://dom.spec.whatwg.org/#htmlcollection):
  // The supported property names are the values from the list returned by these
  // steps:
  // 1. Let result be an empty list.
  // 2. For each element represented by the collection, in tree order, run these
  //    substeps:
  //   1. If element has an ID which is neither the empty string nor is in
  //      result, append element's ID to result.
  //   2. If element is in the HTML namespace and has a name attribute whose
  //      value is neither the empty string nor is in result, append element's
  //      name attribute value to result.
  // 3. Return result.
  HashSet<AtomicString> existingNames;
  unsigned length = this->length();
  for (unsigned i = 0; i < length; ++i) {
    Element* element = item(i);
    const AtomicString& idAttribute = element->getIdAttribute();
    if (!idAttribute.isEmpty()) {
      HashSet<AtomicString>::AddResult addResult =
          existingNames.add(idAttribute);
      if (addResult.isNewEntry)
        names.push_back(idAttribute);
    }
    if (!element->isHTMLElement())
      continue;
    const AtomicString& nameAttribute = element->getNameAttribute();
    if (!nameAttribute.isEmpty() &&
        (type() != DocAll ||
         nameShouldBeVisibleInDocumentAll(toHTMLElement(*element)))) {
      HashSet<AtomicString>::AddResult addResult =
          existingNames.add(nameAttribute);
      if (addResult.isNewEntry)
        names.push_back(nameAttribute);
    }
  }
}

void HTMLCollection::namedPropertyEnumerator(Vector<String>& names,
                                             ExceptionState&) {
  supportedPropertyNames(names);
}

void HTMLCollection::updateIdNameCache() const {
  if (hasValidIdNameCache())
    return;

  NamedItemCache* cache = NamedItemCache::create();
  unsigned length = this->length();
  for (unsigned i = 0; i < length; ++i) {
    Element* element = item(i);
    const AtomicString& idAttrVal = element->getIdAttribute();
    if (!idAttrVal.isEmpty())
      cache->addElementWithId(idAttrVal, element);
    if (!element->isHTMLElement())
      continue;
    const AtomicString& nameAttrVal = element->getNameAttribute();
    if (!nameAttrVal.isEmpty() && idAttrVal != nameAttrVal &&
        (type() != DocAll ||
         nameShouldBeVisibleInDocumentAll(toHTMLElement(*element))))
      cache->addElementWithName(nameAttrVal, element);
  }
  // Set the named item cache last as traversing the tree may cause cache
  // invalidation.
  setNamedItemCache(cache);
}

void HTMLCollection::namedItems(const AtomicString& name,
                                HeapVector<Member<Element>>& result) const {
  DCHECK(result.isEmpty());
  if (name.isEmpty())
    return;

  updateIdNameCache();

  const NamedItemCache& cache = namedItemCache();
  if (HeapVector<Member<Element>>* idResults = cache.getElementsById(name)) {
    for (const auto& element : *idResults)
      result.push_back(element);
  }
  if (HeapVector<Member<Element>>* nameResults =
          cache.getElementsByName(name)) {
    for (const auto& element : *nameResults)
      result.push_back(element);
  }
}

HTMLCollection::NamedItemCache::NamedItemCache() {}

DEFINE_TRACE(HTMLCollection) {
  visitor->trace(m_namedItemCache);
  visitor->trace(m_collectionItemsCache);
  LiveNodeListBase::trace(visitor);
}

}  // namespace blink

redpajama_set_name: RedPajamaGithub


text:
"""
    test_common
    ~~~~~~~~~~~

    Test common functionality
"""

import base64

from utils import authenticate, json_authenticate, logout

try:
    from cookielib import Cookie
except ImportError:
    from http.cookiejar import Cookie

def test_login_view(client):
    response = client.get('/login')
    assert b'
Login
' in response.data

def test_authenticate(client):
    response = authenticate(client)
    assert response.status_code == 302
    response = authenticate(client, follow_redirects=True)
    assert b'Hello matt@lp.com' in response.data

def test_authenticate_with_next(client):
    data = dict(email='matt@lp.com', password='password')
    response = client.post(
        '/login?next=/page1',
        data=data,
        follow_redirects=True)
    assert b'Page 1' in response.data

def test_authenticate_with_invalid_next(client, get_message):
    data = dict(email='matt@lp.com', password='password')
    response = client.post('/login?next=http://google.com', data=data)
    assert get_message('INVALID_REDIRECT') in response.data

def test_authenticate_with_invalid_malformed_next(client, get_message):
    data = dict(email='matt@lp.com', password='password')
    response = client.post('/login?next=http:///google.com', data=data)
    assert get_message('INVALID_REDIRECT') in response.data

def test_authenticate_case_insensitive_email(app, client):
    response = authenticate(client, 'MATT@lp.com', follow_redirects=True)
    assert b'Hello matt@lp.com' in response.data

def test_authenticate_with_invalid_input(client, get_message):
    response = client.post(
        '/login',
        data='{}',
        headers={'Content-Type': 'application/json'},
    )
    assert get_message('EMAIL_NOT_PROVIDED') in response.data

def test_login_form(client):
    response = client.post('/login', data={'email': 'matt@lp.com'})
    assert b'matt@lp.com' in response.data

def test_unprovided_username(client, get_message):
    response = authenticate(client, "")
    assert get_message('EMAIL_NOT_PROVIDED') in response.data

def test_unprovided_password(client, get_message):
    response = authenticate(client, password="")
    assert get_message('PASSWORD_NOT_PROVIDED') in response.data

def test_invalid_user(client, get_message):
    response = authenticate(client, email="bogus@bogus.com")
    assert get_message('USER_DOES_NOT_EXIST') in response.data

def test_bad_password(client, get_message):
    response = authenticate(client, password="bogus")
    assert get_message('INVALID_PASSWORD') in response.data

def test_inactive_user(client, get_message):
    response = authenticate(client, "tiya@lp.com", "password")
    assert get_message('DISABLED_ACCOUNT') in response.data

def test_unset_password(client, get_message):
    response = authenticate(client, "jess@lp.com", "password")
    assert get_message('PASSWORD_NOT_SET') in response.data

def test_logout(client):
    authenticate(client)
    response = logout(client, follow_redirects=True)
    assert b'Home Page' in response.data

def test_logout_with_next(client, get_message):
    authenticate(client)
    response = client.get('/logout?next=http://google.com')
    assert 'google.com' not in response.location

def test_missing_session_access(client, get_message):
    response = client.get('/profile', follow_redirects=True)
    assert get_message('LOGIN') in response.data

def test_has_session_access(client):
    authenticate(client)
    response = client.get("/profile", follow_redirects=True)
    assert b'profile' in response.data

def test_authorized_access(client):
    authenticate(client)
    response = client.get("/admin")
    assert b'Admin Page' in response.data

def test_unauthorized_access(client, get_message):
    authenticate(client, "joe@lp.com")
    response = client.get("/admin", follow_redirects=True)
    assert get_message('UNAUTHORIZED') in response.data

def test_roles_accepted(client):
    for user in ("matt@lp.com", "joe@lp.com"):
        authenticate(client, user)
        response = client.get("/admin_or_editor")
        assert b'Admin or Editor Page' in response.data
        logout(client)

    authenticate(client, "jill@lp.com")
    response = client.get("/admin_or_editor", follow_redirects=True)
    assert b'Home Page' in response.data

def test_unauthenticated_role_required(client, get_message):
    response = client.get('/admin', follow_redirects=True)
    assert get_message('UNAUTHORIZED') in response.data

def test_multiple_role_required(client):
    for user in ("matt@lp.com", "joe@lp.com"):
        authenticate(client, user)
        response = client.get("/admin_and_editor", follow_redirects=True)
        assert b'Home Page' in response.data
        client.get('/logout')

    authenticate(client, 'dave@lp.com')
    response = client.get("/admin_and_editor", follow_redirects=True)
    assert b'Admin and Editor Page' in response.data

def test_ok_json_auth(client):
    response = json_authenticate(client)
    assert response.jdata['meta']['code'] == 200
    assert 'authentication_token' in response.jdata['response']['user']

def test_invalid_json_auth(client):
    response = json_authenticate(client, password='junk')
    assert b'"code": 400' in response.data

def test_token_auth_via_querystring_valid_token(client):
    response = json_authenticate(client)
    token = response.jdata['response']['user']['authentication_token']
    response = client.get('/token?auth_token=' + token)
    assert b'Token Authentication' in response.data

def test_token_auth_via_header_valid_token(client):
    response = json_authenticate(client)
    token = response.jdata['response']['user']['authentication_token']
    headers = {"Authentication-Token": token}
    response = client.get('/token', headers=headers)
    assert b'Token Authentication' in response.data

def test_token_auth_via_querystring_invalid_token(client):
    response = client.get('/token?auth_token=X')
    assert 401 == response.status_code

def test_token_auth_via_header_invalid_token(client):
    response = client.get('/token', headers={"Authentication-Token": 'X'})
    assert 401 == response.status_code

def test_http_auth(client):
    response = client.get('/http', headers={
        'Authorization': 'Basic %s' % base64.b64encode(
            b"joe@lp.com:password").decode('utf-8')
    })
    assert b'HTTP Authentication' in response.data

def test_http_auth_no_authorization(client):
    response = client.get('/http', headers={})
    assert b'
Unauthorized
' in response.data
    assert 'WWW-Authenticate' in response.headers
    assert 'Basic realm="Login Required"' == response.headers[
        'WWW-Authenticate']

def test_invalid_http_auth_invalid_username(client):
    response = client.get('/http', headers={
        'Authorization': 'Basic %s' % base64.b64encode(
            b"bogus:bogus").decode('utf-8')
    })
    assert b'
Unauthorized
' in response.data
    assert 'WWW-Authenticate' in response.headers
    assert 'Basic realm="Login Required"' == response.headers[
        'WWW-Authenticate']

def test_invalid_http_auth_bad_password(client):
    response = client.get('/http', headers={
        'Authorization': 'Basic %s' % base64.b64encode(
            b"joe@lp.com:bogus").decode('utf-8')
    })
    assert b'
Unauthorized
' in response.data
    assert 'WWW-Authenticate' in response.headers
    assert 'Basic realm="Login Required"' == response.headers[
        'WWW-Authenticate']

def test_custom_http_auth_realm(client):
    response = client.get('/http_custom_realm', headers={
        'Authorization': 'Basic %s' % base64.b64encode(
            b"joe@lp.com:bogus").decode('utf-8')
    })
    assert b'
Unauthorized
' in response.data
    assert 'WWW-Authenticate' in response.headers
    assert 'Basic realm="My Realm"' == response.headers['WWW-Authenticate']

def test_multi_auth_basic(client):
    response = client.get('/multi_auth', headers={
        'Authorization': 'Basic %s' % base64.b64encode(
            b"joe@lp.com:password").decode('utf-8')
    })
    assert b'Basic' in response.data

    response = client.get('/multi_auth')
    assert response.status_code == 401

def test_multi_auth_basic_invalid(client):
    response = client.get('/multi_auth', headers={
        'Authorization': 'Basic %s' % base64.b64encode(
            b"bogus:bogus").decode('utf-8')
    })
    assert b'
Unauthorized
' in response.data
    assert 'WWW-Authenticate' in response.headers
    assert 'Basic realm="Login Required"' == response.headers[
        'WWW-Authenticate']

    response = client.get('/multi_auth')
    print(response.headers)
    assert response.status_code == 401

def test_multi_auth_token(client):
    response = json_authenticate(client)
    token = response.jdata['response']['user']['authentication_token']
    response = client.get('/multi_auth?auth_token=' + token)
    assert b'Token' in response.data

def test_multi_auth_session(client):
    authenticate(client, )
    response = client.get('/multi_auth')
    assert b'Session' in response.data

def test_user_deleted_during_session_reverts_to_anonymous_user(app, client):
    authenticate(client)

    with app.test_request_context('/'):
        user = app.security.datastore.find_user(email='matt@lp.com')
        app.security.datastore.delete_user(user)
        app.security.datastore.commit()

    response = client.get('/')
    assert b'Hello matt@lp.com' not in response.data

def test_remember_token(client):
    response = authenticate(client, follow_redirects=False)
    client.cookie_jar.clear_session_cookies()
    response = client.get('/profile')
    assert b'profile' in response.data

def test_request_loader_does_not_fail_with_invalid_token(client):
    c = Cookie(version=0, name='remember_token', value='None', port=None,
               port_specified=False, domain='www.example.com',
               domain_specified=False, domain_initial_dot=False, path='/',
               path_specified=True, secure=False, expires=None,
               discard=True, comment=None, comment_url=None,
               rest={'HttpOnly': None}, rfc2109=False)

    client.cookie_jar.set_cookie(c)
    response = client.get('/')
    assert b'BadSignature' not in response.data

def test_sending_auth_token_with_json(client):
    response = json_authenticate(client)
    token = response.jdata['response']['user']['authentication_token']
    data = '{"auth_token": "%s"}' % token
    response = client.post(
        '/token',
        data=data,
        headers={
            'Content-Type': 'application/json'})
    assert b'Token Authentication' in response.data


text:
{% extends "hqwebapp/two_column.html" %}
{% load url from future %}
{% load report_tags %}
{% load i18n %}

{% block head %}
    {{ block.super }}
{% endblock %}

{% block main_column %}
    {% block extrahead %}
        <script type="text/javascript">
            var autoRefresh = '';
            var pollDownloader = function () {
                if ($('#ready_{{ download_id }}').length == 0)
                    {
                        $.get("{% url "importer_job_poll" domain download_id %}", function(data) {
                            $("#display_{{ download_id }}").html(data);
                        });
                    } else {
                        clearInterval(autoRefresh);
                    }
            };
            $(document).ready(function () {
                pollDownloader();
                autoRefresh = setInterval(pollDownloader, 2000);
            });
        </script>
    {% endblock extrahead %}

    <div class="downloader_container" id="display_{{ download_id }}">
        <legend>
            {% trans "Importing your data. This may take some time..." %}
        </legend>
    </div>
{% endblock %}


text:
require "spec_helper"

describe Refinery do
  describe "Alerts" do
    describe "Admin" do
      describe "alerts" do
        refinery_login_with :refinery_user

        describe "alerts list" do
          before do
            FactoryGirl.create(:alert, :title => "UniqueTitleOne")
            FactoryGirl.create(:alert, :title => "UniqueTitleTwo")
          end

          it "shows two items" do
            visit refinery.alerts_admin_alerts_path
            page.should have_content("UniqueTitleOne")
            page.should have_content("UniqueTitleTwo")
          end
        end

        describe "create" do
          before do
            visit refinery.alerts_admin_alerts_path

            click_link "Add New Alert"
          end

          context "valid data" do
            it "should succeed" do
              fill_in "Title", :with => "This is a test of the first string field"
              click_button "Save"

              page.should have_content("'This is a test of the first string field' was successfully added.")
              Refinery::Alerts::Alert.count.should == 1
            end
          end

          context "invalid data" do
            it "should fail" do
              click_button "Save"

              page.should have_content("Title can't be blank")
              Refinery::Alerts::Alert.count.should == 0
            end
          end

          context "duplicate" do
            before { FactoryGirl.create(:alert, :title => "UniqueTitle") }

            it "should fail" do
              visit refinery.alerts_admin_alerts_path

              click_link "Add New Alert"

              fill_in "Title", :with => "UniqueTitle"
              click_button "Save"

              page.should have_content("There were problems")
              Refinery::Alerts::Alert.count.should == 1
            end
          end

        end

        describe "edit" do
          before { FactoryGirl.create(:alert, :title => "A title") }

          it "should succeed" do
            visit refinery.alerts_admin_alerts_path

            within ".actions" do
              click_link "Edit this alert"
            end

            fill_in "Title", :with => "A different title"
            click_button "Save"

            page.should have_content("'A different title' was successfully updated.")
            page.should have_no_content("A title")
          end
        end

        describe "destroy" do
          before { FactoryGirl.create(:alert, :title => "UniqueTitleOne") }

          it "should succeed" do
            visit refinery.alerts_admin_alerts_path

            click_link "Remove this alert forever"

            page.should have_content("'UniqueTitleOne' was successfully removed.")
            Refinery::Alerts::Alert.count.should == 0
          end
        end

      end
    end
  end
end


text:
<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>angular-route-urls tests</title>

        <!-- jasmine -->
        <script src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine-html.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/boot.js"></script>
        <link href="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.css" rel="stylesheet" />

        <!-- angular -->
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular-route.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular-mocks.js"></script>

        <!-- angular-route-urls & test specs -->
        <script src="../route-urls.js"></script>
        <script src="specs.js"></script>

    </head>
    <body>
    </body>
</html>


text:
<?php

namespace Spark\Db\Query;

/**
 *
 *
 * @author Chris Harris
 * @version 0.0.1
 * @since 0.0.1
 */
interface LimitCapableInterface
{
    /**
     * Specifies the amount of results to return. Passing a 'null' literal will
     * remove any previously set limit.
     *
     * <code>
     *    $queryBuilder = $adapter->getQueryBuilder();
     *                            ->select('t.name')
     *                            ->from('table', 't')
     *                            ->limit(5);
     * </code>
     *
     * @param int|null $limit the number of result to return.
     */
    public function limit($limit = null);
}


text:
local ConstrainedMul, parent = torch.class('nn.ConstrainedMul', 'nn.Module')

function ConstrainedMul:__init(inplace)
   parent.__init(self)

   self.weight = torch.ones(1)
   self.gradWeight = torch.zeros(1)
   self.inplace = inplace or false

   self:reset()
end

function ConstrainedMul:reset(stdv)
   self.weight:fill(1);
end

function ConstrainedMul:updateOutput(input)
   if self.weight[1] >= 2 then
      self.weight[1] = 1.99
   end
   if self.weight[1] <= 0.1 then
      self.weight[1] = 0.11
   end
   if self.inplace then
      self.output = input
   else
      self.output:resizeAs(input):copy(input);
   end
   self.output:mul(self.weight[1]);
   return self.output
end

function ConstrainedMul:updateGradInput(input, gradOutput)
   if self.inplace then
      self.gradInput = gradOutput
      self.gradInput:add(self.weight[1])
   else
      self.gradInput:resizeAs(input):zero()
      self.gradInput:add(self.weight[1], gradOutput)
   end
   return self.gradInput
end

function ConstrainedMul:accGradParameters(input, gradOutput, scale)
   scale = scale or 1
   self.gradWeight[1] = self.gradWeight[1] + scale*input:dot(gradOutput);
end


text:
<?php

namespace MushroomFramework\ORMushroom;
use \Exception;

/**
 * Migration Class
 * @version 0.1.0
 * @author Smoren <ofigate@gmail.com>
 */
abstract class Migration {
	/**
	 * @var string $tableName Name of the migrations table
	 */
	protected static $tableName = 'migrations';
	protected static $dumpFileName = MUSHROOM_DIR_APP_MIGRATIONS.'/dump.csv';

	/**
	 * Executes the migration's up actions
	 * @return void
	 */
	abstract public function up();

	/**
	 * Executes the migration's down actions
	 * @return void
	 */
	abstract public function down();

	/**
	 * Console application's method for making new migration with name=$name
	 * @throws Exception
	 * @param string $name Name of the migration
	 * @return void
	 */
	public static function make($name) {
		if(!static::installed()) {
			throw new Exception('migrations table is not installed');
		}
		$timestamp = @mktime();
		$datetime = @date('Y_m_d_H_i_s', $timestamp);
		$className = "Migration_{$datetime}_{$name}";
		$fileName = "{$className}.php";
		$migrationClassString = "<?php\n\nclass $className extends Migration {\n\tpublic function up() {\n\t\t\n\t}\n\tpublic function down() {\n\t\t\n\t}\n}";
		file_put_contents(MUSHROOM_DIR_APP_MIGRATIONS.'/'.$fileName, $migrationClassString);
		QueryBuilder::insert(static::$tableName, array(
			'name' => $name,
			'timestamp' => $timestamp,
			'className' => $className,
			'active' => 0,
		))->exec();
		static::updateDump();
	}

	/**
	 * Saves migrations' table dump
	 * @return void
	 */
	public static function updateDump() {
		$rs = QueryBuilder::select('id', 'name', 'timestamp', 'className')
			->from(static::$tableName)
			->exec();
		$fh = fopen(static::$dumpFileName, 'w');
		while($row = $rs->fetch()) {
			fputcsv($fh, $row);
		}
		fclose($fh);
	}

	/**
	 * Console application's method for installing migrations' table
	 * @throws Exception
	 * @return void
	 */
	public static function install() {
		if(static::installed()) {
			throw new Exception('migrations table is already installed');
		}
		QueryBuilder::createTable(static::$tableName, array(
			'id' => 'INT NOT NULL AUTO_INCREMENT PRIMARY KEY',
			'name' => 'VARCHAR(100)',
			'timestamp' => 'INT',
			'className' => 'VARCHAR(100)',
			'active' => 'TINYINT NOT NULL DEFAULT 0',
		))->exec();

		$fh = fopen(static::$dumpFileName, 'r');
		while($row = fgetcsv($fh)) {
			QueryBuilder::insert(static::$tableName, array(
				'id' => $row[0],
				'name' => $row[1],
				'timestamp' => $row[2],
				'className' => $row[3],
			))->exec();
		}
		fclose($fh);
	}

	/**
	 * Console application's method for checking if migrations' table installed
	 * @return boolean
	 */
	public static function installed() {
		if(QueryBuilder::showTables(static::$tableName)->exec()->fetch()) {
			return true;
		}
		return false;
	}

	/**
	 * Console application's method for rolling $maxSteps unrolled migrations.
	 * Method rolls all the unrolled migrations if $maxSteps=false or not defined
	 * @throws Exception
	 * @param int $maxSteps
	 * @return void
	 */
	public static function roll($maxSteps=false) {
		if(!static::installed()) {
			throw new Exception('migrations table is not installed');
		}
		$sql = QueryBuilder::select()->from(static::$tableName)->where('active', '=', '0')->orderBy(array('timestamp' => 'ASC'));
		if($maxSteps) $sql->limit(intval($maxSteps));
		$rs = $sql->exec();
		while($migration = $rs->fetch()) {
			$path = MUSHROOM_DIR_APP_MIGRATIONS.'/'.$migration['className'].'.php';
			if(is_file($path)) {
				include($path);
				$instance = new $migration['className']();
				$instance->up();
				QueryBuilder::update(static::$tableName, array('active' => 1))->where('id', '=', $migration['id'])->exec();
				echo "Migration '{$migration['name']}' installed\n";
			} else {
				QueryBuilder::delete(static::$tableName)->where('id', '=', $migration['id'])->exec();
				echo "Migration '{$migration['name']}' not installed (file '$path' not found)\n";
			}
		}
	}

	/**
	 * Console application's method for rolling back $maxSteps unrolled migrations.
	 * Method rolls back 1 unrolled migration if $maxSteps is not defined
	 * @throws Exception
	 * @param int $maxSteps
	 * @return void
	 */
	public static function rollback($maxSteps=1) {
		if(!static::installed()) {
			throw new Exception('migrations table is not installed');
		}
		$sql = QueryBuilder::select()->from(static::$tableName)->where('active', '=', '1')->orderBy(array('timestamp' => 'DESC'));
		if($maxSteps) $sql->limit(intval($maxSteps));
		$rs = $sql->exec();
		while($migration = $rs->fetch()) {
			$path = MUSHROOM_DIR_APP_MIGRATIONS.'/'.$migration['className'].'.php';
			if(is_file($path)) {
				include($path);
				$instance = new $migration['className']();
				$instance->down();
				QueryBuilder::update(static::$tableName, array('active' => 0))->where('id', '=', $migration['id'])->exec();
				echo "Migration '{$migration['name']}' uninstalled\n";
			} else {
				QueryBuilder::delete(static::$tableName)->where('id', '=', $migration['id'])->exec();
				echo "Migration '{$migration['name']}' not uninstalled (file '$path' not found)\n";
			}
		}
	}

	/**
	 * Console application's method for rolling back all unrolled migrations.
	 * @return void
	 */
	public static function reset() {
		static::rollback(0);
	}

	/**
	 * Console application's method for rolling back all unrolled migrations.
	 * @param string $tableName Database table name
	 * @return Table
	 */
	protected function table($tableName) {
		return Table::get($tableName);
	}

	/**
	 * Creates table by using Table class
	 * @param string $tableName Database table name
	 * @param array $fields Table fields' array
	 * @return Table
	 */
	protected function createTable($tableName, array $fields) {
		return Table::create($tableName, $fields);
	}
}


text:
package org.camunda.bpm.engine.history;

import java.util.Date;

/**
 * Represents one execution of an activity and it's stored permanent for statistics, audit and other business intelligence purposes.
 *
 * @author Christian Stettler
 */
public interface HistoricActivityInstance {

  /** The unique identifier of this historic activity instance. */
  String getId();

  /** return the id of the parent activity instance */
  String getParentActivityInstanceId();

  /** The unique identifier of the activity in the process */
  String getActivityId();

  /** The display name for the activity */
  String getActivityName();

  /**
   * The activity type of the activity.
   * Typically the activity type correspond to the XML tag used in the BPMN 2.0 process definition file.
   *
   * All activity types are available in {@link org.camunda.bpm.engine.ActivityTypes}
   *
   * @see org.camunda.bpm.engine.ActivityTypes
   */
  String getActivityType();

  /** Process definition key reference */
  String getProcessDefinitionKey();

  /** Process definition reference */
  String getProcessDefinitionId();

  /** Root process instance reference */
  String getRootProcessInstanceId();

  /** Process instance reference */
  String getProcessInstanceId();

  /** Execution reference */
  String getExecutionId();

  /** The corresponding task in case of task activity */
  String getTaskId();

  /** The called process instance in case of call activity */
  String getCalledProcessInstanceId();

  /** The called case instance in case of (case) call activity */
  String getCalledCaseInstanceId();

  /** Assignee in case of user task activity */
  String getAssignee();

  /** Time when the activity instance started */
  Date getStartTime();

  /** Time when the activity instance ended */
  Date getEndTime();

  /** Difference between {@link #getEndTime()} and {@link #getStartTime()}.  */
  Long getDurationInMillis();

  /** Did this activity instance complete a BPMN 2.0 scope */
  boolean isCompleteScope();

  /** Was this activity instance canceled */
  boolean isCanceled();

  /**
   * The id of the tenant this historic activity instance belongs to. Can be null
   * if the historic activity instance belongs to no single tenant.
   */
  String getTenantId();

  /** The time the historic activity instance will be removed. */
  Date getRemovalTime();

}


text:
'use strict';

const compose = require('koa-compose');
const randToken = require('rand-token');

const identify = require('../../middlewares/identify');
const authenticate = require('../../middlewares/authenticate');

const orm = require('../../orm');

module.exports.path = '/';
module.exports.method = 'post';

module.exports.handler = compose([
  identify(),
  authenticate(),
  function * createSession () {
    const session = yield orm.models.Session.create({
      token: randToken.generate(32),
      UserId: this.state.user.id
    });

    this.status = 201;
    this.body = session.toJSON();
  }
]);


text:
ActiveRecord::Schema.define(version: 20160123232335) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "stocks", force: :cascade do |t|
    t.string   "ticker"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end


text:
'use strict';

tripExchange.factory('TripsResource', ['$resource', 'authorization', 'baseServiceUrl', function($resource, authorization, baseServiceUrl) {
    var headers = authorization.getAuthorizationHeader();
    var TripsResource = $resource(baseServiceUrl + '/api/trips/:id', null, {
            'create': { method: 'POST', params: { id: '@id' }, isArray: false, headers: headers },
            'public': {  method: 'GET', isArray: true },
            'request': {  method: 'GET', isArray: true, headers: headers },
            'byId': { method: 'GET', params: { id: '@id' }, isArray: false, headers: headers },
            'join': { method:'PUT', params: { id: '@id' }, isArray: false, headers: headers }
        });

    return {
        create: function(trip) {
            return TripsResource.create(trip).$promise;
        },
        public: function() {
            return TripsResource.public();
        },
        all: function(request) {
            return TripsResource.request(request);
        },
        byId: function(id) {
            return TripsResource.byId({id: id});
        },
        join: function(id) {
            return TripsResource.join({id: id}).$promise;
        }
    }
}]);


text:
package edu.uci.ics.asterix.metadata.entitytupletranslators;

import java.io.ByteArrayInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Calendar;

import edu.uci.ics.asterix.common.exceptions.AsterixException;
import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
import edu.uci.ics.asterix.metadata.MetadataException;
import edu.uci.ics.asterix.metadata.bootstrap.MetadataPrimaryIndexes;
import edu.uci.ics.asterix.metadata.bootstrap.MetadataRecordTypes;
import edu.uci.ics.asterix.metadata.entities.DatasourceAdapter;
import edu.uci.ics.asterix.metadata.entities.DatasourceAdapter.AdapterType;
import edu.uci.ics.asterix.metadata.feeds.AdapterIdentifier;
import edu.uci.ics.asterix.om.base.ARecord;
import edu.uci.ics.asterix.om.base.AString;
import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
import edu.uci.ics.hyracks.dataflow.common.data.accessors.ITupleReference;

public class DatasourceAdapterTupleTranslator extends AbstractTupleTranslator<DatasourceAdapter> {

    // Field indexes of serialized Adapter in a tuple.
    // First key field.
    public static final int ADAPTER_DATAVERSENAME_TUPLE_FIELD_INDEX = 0;
    // Second key field.
    public static final int ADAPTER_NAME_TUPLE_FIELD_INDEX = 1;

    // Payload field containing serialized Adapter.
    public static final int ADAPTER_PAYLOAD_TUPLE_FIELD_INDEX = 2;

    @SuppressWarnings("unchecked")
    private ISerializerDeserializer<ARecord> recordSerDes = AqlSerializerDeserializerProvider.INSTANCE
            .getSerializerDeserializer(MetadataRecordTypes.DATASOURCE_ADAPTER_RECORDTYPE);

    public DatasourceAdapterTupleTranslator(boolean getTuple) {
        super(getTuple, MetadataPrimaryIndexes.DATASOURCE_ADAPTER_DATASET.getFieldCount());
    }

    @Override
    public DatasourceAdapter getMetadataEntityFromTuple(ITupleReference tuple) throws MetadataException, IOException {
        byte[] serRecord = tuple.getFieldData(ADAPTER_PAYLOAD_TUPLE_FIELD_INDEX);
        int recordStartOffset = tuple.getFieldStart(ADAPTER_PAYLOAD_TUPLE_FIELD_INDEX);
        int recordLength = tuple.getFieldLength(ADAPTER_PAYLOAD_TUPLE_FIELD_INDEX);
        ByteArrayInputStream stream = new ByteArrayInputStream(serRecord, recordStartOffset, recordLength);
        DataInput in = new DataInputStream(stream);
        ARecord adapterRecord = (ARecord) recordSerDes.deserialize(in);
        return createAdapterFromARecord(adapterRecord);
    }

    private DatasourceAdapter createAdapterFromARecord(ARecord adapterRecord) {
        String dataverseName = ((AString) adapterRecord
                .getValueByPos(MetadataRecordTypes.DATASOURCE_ADAPTER_ARECORD_DATAVERSENAME_FIELD_INDEX))
                .getStringValue();
        String adapterName = ((AString) adapterRecord
                .getValueByPos(MetadataRecordTypes.DATASOURCE_ADAPTER_ARECORD_NAME_FIELD_INDEX)).getStringValue();
        String classname = ((AString) adapterRecord
                .getValueByPos(MetadataRecordTypes.DATASOURCE_ADAPTER_ARECORD_CLASSNAME_FIELD_INDEX)).getStringValue();
        AdapterType adapterType = AdapterType.valueOf(((AString) adapterRecord
                .getValueByPos(MetadataRecordTypes.DATASOURCE_ADAPTER_ARECORD_TYPE_FIELD_INDEX)).getStringValue());

        return new DatasourceAdapter(new AdapterIdentifier(dataverseName, adapterName), classname, adapterType);
    }

    @Override
    public ITupleReference getTupleFromMetadataEntity(DatasourceAdapter adapter) throws IOException, MetadataException {
        // write the key in the first 2 fields of the tuple
        tupleBuilder.reset();
        aString.setValue(adapter.getAdapterIdentifier().getNamespace());
        stringSerde.serialize(aString, tupleBuilder.getDataOutput());
        tupleBuilder.addFieldEndOffset();
        aString.setValue(adapter.getAdapterIdentifier().getAdapterName());
        stringSerde.serialize(aString, tupleBuilder.getDataOutput());
        tupleBuilder.addFieldEndOffset();

        // write the pay-load in the third field of the tuple

        recordBuilder.reset(MetadataRecordTypes.DATASOURCE_ADAPTER_RECORDTYPE);

        // write field 0
        fieldValue.reset();
        aString.setValue(adapter.getAdapterIdentifier().getNamespace());
        stringSerde.serialize(aString, fieldValue.getDataOutput());
        recordBuilder.addField(MetadataRecordTypes.DATASOURCE_ADAPTER_ARECORD_DATAVERSENAME_FIELD_INDEX, fieldValue);

        // write field 1
        fieldValue.reset();
        aString.setValue(adapter.getAdapterIdentifier().getAdapterName());
        stringSerde.serialize(aString, fieldValue.getDataOutput());
        recordBuilder.addField(MetadataRecordTypes.DATASOURCE_ADAPTER_ARECORD_NAME_FIELD_INDEX, fieldValue);

        // write field 2
        fieldValue.reset();
        aString.setValue(adapter.getClassname());
        stringSerde.serialize(aString, fieldValue.getDataOutput());
        recordBuilder.addField(MetadataRecordTypes.DATASOURCE_ADAPTER_ARECORD_CLASSNAME_FIELD_INDEX, fieldValue);

        // write field 3
        fieldValue.reset();
        aString.setValue(adapter.getType().name());
        stringSerde.serialize(aString, fieldValue.getDataOutput());
        recordBuilder.addField(MetadataRecordTypes.DATASOURCE_ADAPTER_ARECORD_TYPE_FIELD_INDEX, fieldValue);

        // write field 4
        fieldValue.reset();
        aString.setValue(Calendar.getInstance().getTime().toString());
        stringSerde.serialize(aString, fieldValue.getDataOutput());
        recordBuilder.addField(MetadataRecordTypes.DATASOURCE_ADAPTER_ARECORD_TIMESTAMP_FIELD_INDEX, fieldValue);

        // write record
        try {
            recordBuilder.write(tupleBuilder.getDataOutput(), true);
        } catch (AsterixException e) {
            throw new MetadataException(e);
        }
        tupleBuilder.addFieldEndOffset();

        tuple.reset(tupleBuilder.getFieldEndOffsets(), tupleBuilder.getByteArray());
        return tuple;
    }

}


text:
FROM ubuntu:16.10

MAINTAINER Ding Wen Xiang "624380857@qq.com"

ADD https://raw.githubusercontent.com/docker-zone/docker-os-sshd/master/run.sh /run.sh
ADD https://raw.githubusercontent.com/docker-zone/docker-os-sshd/master/process_ssh.sh /process_ssh.sh

RUN apt-get update -y \
    && apt-get install -y openssh-server \
    && apt-get install -y pwgen \
    && chmod +x /process_ssh.sh \
    && /process_ssh.sh \
    && rm -rf /process_ssh.sh \
    && chmod +x /run.sh \
    && apt-get clean

EXPOSE 22

CMD ["/run.sh"]


text:
using System;

class Digits
{
    static void Main()
    {
        string input = Console.ReadLine();

        long[] numbers = ConvertStringToInt(input);
        long diffrence = 0;
        long sum = 0;

        for (long i = 1; i < numbers.Length; i++)
        {
            diffrence = Math.Abs(numbers[i] - numbers[i - 1]);

            if (diffrence % 2 != 0)
            {
                sum += diffrence;
            }

            if (diffrence % 2 == 0)
            {
                i++;
            }
        }

        Console.WriteLine(sum);
    }

    static long[] ConvertStringToInt(string input)
    {
        string[] numbersString = input.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

        long[] numbers = new long[numbersString.Length];
        for (int i = 0; i < numbers.Length; i++)
        {
            numbers[i] = long.Parse(numbersString[i]);
        }

        return numbers;
    }
}


text:
__author__ = 'zeek'
import socket
import sys

HOST = '119.90.49.107'    # The remote host
PORT = 8034              # The same port as used by the server
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
    af, socktype, proto, canonname, sa = res
    try:
        s = socket.socket(af, socktype, proto)
    except OSError as msg:
        s = None
        continue
    try:
        s.connect(sa)
    except OSError as msg:
        s.close()
        s = None
        continue
    break
if s is None:
    print('could not open socket')
    sys.exit(1)
s.sendall(b'Hello, world')
data = s.recv(1024)
s.close()
print('Received', repr(data))


text:
#include "condor_common.h"
#include "dap_constants.h"
#include "dap_error.h"
#include "dap_utility.h"

#include <unistd.h>
#include <errno.h>

#define MSSCMD	"msscmd"

int transfer_from_unitree_to_file(char *src_file, char *dest_file)
{

  FILE *pipe = 0;
  char pipecommand[MAXSTR], t[MAXSTR];
  int ret = -1;
  struct stat filestat;
  unsigned long src_filesize = 1, dest_filesize = 0;
  char linebuf[MAXSTR] = "";

  //get the source file size
  snprintf(pipecommand, MAXSTR, "%s ls %s", MSSCMD, src_file);

  pipe = popen (pipecommand, "r");
  if ( pipe == 0 ) {
    fprintf(stderr,"Error:couldn't open pipe to %s ls!\n", MSSCMD);
    return DAP_ERROR;
  }

  while ( 1 ) {
    if ( fgets( linebuf, MAXSTR, pipe ) == 0 ) {
      break;
    }
    if (sscanf(linebuf, "-r%s      1 %s    ac       %s  common    %lu", t, t, t, &src_filesize) > 0){
      break;
    }
  }
  fprintf(stdout, ">source_filesize: %lu\n", src_filesize);

  //get the file
  snprintf(pipecommand, MAXSTR, "%s get %s %s", MSSCMD, src_file, dest_file);

  pipe = popen (pipecommand, "r");
  if ( pipe == 0 ) {
    fprintf(stderr,"Error:couldn't open pipe to %s get!\n", MSSCMD);
    return DAP_ERROR;
  }
  /*
  while ( 1 ) {
    if ( fgets( linebuf, MAXSTR, pipe ) == 0 ) {
      break;
    }
    if (sscanf(linebuf, "%d bytes received in %f seconds", &bytes_sent, &time ) == 2){
      if (bytes_sent == src_filesize){
        ret = 0;
        break;
      }
    }
    fprintf(stdout, ">bytes_sent:%d\n", bytes_sent);
  }
  */

  pclose(pipe);

  //check destination filesize
  if (!lstat(dest_file, &filestat)){//if file exist
    fprintf(stdout, ">dest_file:%s, size:%lu\n", dest_file,
			(unsigned long)filestat.st_size);
    dest_filesize = filestat.st_size;
  }

  fprintf(stdout, ">dest_filesize:%lu\n", dest_filesize);

  if (src_filesize == dest_filesize){
    ret = 0;
    printf("* SUCCESS!\n");
  }

  fprintf(stdout, "Command terminated with err_code: %d\n", ret);

  if (ret == 0)
    return DAP_SUCCESS;
  else
    return DAP_ERROR;
}

int transfer_from_file_to_unitree(char *src_file, char *dest_file)
{

  FILE *pipe = 0;
  char pipecommand[MAXSTR];
  int ret = -1;
  struct stat filestat;
  unsigned long src_filesize = 0, dest_filesize = 0;
  float time;
  char linebuf[MAXSTR] = "";

  //check source filesize
  if (!lstat(src_file, &filestat)){//if file exist
    src_filesize = filestat.st_size;
  }

  snprintf(pipecommand, MAXSTR, "%s put %s %s",
  	   MSSCMD, src_file, dest_file);

  pipe = popen (pipecommand, "r");
  if ( pipe == 0 ) {
    fprintf(stderr,"Error:couldn't open pipe to %s put!\n", MSSCMD);
    return -1;
  }

  while ( 1 ) {
    if ( fgets( linebuf, MAXSTR, pipe ) == 0 ) {
      break;
    }

    if (sscanf(linebuf, "%lu bytes sent in %f seconds", &dest_filesize, &time ) == 2){
      if (src_filesize == dest_filesize){
	ret = 0;
	break;
      }
    }
    //    fprintf(stdout, ">%s", linebuf);
  }
  // fprintf(stdout, ">%s", linebuf);

  pclose(pipe);
  fprintf(stdout, "Command terminated with err_code: %d\n", ret);

  if (ret == 0)
    return DAP_SUCCESS;
  else
    return DAP_ERROR;
}

int main(int argc, char *argv[])
{
  char src_url[MAXSTR], dest_url[MAXSTR];
  char src_protocol[MAXSTR], src_host[MAXSTR], src_file[MAXSTR];
  char dest_protocol[MAXSTR], dest_host[MAXSTR], dest_file[MAXSTR];
  char arguments[MAXSTR];
  int status;

  if (argc < 3){
    fprintf(stderr, "==============================================================\n");
    fprintf(stderr, "USAGE: %s <src_url> <dest_url>\n", argv[0]);
    fprintf(stderr, "==============================================================\n");
    exit(-1);
  }

  strncpy(src_url, argv[1], MAXSTR);
  strncpy(dest_url, argv[2], MAXSTR);

  strncpy(arguments, "", MAXSTR);
  for(int i=3;i<argc;i++) {
    size_t len = strlen(arguments);
    if(len) {
      strncpy(arguments+len, " ", MAXSTR-len);
      len++;
    }
    strncpy(arguments+len, argv[i], MAXSTR-len);
  }

  parse_url(src_url, src_protocol, src_host, src_file);
  parse_url(dest_url, dest_protocol, dest_host, dest_file);

  fprintf(stdout, "FROM: %s:%s:%s\n",
	  src_protocol, src_host, src_file );
  fprintf(stdout, "TO  : %s:%s:%s\n",
	  dest_protocol, dest_host, dest_file);

  fprintf(stdout, "Transfering from: %s to: %s\n", src_url, dest_url);

  if (!strcmp(strip_str(src_protocol), "unitree")
      && !strcmp(strip_str(dest_protocol), "file")){

    status = transfer_from_unitree_to_file(strip_str(src_file), strip_str(dest_file));
  }
  else if (!strcmp(strip_str(src_protocol), "file")
	   && !strcmp(strip_str(dest_protocol), "unitree")){

    status = transfer_from_file_to_unitree(strip_str(src_file), strip_str(dest_file));
  }
  else{
    fprintf(stderr, "Error: Transfer from %s to %s using this module not supported!\n",
	    src_protocol, dest_protocol);
    exit(-1);
  }

  //-- output to a temporary file....
  if (status != DAP_SUCCESS){
    unsigned int mypid;
    FILE *f;
    char fname[MAXSTR];

    mypid = getpid();
    snprintf(fname, MAXSTR, "out.%d", mypid);

    f = safe_fopen_wrapper(fname, "w");
    fprintf(f, "SRB error!");
    fclose(f);
  }
  //--

  return status;
}


text:
package commitlog

import (
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"

	"github.com/compose/transporter/log"
)

const (
	defaultMaxSegmentBytes = 1024 * 1024 * 100
	logFileSuffix          = ".log"
	cleanedFileSuffix      = ".cleaned"
	swapFileSuffix         = ".swap"
	deletedFileSuffix      = ".deleted"
)

var (
	defaultPath = filepath.Join(os.TempDir(), "transporter")
	encoding    = binary.BigEndian

	// ErrEmptyPath will be returned if the provided path is an empty string
	ErrEmptyPath = errors.New("path is empty")
	// ErrSegmentNotFound is returned with no segment is found given the provided offset
	ErrSegmentNotFound = errors.New("segment not found")
)

// CommitLog is how the rest of the system will interact with the underlying log segments
// to persist and read messages.
type CommitLog struct {
	path            string
	maxSegmentBytes int64

	mu             sync.RWMutex
	segments       []*Segment
	vActiveSegment atomic.Value
}

// OptionFunc is a function that configures a CommitLog.
// It is used in New.
type OptionFunc func(*CommitLog) error

// New creates a new CommitLog for persisting and reading messages.
//
// The caller can configure the CommitLog by passing configuration options
// to the func.
//
// Example:
//
//   c, err := New(
//     WithPath("path/to/dir"),
//     WithMaxSegmentBytes(1024))
//
// An error is also returned when some configuration option is invalid
func New(options ...OptionFunc) (*CommitLog, error) {
	// Set up the client
	c := &CommitLog{
		path:            defaultPath,
		maxSegmentBytes: defaultMaxSegmentBytes,
	}

	// Run the options on it
	for _, option := range options {
		if err := option(c); err != nil {
			return nil, err
		}
	}

	if err := c.init(); err != nil {
		return nil, err
	}

	if err := c.open(); err != nil {
		return nil, err
	}

	return c, nil
}

// WithPath defines the directory where all data will be stored.
func WithPath(path string) OptionFunc {
	return func(c *CommitLog) error {
		if path == "" {
			return ErrEmptyPath
		}
		c.path = path
		return nil
	}
}

// WithMaxSegmentBytes defines the maximum limit a log segment can reach before needing
// to create a new one.
func WithMaxSegmentBytes(max int64) OptionFunc {
	return func(c *CommitLog) error {
		if max > 0 {
			c.maxSegmentBytes = max
		}
		return nil
	}
}

func (c *CommitLog) init() error {
	return os.MkdirAll(c.path, 0755)
}

func (c *CommitLog) open() error {
	files, err := ioutil.ReadDir(c.path)
	if err != nil {
		return err
	}

	// first pass through to clean up any interrupted compactions
	for _, file := range files {
		switch filepath.Ext(file.Name()) {
		case deletedFileSuffix, cleanedFileSuffix:
			os.Remove(filepath.Join(c.path, file.Name()))
		case swapFileSuffix:
			offsetStr := strings.TrimSuffix(file.Name(), swapFileSuffix)
			baseOffset, err := strconv.Atoi(offsetStr)
			if err != nil {
				return err
			}
			os.Rename(
				filepath.Join(c.path, file.Name()),
				filepath.Join(c.path, fmt.Sprintf(LogNameFormat, baseOffset)),
			)
		}
	}

	// now load each segment file
	for _, file := range files {
		if strings.HasSuffix(file.Name(), logFileSuffix) {
			offsetStr := strings.TrimSuffix(file.Name(), logFileSuffix)
			baseOffset, err := strconv.Atoi(offsetStr)
			segment, err := NewSegment(c.path, LogNameFormat, int64(baseOffset), c.maxSegmentBytes)
			if err != nil {
				return err
			}
			// we don't want to keep file handles open unless they are needed
			// if len(c.segments) > 0 {
			// 	c.segments[len(c.segments)-1].Close()
			// }
			c.segments = append(c.segments, segment)
		}
	}
	if len(c.segments) == 0 {
		segment, err := NewSegment(c.path, LogNameFormat, 0, c.maxSegmentBytes)
		if err != nil {
			return err
		}
		c.segments = append(c.segments, segment)
	}
	c.vActiveSegment.Store(c.segments[len(c.segments)-1])
	return nil
}

// Append will convert the set the offset for the provided []byte and then persist
// it to the active segment.
func (c *CommitLog) Append(p []byte) (offset int64, err error) {
	l := Log(p)
	if c.checkSplit() {
		if err := c.split(); err != nil {
			return offset, err
		}
	}
	offset = c.NewestOffset()
	l.PutOffset(offset)
	if _, err := c.activeSegment().Write(l); err != nil {
		return offset, err
	}
	return offset, nil
}

// Close iterates over all segments and calls its Close() func.
func (c *CommitLog) Close() error {
	c.mu.Lock()
	defer c.mu.Unlock()
	for _, segment := range c.segments {
		if err := segment.Close(); err != nil {
			return err
		}
	}
	return nil
}

// NewestOffset obtains the NextOffset of the current segment in use.
func (c *CommitLog) NewestOffset() int64 {
	return c.activeSegment().NextOffset
}

// OldestOffset obtains the BaseOffset from the oldest segment on disk.
func (c *CommitLog) OldestOffset() int64 {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.segments[0].BaseOffset
}

// Segments provides access to the underlying segments stored on disk.
func (c *CommitLog) Segments() []*Segment {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.segments
}

// DeleteAll cleans out all data in the path.
func (c *CommitLog) DeleteAll() error {
	if err := c.Close(); err != nil {
		return err
	}
	return os.RemoveAll(c.path)
}

// NewReader returns an io.Reader based on the provider offset.
func (c *CommitLog) NewReader(offset int64) (io.Reader, error) {
	c.mu.RLock()
	defer c.mu.RUnlock()
	log.With("num_segments", len(c.segments)).
		With("offset", offset).
		Infoln("searching segments")

	// in the event there has been data committed to the segment but no offset for a path,
	// then we need to create a reader that starts from the very beginning
	if offset < 0 && len(c.segments) > 0 {
		// if err := c.segments[0].Open(); err != nil {
		// 	log.Errorf("unable to open segment, %s", err)
		// }
		return &Reader{commitlog: c, idx: 0, position: 0}, nil
	}

	var idx int
	for i := 0; i < len(c.segments); i++ {
		idx = i
		if (i + 1) != len(c.segments) {
			lowerOffset := c.segments[i].BaseOffset
			upperOffset := c.segments[i+1].BaseOffset
			log.With("lower_offset", lowerOffset).
				With("upper_offset", upperOffset).
				With("offset", offset).
				With("segment", idx).
				Debugln("checking if offset in segment")
			if offset >= lowerOffset && offset < upperOffset {
				break
			}
		}
	}

	log.With("offset", offset).With("segment_index", idx).Debugln("finding offset in segment")
	// if err := c.segments[idx].Open(); err != nil {
	// 	log.Errorf("unable to open segment, %s", err)
	// }
	position, err := c.segments[idx].FindOffsetPosition(uint64(offset))
	if err != nil {
		return nil, err
	}

	return &Reader{
		commitlog: c,
		idx:       idx,
		position:  position,
	}, nil
}

func (c *CommitLog) replaceSegment(newSegment, oldSegment *Segment) error {
	log.With("new_segment", newSegment.path).
		With("old_segment", oldSegment.path).
		Infoln("replacing segment...")
	c.mu.Lock()
	defer c.mu.Unlock()
	log.With("new_segment", newSegment.path).
		With("format", swapNameFormat).
		Infoln("renaming")
	newSegment.rename(c.path, swapNameFormat)
	// TODO: this may become ineffienct but works for now
	for i, s := range c.segments {
		if s == oldSegment {
			c.segments[i] = newSegment
			break
		}
	}
	// TODO: make this async
	log.With("old_segment", c.path).Infoln("configuring for deletion")
	oldSegment.rename(c.path, deleteNameFormat)
	log.With("old_segment", oldSegment.log.Name()).Infoln("deleting segment")
	os.Remove(oldSegment.log.Name())

	log.With("new_segment", newSegment.path).
		With("format", LogNameFormat).
		Infoln("renaming")
	newSegment.rename(c.path, LogNameFormat)

	// no need to keep a file handle open once compaction has completed
	// if err := newSegment.Close(); err != nil {
	// 	log.With("new_segment", newSegment.path).Errorf("failed to Close, %s", err)
	// }
	log.With("new_segment", newSegment.path).
		With("old_segment", oldSegment.path).
		Infoln("segment replacement complete")
	return nil
}

func (c *CommitLog) activeSegment() *Segment {
	return c.vActiveSegment.Load().(*Segment)
}

func (c *CommitLog) checkSplit() bool {
	return c.activeSegment().IsFull()
}

func (c *CommitLog) split() error {
	segment, err := NewSegment(c.path, LogNameFormat, c.NewestOffset(), c.maxSegmentBytes)
	log.With("segment", segment.path).Infoln("new segment created")
	if err != nil {
		return err
	}
	c.mu.Lock()
	c.segments = append(c.segments, segment)
	// c.activeSegment().Close()
	c.vActiveSegment.Store(segment)
	c.mu.Unlock()
	return nil
}


text:
// Copyright 2017 TODO Group. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

const spawnSync = require('child_process').spawnSync
const Result = require('../lib/result')
// eslint-disable-next-line no-unused-vars
const FileSystem = require('../lib/file_system')

function listCommitsWithLines(fileSystem, options) {
  const pattern = '(' + options.denylist.join('|') + ')'
  const commits = gitAllCommits(fileSystem.targetDir)
  return commits
    .map(commit => {
      return {
        hash: commit,
        lines: gitLinesAtCommit(
          fileSystem.targetDir,
          pattern,
          options.ignoreCase,
          commit
        ).filter(line => fileSystem.shouldInclude(line.path))
      }
    })
    .filter(commit => commit.lines.length > 0)
}

/**
 * @param targetDir
 * @ignore
 */
function gitAllCommits(targetDir) {
  const args = ['-C', targetDir, 'rev-list', '--all']
  return spawnSync('git', args).stdout.toString().trim().split('\n')
}

/**
 * @param targetDir
 * @param pattern
 * @param ignoreCase
 * @param commit
 * @ignore
 */
function gitGrep(targetDir, pattern, ignoreCase, commit) {
  const args = [
    '-C',
    targetDir,
    'grep',
    '-E',
    ignoreCase ? '-i' : '',
    pattern,
    commit
  ]
  return spawnSync('git', args)
    .stdout.toString()
    .split('\n')
    .filter(x => !!x)
}

/**
 * @param targetDir
 * @param pattern
 * @param ignoreCase
 * @param commit
 * @ignore
 */
function gitLinesAtCommit(targetDir, pattern, ignoreCase, commit) {
  const lines = gitGrep(targetDir, pattern, ignoreCase, commit).map(entry => {
    const [path, ...rest] = entry.substring(commit.length + 1).split(':')
    return { path: path, content: rest.join(':') }
  })

  return lines
}

/**
 * @param fileSystem
 * @param options
 * @ignore
 */
function listFiles(fileSystem, options) {
  const files = []

  const commits = listCommitsWithLines(fileSystem, options)
  commits.forEach(commit => {
    commit.lines.forEach(line => {
      const existingFile = files.find(f => f.path === line.path)

      if (existingFile) {
        const existingCommit = existingFile.commits.find(
          c => c.hash === commit.hash
        )

        if (existingCommit) {
          existingCommit.lines.push(line.content)
        } else {
          existingFile.commits.push({
            hash: commit.hash,
            lines: [line.content]
          })
        }
      } else {
        files.push({
          path: line.path,
          commits: [{ hash: commit.hash, lines: [line.content] }]
        })
      }
    })
  })

  return files
}

/**
 *
 * @param {FileSystem} fs A filesystem object configured with filter paths and target directories
 * @param {object} options The rule configuration
 * @returns {Result} The lint rule result
 * @ignore
 */
function gitGrepCommits(fs, options) {
  // backwards compatibility with blacklist
  options.denylist = options.denylist || options.blacklist

  const files = listFiles(fs, options)
  const targets = files.map(file => {
    const [firstCommit, ...rest] = file.commits
    const restMessage =
      rest.length > 0 ? `, and ${rest.length} more commits` : ''

    const message = [
      `(${
        file.path
      }) contains denylisted words in commit ${firstCommit.hash.substr(
        0,
        7
      )}${restMessage}.`,
      `\tdenylist: ${options.denylist.join(', ')}`
    ].join('\n')

    return {
      passed: false,
      path: file.path,
      message
    }
  })

  if (targets.length === 0) {
    const message = [
      'No denylisted words found in any commits.',
      `\tdenylist: ${options.denylist.join(', ')}`
    ].join('\n')
    return new Result(message, [], true)
  }

  return new Result('', targets, false)
}

module.exports = gitGrepCommits


text:
CREATE EXTENSION hstore;
CREATE EXTENSION pg_freespacemap;
CREATE EXTENSION tdigest;
CREATE EXTENSION btree_gin;
CREATE EXTENSION btree_gist;
CREATE EXTENSION citext;
CREATE EXTENSION dblink;
CREATE EXTENSION hll;
CREATE EXTENSION intarray;
CREATE EXTENSION ltree;
CREATE EXTENSION pg_buffercache;
CREATE EXTENSION pg_prewarm;
CREATE EXTENSION pg_stat_statements;
CREATE EXTENSION pg_trgm;
CREATE EXTENSION pgcrypto;
CREATE EXTENSION pgrowlocks;
CREATE EXTENSION pgstattuple;
CREATE EXTENSION sslinfo;
CREATE EXTENSION tablefunc;
CREATE EXTENSION topn;
CREATE EXTENSION unaccent;
CREATE EXTENSION "uuid-ossp";
CREATE EXTENSION xml2;
CREATE EXTENSION cube;
CREATE EXTENSION earthdistance;
CREATE EXTENSION fuzzystrmatch;


text:
package fpt.com.core;

import fpt.com.core.controller.BaseController;

import java.util.HashMap;

/**
 * ControllerManager
 *

 * Global manager for accessing all controllers
 * from everywhere...
 *
 * @author senycorp
 */
public class ControllerManager
        extends HashMap<String, BaseController> {

    private static ControllerManager instance;

    /**
     * Constructor
     *

     * This is private to prevent multiple instances of this manager
     */
    private ControllerManager() {
        /**
         * Nothing to implement
         */
    }

    /**
     * Get singleton object
     *
     * @return
     */
    public static ControllerManager getInstance() {
        // Check for existing instance
        if (instance == null) {
            instance = new ControllerManager();
        }

        return instance;
    }

    /**
     * Get controller by id
     *
     * @param controllerID
     * @return
     */
    public BaseController getControllerById(String controllerID) {
        return this.get(controllerID);
    }
}


text:
namespace FsxWebApi.Helpers
{
    using Infrastructure;
    using Model;

    public class FsxManager
    {
        private readonly FsxCommunicator _fsxCommunicator = new FsxCommunicator(new Logger());

        public PlaneData GetCurrentPlaneData()
        {
            PlaneData planeData = _fsxCommunicator.GetPlaneData();

            return planeData;
        }

        public bool SetNewPlaneLocation(Location planeLocation)
        {
            return _fsxCommunicator.SetPlaneLocation(planeLocation);
        }
    }
}


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

/**
 * @fileoverview Calendar-related utils, all under the utils namespace.
 *
 * @author manas@google.com (Manas Tungare)
 */

/**
 * The namespace for calendar-related utils.
 * @namespace
 */
var utils = {};

/**
 * The maximum number of characters per field, to keep the resulting Google
 * Calendar template URL below acceptable limits.
 * @type {number}
 * @const
 * @private
 */
utils.MAX_CHARS_PER_FIELD_ = 300;

/**
 * Processes a calendar event object by inferring missing fields,
 * trimming lengths of fields that are too long, and adding computed fields.
 * @param {CalendarEvent} event The event to process.
 * @return {CalendarEvent} The processed event.
 */
utils.processEvent = function(event) {
  if (!event.end) {  // If there's no end time, infer one as best as we can.
    var startMoment = moment(event.start);
    if (startMoment.hours() === 0 && startMoment.minutes() === 0) {
      // Assume it's an all-day event if hh=0 & mm=0.
      event.end = startMoment.add('d', 1).valueOf();
    } else {
      // It's not an all-day event, so default to start + X hours, and the user
      // can tweak it before adding to their calendar.
      event.end = startMoment.add('h', 2).valueOf();
    }
  }

  // Trim each field to a maximum acceptable length.
  for (var field in event) {
    if (event.hasOwnProperty(field) &&
        event[field].length > utils.MAX_CHARS_PER_FIELD_) {
      event[field] = event[field].replace(/[\s]+/gi, ' ').
          substring(0, utils.MAX_CHARS_PER_FIELD_ - 2) + ' \u2026';
    }
  }

  if (event.address) {
    if (event.location) {
      event.location = event.address + ' (' + event.location + ')';
    } else {
      event.location = event.address;
    }
    delete event.address;
  }

  // Create Calendar URL after all fields have been trimmed.
  event.gcal_url = utils.getGCalUrl_(event);

  return event;
};

/**
 * Returns a link to a template URL that prefills a Google Calendar event
 * template with the details of this event.
 * @param {CalendarEvent} event The event to create the URL for.
 * @return {string} Google Calendar event template link.
 * @private
 */
utils.getGCalUrl_ = function(event) {
  // Basic event information: Title, Start, End.
  var link =
      'https://calendar.google.com/calendar/event?action=TEMPLATE&trp=false&ctext=' +
      encodeURIComponent(event.title);

  // Dates could be optional.
  if (event.start) {
    // If the time is exactly midnight, this might be an all-day event, so skip
    // the T000000 part.
    link += '&dates=' +
        moment(event.start).format('YYYYMMDDTHHmmss').replace('T000000', '');

    // Even if start date is present, end date could be missing.
    if (event.end) {
      link += '/' +
          moment(event.end).format('YYYYMMDDTHHmmss').replace('T000000', '');
    }
  }

  // Location
  if (event.location) {
    link += '&location=' + encodeURIComponent(event.location);
  }

  // URL
  if (event.url) {
    link += '&sprop=' + encodeURIComponent(event.url) +
        '&sprop=name:' + encodeURIComponent(event.title);
  }

  // Details
  if (event.description || event.url) {
    link += '&details=';

    if (event.description) {
      link += encodeURIComponent(event.description + '\n\n');
    }

    if (event.url) {
      link += chrome.i18n.getMessage('read_more_at_original_url') +
          encodeURIComponent(event.url);
    }
  }

  return link;
};

/**
 * Parse ISO 8601 date/time into a JavaScript date.
 * @param {string|number} date ISO 8601 date as a string, or milliseconds since the epoch.
 * @return {Moment} Parsed JavaScript date object.
 */
utils.fromIso8601 = function(date) {
  // TODO(manas): Audit and fix this so that it's not used for dates expressed as milliseconds since the epoch.

  if (!date) {
    return null;
  }

  if (typeof date === 'string') {
    date = date.replace('Z', '+00:00');
    return moment(date, [
      'YYYY-MM-DDTHH:mm:ssZZ', 'YYYY-MM-DDTHHmmssZZ', 'YYYYMMDDTHHmmssZZ',
      'YYYY-MM-DDTHH:mm:ss',   'YYYY-MM-DDTHHmmss',   'YYYYMMDDTHHmmss',
      'YYYY-MM-DDTHH:mmZZ',    'YYYY-MM-DDTHHmmZZ',   'YYYYMMDDTHHmmZZ',
      'YYYY-MM-DDTHH:mm',      'YYYY-MM-DDTHHmm',     'YYYYMMDDTHHmm',
      'YYYY-MM-DDTHH',                                'YYYYMMDDTHH',
      'YYYY-MM-DD',                                   'YYYYMMDD'
    ]);
  } else {
    return moment(date);
  }
};

/**
 * In a DOMElement, locate the first instance of the given selector. If
 * such an instance is present, then return its text. Else return "".
 * @param {Element} element The DOMElement to start looking under.
 * @param {string} selector What to look for, as a CSS selector.
 * @return {string} The text of the first child if found; "" otherwise.
 */
utils.getFirstFieldText = function(element, selector) {
  var rawField = $(element).find(selector);
  if (rawField && rawField.length > 0) {
    return $(rawField[0]).text().trim();
  }
  return '';
};

/**
 * Loads Google Analytics.
 */
utils.startAnalytics_ = function() {
  window._gaq = window._gaq || [];
  _gaq.push(['_setAccount', 'UA-21917188-3']);

  var ga = document.createElement('script');
  ga.type = 'text/javascript';
  ga.async = true;
  ga.src = 'https://ssl.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(ga, s);
};


text:
namespace Dropbox.Api.TeamLog
{
    using sys = System;
    using col = System.Collections.Generic;
    using re = System.Text.RegularExpressions;

    using enc = Dropbox.Api.Stone;

    /// <summary>
    /// <para>Group's logged information.</para>
    /// </summary>
    public class GroupLogInfo
    {
        #pragma warning disable 108

        /// <summary>
        /// <para>The encoder instance.</para>
        /// </summary>
        internal static enc.StructEncoder<GroupLogInfo> Encoder = new GroupLogInfoEncoder();

        /// <summary>
        /// <para>The decoder instance.</para>
        /// </summary>
        internal static enc.StructDecoder<GroupLogInfo> Decoder = new GroupLogInfoDecoder();

        /// <summary>
        /// <para>Initializes a new instance of the <see cref="GroupLogInfo" /> class.</para>
        /// </summary>
        /// <param name="displayName">The name of this group.</param>
        /// <param name="groupId">The unique id of this group.</param>
        /// <param name="externalId">External group ID.</param>
        public GroupLogInfo(string displayName,
                            string groupId = null,
                            string externalId = null)
        {
            if (displayName == null)
            {
                throw new sys.ArgumentNullException("displayName");
            }

            this.DisplayName = displayName;
            this.GroupId = groupId;
            this.ExternalId = externalId;
        }

        /// <summary>
        /// <para>Initializes a new instance of the <see cref="GroupLogInfo" /> class.</para>
        /// </summary>
        /// <remarks>This is to construct an instance of the object when
        /// deserializing.</remarks>
        [sys.ComponentModel.EditorBrowsable(sys.ComponentModel.EditorBrowsableState.Never)]
        public GroupLogInfo()
        {
        }

        /// <summary>
        /// <para>The name of this group.</para>
        /// </summary>
        public string DisplayName { get; protected set; }

        /// <summary>
        /// <para>The unique id of this group.</para>
        /// </summary>
        public string GroupId { get; protected set; }

        /// <summary>
        /// <para>External group ID.</para>
        /// </summary>
        public string ExternalId { get; protected set; }

        #region Encoder class

        /// <summary>
        /// <para>Encoder for  <see cref="GroupLogInfo" />.</para>
        /// </summary>
        private class GroupLogInfoEncoder : enc.StructEncoder<GroupLogInfo>
        {
            /// <summary>
            /// <para>Encode fields of given value.</para>
            /// </summary>
            /// <param name="value">The value.</param>
            /// <param name="writer">The writer.</param>
            public override void EncodeFields(GroupLogInfo value, enc.IJsonWriter writer)
            {
                WriteProperty("display_name", value.DisplayName, writer, enc.StringEncoder.Instance);
                if (value.GroupId != null)
                {
                    WriteProperty("group_id", value.GroupId, writer, enc.StringEncoder.Instance);
                }
                if (value.ExternalId != null)
                {
                    WriteProperty("external_id", value.ExternalId, writer, enc.StringEncoder.Instance);
                }
            }
        }

        #endregion

        #region Decoder class

        /// <summary>
        /// <para>Decoder for  <see cref="GroupLogInfo" />.</para>
        /// </summary>
        private class GroupLogInfoDecoder : enc.StructDecoder<GroupLogInfo>
        {
            /// <summary>
            /// <para>Create a new instance of type <see cref="GroupLogInfo" />.</para>
            /// </summary>
            /// <returns>The struct instance.</returns>
            protected override GroupLogInfo Create()
            {
                return new GroupLogInfo();
            }

            /// <summary>
            /// <para>Set given field.</para>
            /// </summary>
            /// <param name="value">The field value.</param>
            /// <param name="fieldName">The field name.</param>
            /// <param name="reader">The json reader.</param>
            protected override void SetField(GroupLogInfo value, string fieldName, enc.IJsonReader reader)
            {
                switch (fieldName)
                {
                    case "display_name":
                        value.DisplayName = enc.StringDecoder.Instance.Decode(reader);
                        break;
                    case "group_id":
                        value.GroupId = enc.StringDecoder.Instance.Decode(reader);
                        break;
                    case "external_id":
                        value.ExternalId = enc.StringDecoder.Instance.Decode(reader);
                        break;
                    default:
                        reader.Skip();
                        break;
                }
            }
        }

        #endregion
    }
}


text:
use std::convert::TryInto;

use anyhow::{Context, Result};

use crate::fixtures::*;
use crate::helper::*;

#[tokio::test]
/// Spin up the daemon and send a SIGTERM shortly afterwards.
/// This should trigger the graceful shutdown and kill the process.
async fn test_ctrlc() -> Result<()> {
    let (settings, _tempdir) = daemon_base_setup()?;
    let mut child = standalone_daemon(&settings.shared).await?;

    use nix::sys::signal::{kill, Signal};
    // Send SIGTERM signal to process via nix
    let nix_pid = nix::unistd::Pid::from_raw(child.id() as i32);
    kill(nix_pid, Signal::SIGTERM).context("Failed to send SIGTERM to pid")?;

    // Sleep for 500ms and give the daemon time to shut down
    sleep_ms(500);

    let result = child.try_wait();
    assert!(matches!(result, Ok(Some(_))));
    let code = result.unwrap().unwrap();
    assert!(matches!(code.code(), Some(1)));

    Ok(())
}

#[tokio::test]
/// Spin up the daemon and send a graceful shutdown message afterwards.
/// The daemon should shutdown normally and exit with a 0.
async fn test_graceful_shutdown() -> Result<()> {
    let (settings, _tempdir) = daemon_base_setup()?;
    let mut child = standalone_daemon(&settings.shared).await?;

    // Kill the daemon gracefully and wait for it to shut down.
    assert_success(shutdown_daemon(&settings.shared).await?);
    wait_for_shutdown(child.id().try_into()?)?;

    // Sleep for 500ms and give the daemon time to shut down
    sleep_ms(500);

    let result = child.try_wait();
    assert!(matches!(result, Ok(Some(_))));
    let code = result.unwrap().unwrap();
    assert!(matches!(code.code(), Some(0)));

    Ok(())
}


text:
package com.webcontext.apps.services.user.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
 * User is a user modeling for a System connected user.
 *
 * @author Frédéric Delorme<frederic.delorme@web-context.com>
 *
 */
@Entity
@NamedQueries({
		@NamedQuery(name = "findByUsername", query = "SELECT u FROM User u WHERE u.username=:username"),
		@NamedQuery(name = "findAll", query = "SELECT u FROM User u ORDER BY u.username ASC"),
		@NamedQuery(name="count",query="SELECT COUNT(u) FROM User u")})
@Table(name="RWAUSERS")
public class User {
	@Id
	private String username;

	private String password;
	private String email;
	private String firstname;
	private String lastname;

	/**
	 * Default Standard constructor.
	 */
	public User() {
	}

	/**
	 * Default Standard constructor.
	 */
	public User(String username, String firstname, String lastname,
			String email, String password) {

		this.username = username;
		this.firstname = firstname;
		this.lastname = lastname;
		this.email = email;
		this.password = password;
	}

	/**
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * @param username
	 *            the username to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password
	 *            the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @return the email
	 */
	public String getEmail() {
		return email;
	}

	/**
	 * @param email
	 *            the email to set
	 */
	public void setEmail(String email) {
		this.email = email;
	}

	/**
	 * @return the firstname
	 */
	public String getFirstname() {
		return firstname;
	}

	/**
	 * @param firstname
	 *            the firstname to set
	 */
	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}

	/**
	 * @return the lastname
	 */
	public String getLastname() {
		return lastname;
	}

	/**
	 * @param lastname
	 *            the lastname to set
	 */
	public void setLastname(String lastname) {
		this.lastname = lastname;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("User [");
		if (username != null)
			builder.append("username=").append(username).append(", ");
		if (password != null)
			builder.append("password=").append(password).append(", ");
		if (email != null)
			builder.append("email=").append(email).append(", ");
		if (firstname != null)
			builder.append("firstname=").append(firstname).append(", ");
		if (lastname != null)
			builder.append("lastname=").append(lastname);
		builder.append("]");
		return builder.toString();
	}

}


text:
using io.rong.models.push;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using io.rong.util;
using io.rong.models;
using System.Web;
using io.rong.models.response;
using io.rong.util;

namespace io.rong.methods.user.block
{
    public class Block

    {
        private static Encoding UTF8 = Encoding.UTF8;
        private static String PATH = "user/block";
        private String appKey;
        private String appSecret;
        private RongCloud rongCloud;

        public RongCloud RongCloud
        {
            get { return this.rongCloud; }
            set { this.rongCloud = value; }
        }

        public Block(String appKey, String appSecret)
        {
            this.appKey = appKey;
            this.appSecret = appSecret;

        }
        /**
         * 封禁用户方法(每秒钟限 100 次)
         *
         * @param  user :用户信息 Id,minute(必传)
         *
         * @return Result
         **/
        public Result Add(UserModel user)
        {

            String message = CommonUtil.CheckFiled(user, PATH, CheckMethod.ADD);
            if (null != message)
            {
                return RongJsonUtil.JsonStringToObj<ResponseResult>(message);
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("&userId=").Append(HttpUtility.UrlEncode(user.Id.ToString(), UTF8));
            sb.Append("&minute=").Append(HttpUtility.UrlEncode(user.Minute.ToString(), UTF8));
            String body = sb.ToString();
            if (body.IndexOf("&") == 0)
            {
                body = body.Substring(1, body.Length - 1);
            }

            String result = RongHttpClient.ExecutePost(appKey, appSecret, body, RongCloud.ApiHostType.Type + "/user/block.json", "application/x-www-form-urlencoded");

            return (ResponseResult)RongJsonUtil.JsonStringToObj<ResponseResult>(CommonUtil.GetResponseByCode(PATH, CheckMethod.ADD, result));
        }

        /**
         * 解除用户封禁方法(每秒钟限 100 次)
         *
         * @param  userId:用户 Id。(必传)
         *
         * @return ResponseResult
         **/
        public ResponseResult Remove(String userId)
        {
            //参数校验
            String message = CommonUtil.CheckParam("id", userId, PATH, CheckMethod.REMOVE);
            if (null != message)
            {
                return (ResponseResult)RongJsonUtil.JsonStringToObj<ResponseResult>(message);
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("&userId=").Append(HttpUtility.UrlEncode(userId.ToString(), UTF8));
            String body = sb.ToString();
            if (body.IndexOf("&") == 0)
            {
                body = body.Substring(1, body.Length - 1);
            }

            String result = RongHttpClient.ExecutePost(appKey, appSecret, body, RongCloud.ApiHostType.Type + "/user/unblock.json", "application/x-www-form-urlencoded");

            return (ResponseResult)RongJsonUtil.JsonStringToObj<ResponseResult>(CommonUtil.GetResponseByCode(PATH, CheckMethod.REMOVE, result));

        }

        /**
         * 获取被封禁用户方法(每秒钟限 100 次)
         *
         *
         * @return QueryBlockUserResult
         **/
        public BlockUserResult GetList()
        {
            StringBuilder sb = new StringBuilder();
            String body = sb.ToString();
            if (body.IndexOf("&") == 0)
            {
                body = body.Substring(1, body.Length - 1);
            }
            String result = RongHttpClient.ExecutePost(appKey, appSecret, body, RongCloud.ApiHostType.Type + "/user/block/query.json", "application/x-www-form-urlencoded");

            return (BlockUserResult)RongJsonUtil.JsonStringToObj<BlockUserResult>(CommonUtil.GetResponseByCode(PATH, CheckMethod.GETLIST, result));

        }
    }
}