text:
from __future__ import unicode_literals

from django.db import migrations, models
import uuid

class Migration(migrations.Migration):

    dependencies = [
        ('arach', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='archetype',
            name='uuid',
            field=models.UUIDField(default=uuid.uuid4, editable=False),
        ),
        migrations.AlterField(
            model_name='archetype',
            name='cast',
            field=models.PositiveIntegerField(choices=[(1, 'Fongeux'), (2, 'Monteurs'), (3, 'Rapiats'), (4, 'Pisteurs')]),
        ),
    ]


text:
const XLSX = require('xlsx');
const Apify = require('apify');

function toXlsxBuffer(array){
    //flattenRecords(array)
    const ws = XLSX.utils.json_to_sheet(array);
    const wb = {SheetNames:['results'], Sheets:{'results': ws}};
    const wopts = {bookType:'xlsx', bookSST:false, type:'binary'};
    const wbout = XLSX.write(wb, wopts);

    function s2ab(s){
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for(let i=0; i!=s.length; ++i){
            view[i] = s.charCodeAt(i) & 0xFF;
        }
        return Buffer.from(buf);
    }

    return s2ab(wbout);
}

function flattenRecord(record){
    if(record && typeof record === 'object'){
        for(const key in record){
            const value = record[key];
            if(value && Array.isArray(value)){
                if(value.length > 0){
                    record[key] = undefined;
                    //delete record[key];
                    flattenRecords(value);
                    for(let i = 0; i < value.length; i++){
                        record[key + '/' + i] = value[i];
                    }
                }
            }
        }
    }
}

function flattenRecords(data){
    for(let i = 0; i < data.length; i++){
        flattenRecord(data[i]);
    }
}

Apify.main(async () => {
    const input = await Apify.getValue('INPUT');
    let buffer;

    if(Array.isArray(input)){
        buffer = toXlsxBuffer(input);
    }
    else if(input.storeId && input.key){
        const jsonFromStore = await Apify.client.keyValueStores.getRecord(input);
        buffer = toXlsxBuffer(jsonFromStore.body);
    }
    else{
        throw new Error('Invalid input');
    }

    const storeId = (await Apify.getEnv()).defaultKeyValueStoreId;
    const url = "https://api.apifier.com/v2/key-value-stores/" + storeId + "/records/results.xlsx?rawBody=1&disableRedirect=1";
    const type = "application/octet-stream";
    await Apify.setValue('results.xlsx', buffer, {contentType: type});
    await Apify.setValue('OUTPUT', {output: url});
    console.log('Output URL: ' + url);
});

redpajama_set_name: RedPajamaGithub


text:
<?php

use Zizaco\Confide\ConfideUser;
use Zizaco\Confide\ConfideUserInterface;

class User extends Eloquent implements ConfideUserInterface {

	use ConfideUser;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = array('password', 'remember_token');

}


text:
const chai = require('chai');

const expect = chai.expect;

const Node = require('../graph/graphNode');
const breadthFirstSearch = require('../graph-traversing/breadth-first-search');
const depthFirstSearch = require('../graph-traversing/depth-first-search-imperative');
const depthFirstSearchRecursive = require('../graph-traversing/depth-first-search-recursive');

describe('Graph Traversing', () => {
  describe('Depth First Search - Recursive', () => {
    let A;
    let B;
    let C;
    let D;
    let E;
    let F;

    beforeEach(() => {
      A = new Node('A', 'Joe');
      B = new Node('B', 'Jon');
      C = new Node('C', 'Ray');
      D = new Node('D', 'JSON');
      E = new Node('E', 'Marifel');
      F = new Node('F', 'Nigel');
      A.addNeighbors([B, C]);
      B.addNeighbors([D, E]);
      C.addNeighbors([F]);
    });

    it('should be a function that exists', () => {
      expect(depthFirstSearchRecursive).to.exist;
      expect(depthFirstSearchRecursive).to.be.a('function');
    });

    it('should return the node with the value of `searchFor` stored in its value property', () => {
      expect(depthFirstSearchRecursive(A, 'Joe').value).to.equal('Joe');
      expect(depthFirstSearchRecursive(A, 'JSON').value).to.equal('JSON');
      expect(depthFirstSearchRecursive(A, 'JSON').name).to.equal('D');
      expect(depthFirstSearchRecursive(A, 'Nigel').value).to.equal('Nigel');
      expect(depthFirstSearchRecursive(A, 'Nigel').name).to.equal('F');
      expect(depthFirstSearchRecursive(B, 'Marifel').value).to.equal('Marifel');
      expect(depthFirstSearchRecursive(A, 'Marifel').name).to.equal('E');
    });

    it('should return false if it cant find the value in the graph', () => {
      expect(depthFirstSearchRecursive(F, 'Joe')).to.equal(false);
      expect(depthFirstSearchRecursive(E, 'Joe')).to.equal(false);
    });
  });

  describe('Depth First Search - Imperative', () => {
    let A;
    let B;
    let C;
    let D;
    let E;
    let F;

    beforeEach(() => {
      A = new Node('A', 'Joe');
      B = new Node('B', 'Jon');
      C = new Node('C', 'Ray');
      D = new Node('D', 'JSON');
      E = new Node('E', 'Marifel');
      F = new Node('F', 'Nigel');
      A.addNeighbors([B, C]);
      B.addNeighbors([D, E]);
      C.addNeighbors([F]);
    });

    it('should be a function that exists', () => {
      expect(depthFirstSearch).to.exist;
      expect(depthFirstSearch).to.be.a('function');
    });

    it('should return the node with the value of `searchFor` stored in its value property', () => {
      expect(depthFirstSearch(A, 'Joe').value).to.equal('Joe');
      expect(depthFirstSearch(A, 'JSON').value).to.equal('JSON');
      expect(depthFirstSearch(A, 'JSON').name).to.equal('D');
      expect(depthFirstSearch(A, 'Nigel').value).to.equal('Nigel');
      expect(depthFirstSearch(A, 'Nigel').name).to.equal('F');
      expect(depthFirstSearch(B, 'Marifel').value).to.equal('Marifel');
      expect(depthFirstSearch(A, 'Marifel').name).to.equal('E');
    });

    it('should return false if it cant find the value in the graph', () => {
      expect(depthFirstSearch(F, 'Joe')).to.equal(false);
      expect(depthFirstSearch(E, 'Joe')).to.equal(false);
    });
  });

  describe('Breadth First Search - Imperative', () => {
    let A;
    let B;
    let C;
    let D;
    let E;
    let F;

    beforeEach(() => {
      A = new Node('A', 'Joe');
      B = new Node('B', 'Jon');
      C = new Node('C', 'Ray');
      D = new Node('D', 'JSON');
      E = new Node('E', 'Marifel');
      F = new Node('F', 'Nigel');
      A.addNeighbors([B, C]);
      B.addNeighbors([D, E]);
      C.addNeighbors([F]);
    });

    it('should be a function that exists', () => {
      expect(breadthFirstSearch).to.exist;
      expect(breadthFirstSearch).to.be.a('function');
    });

    it('should return the traversal path from the starting point all the way to the end', () => {
      expect(breadthFirstSearch(A)).to.deep.equal(['A', 'B', 'C', 'D', 'E', 'F']);
      expect(breadthFirstSearch(B)).to.deep.equal(['B', 'D', 'E']);
      expect(breadthFirstSearch(C)).to.deep.equal(['C', 'F']);
      expect(breadthFirstSearch(D)).to.deep.equal(['D']);
      expect(breadthFirstSearch(E)).to.deep.equal(['E']);
      expect(breadthFirstSearch(F)).to.deep.equal(['F']);
    });
  });
});


text:
from settings.base import rel

STATIC_ROOT = rel('public', 'static')
MEDIA_ROOT = rel('public', 'media')

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

STATICFILES_DIRS = (rel('static'),)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

IMAGE_UPLOAD_DIR = "img"
SESSION_SAVE_EVERY_REQUEST = True

CKEDITOR_UPLOAD_PATH = 'uploads/'

CKEDITOR_IMAGE_BACKEND = 'pillow'

CKEDITOR_CONFIGS = {
    "default": {
        "removePlugins": "stylesheetparser",
        'allowedContent': True,
        'toolbar': None,
        'toolbarCanCollapse': False,
        'forcePasteAsPlainText': True
    }
}

CKEDITOR_JQUERY_URL = 'static/pangolin/js/jquery-1.12.4.min.js'


text:
[Entitas.CodeGeneration.Attributes.DontGenerate(false)]
public sealed class SomeOtherClassComponent : Entitas.IComponent {
    public SomeNamespace.SomeOtherClass value;
}


text:
namespace content {
class DownloadItem;
}

namespace gdata {

class GDataFileSystem;
struct UploadFileInfo;

class GDataUploader {
 public:
  explicit GDataUploader(GDataFileSystem* file_system);
  virtual ~GDataUploader();

  // Uploads a file specified by |upload_file_info|. Transfers ownership.
  // Returns the upload_id.
  int UploadFile(scoped_ptr<UploadFileInfo> upload_file_info);

  // Updates attributes of streaming upload.
  void UpdateUpload(int upload_id, content::DownloadItem* download);

  // Returns the count of bytes confirmed as uploaded so far.
  int64 GetUploadedBytes(int upload_id) const;

  // TODO(achuith): Make this private.
  // Destroys |upload_file_info|.
  void DeleteUpload(UploadFileInfo* upload_file_info);

 private:
  // Lookup UploadFileInfo* in pending_uploads_.
  UploadFileInfo* GetUploadFileInfo(int upload_id) const;

  // Open the file.
  void OpenFile(UploadFileInfo* upload_file_info);

  // net::FileStream::Open completion callback. The result of the file
  // open operation is passed as |result|.
  void OpenCompletionCallback(int upload_id, int result);

  // DocumentsService callback for InitiateUpload.
  void OnUploadLocationReceived(int upload_id,
                                GDataErrorCode code,
                                const GURL& upload_location);

  // Uploads the next chunk of data from the file.
  void UploadNextChunk(UploadFileInfo* upload_file_info);

  // net::FileStream::Read completion callback.
  void ReadCompletionCallback(int upload_id,
      int bytes_to_read,
      int bytes_read);

  // DocumentsService callback for ResumeUpload.
  void OnResumeUploadResponseReceived(int upload_id,
                                      const ResumeUploadResponse& response,
                                      scoped_ptr<DocumentEntry> entry);

  // When upload completes, move the file into the gdata cache.
  void MoveFileToCache(UploadFileInfo* upload_file_info);

  // Handle failed uploads.
  void UploadFailed(UploadFileInfo* upload_file_info);

  // Private data.
  GDataFileSystem* file_system_;

  int next_upload_id_;  // id counter.

  typedef std::map<int, UploadFileInfo*> UploadFileInfoMap;
  UploadFileInfoMap pending_uploads_;

  // Factory for various callbacks.
  base::WeakPtrFactory<GDataUploader> uploader_factory_;

  DISALLOW_COPY_AND_ASSIGN(GDataUploader);
};

}  // namespace gdata

#endif  // CHROME_BROWSER_CHROMEOS_GDATA_GDATA_UPLOADER_H_


text:
#ifndef __aml_vm__reference__
#define __aml_vm__reference__

#include "../../lib/predef.hpp"
#include "../../config/config.hpp"
#include "variable.hpp"
#include "../psi/psi.hpp"

#include <mutex>

namespace AVM {
	enum AReferenceType : unsigned_integer_8 {

		/* main point of interest */
		AReferenceTypeObject =             0x00,

		/* type for native extensions and libraries */
		AReferenceTypeUnmanagedUnsafe =    0x01,

		/* extended numeric types that do not fit into AValue */
		AReferenceTypeInteger64 =          0x02,
		AReferenceTypeUnsignedInteger64 =  0x03,
		AReferenceTypeInteger128 =         0x04,
		AReferenceTypeUnsignedInteger128 = 0x05,
		AReferenceTypeFloat128 =           0x06,

		/* composite numeric types */
		AReferenceTypeComplex =            0x07,
		AReferenceTypeRational =           0x08,
		AReferenceTypeDecimalLimited =     0x09,
		AReferenceTypeDecimalUnlimited =   0x0a,

		/* array type */
		AReferenceTypeArray =              0x0b,

		/* when a AValue pointer did not fit into 48 bits, the future is upon us, or more likely Solaris */
		AReferenceTypeNestedPointer =      0x0c,

		/* to break strong reference cycles */
		AReferenceTypeWeakPointer =        0x0d,

		/* an object associated with a PSI element */
		AReferenceTypePsiBearer =          0x0e
	};

	union AReferenceValue;

	struct ATypedVariableLink {
	public:
		const char *name;
		struct ATypedVariable variable;
		struct ATypedVariableLink *next;
	};

	/* Here's an optimization idea: pre-allocate an array of AReferences to be used whenever a new one
	 * would be needed, automatically grow it etc. (like std::vector<AReference> or something), to prevent
	 * some random memory accesses (also that could open the possibility of garbage collection...)
	 */
	struct AReference {
	public:
		struct std::atomic<union AReferenceValue *> const referenced_value;
		struct std::atomic<STRONG_REFERENCE_COUNT_TYPE> strong_reference_count;
		struct std::atomic<WEAK_REFERENCE_COUNT_TYPE> weak_reference_count;

		AReference(union AReferenceValue *);
		~AReference() noexcept;

		void
		retain(void * /* env */);

		void
		release(void * /* env */);

		AValue /* tagged pointer to AReference to CWeakReference */
		downgrade(void * /* env */);

		STRONG_REFERENCE_COUNT_TYPE
		strong_count() const noexcept;

		WEAK_REFERENCE_COUNT_TYPE
		weak_count() const noexcept;

	private:
		void
		release_slow(void * /* env */);
	};

	struct AReferenceCommon {
		const AReferenceType reference_type;

		AReferenceCommon(AReferenceType);
	};

	struct AObject {
	public:
		struct AReferenceCommon common;
		/* non-const psi_type, because hot code loading may upgrade it to new version */
		PsiElement *psi_type;
		struct ATypedVariableLink *dynamic_ivars;
		unsigned_integer_8 ivars_count;
		AVariable *ivars;

		static
		AValue
		allocate(PsiElement * /* psi_type */, void * /* env */) noexcept;

		AObject(PsiElement * /* psi_type */, unsigned_integer_8 /* ivars_count */);
		~AObject();
	};

	struct AUnmanagedUnsafe {
	public:
		struct AReferenceCommon common;
		void *pointer;
		void (*deallocator)(void *);

		AUnmanagedUnsafe(void * /* pointer */, void (*)(void *) /* deallocator */);
		~AUnmanagedUnsafe();

		static
		AValue
		allocate(void * /* pointer */, void (*)(void *) /* deallocator */, void * /* env */) noexcept;
	};

	struct AInteger64 {
	public:
		struct AReferenceCommon common;
		const integer_64 value;

		AInteger64(const integer_64) noexcept;

		static
		AValue
		allocate(const integer_64, void * /* env */) noexcept;
	};

	struct AInteger64Unsigned {
	public:
		struct AReferenceCommon common;
		const unsigned_integer_64 value;

		AInteger64Unsigned(const unsigned_integer_64) noexcept;

		static
		AValue
		allocate(const unsigned_integer_64, void * /* env */) noexcept;
	};

	struct AInteger128 {
	public:
		struct AReferenceCommon common;
		const integer_128 value;

		AInteger128(const integer_128) noexcept;

		static
		AValue
		allocate(const integer_128, void * /* env */) noexcept;
	};

	struct AInteger128Unsigned {
	public:
		struct AReferenceCommon common;
		const unsigned_integer_128 value;

		AInteger128Unsigned(const unsigned_integer_128) noexcept;

		static
		AValue
		allocate(const unsigned_integer_128, void * /* env */) noexcept;
	};

	struct AFloat128 {
	public:
		struct AReferenceCommon common;
		const float_128 value;

		AFloat128(const float_128) noexcept;

		static
		AValue
		allocate(const float_128, void * /* env */) noexcept;
	};

	struct AComplex {
	public:
		struct AReferenceCommon common;
		const AValue real;
		const AValue imaginary;

		AComplex(const AValue, const AValue) noexcept;

		static
		AValue
		allocate(const AValue /* real */, const AValue /* imaginary, obviously */, void * /* env */) noexcept;
	};

	struct ARational {
	public:
		struct AReferenceCommon common;
		const AValue numerator;
		const AValue denominator;

		ARational(const AValue, const AValue) noexcept;

		static
		AValue
		allocate(const AValue /* numerator */, const AValue /* denominator, obviously */, void * /* env */) noexcept;
	};

	struct ADecimalLimited {
	public:
		struct AReferenceCommon common;
		const unsigned_integer_128 value;
		/* Here's the idea: unsigned 128bit integer has at most 39 total digits,
		 * thus that should fit easily into max 2^7 - 1 decimal digits of them, thus we can safely use
		 * the first bit as the sign */
		/** the number of digits *after* the decimal point; first bit is the sign */
		const unsigned_integer_8 decimal_digits;

		ADecimalLimited(const unsigned_integer_128, const unsigned_integer_8) noexcept;

		static
		AValue
		allocate(const unsigned_integer_128, const unsigned_integer_8, void * /* env */) noexcept;
	};

	/* Stop right there for a moment: ADecimalLimited has the ability to save a number as big as
	 * 340 undecillion (340_282_366_920_938_463_463_374_607_431_768_211_455), which is more than
	 * memory addressable in the full 64bit range (16 EiB), which is A LOT, are you 100% sure
	 * you need more? */
	struct ADecimalUnlimited {
	public:
		struct AReferenceCommon common;
		/* Discussion: each unsigned_integer_8 can hold two base-10 digits without bits interleaving */
		unsigned_integer_8 *const individual_digits;
		const size_t digits_count;
		/** the number of digits *after* the decimal point; first bit is the sign */
		const unsigned_integer_64 decimal_digits; /* we say "unlimited", but 63bit decimal digits is the limit */

		ADecimalUnlimited(unsigned_integer_8 *const, const size_t, const unsigned_integer_64) noexcept;
		~ADecimalUnlimited() noexcept;

		static
		AValue
		allocate(unsigned_integer_8 *const, const size_t, const unsigned_integer_64, void * /* env */) noexcept;
	};

	struct AArray {
	public:
		struct AReferenceCommon common;
		unsigned_integer_64 elements_count;
		AValue *elements;

		static
		AValue
		allocate(const unsigned_integer_64 /* elements_count */, void * /* env */) noexcept;
	};

	/* just do not use this yet */
	struct ANestedPointer {
	public:
		struct AReferenceCommon common;
		union AReferenceValue *pointer;

		static
		AValue
		allocate(union AReferenceValue * /* pointer */, void * /* env */) = delete;
	};

	/* only allocate from an existing strong reference, using downgrade() on AReference */
	struct AWeakPointer {
	public:
		struct AReferenceCommon common;
		std::atomic<AReference *> const pointer;

		AWeakPointer(AReference *);

		AValue
		upgrade(void * /* env */);

		void
		on_release() noexcept;
	};

	struct APsiBearer {
	public:
		struct AReferenceCommon common;
		/* non-const psi_type, because hot code loading may upgrade it to new version */
		PsiElement *psi_element;
		struct ATypedVariableLink *dynamic_ivars;
		unsigned_integer_8 ivars_count;
		AVariable *ivars;

		static
		AValue
		allocate(PsiElement * /* psi_element */, void * /* env */) noexcept;

		APsiBearer(PsiElement * /* psi_element */, unsigned_integer_8 /* ivars_count */);
		~APsiBearer();
	};

	union AReferenceValue {
		struct AReferenceCommon common;
		struct AObject object;
		struct AUnmanagedUnsafe unmanaged_unsafe;
		struct AInteger64 integer_64;
		struct AInteger64Unsigned integer_64_unsigned;
		struct AInteger128 integer_128;
		struct AInteger128Unsigned integer_128_unsigned;
		struct AFloat128 float_128;
		struct AComplex complex;
		struct ARational rational;
		struct ADecimalLimited decimal_limited;
		struct ADecimalUnlimited decimal_unlimited;
		struct AArray array;
		struct ANestedPointer nested_pointer;
		struct AWeakPointer weak_pointer;
		struct APsiBearer psi_bearer;
	};

	typedef struct std::mutex AReferenceLock;

	AReferenceLock &
	lock_for_reference(union AReferenceValue *) noexcept;
}

#endif /* defined(__aml_vm__reference__) */


text:
package org.lambda4j.function.to;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

class ToCharFunctionTest {

    @Test
    void of_givenExpression_returnsFunctionalInterface() {
        ToCharFunction<String> function = ToCharFunction.of(t -> t.charAt(0));
        Assertions.assertNotNull(function);
    }

    @Test
    void of_givenNull_returnsNull() {
        ToCharFunction<String> function = ToCharFunction.of(null);
        Assertions.assertNull(function);
    }
}


text:
package com.github.tomakehurst.wiremock.matching;

import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.github.tomakehurst.wiremock.common.ListOrSingle;
import com.github.tomakehurst.wiremock.common.Pair;
import com.github.tomakehurst.wiremock.common.xml.*;
import com.google.common.collect.ImmutableMap;

import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.SortedSet;
import java.util.stream.Collectors;

import static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.collect.Sets.newTreeSet;

@JsonSerialize(using = XPathPatternJsonSerializer.class)
public class MatchesXPathPattern extends PathPattern {

    private final Map<String, String> xpathNamespaces;

    public MatchesXPathPattern(String xpath) {
        this(xpath, null, null);
    }

    public MatchesXPathPattern(String xpath, StringValuePattern valuePattern) {
        this(xpath, null, valuePattern);
    }

    public MatchesXPathPattern(String xpath, Map<String, String> namespaces) {
        this(xpath, namespaces, null);
    }

    public MatchesXPathPattern(@JsonProperty("matchesXPath") String xpath,
                               @JsonProperty("namespaces") Map<String, String> namespaces,
                               @JsonProperty("valuePattern") StringValuePattern valuePattern) {
        super(xpath, valuePattern);
        xpathNamespaces = namespaces == null || namespaces.isEmpty() ? null : namespaces;
    }

    public MatchesXPathPattern withXPathNamespace(String name, String namespaceUri) {
        Map<String, String> namespaceMap = ImmutableMap.<String, String>builder()
            .putAll(firstNonNull(xpathNamespaces, Collections.<String, String>emptyMap()))
            .put(name, namespaceUri)
            .build();
        return new MatchesXPathPattern(expectedValue, namespaceMap);
    }

    public String getMatchesXPath() {
        return expectedValue;
    }

    @JsonGetter("xPathNamespaces")
    public Map<String, String> getXPathNamespaces() {
        return xpathNamespaces;
    }

    @Override
    protected MatchResult isSimpleMatch(String value) {
        ListOrSingle<XmlNode> nodeList = findXmlNodes(value);
        return MatchResult.of(nodeList != null && nodeList.size() > 0);
    }

    @Override
    protected MatchResult isAdvancedMatch(String value) {
        ListOrSingle<XmlNode> nodeList = findXmlNodes(value);
        if (nodeList == null || nodeList.size() == 0) {
            return MatchResult.noMatch();
        }

        SortedSet<MatchResult> results = newTreeSet();
        for (XmlNode node: nodeList) {
            results.add(valuePattern.match(node.toString()));
        }

        return results.last();
    }

    @Override
    public ListOrSingle<String> getExpressionResult(String value) {
        ListOrSingle<XmlNode> nodeList = findXmlNodes(value);
        if (nodeList == null || nodeList.size() == 0) {
            return ListOrSingle.of();
        }

        return ListOrSingle.of(
                nodeList.stream()
                .map(XmlNode::toString)
                .collect(Collectors.toList())
        );
    }

    private ListOrSingle<XmlNode> findXmlNodes(String value) {
        // For performance reason, don't try to parse non XML value
        if (value == null || !value.trim().startsWith("<")) {
            notifier().info(String.format(
                    "Warning: failed to parse the XML document\nXML: %s", value));
            return null;
        }

        try {
            XmlDocument xmlDocument = Xml.parse(value);
            return xmlDocument.findNodes(expectedValue, xpathNamespaces);
        } catch (XmlException e) {
            notifier().info(String.format(
                    "Warning: failed to parse the XML document. Reason: %s\nXML: %s", e.getMessage(), value));
            return null;
        } catch (XPathException e) {
            notifier().info("Warning: failed to evaluate the XPath expression " + expectedValue);
            return null;
        }
    }
}


text:
<?php

namespace Jirro\Bundle\AdminBundle\Controllers;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\ParameterBag;
use Jirro\Component\Http\Controller\StandardController;
use Jirro\Component\ORM\Tools\Pagination\Paginator;
use Jirro\Bundle\AccountBundle\Domain\User;

class UsersController extends StandardController
{
    public function indexAction(Request $request)
    {
        $page        = $request->query->get('page', 1);
        $maxResults  = 10;
        $firstResult = $maxResults * ($page - 1);

        if ($request->isMethod(Request::METHOD_POST)) {
            switch (strtoupper($request->request->get('formAction'))) {
                case 'FILTER':
                    $request->getSession()->set(__METHOD__, $request->request);
                    break;
                default :
                    $request->getSession()->set(__METHOD__, new ParameterBag());
            }
        }

        $queryBuilder = $this
            ->getObjectManager()
            ->createQueryBuilder()
            ->select('users')
            ->from('Jirro\Bundle\AccountBundle\Domain\User', 'users')
            ->setFirstResult($firstResult)
            ->setMaxResults($maxResults)
        ;

        $filters = $request->getSession()->get(__METHOD__, new ParameterBag());
        if ($filters) {
            if ($filters->get('username') !== null && $filters->get('username') !== '') {
                $queryBuilder
                    ->andWhere('UPPER(users.username) = :username')
                    ->setParameter('username', strtoupper($filters->get('username')))
                ;
            }

            if ($filters->get('email') !== null && $filters->get('email') !== '') {
                $queryBuilder
                    ->andWhere('UPPER(users.email) = :email')
                    ->setParameter('email', strtoupper($filters->get('email')))
                ;
            }

            if ($filters->get('name') !== null && $filters->get('name') !== '') {
                $queryBuilder
                    ->andWhere('(
                        UPPER(users.firstName) = :name
                        OR UPPER(users.middleName) = :name
                        OR UPPER(users.lastName) = :name
                    )')
                    ->setParameter('name', strtoupper($filters->get('name')))
                ;
            }

            if ($filters->get('state') !== null && $filters->get('state') !== '') {
                $queryBuilder
                    ->andWhere('UPPER(users.state) = :state')
                    ->setParameter('state', $filters->get('state'))
                ;
            }
        }

        $paginator = new Paginator($queryBuilder->getQuery(), $page);

        return new Response($this->getView()->render('Admin::users/index', [
            'paginator' => $paginator,
            'filters'   => $filters,
            'states'    => User::getStates(),
        ]));
    }
}


text:
def extractKieshitlWordpressCom(item):
	'''
	Parser for 'kieshitl.wordpress.com'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	tagmap = [
		('I am a Big Villain',       'I am a Big Villain',                      'translated'),
		('PRC',       'PRC',                      'translated'),
		('Loiterous', 'Loiterous',                'oel'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


text:
using namespace naoth;
using namespace std;

double JointData::min[JointData::numOfJoint];
double JointData::max[JointData::numOfJoint];

JointData::JointData()
{
  // init the arrays
  for (int i = 0; i < numOfJoint; i++)
  {
    position[i] = 0.0;
    dp[i] = 0.0;
    ddp[i] = 0.0;
    stiffness[i] = 0.0;
  }
}

void JointData::loadJointLimitsFromConfig()
{
  const Configuration& cfg = Platform::getInstance().theConfiguration;
  for (int i = 0; i < JointData::numOfJoint; i++)
  {
    string jointName = JointData::getJointName((JointData::JointID)i);

    if (cfg.hasKey("joints", jointName + "Max")) {
      double v = cfg.getDouble("joints", jointName + "Max");
      max[i] = (i == LHand || i == RHand)?v:Math::fromDegrees(v);
    } else {
      THROW("JointData: can not get " + jointName + " max angle");
    }

    if (cfg.hasKey("joints", jointName + "Min")) {
      double v = cfg.getDouble("joints", jointName + "Min");
      min[i] = (i == LHand || i == RHand)?v:Math::fromDegrees(v);
    } else {
      THROW("JointData: can not get " + jointName + " min angle");
    }
  }//enf for
}//end init

string JointData::getJointName(JointID joint)
{
  switch (joint)
  {
    case HeadPitch: return string("HeadPitch");
    case HeadYaw: return string("HeadYaw");
    case RShoulderRoll: return string("RShoulderRoll");
    case LShoulderRoll: return string("LShoulderRoll");
    case RShoulderPitch: return string("RShoulderPitch");
    case LShoulderPitch: return string("LShoulderPitch");
    case RElbowRoll: return string("RElbowRoll");
    case LElbowRoll: return string("LElbowRoll");
    case RElbowYaw: return string("RElbowYaw");
    case LElbowYaw: return string("LElbowYaw");

    case LWristYaw: return string("LWristYaw");
    case RWristYaw: return string("RWristYaw");
    case LHand: return string("LHand");
    case RHand: return string("RHand");

    case LHipYawPitch: return string("LHipYawPitch");
    case RHipYawPitch: return string("RHipYawPitch");
    case RHipPitch: return string("RHipPitch");
    case LHipPitch: return string("LHipPitch");
    case RHipRoll: return string("RHipRoll");
    case LHipRoll: return string("LHipRoll");
    case RKneePitch: return string("RKneePitch");
    case LKneePitch: return string("LKneePitch");
    case RAnklePitch: return string("RAnklePitch");
    case LAnklePitch: return string("LAnklePitch");
    case RAnkleRoll: return string("RAnkleRoll");
    case LAnkleRoll: return string("LAnkleRoll");
    default: return string("Unknown Joint");
  }//end switch
}//end getJointName

double JointData::mirrorData(JointID joint) const
{
  switch (joint)
  {
      // Head (don't mirror)
    case HeadYaw: return -position[HeadYaw];
    case HeadPitch: return position[HeadPitch];

      // Arms
    case RShoulderPitch: return position[LShoulderPitch];
    case RShoulderRoll: return -position[LShoulderRoll];
    case RElbowYaw: return -position[LElbowYaw];
    case RElbowRoll: return -position[LElbowRoll];

    case LShoulderPitch: return position[RShoulderPitch];
    case LShoulderRoll: return -position[RShoulderRoll];
    case LElbowYaw: return -position[RElbowYaw];
    case LElbowRoll: return -position[RElbowRoll];

      // Legs
    case RHipYawPitch: return position[LHipYawPitch];
    case RHipPitch: return position[LHipPitch];
    case RHipRoll: return -position[LHipRoll];
    case RKneePitch: return position[LKneePitch];
    case RAnklePitch: return position[LAnklePitch];
    case RAnkleRoll: return -position[LAnkleRoll];

    case LHipYawPitch: return position[RHipYawPitch];
    case LHipPitch: return position[RHipPitch];
    case LHipRoll: return -position[RHipRoll];
    case LKneePitch: return position[RKneePitch];
    case LAnklePitch: return position[RAnklePitch];
    case LAnkleRoll: return -position[RAnkleRoll];
    default: return position[joint];
  }
}//end mirrorData

JointData::JointID JointData::jointIDFromName(std::string name)
{
  for (int i = 0; i < numOfJoint; i++) {
    if (name == getJointName((JointID) i)) return (JointID) i;
  }

  return numOfJoint;
}//end getJointName

void JointData::mirrorFrom(const JointData& jointData)
{
  for (int i = 0; i < numOfJoint; i++) {
    position[i] = jointData.mirrorData((JointID) i);
  }
}//end mirror

void JointData::mirror()
{
  JointData tmp = *this;
  mirrorFrom(tmp);
}

void JointData::clamp(JointID id)
{
  position[id] = Math::clamp(position[id], min[id], max[id]);
}

void JointData::clamp()
{
  for( int i=0; i<numOfJoint; i++) {
    clamp((JointID)i);
  }
}

bool JointData::isInRange(JointData::JointID id, double ang) const
{
    return ang <= max[id] && ang >= min[id];
}

bool JointData::isInRange(JointData::JointID id) const
{
    return isInRange(id, position[id]);
}

void JointData::updateSpeed(const JointData& lastData, double dt)
{
  const double* lastPose = lastData.position;
  double idt = 1 / dt;
  for ( int i=0; i<JointData::numOfJoint; i++)
  {
    dp[i] = (position[i] - lastPose[i]) * idt;
  }
}

void JointData::updateAcceleration(const JointData& lastData, double dt)
{
  const double* lastSpeed = lastData.dp;
  double idt = 1 / dt;
  for (int i = 0; i < JointData::numOfJoint; i++)
  {
    ddp[i] = (dp[i] - lastSpeed[i]) * idt;
  }
}

bool JointData::isLegStiffnessOn() const
{
  for ( int i = JointData::RHipYawPitch; i <= JointData::LAnkleRoll; i++)
  {
    if ( stiffness[i] < 0 ) {
      return false;
    }
  }
  return true;
}

int JointData::checkStiffness() const
{
  for(int i=0; i<JointData::numOfJoint; i++)
  {
    double v = stiffness[i];
    if ( v > 1 || v < -1 )
    {
      return i;
      //THROW("Get ILLEGAL Stiffness: "<<getJointName(JointData::JointID(i))<<" = "<<v);
    }
  }
  return -1;
}

SensorJointData::SensorJointData()
  : timestamp(0)
{
  for (int i = 0; i < numOfJoint; i++)
  {
    electricCurrent[i] = 0.0;
    temperature[i] = 0.0;
  }
}

void SensorJointData::print(ostream& stream) const
{
  stream << "Timestamp: " << timestamp << endl;
  stream << "Joint [pos(deg), stiffness, temperature,current]" << endl;
  stream << "------------------------" << endl;
  for (int i = 0; i < numOfJoint; i++)
  {
    stream.precision(4);
    stream << getJointName((JointData::JointID) i) << "\t[" << fixed << Math::toDegrees(position[i]) << ", " << stiffness[i] << ", ";
    stream.precision(0);
    stream << temperature[i] << ", ";
    stream.precision(3);
    stream << electricCurrent[i] << "]" <<  endl;
  }
}//end print

SensorJointData::~SensorJointData()
{
}

MotorJointData::MotorJointData()
{
}

MotorJointData::~MotorJointData()
{
}

void MotorJointData::print(ostream& stream) const
{
  stream << "Joint [pos, stiffness]" << endl;
  stream << "------------------------" << endl;
  for (int i = 0; i < numOfJoint; i++) {
    stream << getJointName((JointData::JointID) i) << "[" << position[i] << ", " << stiffness[i] << "]" << endl;
  }
}//end print

OffsetJointData::OffsetJointData()
{
}

OffsetJointData::~OffsetJointData()
{
}

void OffsetJointData::print(ostream& stream) const
{
  stream << "Joint [offset]" << endl;
  stream << "------------------------" << endl;
  for (int i = 0; i < numOfJoint; i++) {
    stream << getJointName((JointData::JointID) i) << "[" << position[i] << "]" << endl;
  }
}//end print

void Serializer<SensorJointData>::serialize(const SensorJointData& representation, std::ostream& stream)
{
  naothmessages::SensorJointData message;

  for(int i=0; i < JointData::numOfJoint; i++)
  {
    message.add_electriccurrent(representation.electricCurrent[i]);
    message.add_temperature(representation.temperature[i]);

    message.mutable_jointdata()->add_position(representation.position[i]);
    message.mutable_jointdata()->add_stiffness(representation.stiffness[i]);
    message.mutable_jointdata()->add_dp(representation.dp[i]);
    message.mutable_jointdata()->add_ddp(representation.ddp[i]);
  }

  google::protobuf::io::OstreamOutputStream buf(&stream);
  message.SerializeToZeroCopyStream(&buf);
}

void Serializer<SensorJointData>::deserialize(std::istream& stream, SensorJointData& representation)
{
  naothmessages::SensorJointData message;
  google::protobuf::io::IstreamInputStream buf(&stream);
  message.ParseFromZeroCopyStream(&buf);

  // assure the integrity of the message
  ASSERT( message.electriccurrent().size() == JointData::numOfJoint ||
          message.electriccurrent().size() == JointData::numOfJoint - 4);
  ASSERT( message.temperature().size() == JointData::numOfJoint ||
          message.temperature().size() == JointData::numOfJoint - 4);
  ASSERT( message.jointdata().position().size() == JointData::numOfJoint ||
          message.jointdata().position().size() == JointData::numOfJoint - 4);
  ASSERT( message.jointdata().stiffness().size() == JointData::numOfJoint ||
          message.jointdata().stiffness().size() == JointData::numOfJoint - 4);
  ASSERT( message.jointdata().dp().size() == JointData::numOfJoint ||
          message.jointdata().dp().size() == JointData::numOfJoint - 4);
  ASSERT( message.jointdata().ddp().size() == JointData::numOfJoint ||
          message.jointdata().ddp().size() == JointData::numOfJoint - 4);

  for (int i = 0; i < JointData::numOfJoint; i++)
  {
    if(i < message.jointdata().position().size())
    {
      representation.electricCurrent[i] = message.electriccurrent(i);
      representation.temperature[i] = message.temperature(i);
      // joint data
      representation.position[i] = message.jointdata().position(i);
      representation.stiffness[i] = message.jointdata().stiffness(i);
      representation.dp[i] = message.jointdata().dp(i);
      representation.ddp[i] = message.jointdata().ddp(i);
    }
    else // LWristYaw, RWristYaw, LHand, RHand don't exist in old messages
    {
      representation.electricCurrent[i] = 0;
      representation.temperature[i] = 0;
      // joint data
      representation.position[i] = 0;
      representation.stiffness[i] = 0;
      representation.dp[i] = 0;
      representation.ddp[i] = 0;
    }
  }
}

void Serializer<MotorJointData>::serialize(const MotorJointData& representation, std::ostream& stream)
{
  naothmessages::JointData message;

  for(int i=0; i < JointData::numOfJoint; i++)
  {
    message.add_position(representation.position[i]);
    message.add_stiffness(representation.stiffness[i]);
    message.add_dp(representation.dp[i]);
    message.add_ddp(representation.ddp[i]);
  }

  google::protobuf::io::OstreamOutputStream buf(&stream);
  message.SerializeToZeroCopyStream(&buf);
}

void Serializer<MotorJointData>::deserialize(std::istream& stream, MotorJointData& representation)
{
  naothmessages::JointData message;
  google::protobuf::io::IstreamInputStream buf(&stream);
  message.ParseFromZeroCopyStream(&buf);

  // assure the integrity of the message
  ASSERT(message.position().size() == JointData::numOfJoint);
  ASSERT(message.stiffness().size() == JointData::numOfJoint);
  ASSERT(message.dp().size() == JointData::numOfJoint);
  ASSERT(message.ddp().size() == JointData::numOfJoint);

  for(int i=0; i < JointData::numOfJoint; i++)
  {
    representation.position[i] = message.position(i);
    representation.stiffness[i] = message.stiffness(i);
    representation.dp[i] = message.dp(i);
    representation.ddp[i] = message.ddp(i);
  }
}

void Serializer<OffsetJointData>::serialize(const OffsetJointData& representation, std::ostream& stream)
{
  naothmessages::JointData message;

  for(int i=0; i < JointData::numOfJoint; i++)
  {
    message.add_position(representation.position[i]);
    message.add_stiffness(representation.stiffness[i]);
    message.add_dp(representation.dp[i]);
    message.add_ddp(representation.ddp[i]);
  }

  google::protobuf::io::OstreamOutputStream buf(&stream);
  message.SerializeToZeroCopyStream(&buf);
}

void Serializer<OffsetJointData>::deserialize(std::istream& stream, OffsetJointData& representation)
{
  naothmessages::JointData message;
  google::protobuf::io::IstreamInputStream buf(&stream);
  message.ParseFromZeroCopyStream(&buf);

  // assure the integrity of the message
  ASSERT(message.position().size() == JointData::numOfJoint);
  ASSERT(message.stiffness().size() == JointData::numOfJoint);
  ASSERT(message.dp().size() == JointData::numOfJoint);
  ASSERT(message.ddp().size() == JointData::numOfJoint);

  for(int i=0; i < JointData::numOfJoint; i++)
  {
    representation.position[i] = message.position(i);
    representation.stiffness[i] = message.stiffness(i);
    representation.dp[i] = message.dp(i);
    representation.ddp[i] = message.ddp(i);
  }
}


text:
using System;
using System.Data;
using System.Data.Common;

namespace LinqToDB.DataProvider.Firebird
{
	using Common;
	using Expressions;
	using Mapping;
	using SqlQuery;

	public class FirebirdProviderAdapter : IDynamicProviderAdapter
	{
		public const string AssemblyName    = "FirebirdSql.Data.FirebirdClient";
		public const string ClientNamespace = "FirebirdSql.Data.FirebirdClient";
		public const string TypesNamespace  = "FirebirdSql.Data.Types";

		FirebirdProviderAdapter()
		{
			var assembly = Tools.TryLoadAssembly(AssemblyName, null);

			if (assembly == null)
				throw new InvalidOperationException($"Cannot load assembly {AssemblyName}");

			ConnectionType      = assembly.GetType($"{ClientNamespace}.FbConnection" , true)!;
			DataReaderType      = assembly.GetType($"{ClientNamespace}.FbDataReader" , true)!;
			ParameterType       = assembly.GetType($"{ClientNamespace}.FbParameter"  , true)!;
			CommandType         = assembly.GetType($"{ClientNamespace}.FbCommand"    , true)!;
			TransactionType     = assembly.GetType($"{ClientNamespace}.FbTransaction", true)!;

			var dbType          = assembly.GetType($"{ClientNamespace}.FbDbType"     , true)!;

			FbDecFloatType      = assembly.GetType($"{TypesNamespace}.FbDecFloat"       , false);
			FbZonedDateTimeType = assembly.GetType($"{TypesNamespace}.FbZonedDateTime"  , false);
			FbZonedTimeType     = assembly.GetType($"{TypesNamespace}.FbZonedTime"      , false);

			var decimalTypeType = assembly.GetType("FirebirdSql.Data.Common.DecimalType", false)!;

			var typeMapper = new TypeMapper();

			typeMapper.RegisterTypeWrapper<FbConnection>(ConnectionType);
			typeMapper.RegisterTypeWrapper<FbParameter>(ParameterType);
			typeMapper.RegisterTypeWrapper<FbDbType>(dbType);

			MappingSchema = new FirebirdAdapterMappingSchema();

			// we don't provide default mappings to non-provider types
			// as it looks like there is no suitable .net types
			// such mappings could be added by user manually
			if (FbDecFloatType != null)
			{
				typeMapper.RegisterTypeWrapper<FbDecFloat>(FbDecFloatType);
				MappingSchema.SetDataType(FbDecFloatType, new SqlDataType(DataType.DecFloat, FbDecFloatType));
				// we don't register literal generation for decfloat as it looks like special values (inf, (s)nan are not supported in literals)
			}

			if (FbZonedDateTimeType != null)
			{
				typeMapper.RegisterTypeWrapper<FbZonedDateTime>(FbZonedDateTimeType);
				MappingSchema.SetDataType(FbZonedDateTimeType, new SqlDataType(DataType.DateTimeOffset, FbZonedDateTimeType));
			}

			if (FbZonedTimeType != null)
			{
				typeMapper.RegisterTypeWrapper<FbZonedTime>(FbZonedTimeType);
				MappingSchema.SetDataType(FbZonedTimeType, new SqlDataType(DataType.TimeTZ, FbZonedTimeType));
			}

			typeMapper.FinalizeMappings();

			var dbTypeBuilder = typeMapper.Type<FbParameter>().Member(p => p.FbDbType);

			SetDbType = dbTypeBuilder.BuildSetter<IDbDataParameter>();
			GetDbType = dbTypeBuilder.BuildGetter<IDbDataParameter>();

			ClearAllPools = typeMapper.BuildAction(typeMapper.MapActionLambda(() => FbConnection.ClearAllPools()));

			IsDateOnlySupported = assembly.GetName().Version >= MinDateOnlyVersion;
		}

		static readonly Lazy<FirebirdProviderAdapter> _lazy    = new (() => new ());
		internal static FirebirdProviderAdapter       Instance => _lazy.Value;

		sealed class FirebirdAdapterMappingSchema : LockedMappingSchema
		{
			public FirebirdAdapterMappingSchema() : base("FirebirdAdapter")
			{
			}
		}

		public Type ConnectionType  { get; }
		public Type DataReaderType  { get; }
		public Type ParameterType   { get; }
		public Type CommandType     { get; }
		public Type TransactionType { get; }

		/// <summary>
		/// FB client 7.10.0+.
		/// </summary>
		public Type? FbDecFloatType      { get; }
		public Type? FbZonedDateTimeType { get; }
		public Type? FbZonedTimeType     { get; }

		public string? ProviderTypesNamespace => FbDecFloatType != null || FbZonedDateTimeType != null || FbZonedTimeType != null ? TypesNamespace : null;

		public MappingSchema MappingSchema { get; }

		public Action<DbParameter, FbDbType> SetDbType { get; }
		public Func<DbParameter  , FbDbType> GetDbType { get; }

		public Action ClearAllPools { get; }

		public bool IsDateOnlySupported { get; }

		private static readonly Version MinDateOnlyVersion = new (9, 0, 0);

		#region Wrappers

		[Wrapper]
		private class FbDecFloat
		{
		}

		[Wrapper]
		private class FbZonedDateTime
		{
		}

		[Wrapper]
		private class FbZonedTime
		{
		}

		[Wrapper]
		private class FbConnection
		{
			public static void ClearAllPools() => throw new NotImplementedException();
		}

		[Wrapper]
		private class FbParameter
		{
			public FbDbType FbDbType { get; set; }
		}

		[Wrapper]
		public enum FbDbType
		{
			Array     = 0,
			BigInt    = 1,
			Binary    = 2,
			Boolean   = 3,
			Char      = 4,
			Date      = 5,
			Decimal   = 6,
			Double    = 7,
			Float     = 8,
			Guid      = 9,
			Integer   = 10,
			Numeric   = 11,
			SmallInt  = 12,
			Text      = 13,
			Time      = 14,
			TimeStamp = 15,
			VarChar       = 16,

			// new in 7.10.0
			TimeStampTZ   = 17,
			TimeStampTZEx = 18,
			TimeTZ        = 19,
			TimeTZEx      = 20,
			Dec16         = 21,
			Dec34         = 22,
			Int128        = 23,
		}

		#endregion
	}
}


text:
/**
 * Created by ane on 5/18/15.
 */
var app = angular.module('app', []);
app.controller('FirstController', function($rootScope) {
    $rootScope.name = "hello";
});


text:
// Overview of electron-dotnet.js: https://github.com/xamarin/WebSharp/tree/master/electron-dotnet

var dotnet = require('electron-dotnet');

var hellofunction = dotnet.func(function () {/*
	async (input) =>
	{
		return ".NET welcomes " + input.ToString();
	}
*/});

function hello_function()
{
	hellofunction('Electron', function (error, result) {
		if (error) throw error;
		console.log(result);
	});
}


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8">

	<title>Bespin Release Notes</title>

	<link rel="stylesheet" type="text/css" href="../css/reset.css">
	<link rel="stylesheet" type="text/css" href="../css/stylesheet.css" media="screen,projection">
	<link rel="stylesheet" type="text/css" href="../css/colorful.css">

Home

Using Bespin

Creating Plugins

Embedding

Developing Bespin

Bespin Release Notes

0.9a1

0.8

0.7.3

0.7.2

0.7.1

0.7

0.6.3

0.6.2

0.6.1

0.6

0.5.1

0.5

Useful Links

Bespin project home page

Wiki

Developer Resources

Main Code Repository

Python server repository

bespin-core mailing list for developers

bespin-commits mailing list for repository commit messages

Bug List

Get Help

The Bespin mailing list

Via IRC: #bespin on irc.mozilla.org

Documentation Template

Adapted from a design by Matěj Grabovský


text:
package com.bladecoder.engine.actions;

import java.util.HashMap;

import com.badlogic.gdx.math.Vector2;
import com.bladecoder.engine.actions.Param.Type;
import com.bladecoder.engine.assets.EngineAssetManager;
import com.bladecoder.engine.model.BaseActor;
import com.bladecoder.engine.model.Scene;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.fasterxml.jackson.annotation.JsonTypeName;

@JsonTypeName("Position")
@ModelDescription("Changes the actor position")
public class PositionAction extends AbstractAction {
	@JsonProperty(value = "actor", required = true)
	@JsonPropertyDescription("The target actor")
	@ModelPropertyType(Type.SCENE_ACTOR)
	private SceneActorRef sceneActorRef;

	@JsonProperty(required = true)
	@JsonPropertyDescription("The actor position")
	@ModelPropertyType(Type.VECTOR2)
	private Vector2 position;

	@Override
	public void setParams(HashMap<String, String> params) {
		String[] a = Param.parseString2(params.get("actor"));

		sceneActorRef = a == null ? new SceneActorRef() : new SceneActorRef(a[0], a[1]);

		position = Param.parseVector2(params.get("position"));
	}

	@Override
	public boolean run(ActionCallback cb) {
		Scene s = sceneActorRef.getScene();

		BaseActor actor = s.getActor(sceneActorRef.getActorId(), true);

		float scale = EngineAssetManager.getInstance().getScale();

		actor.setPosition(position.x * scale, position.y * scale);

		return false;
	}

}


text:
Borderlands2-Golden-Keys
========================

Web site listing Borderlands 2 Golden Keys - ASP.NET MVC 5 / RavenDB pet project

http://borderlands2goldenkeys.laedit.net


text:
import fnmatch
import logging
import os
import re
import subprocess
import tempfile
from difflib import SequenceMatcher

try:
    import pygments
    from pygments.lexers import get_lexer_for_filename
    # from pygments.lexers import guess_lexer_for_filename
    from pygments.formatters import HtmlFormatter
except ImportError:
    pass

from django.utils.html import escape
from django.utils.http import urlquote
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _

from djblets.log import log_timed
from djblets.siteconfig.models import SiteConfiguration
from djblets.util.misc import cache_memoize

from reviewboard.accounts.models import Profile
from reviewboard.admin.checks import get_can_enable_syntax_highlighting
from reviewboard.diffviewer.myersdiff import MyersDiffer
from reviewboard.diffviewer.smdiff import SMDiffer
from reviewboard.scmtools.core import PRE_CREATION, HEAD

DEFAULT_DIFF_COMPAT_VERSION = 1

class UserVisibleError(Exception):
    pass

class DiffCompatError(Exception):
    pass

def Differ(a, b, ignore_space=False,
           compat_version=DEFAULT_DIFF_COMPAT_VERSION):
    """
    Factory wrapper for returning a differ class based on the compat version
    and flags specified.
    """
    if compat_version == 0:
        return SMDiffer(a, b)
    elif compat_version == 1:
        return MyersDiffer(a, b, ignore_space)
    else:
        raise DiffCompatError(
            "Invalid diff compatibility version (%s) passed to Differ" %
                (compat_version))

def convert_line_endings(data):
    # Files without a trailing newline come out of Perforce (and possibly
    # other systems) with a trailing \r. Diff will see the \r and
    # add a "\ No newline at end of file" marker at the end of the file's
    # contents, which patch understands and will happily apply this to
    # a file with a trailing \r.
    #
    # The problem is that we normalize \r's to \n's, which breaks patch.
    # Our solution to this is to just remove that last \r and not turn
    # it into a \n.
    #
    # See http://code.google.com/p/reviewboard/issues/detail?id=386
    # and http://reviews.reviewboard.org/r/286/
    if data == "":
        return ""

    if data[-1] == "\r":
        data = data[:-1]

    temp = data.replace('\r\r\n', '\n')
    temp = data.replace('\r\n', '\n')
    temp = temp.replace('\r', '\n')
    return temp

def patch(diff, file, filename):
    """Apply a diff to a file.  Delegates out to `patch` because noone
       except Larry Wall knows how to patch."""

    log_timer = log_timed("Patching file %s" % filename)

    if diff.strip() == "":
        # Someone uploaded an unchanged file. Return the one we're patching.
        return file

    # Prepare the temporary directory if none is available
    tempdir = tempfile.mkdtemp(prefix='reviewboard.')

    (fd, oldfile) = tempfile.mkstemp(dir=tempdir)
    f = os.fdopen(fd, "w+b")
    f.write(convert_line_endings(file))
    f.close()

    diff = convert_line_endings(diff)

    # XXX: catch exception if Popen fails?
    newfile = '%s-new' % oldfile
    p = subprocess.Popen(['patch', '-o', newfile, oldfile],
                         stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
    p.stdin.write(diff)
    p.stdin.close()
    patch_output = p.stdout.read()
    failure = p.wait()

    if failure:
        f = open("%s.diff" %
                 (os.path.join(tempdir, os.path.basename(filename))), "w")
        f.write(diff)
        f.close()

        log_timer.done()

        # FIXME: This doesn't provide any useful error report on why the patch
        # failed to apply, which makes it hard to debug.  We might also want to
        # have it clean up if DEBUG=False
        raise Exception(_("The patch to '%s' didn't apply cleanly. The temporary " +
                          "files have been left in '%s' for debugging purposes.\n" +
                          "`patch` returned: %s") %
                        (filename, tempdir, patch_output))

    f = open(newfile, "r")
    data = f.read()
    f.close()

    os.unlink(oldfile)
    os.unlink(newfile)
    os.rmdir(tempdir)

    log_timer.done()

    return data

def get_line_changed_regions(oldline, newline):
    if oldline is None or newline is None:
        return (None, None)

    # Use the SequenceMatcher directly. It seems to give us better results
    # for this. We should investigate steps to move to the new differ.
    differ = SequenceMatcher(None, oldline, newline)

    # This thresholds our results -- we don't want to show inter-line diffs if
    # most of the line has changed, unless those lines are very short.

    # FIXME: just a plain, linear threshold is pretty crummy here.  Short
    # changes in a short line get lost.  I haven't yet thought of a fancy
    # nonlinear test.
    if differ.ratio() < 0.6:
        return (None, None)

    oldchanges = []
    newchanges = []
    back = (0, 0)

    for tag, i1, i2, j1, j2 in differ.get_opcodes():
        if tag == "equal":
            if (i2 - i1 < 3) or (j2 - j1 < 3):
                back = (j2 - j1, i2 - i1)
            continue

        oldstart, oldend = i1 - back[0], i2
        newstart, newend = j1 - back[1], j2

        if oldchanges != [] and oldstart <= oldchanges[-1][1] < oldend:
            oldchanges[-1] = (oldchanges[-1][0], oldend)
        elif not oldline[oldstart:oldend].isspace():
            oldchanges.append((oldstart, oldend))

        if newchanges != [] and newstart <= newchanges[-1][1] < newend:
            newchanges[-1] = (newchanges[-1][0], newend)
        elif not newline[newstart:newend].isspace():
            newchanges.append((newstart, newend))

        back = (0, 0)

    return (oldchanges, newchanges)

def convert_to_utf8(s, enc):
    """
    Returns the passed string as a unicode string. If conversion to UTF-8
    fails, we try the user-specified encoding, which defaults to ISO 8859-15.
    This can be overridden by users inside the repository configuration, which
    gives users repository-level control over file encodings (file-level control
    is really, really hard).
    """
    if isinstance(s, unicode):
        return s
    elif isinstance(s, basestring):
        try:
            u = unicode(s, 'utf-8')
            return u
        except UnicodeError:
            for e in enc.split(','):
                try:
                    u = unicode(s, e)
                    return u.encode('utf-8')
                except UnicodeError:
                    pass
            raise Exception(_("Diff content couldn't be converted to UTF-8 "
                              "using the following encodings: %s") % enc)
    else:
        raise TypeError("Value to convert is unexpected type %s", type(s))

def get_original_file(filediff):
    """
    Get a file either from the cache or the SCM, applying the parent diff if
    it exists.

    SCM exceptions are passed back to the caller.
    """
    data = ""

    if filediff.source_revision != PRE_CREATION:
        def fetch_file(file, revision):
            log_timer = log_timed("Fetching file '%s' r%s from %s" %
                                  (file, revision, repository))
            data = tool.get_file(file, revision)
            data = convert_line_endings(data)
            log_timer.done()
            return data

        repository = filediff.diffset.repository
        tool = repository.get_scmtool()
        file = filediff.source_file
        revision = filediff.source_revision

        key = "%s:%s:%s" % (filediff.diffset.repository.path, urlquote(file),
                            revision)

        # We wrap the result of get_file in a list and then return the first
        # element after getting the result from the cache. This prevents the
        # cache backend from converting to unicode, since we're no longer
        # passing in a string and the cache backend doesn't recursively look
        # through the list in order to convert the elements inside.
        #
        # Basically, this fixes the massive regressions introduced by the
        # Django unicode changes.
        data = cache_memoize(key, lambda: [fetch_file(file, revision)],
                             large_data=True)[0]

    # If there's a parent diff set, apply it to the buffer.
    if filediff.parent_diff:
        data = patch(filediff.parent_diff, data, filediff.source_file)

    return data

def get_patched_file(buffer, filediff):
    return patch(filediff.diff, buffer, filediff.dest_file)

def get_chunks(diffset, filediff, interfilediff, force_interdiff,
               enable_syntax_highlighting):
    def diff_line(vlinenum, oldlinenum, newlinenum, oldline, newline,
                  oldmarkup, newmarkup):
        if oldline and newline and oldline != newline:
            oldregion, newregion = get_line_changed_regions(oldline, newline)
        else:
            oldregion = newregion = []

        return [vlinenum,
                oldlinenum or '', mark_safe(oldmarkup or ''), oldregion,
                newlinenum or '', mark_safe(newmarkup or ''), newregion]

    def new_chunk(lines, numlines, tag, collapsable=False):
        return {
            'lines': lines,
            'numlines': numlines,
            'change': tag,
            'collapsable': collapsable,
        }

    def add_ranged_chunks(lines, start, end, collapsable=False):
        numlines = end - start
        chunks.append(new_chunk(lines[start:end], end - start, 'equal',
                      collapsable))

    def apply_pygments(data, filename):
        # XXX Guessing is preferable but really slow, especially on XML
        #     files.
        #if filename.endswith(".xml"):
        lexer = get_lexer_for_filename(filename, stripnl=False)
        #else:
        #    lexer = guess_lexer_for_filename(filename, data, stripnl=False)

        try:
            # This is only available in 0.7 and higher
            lexer.add_filter('codetagify')
        except AttributeError:
            pass

        return pygments.highlight(data, lexer, HtmlFormatter()).splitlines()

    # There are three ways this function is called:
    #
    #     1) filediff, no interfilediff
    #        - Returns chunks for a single filediff. This is the usual way
    #          people look at diffs in the diff viewer.
    #
    #          In this mode, we get the original file based on the filediff
    #          and then patch it to get the resulting file.
    #
    #          This is also used for interdiffs where the source revision
    #          has no equivalent modified file but the interdiff revision
    #          does. It's no different than a standard diff.
    #
    #     2) filediff, interfilediff
    #        - Returns chunks showing the changes between a source filediff
    #          and the interdiff.
    #
    #          This is the typical mode used when showing the changes
    #          between two diffs. It requires that the file is included in
    #          both revisions of a diffset.
    #
    #     3) filediff, no interfilediff, force_interdiff
    #        - Returns chunks showing the changes between a source
    #          diff and an unmodified version of the diff.
    #
    #          This is used when the source revision in the diffset contains
    #          modifications to a file which have then been reverted in the
    #          interdiff revision. We don't actually have an interfilediff
    #          in this case, so we have to indicate that we are indeed in
    #          interdiff mode so that we can special-case this and not
    #          grab a patched file for the interdiff version.

    assert filediff

    file = filediff.source_file
    revision = filediff.source_revision

    old = get_original_file(filediff)
    new = get_patched_file(old, filediff)

    if interfilediff:
        old = new
        interdiff_orig = get_original_file(interfilediff)
        new = get_patched_file(interdiff_orig, interfilediff)
    elif force_interdiff:
        # Basically, revert the change.
        temp = old
        old = new
        new = temp

    encoding = diffset.repository.encoding or 'iso-8859-15'
    old = convert_to_utf8(old, encoding)
    new = convert_to_utf8(new, encoding)

    # Normalize the input so that if there isn't a trailing newline, we add
    # it.
    if old and old[-1] != '\n':
        old += '\n'

    if new and new[-1] != '\n':
        new += '\n'

    a = re.split(r"\r?\n", old or '')
    b = re.split(r"\r?\n", new or '')

    # Remove the trailing newline, now that we've split this. This will
    # prevent a duplicate line number at the end of the diff.
    del(a[-1])
    del(b[-1])

    a_num_lines = len(a)
    b_num_lines = len(b)

    markup_a = markup_b = None

    siteconfig = SiteConfiguration.objects.get_current()

    threshold = siteconfig.get('diffviewer_syntax_highlighting_threshold')

    if threshold and (a_num_lines > threshold or b_num_lines > threshold):
        enable_syntax_highlighting = False

    if enable_syntax_highlighting:
        try:
            # TODO: Try to figure out the right lexer for these files
            #       once instead of twice.
            markup_a = apply_pygments(old or '', filediff.source_file)
            markup_b = apply_pygments(new or '', filediff.dest_file)
        except ValueError:
            pass

    if not markup_a:
        markup_a = re.split(r"\r?\n", escape(old))

    if not markup_b:
        markup_b = re.split(r"\r?\n", escape(new))

    chunks = []
    linenum = 1

    ignore_space = True
    for pattern in siteconfig.get("diffviewer_include_space_patterns"):
        if fnmatch.fnmatch(file, pattern):
            ignore_space = False
            break

    differ = Differ(a, b, ignore_space=ignore_space,
                    compat_version=diffset.diffcompat)

    # TODO: Make this back into a preference if people really want it.
    context_num_lines = siteconfig.get("diffviewer_context_num_lines")
    collapse_threshold = 2 * context_num_lines + 3

    if interfilediff:
        logging.debug("Generating diff chunks for interdiff ids %s-%s",
                      filediff.id, interfilediff.id)
    else:
        logging.debug("Generating diff chunks for filediff id %s", filediff.id)

    for tag, i1, i2, j1, j2 in differ.get_opcodes():
        oldlines = markup_a[i1:i2]
        newlines = markup_b[j1:j2]
        numlines = max(len(oldlines), len(newlines))

        lines = map(diff_line,
                    xrange(linenum, linenum + numlines),
                    xrange(i1 + 1, i2 + 1), xrange(j1 + 1, j2 + 1),
                    a[i1:i2], b[j1:j2], oldlines, newlines)
        linenum += numlines

        if tag == 'equal' and numlines > collapse_threshold:
            last_range_start = numlines - context_num_lines

            if len(chunks) == 0:
                add_ranged_chunks(lines, 0, last_range_start, True)
                add_ranged_chunks(lines, last_range_start, numlines)
            else:
                add_ranged_chunks(lines, 0, context_num_lines)

                if i2 == a_num_lines and j2 == b_num_lines:
                    add_ranged_chunks(lines, context_num_lines, numlines, True)
                else:
                    add_ranged_chunks(lines, context_num_lines,
                                      last_range_start, True)
                    add_ranged_chunks(lines, last_range_start, numlines)
        else:
            chunks.append(new_chunk(lines, numlines, tag))

    if interfilediff:
        logging.debug("Done generating diff chunks for interdiff ids %s-%s",
                      filediff.id, interfilediff.id)
    else:
        logging.debug("Done generating diff chunks for filediff id %s",
                      filediff.id)

    return chunks

def get_revision_str(revision):
    if revision == HEAD:
        return "HEAD"
    elif revision == PRE_CREATION:
        return ""
    else:
        return "Revision %s" % revision

def get_diff_files(diffset, filediff=None, interdiffset=None,
                   enable_syntax_highlighting=True,
                   load_chunks=True):
    if filediff:
        filediffs = [filediff]

        if interdiffset:
            log_timer = log_timed("Generating diff file info for "
                                  "interdiffset ids %s-%s, filediff %s" %
                                  (diffset.id, interdiffset.id, filediff.id))
        else:
            log_timer = log_timed("Generating diff file info for "
                                  "diffset id %s, filediff %s" %
                                  (diffset.id, filediff.id))
    else:
        filediffs = diffset.files.all()

        if interdiffset:
            log_timer = log_timed("Generating diff file info for "
                                  "interdiffset ids %s-%s" %
                                  (diffset.id, interdiffset.id))
        else:
            log_timer = log_timed("Generating diff file info for "
                                  "diffset id %s" % diffset.id)

    # A map used to quickly look up the equivalent interfilediff given a
    # source file.
    interdiff_map = {}
    if interdiffset:
        for interfilediff in interdiffset.files.all():
            if not filediff or \
               filediff.source_file == interfilediff.source_file:
                interdiff_map[interfilediff.source_file] = interfilediff

    key_prefix = "diff-sidebyside-"

    if enable_syntax_highlighting:
        key_prefix += "hl-"

    # In order to support interdiffs properly, we need to display diffs
    # on every file in the union of both diffsets. Iterating over one diffset
    # or the other doesn't suffice.
    #
    # We build a list of parts containing the source filediff, the interdiff
    # filediff (if specified), and whether to force showing an interdiff
    # (in the case where a file existed in the source filediff but was
    # reverted in the interdiff).
    filediff_parts = []

    for filediff in filediffs:
        interfilediff = None

        if filediff.source_file in interdiff_map:
            interfilediff = interdiff_map[filediff.source_file]
            del(interdiff_map[filediff.source_file])

        filediff_parts.append((filediff, interfilediff, interdiffset != None))

    if interdiffset:
        # We've removed everything in the map that we've already found.
        # What's left are interdiff files that are new. They have no file
        # to diff against.
        #
        # The end result is going to be a view that's the same as when you're
        # viewing a standard diff. As such, we can pretend the interdiff is
        # the source filediff and not specify an interdiff. Keeps things
        # simple, code-wise, since we really have no need to special-case
        # this.
        for interdiff in interdiff_map.values():
            filediff_parts.append((interdiff, None, False))

    files = []
    index = 0

    for parts in filediff_parts:
        filediff, interfilediff, force_interdiff = parts

        filediff_revision_str = get_revision_str(filediff.source_revision)
        newfile = (filediff.source_revision == PRE_CREATION)

        if interdiffset:
            # First, find out if we want to even process this one.
            # We only process if there's a difference in files.

            if (filediff and interfilediff and
                filediff.diff == interfilediff.diff):
                continue

            source_revision = "Diff Revision %s" % diffset.revision

            if not interfilediff and force_interdiff:
                dest_revision = "Diff Revision %s - File Reverted" % \
                                interdiffset.revision
            else:
                dest_revision = "Diff Revision %s" % interdiffset.revision
        else:
            source_revision = get_revision_str(filediff.source_revision)

            if newfile:
                dest_revision = _("New File")
            else:
                dest_revision = _("New Change")

        i = filediff.source_file.rfind('/')

        if i != -1:
            basepath = filediff.source_file[:i]
            basename = filediff.source_file[i + 1:]
        else:
            basepath = ""
            basename = filediff.source_file

        file = {
            'depot_filename': filediff.source_file,
            'basename': basename,
            'basepath': basepath,
            'revision': source_revision,
            'dest_revision': dest_revision,
            'filediff': filediff,
            'interfilediff': interfilediff,
            'force_interdiff': force_interdiff,
            'binary': filediff.binary,
            'newfile': newfile,
            'index': len(files),
        }

        if load_chunks:
            chunks = []

            if not filediff.binary:
                key = key_prefix

                if not force_interdiff:
                    key += str(filediff.id)
                elif interfilediff:
                    key += "interdiff-%s-%s" % (filediff.id, interfilediff.id)
                else:
                    key += "interdiff-%s-none" % filediff.id

                chunks = cache_memoize(
                    key,
                    lambda: get_chunks(filediff.diffset,
                                       filediff, interfilediff,
                                       force_interdiff,
                                       enable_syntax_highlighting),
                    large_data=True)

            file['chunks'] = chunks
            file['changed_chunks'] = []

            for j, chunk in enumerate(file['chunks']):
                chunk['index'] = j
                if chunk['change'] != 'equal':
                    file['changed_chunks'].append(chunk)

            file['num_changes'] = len(file['changed_chunks'])

        files.append(file)

    def cmp_file(x, y):
        # Sort based on basepath in asc order
        if x["basepath"] != y["basepath"]:
            return cmp(x["basepath"], y["basepath"])
        # Sort based on filename in asc order, then basod on extension in desc
        # order, to make *.h be ahead of *.c/cpp
        x_file, x_ext = os.path.splitext(x["basename"])
        y_file, y_ext = os.path.splitext(y["basename"])
        if x_file != y_file:
            return cmp(x_file, y_file)
        else:
            return cmp(y_ext, x_ext)

    files.sort(cmp_file)

    log_timer.done()

    return files

def get_file_chunks_in_range(context, filediff, interfilediff,
                             first_line, num_lines):
    """
    A generator that yields chunks within a range of lines in the specified
    filediff/interfilediff.

    This is primarily intended for use with templates. It takes a
    RequestContext for looking up the user and for caching file lists,
    in order to improve performance and reduce lookup times for files that have
    already been fetched.

    Each returned chunk is a dictionary with the following fields:

      ============= ========================================================
      Variable      Description
      ============= ========================================================
      ``change``    The change type ("equal", "replace", "insert", "delete")
      ``numlines``  The number of lines in the chunk.
      ``lines``     The list of lines in the chunk.
      ============= ========================================================

    Each line in the list of lines is an array with the following data:

      ======== =============================================================
      Index    Description
      ======== =============================================================
      0        Virtual line number (union of the original and patched files)
      1        Real line number in the original file
      2        HTML markup of the original file
      3        Changed regions of the original line (for "replace" chunks)
      4        Real line number in the patched file
      5        HTML markup of the patched file
      6        Changed regions of the patched line (for "replace" chunks)
      ======== =============================================================
    """
    interdiffset = None

    key = "_diff_files_%s_%s" % (filediff.diffset.id, filediff.id)

    if interfilediff:
        key += "_%s" % (interfilediff.id)
        interdiffset = interfilediff.diffset

    if key in context:
        files = context[key]
    else:
        assert 'user' in context
        files = get_diff_files(filediff.diffset, filediff, interdiffset,
                               get_enable_highlighting(context['user']))
        context[key] = files

    if not files:
        raise StopIteration

    assert len(files) == 1

    for chunk in files[0]['chunks']:
        lines = chunk['lines']
        if lines[-1][0] >= first_line >= lines[0][0]:
            start_index = first_line - lines[0][0]

            if first_line + num_lines <= lines[-1][0]:
                last_index = start_index + num_lines
            else:
                last_index = len(lines)

            new_chunk = {
                'lines': chunk['lines'][start_index:last_index],
                'numlines': last_index - start_index,
                'change': chunk['change'],
            }

            yield new_chunk

            first_line += new_chunk['numlines']
            num_lines -= new_chunk['numlines']

            assert num_lines >= 0
            if num_lines == 0:
                break

def get_enable_highlighting(user):
    if user.is_authenticated():
        profile, profile_is_new = Profile.objects.get_or_create(user=user)
        user_syntax_highlighting = profile.syntax_highlighting
    else:
        user_syntax_highlighting = True

    siteconfig = SiteConfiguration.objects.get_current()
    return (siteconfig.get('diffviewer_syntax_highlighting') and
            user_syntax_highlighting and
            get_can_enable_syntax_highlighting())


text:
if defined?(Rails)

  module CustomValidations
    module Rails
      class Engine < ::Rails::Engine
        # Rails should look in our vendor directory.
      end
    end
  end

end


text:
package views.html

import play.twirl.api._
import play.twirl.api.TemplateMagic._

     object main_Scope0 {
import models._
import controllers._
import play.api.i18n._
import views.html._
import play.api.templates.PlayMagic._
import java.lang._
import java.util._
import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
import play.core.j.PlayMagicForJava._
import play.mvc._
import play.data._
import play.api.data.Field
import play.mvc.Http.Context.Implicit._

class main extends BaseScalaTemplate[play.twirl.api.HtmlFormat.Appendable,Format[play.twirl.api.HtmlFormat.Appendable]](play.twirl.api.HtmlFormat) with play.twirl.api.Template2[String,Html,play.twirl.api.HtmlFormat.Appendable] {

  /*
 * This template is called from the `index` template. This template
 * handles the rendering of the page header and body tags. It takes
 * two arguments, a `String` for the title of the page and an `Html`
 * object to insert into the body of the page.
 */
  def apply/*7.2*/(title: String)(content: Html):play.twirl.api.HtmlFormat.Appendable = {
    _display_ {
      {

Seq[Any](format.raw/*7.32*/("""

"""),format.raw/*9.1*/("""<!DOCTYPE html>
<html lang="en">
    <head>
        """),format.raw/*12.62*/("""
        """),format.raw/*13.9*/("""<title>"""),_display_(/*13.17*/title),format.raw/*13.22*/("""</title>
        <script src=""""),_display_(/*14.23*/routes/*14.29*/.Assets.versioned("scripts/empty.js")),format.raw/*14.66*/("""" type="text/javascript"></script>
    </head>
    <body>
        """),format.raw/*18.32*/("""
        """),_display_(/*19.10*/content),format.raw/*19.17*/("""
    """),format.raw/*20.5*/("""</body>
</html>
"""))
      }
    }
  }

  def render(title:String,content:Html): play.twirl.api.HtmlFormat.Appendable = apply(title)(content)

  def f:((String) => (Html) => play.twirl.api.HtmlFormat.Appendable) = (title) => (content) => apply(title)(content)

  def ref: this.type = this

}

}

/*
 * This template is called from the `index` template. This template
 * handles the rendering of the page header and body tags. It takes
 * two arguments, a `String` for the title of the page and an `Html`
 * object to insert into the body of the page.
 */
object main extends main_Scope0.main
              /*
                  -- GENERATED --
                  DATE: Sat Apr 09 15:55:55 PDT 2016
                  SOURCE: D:/git/trask/glowroot/agent-parent/plugins/play-plugin/tmp-router-files/app/views/main.scala.html
                  HASH: b2b6a7ce02708c8b2822a50b57a56bfd2e7cfd4f
                  MATRIX: 1002->260|1127->290|1155->292|1235->397|1271->406|1306->414|1332->419|1390->450|1405->456|1463->493|1557->649|1594->659|1622->666|1654->671
                  LINES: 32->7|37->7|39->9|42->12|43->13|43->13|43->13|44->14|44->14|44->14|47->18|48->19|48->19|49->20
                  -- GENERATED --
              */


text:
---
permalink: /code_of_conduct/
title: Code of Conduct | DjangoCon in Austin, TX
---

<!DOCTYPE html>

<meta charset="utf-8"/>
<title>Code of Conduct | DjangoCon in Austin, TX</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<meta content="DjangoCon US 2015 in Austin, TX" property="og:title">
<meta content="website" property="og:type">
<meta content="https://2015.djangocon.us/" property="og:url"/>
<meta content="DjangoCon US 2015" property="og:site_name"/>
<meta content="A six-day not-for-profit by-the-community and for-the-community international conference for the Django web framework. " property="og:description"/>
<meta content="https://2015.djangocon.us/site_media/static/images/djangocon-logo-thumb.png" property="og:image"/>
<link href="/site_media/static/main.css" media="screen,projection" rel="stylesheet" type="text/css"/>

<link href="/site_media/static/images/favicon.ico" rel="shortcut icon"/>

</meta></meta>

<button class="navbar-toggle" data-target=".navbar-collapse" data-toggle="collapse" type="button">
Toggle navigation

</button>

                About

What is Djangocon?

DjangoCon Organizers

Code of Conduct

Diversity

Accessibility

Financial Aid

Childcare

Volunteers

Contact Us

                Schedule

Tutorial Schedule

Talk Schedule

Sprints

DjangoGirls Austin Workshop

Beginner's Guide

                Registration

Register for DjangoCon US

Register for DjangoGirls Austin Workshop

Register for Hotel Accommodations

                Venue

Hotel Accommodations

Travel

City Guide to Austin

                Speaking

Call For Proposals

Speaker Mentors

Lightning Talks

                Sponsors

Become a Sponsor

DjangoCon Sponsors

                News

Log in

Sign up

<form action="https://2015.djangocon.us/account/logout/" id="accountLogOutForm" method="POST" style="display: none;">
<input name="csrfmiddlewaretoken" type="hidden" value="vKDUxSvBXQum2uTW0DN1QlXrjKdu8pjA"/>
</form>

Code of Conduct

Contact Information

If you are being harassed, notice that someone else is being harassed, or have any other concerns, please contact a member of conference staff. Conference staff will be wearing badges that say "Organizer." You may also contact hotel staff and ask to be put in touch with the conference chair — Jeff Triplett.

You can also email the Code of Conduct staff at [email protected].

If the matter is especially urgent, please call/contact any of these individuals:

Jeff Triplett

Anna Ossowski

Lacey Williams Henschel

A DEFNA Board Member can always be reached at +1 (415) 295-2728.

DjangoCon's Code of Conduct

DjangoCon US is a community conference intended for networking and collaboration in the developer community.

We value the participation of each member of the Django community and want all attendees to have an enjoyable and fulfilling experience. Accordingly, all attendees are expected to show respect and courtesy to other attendees throughout the conference and at all conference events, whether officially sponsored by DjangoCon or not.

To make clear what is expected, all delegates/attendees, speakers, exhibitors, organizers and volunteers at any DjangoCon event are required to conform to the following Code of Conduct. Organizers will enforce this code throughout the event.

The Short Version

DjangoCon is dedicated to providing a harassment-free conference experience for everyone, regardless of gender, sexual orientation, disability, physical appearance, body size, race, or religion. We do not tolerate harassment of conference participants in any form.

All communication should be appropriate for a professional audience including people of many different backgrounds. Sexual language and imagery is not appropriate for any conference venue, including talks.

Be kind to others. Do not insult or put down other attendees. Behave professionally. Remember that harassment and sexist, racist, or exclusionary jokes are not appropriate for DjangoCon.

Attendees violating these rules may be asked to leave the conference without a refund at the sole discretion of the conference organizers.

Thank you for helping make this a welcoming, friendly event for all.

The Longer Version

Harassment includes offensive verbal comments related to gender, sexual orientation, disability, physical appearance, body size, race, religion, sexual images in public spaces, deliberate intimidation, stalking, following, harassing photography or recording, sustained disruption of talks or other events, inappropriate physical contact, and unwelcome sexual attention.

Participants asked to stop any harassing behavior are expected to comply immediately.

Exhibitors in the expo hall, sponsor or vendor booths, or similar activities are also subject to the anti-harassment policy. In particular, exhibitors should not use sexualized images, activities, or other material. Booth staff (including volunteers) should not use sexualized clothing/uniforms/costumes, or otherwise create a sexualized environment.

Be careful in the words that you choose. Remember that sexist, racist, and other exclusionary jokes can be offensive to those around you. Excessive swearing and offensive jokes are not appropriate for DjangoCon.

If a participant engages in behavior that violates this code of conduct, the conference organizers may take any action they deem appropriate, including warning the offender or expulsion from the conference with no refund.

Important Numbers

Conference staff will be happy to help participants contact hotel/venue security or local law enforcement, provide escorts, or otherwise assist those experiencing harassment to feel safe for the duration of the conference. We value your attendance.

AT&T Conference Center Security: (512) 404-3663

Local law enforcement - Austin Police Department

Non-emergency: (512) 974-5750

Emergency: 911

Local sexual assault hotline:

SafePlace: (512) 267-7233 (SAFE)

Local emergency and non-emergency medical:

St. David's Medical Center (emergency/non-emergency): (512) 544-7111

MedSpring Urgent Care (walk-in urgent care/clinic): (512) 861-8030

Local taxi:

Yellow Cab: 512-452-9999

Photo Policy

In order to make DjangoCon US 2015 a great experience for everyone, do not photograph, video, or audio record anyone at DjangoCon without their express permission, sought in advance. If someone does not want to be photographed, video or audio recorded, please respect their wishes.

Crowd shots are permitted, but when only the faces of a few people are visible, permission should be sought from all of those individuals.

License

This Code of Conduct was forked from the example policy from the Geek Feminism wiki, created by the Ada Initiative and other volunteers. which is under a Creative Commons Zero license.

Conference Code of Conduct by https://2015.djangocon.us/code_of_conduct/ is licensed under a Creative Commons Attribution 3.0 Unported License.

Questions? Comments?
Contact Us

                  Design + Build by
                      Lincoln Loop

                      Hosted on Gondor

                      Presented by DEFNA

©2016 DjangoCon

{% include analytics.html %}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Product
 *
 * @author Kamil Piorun <kamil.piorun@tmsolution.pl>
 */

namespace Piorun\ProjektBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ProductType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name')
                ->add('price')
                ->add('weight')
                ->add('height')
                ->add('description')
                ->add('save', 'submit');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Piorun\ProjektBundle\Entity\Product',
        ));
    }

    public function getName()
    {
        return 'product';
    }

}


text:
import { Component, OnInit }                    from '@angular/core';
import { isBrowser }                            from 'angular2-universal';
import { Router }                               from '@angular/router';
import { Store }                                from '@ngrx/store';
import { URLSearchParams }                      from '@angular/http';
import { AbstractControl, FormGroup, FormBuilder, Validators }   from '@angular/forms';

import { UserService, RegisterRequestModel }    from 'app-shared';
import { AppState, REGISTER_USER }              from 'app';

export class UserReg {
    firstName:    string;
    lastName:     string;
    email:        string;
    password:     string;
    passwordConf: string;
}

@Component({
    selector: 'app-register',
    template: require('./register.component.html'),
    styles: [require('./register.component.css')]
})

export class RegisterComponent implements OnInit {
    public logoImageUrl = require('../../images/logo-large.png');
    title: string = 'Register';
    user: UserReg = new UserReg();
    emailSent: boolean = false;
    regForm: FormGroup;

    formErrors = {
        'fname': '',
        'lname': '',
        'emailaddress': '',
        'pword': ''
    };

    validationMessages = {
        'fname': {
            'required':     'First name is required.',
            'minlength':    'Must be at least 2 characters long',
            'maxlength':    'Can be no longer than 24 characters.'
        },
        'lname': {
            'required':     'Last name is required.',
            'minlength':    'Must be at least 2 characters long',
            'maxlength':    'Can be no longer than 24 characters.'
        },
        'emailaddress': {
            'required':     'Email address is required.',
            'minlength':    'Must be at least 7 characters long.',
            'maxlength':    'Can be no longer than 24 characters.',
            'pattern':      'Not a valid email.'
        },
        'pword': {
            'required':     'Password is required.',
            'minlength':    'Must be at least 8 characters long',
            'maxlength':    'Can be no longer than 24 characters.'
        }
    };

    constructor(private userService: UserService, private router: Router, private store: Store<AppState>,
        private fb: FormBuilder) { }

    registerUser() {
        let request = new RegisterRequestModel();
        // request.firstName = this.user.firstName;
        // request.lastName = this.user.lastName;
        request.email = this.user.email;
        request.password = this.user.password;
        request.confirmPassword = this.user.passwordConf;

        this.userService.register(request)
            .then(url => {
                this.store.dispatch({
                    type: REGISTER_USER,
                    payload: url
                });

                this.router.navigate(['/login']);
            });
    }

    buildForm(): void {
        this.regForm = this.fb.group({
            /*
            fname: [this.user.firstName, [
                Validators.required,
                Validators.minLength(2),
                Validators.maxLength(24)
                ]
            ],
            lname: [this.user.lastName, [
                Validators.required,
                Validators.minLength(2),
                Validators.maxLength(24)
                ]
            ],
            */
            emailaddress:[this.user.email, [
                Validators.required,
                Validators.minLength(7),
                Validators.maxLength(24),
                Validators.pattern( '^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$' )
                ]
            ],
            passwords: this.fb.group({
                pword: [this.user.password, [
                    Validators.required,
                    Validators.minLength(8),
                    Validators.maxLength(24)
                    ]
                ],
                pwordconf: [this.user.passwordConf, [
                    Validators.required,
                    Validators.minLength(8),
                    Validators.maxLength(24)
                    ]
                ]
            }, {validator: passwordMatcher})
        });

        this.regForm.valueChanges
            .subscribe(data => this.onValueChanged(data));

        this.onValueChanged();
    }

    onValueChanged( data?: any ){
        if (!this.regForm) { return; }

        const form = this.regForm;
        const pwordField = this.regForm.get( 'passwords' ).get( 'pword' );

        // tslint:disable-next-line:forin
        for (const field in this.formErrors) {
            // clear previous error message (if any)
            this.formErrors[field] = '';
            const control = form.get(field);

            if ( pwordField.errors && pwordField.dirty ){
                const messages = this.validationMessages['pword'];

                for (const key in pwordField.errors ){
                    this.formErrors['pword'] += messages[key] + ' ';
                }
            }

            if (control && control.dirty && !control.valid) {
                const messages = this.validationMessages[field];
                // tslint:disable-next-line:forin
                for (const key in control.errors) {
                    this.formErrors[field] += messages[key] + ' ';
                }
            }
        }
    }

    ngOnInit() {
        this.buildForm();
    }
}

function passwordMatcher( c: AbstractControl ){
    return c.get( 'pword' ).value === c.get( 'pwordconf' ).value
        ? undefined : { 'nomatch': true };
}


text:
package de.androidbytes.recipr.data.provider.step;

import android.support.annotation.Nullable;
import de.androidbytes.recipr.data.provider.base.BaseModel;

/**
 * A recipe is an Entity used to combine related ingredients and steps for preparation.
 */
public interface StepModel extends BaseModel {

    /**
     * Get the {@code recipe_id} value.
     */
    long getRecipeId();

    /**
     * Title of the StepEntity.
     * Can be {@code null}.
     */
    @Nullable
    int getNumber();

    /**
     * Instruction of the preparation step.
     * Can be {@code null}.
     */
    @Nullable
    String getInstruction();
}


text:
<!doctype html>

		<meta charset="utf-8">
		<link rel="stylesheet" href="./dist/reveal.css">
		<link rel="stylesheet" href="./dist/theme/sky.css" id="theme">
		<link rel="stylesheet" href="./css/bubl.css">
		<meta name="author" content="Martin Carmichael" />
		<meta name="copyright" content="© 2021 Martin Carmichael  all rights reserved" />
		<title>Cauchemars à Sweet City</title>

				Cauchemar à Sweet Cité.

				Docteur Stein!
La Sweet Cité est envahie!

				Attaqués
Par une colonie de crabes!

				Les araignées rejoignent les forces occultes.

				Même les requins
passent à l'attaque.

				Essayons de ne pas paniquer.

				Nous pouvons apeller à l'aide.

				Je vais apeller Marine Boy.

				Il sait parler aux dauphins.

				<audio data-autoplay id="audio" src="./snd/stingray.mp3"></audio>
				Contactez la World Aquanaut Security Patrol (WASP)

				Troy Tempest connaît notre position.

				L'invasion sous-marine se poursuit...

				Les homards géants attaquent!.

				Les araignées mangent les immeubles.

				Hans Stein victime de panique...
				Prenons la sortie d'urgence.

				Vite! Fuyons!

				Hans Stein est parti trop vite...
								J'ai oublié mon téléphone à Sweet Cité!

				<audio data-autoplay id="audio" src="./snd/tbirds.mp3"></audio>
				La Sécurité Internationale a entendu l'appel de détresse
				Allons aider
Sweet Cité!

				Nous avons besoin des dauphins...

				Les pieuvres
étouffent les crabes.

				Les phoques dévorent
la chair de crabe.

				La Télépathie avec les dauphins fonctionne.

				Les tortues
nettoient les débris.

				Un peu plus tard
Frank passe par là...
				Le téléphone de mon père!

				Quelle belle trouvaille!

Fin du Chapitre.

Cauchemar à Sweet Cité.

Table des matières