text:
var storage = require('../../storage/ftp');
var plan = require('../../plan/garbage');
describe('Unit Test.', function() {
  describe('#save()', function() {
    it('should backup file to google cloud storage', function(done) {
      plan.backup(null, function(err, file) {
        if (err) throw err;
        var option = {
          host: 'host',
          user: 'user',
          password: 'password',
          confirm: true
        }
        storage.save(file, option, function(err, response) {
          if (err) throw err;
          console.log(response);
          done();
        });
      });
    })
  });
});

redpajama_set_name: RedPajamaGithub


text:
An IP layer compliant to RFC791 with ARP and ICMP layers (Ping service).
This demo project runs over PIC32 Ethernet Starter Kit and has been tested with an Ubuntu laptop through an Ethernet switch.

This IP stack is implemented on top of my Ethernet driver for PIC32.

The demo application sets a static IP address and then starts a Ping service to a fixed remote address for 5 seconds.
How to use the demo application:
 - set a static local IP address in app_ip.c file;
 - check the IP address of your PC and then set it as remote IP address in app_ip.c file;
 - build and run on the board;
 - you can see ping requests from the board and PC replies with a tool like Wireshark for the first 5 seconds;
 - start a Ping request from your PC to the board, use a command like: $ ping -I eth0 10.42.0.10.

For an example of use please have a look at minUDP project.

Known issues:
 - Ethernet layer remains stacked until an Ethernet cable is connected. It is necessary to add a timeout in order to exit the related infinite loop in eth.c file.
 - Checksum calculation with fragmented packets has not been tested properly.


text:
import pandas as pd
import tweepy

from somecode import data_frame
from somecode import key

def timeline(screen_name):

    keys = key()

    access_token = keys['token']
    access_secret = keys['token_secret']
    consumer_secret = keys['consumer_secret']
    consumer_key = keys['consumer_key']

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_secret)
    api = tweepy.API(auth)

    alltweets = []

    new_tweets = api.user_timeline(screen_name = screen_name,count=200,include_rts=1)
    alltweets.extend(new_tweets)
    oldest = alltweets[-1].id - 1

    while len(new_tweets) > 0:

        new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)
        alltweets.extend(new_tweets)
        oldest = alltweets[-1].id - 1

    df = data_frame(alltweets)
    df.meta_keyword = str(screen_name)

    return df


text:
Declaration: abstract class mle86\WQ\Job\\AbstractJob implements [Job]
Source file: [src/WQ/Job/AbstractJob.php](/src/WQ/Job/AbstractJob.php)

To build a working Job class,
simply extend this class.

* It's your choice
  whether to put your job execution logic in the Job class
  or somewhere else entirely, like the queue worker script.
* If the jobs should be re-tried after an initial failure,
  override the `MAX_RETRY` constant.
* If the retry condition is more complex,
  override the `jobCanRetry()` method instead.
* To change the retry delay interval,
  override the `jobRetryDelay()` method
  (you'll probably want to have an increasing delay,
   so base it on the `jobTryIndex()` counter value).
* If your queued jobs can expire before being executed,
  override `jobIsExpired()` so that it returns `true`
  if the expiry condition is reached. You may need to
  add a job creation timestamp property for that.

It fully implements the [`Job`][Job] interface.

## Methods

* public function jobRetryDelay (): ?int { … }
    See `Job::jobRetryDelay()`.
    This default implementation
    always returns 10 minutes.

* public function jobTryIndex (): int { … }
    See `Job::jobTryIndex()`.
    This default implementation
    always returns the `$_try_index` value
    or `1`, whichever is greater.

* public function serialize () { … }
    This default implementation stores all public and protected properties.
    Override this method if that's not enough or if you want to do some additional pre-serialization processing,
    but don't forget to include `$_try_index + 1` in the serialization!

* public function unserialize (string $serialized) { … }
    This default implementation simply writes all serialized values
    to their corresponding object property.
    That includes the `$_try_index` counter.
    Private and/or static properties will never be written to.

* public function jobCanRetry (): bool { … }
    See `Job::jobCanRetry()`.
    This default implementation
    always returns `true`
    if `jobTryIndex() ≤ MAX_RETRY`.

* public function jobIsExpired (): bool { … }
    See `Job::jobIsExpired()`.
    This default implementation
    always returns `false`,
    meaning that `AbstractJob` implementations
    never expire by default.

## Constants

* const int MAX_RETRY = 0
    How often a job of this type can be retried if it fails.
    Override this as necessary in subclasses.
    Zero or negative values mean that this job can only be tried once, never re-tried.
    (This is used in the `jobCanRetry()` default implementation only,
     so if you override that method in your Job class
     the constant is unused.)

## Internals

* protected $_try_index = 0
    The current try index.
    The default `__serialize()` implementation
    will increase this by 1 before serializing it,
    so that the serialization always contains
    the correct next value.
    *Internal:*
    This should not be accessed directly,
    except for a custom `__serialize()` override.

[Job]: Ref_Job_interface.md


text:
.cmfcmfmedia-css-relative {
  position: relative; }

/* Mimic table appearance */
div.table {
  display: table; }
  div.table .file-row {
    display: table-row; }
    div.table .file-row > div {
      display: table-cell;
      vertical-align: top;
      border-top: 1px solid #ddd;
      padding: 8px; }
    div.table .file-row:nth-child(odd) {
      background: #f9f9f9; }

/* The total progress gets shown by event listeners */
#cmfcmfmedia-upload-total-progress {
  opacity: 0;
  transition: opacity 0.3s linear; }

#cmfcmfmedia-upload-previews {
  /* Hide the progress bar when finished */
  /* Hide the delete button initially */
  /* Hide the start and cancel buttons and show the delete button */ }
  #cmfcmfmedia-upload-previews .file-row.dz-success .progress {
    opacity: 0;
    transition: opacity 0.3s linear; }
  #cmfcmfmedia-upload-previews .file-row .delete {
    display: none; }
  #cmfcmfmedia-upload-previews .file-row.dz-success .start, #cmfcmfmedia-upload-previews .file-row.dz-success .cancel {
    display: none; }
  #cmfcmfmedia-upload-previews .file-row.dz-success .delete {
    display: block; }

/*# sourceMappingURL=upload.css.map */


text:
package org.elasticsearch.common.util;

import org.apache.lucene.util.BytesRef;
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.cache.recycler.PageCacheRecycler;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.elasticsearch.test.cache.recycler.MockBigArrays;
import org.elasticsearch.test.cache.recycler.MockPageCacheRecycler;
import org.elasticsearch.threadpool.ThreadPool;
import org.junit.Before;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class BigArraysTests extends ElasticsearchTestCase {

    public static BigArrays randombigArrays() {
        final PageCacheRecycler recycler = randomBoolean() ? null : new MockPageCacheRecycler(ImmutableSettings.EMPTY, new ThreadPool("BigArraysTests"));
        return new MockBigArrays(ImmutableSettings.EMPTY, recycler);
    }

    private BigArrays bigArrays;

    @Before
    public void init() {
        bigArrays = randombigArrays();
    }

    public void testByteArrayGrowth() {
        final int totalLen = randomIntBetween(1, 4000000);
        final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen);
        ByteArray array = bigArrays.newByteArray(startLen, randomBoolean());
        byte[] ref = new byte[totalLen];
        for (int i = 0; i < totalLen; ++i) {
            ref[i] = randomByte();
            array = bigArrays.grow(array, i + 1);
            array.set(i, ref[i]);
        }
        for (int i = 0; i < totalLen; ++i) {
            assertEquals(ref[i], array.get(i));
        }
        array.close();
    }

    public void testIntArrayGrowth() {
        final int totalLen = randomIntBetween(1, 1000000);
        final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen);
        IntArray array = bigArrays.newIntArray(startLen, randomBoolean());
        int[] ref = new int[totalLen];
        for (int i = 0; i < totalLen; ++i) {
            ref[i] = randomInt();
            array = bigArrays.grow(array, i + 1);
            array.set(i, ref[i]);
        }
        for (int i = 0; i < totalLen; ++i) {
            assertEquals(ref[i], array.get(i));
        }
        array.close();
    }

    public void testLongArrayGrowth() {
        final int totalLen = randomIntBetween(1, 1000000);
        final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen);
        LongArray array = bigArrays.newLongArray(startLen, randomBoolean());
        long[] ref = new long[totalLen];
        for (int i = 0; i < totalLen; ++i) {
            ref[i] = randomLong();
            array = bigArrays.grow(array, i + 1);
            array.set(i, ref[i]);
        }
        for (int i = 0; i < totalLen; ++i) {
            assertEquals(ref[i], array.get(i));
        }
        array.close();
    }

    public void testFloatArrayGrowth() {
        final int totalLen = randomIntBetween(1, 1000000);
        final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen);
        FloatArray array = bigArrays.newFloatArray(startLen, randomBoolean());
        float[] ref = new float[totalLen];
        for (int i = 0; i < totalLen; ++i) {
            ref[i] = randomFloat();
            array = bigArrays.grow(array, i + 1);
            array.set(i, ref[i]);
        }
        for (int i = 0; i < totalLen; ++i) {
            assertEquals(ref[i], array.get(i), 0.001d);
        }
        array.close();
    }

    public void testDoubleArrayGrowth() {
        final int totalLen = randomIntBetween(1, 1000000);
        final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen);
        DoubleArray array = bigArrays.newDoubleArray(startLen, randomBoolean());
        double[] ref = new double[totalLen];
        for (int i = 0; i < totalLen; ++i) {
            ref[i] = randomDouble();
            array = bigArrays.grow(array, i + 1);
            array.set(i, ref[i]);
        }
        for (int i = 0; i < totalLen; ++i) {
            assertEquals(ref[i], array.get(i), 0.001d);
        }
        array.close();
    }

    public void testObjectArrayGrowth() {
        final int totalLen = randomIntBetween(1, 1000000);
        final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen);
        ObjectArray<Object> array = bigArrays.newObjectArray(startLen);
        final Object[] pool = new Object[100];
        for (int i = 0; i < pool.length; ++i) {
            pool[i] = new Object();
        }
        Object[] ref = new Object[totalLen];
        for (int i = 0; i < totalLen; ++i) {
            ref[i] = randomFrom(pool);
            array = bigArrays.grow(array, i + 1);
            array.set(i, ref[i]);
        }
        for (int i = 0; i < totalLen; ++i) {
            assertSame(ref[i], array.get(i));
        }
        array.close();
    }

    public void testByteArrayFill() {
        final int len = randomIntBetween(1, 100000);
        final int fromIndex = randomIntBetween(0, len - 1);
        final int toIndex = randomBoolean()
            ? Math.min(fromIndex + randomInt(100), len) // single page
            : randomIntBetween(fromIndex, len); // likely multiple pages
        final ByteArray array2 = bigArrays.newByteArray(len, randomBoolean());
        final byte[] array1 = new byte[len];
        for (int i = 0; i < len; ++i) {
            array1[i] = randomByte();
            array2.set(i, array1[i]);
        }
        final byte rand = randomByte();
        Arrays.fill(array1, fromIndex, toIndex, rand);
        array2.fill(fromIndex, toIndex, rand);
        for (int i = 0; i < len; ++i) {
            assertEquals(array1[i], array2.get(i), 0.001d);
        }
        array2.close();
    }

    public void testFloatArrayFill() {
        final int len = randomIntBetween(1, 100000);
        final int fromIndex = randomIntBetween(0, len - 1);
        final int toIndex = randomBoolean()
            ? Math.min(fromIndex + randomInt(100), len) // single page
            : randomIntBetween(fromIndex, len); // likely multiple pages
        final FloatArray array2 = bigArrays.newFloatArray(len, randomBoolean());
        final float[] array1 = new float[len];
        for (int i = 0; i < len; ++i) {
            array1[i] = randomFloat();
            array2.set(i, array1[i]);
        }
        final float rand = randomFloat();
        Arrays.fill(array1, fromIndex, toIndex, rand);
        array2.fill(fromIndex, toIndex, rand);
        for (int i = 0; i < len; ++i) {
            assertEquals(array1[i], array2.get(i), 0.001d);
        }
        array2.close();
    }

    public void testDoubleArrayFill() {
        final int len = randomIntBetween(1, 100000);
        final int fromIndex = randomIntBetween(0, len - 1);
        final int toIndex = randomBoolean()
            ? Math.min(fromIndex + randomInt(100), len) // single page
            : randomIntBetween(fromIndex, len); // likely multiple pages
        final DoubleArray array2 = bigArrays.newDoubleArray(len, randomBoolean());
        final double[] array1 = new double[len];
        for (int i = 0; i < len; ++i) {
            array1[i] = randomDouble();
            array2.set(i, array1[i]);
        }
        final double rand = randomDouble();
        Arrays.fill(array1, fromIndex, toIndex, rand);
        array2.fill(fromIndex, toIndex, rand);
        for (int i = 0; i < len; ++i) {
            assertEquals(array1[i], array2.get(i), 0.001d);
        }
        array2.close();
    }

    public void testLongArrayFill() {
        final int len = randomIntBetween(1, 100000);
        final int fromIndex = randomIntBetween(0, len - 1);
        final int toIndex = randomBoolean()
            ? Math.min(fromIndex + randomInt(100), len) // single page
            : randomIntBetween(fromIndex, len); // likely multiple pages
        final LongArray array2 = bigArrays.newLongArray(len, randomBoolean());
        final long[] array1 = new long[len];
        for (int i = 0; i < len; ++i) {
            array1[i] = randomLong();
            array2.set(i, array1[i]);
        }
        final long rand = randomLong();
        Arrays.fill(array1, fromIndex, toIndex, rand);
        array2.fill(fromIndex, toIndex, rand);
        for (int i = 0; i < len; ++i) {
            assertEquals(array1[i], array2.get(i));
        }
        array2.close();
    }

    public void testByteArrayBulkGet() {
        final byte[] array1 = new byte[randomIntBetween(1, 4000000)];
        getRandom().nextBytes(array1);
        final ByteArray array2 = bigArrays.newByteArray(array1.length, randomBoolean());
        for (int i = 0; i < array1.length; ++i) {
            array2.set(i, array1[i]);
        }
        final BytesRef ref = new BytesRef();
        for (int i = 0; i < 1000; ++i) {
            final int offset = randomInt(array1.length - 1);
            final int len = randomInt(Math.min(randomBoolean() ? 10 : Integer.MAX_VALUE, array1.length - offset));
            array2.get(offset, len, ref);
            assertEquals(new BytesRef(array1, offset, len), ref);
        }
        array2.close();
    }

    public void testByteArrayBulkSet() {
        final byte[] array1 = new byte[randomIntBetween(1, 4000000)];
        getRandom().nextBytes(array1);
        final ByteArray array2 = bigArrays.newByteArray(array1.length, randomBoolean());
        for (int i = 0; i < array1.length; ) {
            final int len = Math.min(array1.length - i, randomBoolean() ? randomInt(10) : randomInt(3 * BigArrays.BYTE_PAGE_SIZE));
            array2.set(i, array1, i, len);
            i += len;
        }
        for (int i = 0; i < array1.length; ++i) {
            assertEquals(array1[i], array2.get(i));
        }
        array2.close();
    }

    public void testByteArrayEquals() {
        final ByteArray empty1 = byteArrayWithBytes(BytesRef.EMPTY_BYTES);
        final ByteArray empty2 = byteArrayWithBytes(BytesRef.EMPTY_BYTES);

        // identity = equality
        assertTrue(bigArrays.equals(empty1, empty1));
        // equality: both empty
        assertTrue(bigArrays.equals(empty1, empty2));
        empty1.close();
        empty2.close();

        // not equal: contents differ
        final ByteArray a1 = byteArrayWithBytes(new byte[]{0});
        final ByteArray a2 = byteArrayWithBytes(new byte[]{1});
        assertFalse(bigArrays.equals(a1, a2));
        a1.close();
        a2.close();

        // not equal: contents differ
        final ByteArray a3 = byteArrayWithBytes(new byte[]{1,2,3});
        final ByteArray a4 = byteArrayWithBytes(new byte[]{1,1,3});
        assertFalse(bigArrays.equals(a3, a4));
        a3.close();
        a4.close();

        // not equal: contents differ
        final ByteArray a5 = byteArrayWithBytes(new byte[]{1,2,3});
        final ByteArray a6 = byteArrayWithBytes(new byte[]{1,2,4});
        assertFalse(bigArrays.equals(a5, a6));
        a5.close();
        a6.close();
    }

    public void testByteArrayHashCode() {
        // null arg has hashCode 0
        assertEquals(0, bigArrays.hashCode(null));

        // empty array should have equal hash
        final int emptyHash = Arrays.hashCode(BytesRef.EMPTY_BYTES);
        final ByteArray emptyByteArray = byteArrayWithBytes(BytesRef.EMPTY_BYTES);
        final int emptyByteArrayHash = bigArrays.hashCode(emptyByteArray);
        assertEquals(emptyHash, emptyByteArrayHash);
        emptyByteArray.close();

        // FUN FACT: Arrays.hashCode() and BytesReference.bytesHashCode() are inconsistent for empty byte[]
        // final int emptyHash3 = new BytesArray(BytesRef.EMPTY_BYTES).hashCode();
        // assertEquals(emptyHash1, emptyHash3); -> fail (1 vs. 0)

        // large arrays should be different
        final byte[] array1 = new byte[randomIntBetween(1, 4000000)];
        getRandom().nextBytes(array1);
        final int array1Hash = Arrays.hashCode(array1);
        final ByteArray array2 = byteArrayWithBytes(array1);
        final int array2Hash = bigArrays.hashCode(array2);
        assertEquals(array1Hash, array2Hash);
        array2.close();
    }

    private ByteArray byteArrayWithBytes(byte[] bytes) {
        ByteArray bytearray = bigArrays.newByteArray(bytes.length);
        for (int i = 0; i < bytes.length; ++i) {
            bytearray.set(i, bytes[i]);
        }
        return bytearray;
    }

    public void testByteAccounting() throws Exception {
        for (String type : Arrays.asList("Byte", "Int", "Long", "Float", "Double", "Object")) {
            BigArrays bigArrays = new BigArrays(ImmutableSettings.builder().put(BigArrays.MAX_SIZE_IN_BYTES_SETTING, Long.MAX_VALUE).build(), null);
            Method create = BigArrays.class.getMethod("new" + type + "Array", long.class);
            final int size = scaledRandomIntBetween(5, 1 << 16);
            BigArray array = (BigArray) create.invoke(bigArrays, size);
            assertEquals(array.ramBytesUsed(), bigArrays.sizeInBytes());
            Method resize = BigArrays.class.getMethod("resize", array.getClass().getInterfaces()[0], long.class);
            int newSize = scaledRandomIntBetween(5, 1 << 16);
            array = (BigArray) resize.invoke(bigArrays, array, newSize);
            assertEquals(array.ramBytesUsed(), bigArrays.sizeInBytes());
            array.close();
            assertEquals(0, bigArrays.sizeInBytes());
        }
    }

    public void testMaxSizeExceededOnNew() throws Exception {
        final int size = scaledRandomIntBetween(5, 1 << 22);
        for (String type : Arrays.asList("Byte", "Int", "Long", "Float", "Double", "Object")) {
            BigArrays bigArrays = new BigArrays(ImmutableSettings.builder().put(BigArrays.MAX_SIZE_IN_BYTES_SETTING, randomIntBetween(1, size)).build(), null);
            Method create = BigArrays.class.getMethod("new" + type + "Array", long.class);
            try {
                create.invoke(bigArrays, size);
                fail("expected an exception on " + create);
            } catch (InvocationTargetException e) {
                assertTrue(e.getCause() instanceof ElasticsearchIllegalStateException);
            }
            assertEquals(0, bigArrays.sizeInBytes());
        }
    }

    public void testMaxSizeExceededOnResize() throws Exception {
        for (String type : Arrays.asList("Byte", "Int", "Long", "Float", "Double", "Object")) {
            final long maxSize = randomIntBetween(1 << 10, 1 << 22);
            BigArrays bigArrays = new BigArrays(ImmutableSettings.builder().put(BigArrays.MAX_SIZE_IN_BYTES_SETTING, maxSize).build(), null);
            Method create = BigArrays.class.getMethod("new" + type + "Array", long.class);
            final int size = scaledRandomIntBetween(1, 20);
            BigArray array = (BigArray) create.invoke(bigArrays, size);
            Method resize = BigArrays.class.getMethod("resize", array.getClass().getInterfaces()[0], long.class);
            while (true) {
                long newSize = array.size() * 2;
                assertEquals(array.ramBytesUsed(), bigArrays.sizeInBytes());
                try {
                    array = (BigArray) resize.invoke(bigArrays, array, newSize);
                } catch (InvocationTargetException e) {
                    assertTrue(e.getCause() instanceof ElasticsearchIllegalStateException);
                    break;
                }
            }
            assertEquals(array.ramBytesUsed(), bigArrays.sizeInBytes());
            array.close();
            assertEquals(0, bigArrays.sizeInBytes());
        }
    }

}


text:
"""Test that all expected methods are present, before I/O tests import.

This file is weirdly named so that it's the first test of I/O.
"""

from astropy.cosmology.connect import convert_registry, readwrite_registry

def test_expected_readwrite_io():
    """Test that ONLY the expected I/O is registered."""

    got = {k for k, _ in readwrite_registry._readers.keys()}
    expected = {"ascii.ecsv", "ascii.html"}

    assert got == expected

def test_expected_convert_io():
    """Test that ONLY the expected I/O is registered."""

    got = {k for k, _ in convert_registry._readers.keys()}
    expected = {"astropy.cosmology", "mapping", "astropy.model", "astropy.row",
                "astropy.table", "yaml"}

    assert got == expected


text:
struct BaseComponent
{
    BaseComponent(const std::string& id);

    const std::string ID;
};

#endif


text:
namespace Google.Cloud.Iap.V1.Snippets
{
    // [START iap_v1_generated_IdentityAwareProxyAdminService_UpdateTunnelDestGroup_async_flattened]
    using Google.Cloud.Iap.V1;
    using Google.Protobuf.WellKnownTypes;
    using System.Threading.Tasks;

    public sealed partial class GeneratedIdentityAwareProxyAdminServiceClientSnippets
    {
        /// <summary>Snippet for UpdateTunnelDestGroupAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task UpdateTunnelDestGroupAsync()
        {
            // Create client
            IdentityAwareProxyAdminServiceClient identityAwareProxyAdminServiceClient = await IdentityAwareProxyAdminServiceClient.CreateAsync();
            // Initialize request argument(s)
            TunnelDestGroup tunnelDestGroup = new TunnelDestGroup();
            FieldMask updateMask = new FieldMask();
            // Make the request
            TunnelDestGroup response = await identityAwareProxyAdminServiceClient.UpdateTunnelDestGroupAsync(tunnelDestGroup, updateMask);
        }
    }
    // [END iap_v1_generated_IdentityAwareProxyAdminService_UpdateTunnelDestGroup_async_flattened]
}


text:
package com.fererlab.pattern.structural.bridge.entertainment;

import java.util.List;

public class PrintFormatter implements Formatter {
    @Override
    public String format(String header, List<Detail> details) {
        StringBuilder builder = new StringBuilder();
        builder.append(header);
        builder.append("\n");
        for (Detail detail : details) {
            builder.append(detail.getLabel());
            builder.append(":");
            builder.append(detail.getValue());
            builder.append("\n");
        }
        return builder.toString();
    }
}


text:
"""
    tests.helpers
    ~~~~~~~~~~~~~

    Provides helper functions for unit tests in this package.

    :copyright: 2012, 2013, 2014, 2015 Jeffrey Finkelstein
                <jeffrey.finkelstein@gmail.com> and contributors.
    :license: GNU AGPLv3+ or BSD

"""
import sys
is_python_version_2 = sys.version_info[0] == 2

if is_python_version_2:
    import types

    def isclass(obj):
        return isinstance(obj, (types.TypeType, types.ClassType))
else:
    def isclass(obj):
        return isinstance(obj, type)

import datetime
import functools
import uuid

from flask import Flask
from nose import SkipTest
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import create_engine
from sqlalchemy import Date
from sqlalchemy import DateTime
from sqlalchemy import event
from sqlalchemy import Float
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Interval
from sqlalchemy import select
from sqlalchemy import Time
from sqlalchemy import Unicode
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.session import Session as SessionBase
from sqlalchemy.types import CHAR
from sqlalchemy.types import TypeDecorator
from sqlalchemy.ext.associationproxy import association_proxy

try:
    from flask.ext import sqlalchemy as flask_sa
except ImportError:
    flask_sa = None

from flask.ext.restless import APIManager

def skip_unless(condition, reason=None):
    """Decorator that skips `test` unless `condition` is ``True``.

    This is a replacement for :func:`unittest.skipUnless` that works with
    ``nose``. The argument ``reason`` is a string describing why the test was
    skipped.

    This decorator can be applied to functions, methods, or classes.

    """
    def skip(test):
        message = 'Skipped {0}: {1}'.format(test.__name__, reason)

        if isclass(test):
            for attr, val in test.__dict__.items():
                if callable(val) and not attr.startswith('__'):
                    setattr(test, attr, skip(val))
            return test

        @functools.wraps(test)
        def inner(*args, **kw):
            if not condition:
                raise SkipTest(message)
            return test(*args, **kw)
        return inner

    return skip

def unregister_fsa_session_signals():
    """
    When Flask-SQLAlchemy object is created, it registers some
    session signal handlers.

    In case of using both default SQLAlchemy session and Flask-SQLAlchemy
    session (thats happening in tests), we need to unregister this handlers or
    there will be some exceptions during test executions like:
        AttributeError: 'Session' object has no attribute '_model_changes'

    """
    if not flask_sa:
        return

    event.remove(SessionBase, 'before_commit',
                 flask_sa._SessionSignalEvents.session_signal_before_commit)
    event.remove(SessionBase, 'after_commit',
                 flask_sa._SessionSignalEvents.session_signal_after_commit)
    event.remove(SessionBase, 'after_rollback',
                 flask_sa._SessionSignalEvents.session_signal_after_rollback)

def force_json_contenttype(test_client):
    """Ensures that all requests made by the specified Flask test client have
    the ``Content-Type`` header set to ``application/json``, unless another
    content type is explicitly specified.

    """
    for methodname in ('get', 'put', 'patch', 'post', 'delete'):
        # Create a decorator for the test client request methods that adds
        # a JSON Content-Type by default if none is specified.
        def set_content_type(func):
            def new_func(*args, **kw):
                if 'content_type' not in kw:
                    kw['content_type'] = 'application/json'
                return func(*args, **kw)
            return new_func
        # Decorate the original test client request method.
        old_method = getattr(test_client, methodname)
        setattr(test_client, methodname, set_content_type(old_method))

# This code adapted from
# http://docs.sqlalchemy.org/en/rel_0_8/core/types.html#backend-agnostic-guid-type
class GUID(TypeDecorator):
    """Platform-independent GUID type.

    Uses Postgresql's UUID type, otherwise uses CHAR(32), storing as
    stringified hex values.

    """
    impl = CHAR

    def load_dialect_impl(self, dialect):
        descriptor = UUID() if dialect.name == 'postgresql' else CHAR(32)
        return dialect.type_descriptor(descriptor)

    def process_bind_param(self, value, dialect):
        if value is None:
            return None
        if dialect.name == 'postgresql':
            return str(value)
        if not isinstance(value, uuid.UUID):
            return '{0:.32x}'.format(uuid.UUID(value))
        # hexstring
        return '{0:.32x}'.format(value)

    def process_result_value(self, value, dialect):
        if value is None:
            return None
        return uuid.UUID(value)

class FlaskTestBase(object):
    """Base class for tests which use a Flask application.

    The Flask test client can be accessed at ``self.app``. The Flask
    application itself is accessible at ``self.flaskapp``.

    """

    def setUp(self):
        """Creates the Flask application and the APIManager."""
        # create the Flask application
        app = Flask(__name__)
        app.config['DEBUG'] = True
        app.config['TESTING'] = True
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        # This is required by `manager.url_for()` in order to construct
        # absolute URLs.
        app.config['SERVER_NAME'] = 'localhost'
        app.logger.disabled = True
        self.flaskapp = app

        # create the test client
        self.app = app.test_client()

        force_json_contenttype(self.app)

class DatabaseTestBase(FlaskTestBase):
    """Base class for tests that use a SQLAlchemy database.

    The :meth:`setUp` method does the necessary SQLAlchemy initialization, and
    the subclasses should populate the database with models and then create the
    database (by calling ``self.Base.metadata.create_all()``).

    """

    def setUp(self):
        """Initializes the components necessary for models in a SQLAlchemy
        database.

        """
        super(DatabaseTestBase, self).setUp()
        # initialize SQLAlchemy
        app = self.flaskapp
        engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'],
                               convert_unicode=True)
        self.Session = sessionmaker(autocommit=False, autoflush=False,
                                    bind=engine)
        self.session = scoped_session(self.Session)
        self.Base = declarative_base()
        self.Base.metadata.bind = engine

class ManagerTestBase(DatabaseTestBase):
    """Base class for tests that use a SQLAlchemy database and an
    :class:`flask_restless.APIManager`.

    The :class:`flask_restless.APIManager` is accessible at ``self.manager``.

    """

    def setUp(self):
        """Initializes an instance of :class:`flask.ext.restless.APIManager`.

        """
        super(ManagerTestBase, self).setUp()
        self.manager = APIManager(self.flaskapp, session=self.session)

class TestSupport(ManagerTestBase):
    """Base class for test cases which use a database with some basic models.

    """

    def setUp(self):
        """Creates some example models and creates the database tables.

        This class defines a whole bunch of models with various properties for
        use in testing, so look here first when writing new tests.

        """
        super(TestSupport, self).setUp()

        # declare the models
        class Program(self.Base):
            __tablename__ = 'program'
            id = Column(Integer, primary_key=True)
            name = Column(Unicode, unique=True)

        class ComputerProgram(self.Base):
            __tablename__ = 'computer_program'
            computer_id = Column(Integer, ForeignKey('computer.id'),
                                 primary_key=True)
            program_id = Column(Integer, ForeignKey('program.id'),
                                primary_key=True)
            licensed = Column(Boolean, default=False)
            program = relationship('Program')

        class Computer(self.Base):
            __tablename__ = 'computer'
            id = Column(Integer, primary_key=True)
            name = Column(Unicode, unique=True)
            vendor = Column(Unicode)
            buy_date = Column(DateTime)
            owner_id = Column(Integer, ForeignKey('person.id'))
            owner = relationship('Person')
            programs = relationship('ComputerProgram',
                                    cascade="all, delete-orphan",
                                    backref='computer')

            def speed(self):
                return 42

            @property
            def speed_property(self):
                return self.speed()

        class Screen(self.Base):
            __tablename__ = 'screen'
            id = Column(Integer, primary_key=True)
            width = Column(Integer, nullable=False)
            height = Column(Integer, nullable=False)

            @hybrid_property
            def number_of_pixels(self):
                return self.width * self.height

            @number_of_pixels.setter
            def number_of_pixels(self, value):
                self.height = value / self.width

        class Person(self.Base):
            __tablename__ = 'person'
            id = Column(Integer, primary_key=True)
            name = Column(Unicode, unique=True)
            age = Column(Integer)
            other = Column(Float)
            birth_date = Column(Date)
            computers = relationship('Computer')

            @hybrid_property
            def is_minor(self):
                if getattr(self, 'age') is None:
                    return None
                return self.age < 18

            @hybrid_property
            def is_above_21(self):
                if getattr(self, 'age') is None:
                    return None
                return self.age > 21

            @is_above_21.expression
            def is_above_21(cls):
                return select([cls.age > 21]).as_scalar()

            def name_and_age(self):
                return "{0} (aged {1:d})".format(self.name, self.age)

            def first_computer(self):
                return sorted(self.computers, key=lambda k: k.name)[0]

        class LazyComputer(self.Base):
            __tablename__ = 'lazycomputer'
            id = Column(Integer, primary_key=True)
            name = Column(Unicode)
            ownerid = Column(Integer, ForeignKey('lazyperson.id'))
            owner = relationship('LazyPerson',
                                 backref=backref('computers', lazy='dynamic'))

        class LazyPerson(self.Base):
            __tablename__ = 'lazyperson'
            id = Column(Integer, primary_key=True)
            name = Column(Unicode)

        class User(self.Base):
            __tablename__ = 'user'
            id = Column(Integer, primary_key=True)
            email = Column(Unicode, primary_key=True)
            wakeup = Column(Time)

        class Planet(self.Base):
            __tablename__ = 'planet'
            name = Column(Unicode, primary_key=True)

        class Satellite(self.Base):
            __tablename__ = 'satellite'
            name = Column(Unicode, primary_key=True)
            period = Column(Interval, nullable=True)

        class Star(self.Base):
            __tablename__ = 'star'
            id = Column("star_id", Integer, primary_key=True)
            inception_time = Column(DateTime, nullable=True)

        class Vehicle(self.Base):
            __tablename__ = 'vehicle'
            uuid = Column(GUID, primary_key=True)

        class CarModel(self.Base):
            __tablename__ = 'car_model'
            id = Column(Integer, primary_key=True)
            name = Column(Unicode)
            seats = Column(Integer)

            manufacturer_id = Column(Integer,
                                     ForeignKey('car_manufacturer.id'))
            manufacturer = relationship('CarManufacturer')

        class CarManufacturer(self.Base):
            __tablename__ = 'car_manufacturer'
            id = Column(Integer, primary_key=True)
            name = Column(Unicode)
            models = relationship('CarModel')

        class Project(self.Base):
            __tablename__ = 'project'
            id = Column(Integer, primary_key=True)
            person_id = Column(Integer, ForeignKey('person.id'))
            person = relationship('Person',
                                  backref=backref('projects', lazy='dynamic'))

        class Proof(self.Base):
            __tablename__ = 'proof'
            id = Column(Integer, primary_key=True)
            project = relationship('Project', backref=backref('proofs',
                                                              lazy='dynamic'))
            project_id = Column(Integer, ForeignKey('project.id'))
            person = association_proxy('project', 'person')
            person_id = association_proxy('project', 'person_id')

        self.Person = Person
        self.Program = Program
        self.ComputerProgram = ComputerProgram
        self.LazyComputer = LazyComputer
        self.LazyPerson = LazyPerson
        self.User = User
        self.Computer = Computer
        self.Planet = Planet
        self.Satellite = Satellite
        self.Star = Star
        self.Vehicle = Vehicle
        self.CarManufacturer = CarManufacturer
        self.CarModel = CarModel
        self.Project = Project
        self.Proof = Proof
        self.Screen = Screen

        # create all the tables required for the models
        self.Base.metadata.create_all()

    def tearDown(self):
        """Drops all tables from the temporary database."""
        self.Base.metadata.drop_all()

class TestSupportPrefilled(TestSupport):
    """Base class for tests which use a database and have an
    :class:`flask_restless.APIManager` with a :class:`flask.Flask` app object.

    The test client for the :class:`flask.Flask` application is accessible to
    test functions at ``self.app`` and the :class:`flask_restless.APIManager`
    is accessible at ``self.manager``.

    The database will be prepopulated with five ``Person`` objects. The list of
    these objects can be accessed at ``self.people``.

    """

    def setUp(self):
        """Creates the database, the Flask application, and the APIManager."""
        # create the database
        super(TestSupportPrefilled, self).setUp()
        # create some people in the database for testing
        lincoln = self.Person(name=u'Lincoln', age=23, other=22,
                              birth_date=datetime.date(1900, 1, 2))
        mary = self.Person(name=u'Mary', age=19, other=19)
        lucy = self.Person(name=u'Lucy', age=25, other=20)
        katy = self.Person(name=u'Katy', age=7, other=10)
        john = self.Person(name=u'John', age=28, other=10)
        self.people = [lincoln, mary, lucy, katy, john]
        self.session.add_all(self.people)
        self.session.commit()


text:
<img src="https://raw.githubusercontent.com/Rodd8/Photocheap/master/src/logo.png" width="250">

# EOST Photocheap CC
Par __Emeline Ehles__ et __Robin Dell__.

Photocheap est une logiciel en C ayant pour but d'effectuer des traitements et des analyses sur des images BMP (24 bits uniquement)
- Negatif
- Saturation
- Nuances de gris
- Histogramme
- ...

## Utilisation

- gcc -o pc photocheap.c -lm
- Lancer l'executable ./pc
- Entrez le nom de l'image (si elle n'existe pas, le logiciel se ferme)
- Choisez la transformation a effectuer (chiffre de 1 a 8)
- Attendre, certaines opérations peuvent être longues
- Choisir si on veut continuer : 1 ou 0.

## Fonctions
### Manipulation
- [x] Créer une image BMP
- [x] Charger une image BMP
- [x] Sauvegarder une image BMP
- [X] Copier une image BMP

- [x] Récupérer les valeurs d'un pixel
- [x] Définir un pixel avec certaines valeurs
- [x] RGB2HSL
- [x] HSL2RGB

#### Créer une image BMP :
```C
BMP* newBMP(int largeur, int hauteur);
```
   Renvoit une structure BMP de la taille passée en paramètre.
   La structure contient une largeur (int), une hauteur (int) et un tableau de pixels (Pixel*)

#### Charger une image BMP
```C
BMP* loadBMP(const char* nomDeLimage);
```
   Charger une image bitmap de l'ordinateur dans le logiciel.
   Renvoit une structure BMP de la taille de l'image avec le tableau de pixels contenant les pixels de l'image passée en paramètre

#### Sauvegarder une image BMP
```C
int saveBMP(BMP* image, const char* nomDeLimage);
```
   Enregistre une structure BMP en un fichier bitmap.
   Remplit le _header_ et l'_infoheader_ avec toutes les valeurs necessaires (taille, nombre magique, palette, poids et octets ...)

#### Copier une image BMP
```C
BMP* copyBMP(BMP* bmp);
```
   Créer une copie de l'image passé en paramètre. Utile pour ne pas effectuer les modifications directement sur l'image d'origine.

#### Récupérer les valeurs d'un pixel
```C
Pixel getPixel(BMP* bmp, int i, int j);
```
   Revoit une structure Pixel contenant les valeurs RGB (3 unsigned char 0 -> 255) d'une structure BMP (_BMP* bmp_) aux coordonnées _int i_ et _int j_ passées en paramètres

#### Définir un pixel avec certaines valeurs
```C
void setPixel(BMP* bmp, int i, int j, Pixel p);
```
   Pose un pixel _p_ aux coordonnées _i_ et _j_ sur la structure _bmp_
   Le pixel _p_ est composé des composantes R, G et B.

#### RGB2HSL
```C
HSL RGB2HSL(Pixel p);
```
   Transforme les informations RGB d'un pixel en HSL (Hue, Saturation, Lightness)

#### HSL2RGB
```C
Pixel HSL2RGB(HSL hsl);
```
   Transforme les informations HSL d'un pixel en RGB pour les enregristrer dans l'image

### Modification
- [x] Nuance de gris
- [x] Negatif
- [x] Saturation
- [x] Contrastes
- [x] Colorisé une image noir et blanc (mode RGB, mode HSL, mode Mix);

#### Nuance de gris
```C
BMP* greyScale(BMP* bmp);
```
   Transforme l'image de départ _bmp_ en son équivalent en nuance de gris suivant la formule proposée par la CIE :
   `Gris = 0.2125 Rouge + 0.7154 Vert + 0.0721 Bleu`

#### Negatif
```C
BMP* invert(BMP* bmp);
```
   Transforme l'image de départ _bmp_ en son équivalent en negatif :
   `Negatif = 255 - Couleur`

#### Saturation
```C
BMP* saturation(BMP* bmp, int saturation);
```
   Modifie la saturation des couleurs de l'image de -100% a +100%

#### Contrastes
```C
BMP* constrast(BMP* bmp, int contrast);
```
   Change le constraste d'une image avec des valeurs entre -255 et +255

### Colorisation
```C
BMP* colorizeRGB(BMP* bmp);
BMP* colorizeHSL(BMP* bmp);
BMP* colorizeMIX(BMP* bmp);
```
   Colorise une image en nuance de gris grace a un tableau regroupant le triplet moyen (RGB ou HSL) pour chaque valeur de gris. Le tableau est basé sur une analyse via la fonction ```C meanColorBMP();``` sur un dossier contenant plusieur image d'un même theme.

### Analyse
- [x] Contour \(Sobel + Pewitt)
- [x] Histogramme \(Rouge, Vert, Bleu, Gris)
- [x] Couleur moyenne par teinte de gris
- [x] Couleur moyenne d'une image

#### Contour (Sobel + Pewitt)
```C
BMP* sobel(BMP* bmp);
BMP* pewitt(BMP* bmp);
```
   Renvoi une image représentant les contours d'une images obtenues via les opérateurs de Sobel ou de Pewitt

#### Histogramme
```C
void histogram(BMP* bmp);
```
   Créer 4 images BMP et un fichier texte représentant les histogrammes d'une image. Un histogramme par canal de couleur (Rouge, Vert et Bleu) et un histogramme de la luminosité de l'image (Gris). Plus la densité de pixels est forte vers la valeur 255, plus l'image est sombre; réciproquement, si la densité est forte vers la valeur 0, l'image est claire.

#### Couleur moyenne par teinte de gris
```C
int meanColorBMP(BMP* bmp);
```
  Créer un fichier texte de 6 colones et 256 lignes.

| GRIS |  RED | GREEN | BLUE | HUE | SATURATION | LIGHT |
| --- | --- | --- | --- | --- | --- | --- |
| 0 | moy rouge | moy vert | moy bleu | moy teinte | moy saturation | moy luminosité |
| ... | ... | ... | ... | ... | ... | ... |
| 255 | moy rouge | moy vert | moy bleu | moy teinte | moy saturation | moy luminosité |

#### Couleur moyenne d'une image
```C
float meanPixel(BMP* bmp);
```
   Renvoi la couleur moyenne d'une image, la moyenne des valeurs de tous les pixels.

### Outils
#### Concatenation de chaine
```C
char* concat(int count, ...);
```
   Fusionne 'count' chaine de caractères.
exemple : concat(2, "Bonjour ", "toto")
          concat(3, mot1, "_", mot2)
          ...

#### Nuance de gris
```C
float greyIt(Pixel p, int mode);
```
   Renvoi la nuance de gris associé a un triplet RGB.
mode = 0 -> formule du C.I.E
mode = 1 -> moyenne du triplet RGB

#### Entier vers Chaine
```C
char* toString(int a);
```
   Transforme un entier en chaine de caractères.

## License

MIT License.


text:
/* This file was generated by SableCC (http://www.sablecc.org/). */

package Syntax.node;

public abstract class PExpr extends Node
{
    // Empty body
}


text:
<?php

namespace app\commands;

use yii\console\Controller;

/**
 * This command echoes the first argument that you have entered.
 *
 * This command is provided as an example for you to learn how to create console commands.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class GenerateController extends Controller
{
    public function actionBooks() {
        $i = 0;
        $db = \Yii::$app->getDb();
        while( $i < 1000 ) {
            $date = date('Y-m-d H:i:s');
            $sql = "INSERT INTO books(name, date_create, date_update) VALUES('Книга #".mt_rand(10, 10000)."', '".$date."', '".$date."')";
            $db->createCommand($sql)->execute();
            $i++;
        }
    }
}


text:
[![Build Status](https://travis-ci.org/bahaagalal/terminal-parser.png?branch=master)](https://travis-ci.org/bahaagalal/terminal-parser)

A terminal utility that its sole objective is to parse terminal-like arguments.

Its functionality is super simple to describe.

It turns this `['--environment=development', '--mode=2']` to `{environment: 'development', 'mode': '2'}`

## How to use

Install from npm

```bash
npm install terminal-parser --save
```

Include it in your project

```js
var Terminal = require('terminal-parser');
```

Start parsing arguments

```js
var args = Terminal.parseArgs(['--environment=development', '--mode=2']);
```


text:
from sparc.cache import ICachableItem

class CachableSourceForDirectoryMixin(object):
    #implements(ICachableSource)
    #adapts(IDirectory)
    """implementers to set which interfaces should be filter for in the
    directory.  There must be an available adapter that will convert these
    object into a ICachableItem.

    There is a ICachableItem adapter for sparc.entity.IEntity objects available
    in the sparc.cache package.
    """
    interfaces = ()
    _key = 'id'

    def __init__(self, context):
        self.context = context

    def key(self):
        """Returns string identifier key that marks unique item entries (e.g.
        primary key fieldname)
        """
        return self._key

    def items(self):
        """Returns an iterable of available ICachableItem in the ICachableSource"""
        for item in self.context.values(interfaces=self.interfaces):
            yield ICachableItem(item)

    def getById(self, Id):
        """Returns ICachableItem that matches Id or None if not found"""
        items = list(self.context.search(Id, fields=(id,), interfaces=self.interfaces))
        if len > 1:
            raise LookupError('Did not expect to find more than one search result for given Id')
        return items[0] if items else None

    def first(self):
        """Returns the first ICachableItem available in the ICachableSource or None"""
        items = self.items()
        return items.next()


text:
#include <aws/codeguruprofiler/model/Recommendation.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace CodeGuruProfiler
{
namespace Model
{

Recommendation::Recommendation() :
    m_allMatchesCount(0),
    m_allMatchesCountHasBeenSet(false),
    m_allMatchesSum(0.0),
    m_allMatchesSumHasBeenSet(false),
    m_endTimeHasBeenSet(false),
    m_patternHasBeenSet(false),
    m_startTimeHasBeenSet(false),
    m_topMatchesHasBeenSet(false)
{
}

Recommendation::Recommendation(JsonView jsonValue) :
    m_allMatchesCount(0),
    m_allMatchesCountHasBeenSet(false),
    m_allMatchesSum(0.0),
    m_allMatchesSumHasBeenSet(false),
    m_endTimeHasBeenSet(false),
    m_patternHasBeenSet(false),
    m_startTimeHasBeenSet(false),
    m_topMatchesHasBeenSet(false)
{
  *this = jsonValue;
}

Recommendation& Recommendation::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("allMatchesCount"))
  {
    m_allMatchesCount = jsonValue.GetInteger("allMatchesCount");

    m_allMatchesCountHasBeenSet = true;
  }

  if(jsonValue.ValueExists("allMatchesSum"))
  {
    m_allMatchesSum = jsonValue.GetDouble("allMatchesSum");

    m_allMatchesSumHasBeenSet = true;
  }

  if(jsonValue.ValueExists("endTime"))
  {
    m_endTime = jsonValue.GetString("endTime");

    m_endTimeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("pattern"))
  {
    m_pattern = jsonValue.GetObject("pattern");

    m_patternHasBeenSet = true;
  }

  if(jsonValue.ValueExists("startTime"))
  {
    m_startTime = jsonValue.GetString("startTime");

    m_startTimeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("topMatches"))
  {
    Aws::Utils::Array<JsonView> topMatchesJsonList = jsonValue.GetArray("topMatches");
    for(unsigned topMatchesIndex = 0; topMatchesIndex < topMatchesJsonList.GetLength(); ++topMatchesIndex)
    {
      m_topMatches.push_back(topMatchesJsonList[topMatchesIndex].AsObject());
    }
    m_topMatchesHasBeenSet = true;
  }

  return *this;
}

JsonValue Recommendation::Jsonize() const
{
  JsonValue payload;

  if(m_allMatchesCountHasBeenSet)
  {
   payload.WithInteger("allMatchesCount", m_allMatchesCount);

  }

  if(m_allMatchesSumHasBeenSet)
  {
   payload.WithDouble("allMatchesSum", m_allMatchesSum);

  }

  if(m_endTimeHasBeenSet)
  {
   payload.WithString("endTime", m_endTime.ToGmtString(Aws::Utils::DateFormat::ISO_8601));
  }

  if(m_patternHasBeenSet)
  {
   payload.WithObject("pattern", m_pattern.Jsonize());

  }

  if(m_startTimeHasBeenSet)
  {
   payload.WithString("startTime", m_startTime.ToGmtString(Aws::Utils::DateFormat::ISO_8601));
  }

  if(m_topMatchesHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> topMatchesJsonList(m_topMatches.size());
   for(unsigned topMatchesIndex = 0; topMatchesIndex < topMatchesJsonList.GetLength(); ++topMatchesIndex)
   {
     topMatchesJsonList[topMatchesIndex].AsObject(m_topMatches[topMatchesIndex].Jsonize());
   }
   payload.WithArray("topMatches", std::move(topMatchesJsonList));

  }

  return payload;
}

} // namespace Model
} // namespace CodeGuruProfiler
} // namespace Aws


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 5: 840 (1887)

#### Original name
Agaricus sticticus Fr.

### Remarks
null


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Arch. Jard. Bot. Rio de Janeiro 12:7, t. 1, 5. 1952

#### Original name
null

### Remarks
null


text:
<?php

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Factory\AppFactory;
use Twilio\Rest\Client as TwilioClient;
use Twilio\TwiML\VoiceResponse;
use Twilio\TwiML\MessagingResponse;

// Create App
$app = AppFactory::create();

// Display errors
$app->addErrorMiddleware(true, true, true);

$twilioAccountSid = getenv('TWILIO_ACCOUNT_SID');
$twilioAuthToken = getenv('TWILIO_AUTH_TOKEN');
$twilioNumber = getenv('TWILIO_FROM_NUMBER');

# [START gae_flex_twilio_receive_call]
/***
 * Answers a call and replies with a simple greeting.
 */
$app->post('/call/receive', function (Request $request, Response $response) {
    $twiml = new VoiceResponse();
    $twiml->say('Hello from Twilio!');
    $response->getBody()->write((string) $twiml);
    return $response
        ->withHeader('Content-Type', 'application/xml');
});
# [END gae_flex_twilio_receive_call]

# [START gae_flex_twilio_send_sms]
/***
 * Send an sms.
 */
$app->post('/sms/send', function (
    Request $request,
    Response $response
) use ($twilioAccountSid, $twilioAuthToken, $twilioNumber) {
    $twilio = new TwilioClient(
        $twilioAccountSid, // Your Twilio Account SID
        $twilioAuthToken   // Your Twilio Auth Token
    );
    parse_str((string) $request->getBody(), $postData);
    $sms = $twilio->messages->create(
        $postData['to'] ?? '', // to this number
        [
            'from' => $twilioNumber,   // from this number
            'body' => 'Hello from Twilio!',
        ]
    );
    $response->getBody()->write(
        sprintf('Message ID: %s, Message Body: %s', $sms->sid, $sms->body)
    );
    return $response;
});
# [END gae_flex_twilio_send_sms]

# [START gae_flex_twilio_receive_sms]
/***
 * Receive an sms.
 */
$app->post('/sms/receive', function (Request $request, Response $response) {
    parse_str((string) $request->getBody(), $postData);
    $sender = $postData['From'] ?? '';
    $body = $postData['Body'] ?? '';
    $message = "Hello, $sender, you said: $body";
    $twiml = new MessagingResponse();
    $twiml->message($message);
    $response->getBody()->write((string) $twiml);
    return $response
        ->withHeader('Content-Type', 'application/xml');
});
# [END gae_flex_twilio_receive_sms]

return $app;


text:
import { jQuery, jq, assert, JQStatic, toTextContentArray } from '../utils.js';
import '../../methods/replaceAll.js';
import '../../methods/children.js';

const test = ($: JQStatic, type: string): void => {
  describe(`${type} - .replaceAll`, () => {
    beforeEach(() => {
      document.querySelector('#frame')!.innerHTML = `

Hello

And

Goodbye

  test
  yyy

`;
    });

    it('.replaceAll(target)', () => {
      // 用新元素替换一个现有元素
      const $result = $('
new1

new2
').replaceAll('.second');
      assert.sameOrderedMembers(toTextContentArray($result), ['new1', 'new2']);

      const $children = $('.container').children();
      assert.sameOrderedMembers(toTextContentArray($children), [
        'Hello',
        'new1',
        'new2',
        'Goodbye',
        'test',
        'yyy',
      ]);
    });

    it('.replaceAll(target)', () => {
      // 用新元素替换多个现有元素
      const $result = $('
new1

new2
').replaceAll('.other');
      assert.sameOrderedMembers(toTextContentArray($result), [
        'new1',
        'new2',
        'new1',
        'new2',
      ]);

      const $children = $('.container').children();
      assert.sameOrderedMembers(toTextContentArray($children), [
        'Hello',
        'And',
        'Goodbye',
        'new1',
        'new2',
        'new1',
        'new2',
      ]);
    });

    it('.replaceAll(target)', () => {
      // 用已有元素替换一个现有元素
      const $result = $('.third').replaceAll('.other');
      assert.sameOrderedMembers(toTextContentArray($result), [
        'Goodbye',
        'Goodbye',
      ]);

      const $children = $('.container').children();
      assert.sameOrderedMembers(toTextContentArray($children), [
        'Hello',
        'And',
        'Goodbye',
        'Goodbye',
      ]);
    });

    it('.replaceAll(target)', () => {
      // 用多个已有元素替换现有元素
      const $result = $('.other').replaceAll('.inner');
      assert.sameOrderedMembers(toTextContentArray($result), [
        'test',
        'yyy',
        'test',
        'yyy',
        'test',
        'yyy',
      ]);

      const $children = $('.container').children();
      assert.sameOrderedMembers(toTextContentArray($children), [
        'test',
        'yyy',
        'test',
        'yyy',
        'test',
        'yyy',
      ]);
    });
  });
};

test(jq, 'jq');
test(jQuery as unknown as JQStatic, 'jQuery');


text:
from __future__ import absolute_import

from collections import OrderedDict

import logging

from tabulate import tabulate

from numpy import asarray
from numpy import sqrt
from numpy import ones

from numpy_sugar.linalg import economic_svd

from ...tool.kinship import gower_normalization
from ...tool.normalize import stdnorm
from limix_inference.lmm import SlowLMM
from limix_inference.mean import LinearMean
from limix_inference.cov import LinearCov
from limix_inference.cov import SumCov

class InputInfo(object):
    def __init__(self):
        self.background_markers_user_provided = None
        self.nconst_background_markers = None
        self.covariates_user_provided = None
        self.nconst_markers = None
        self.kinship_rank = None
        self.candidate_nmarkers = None
        self.phenotype_info = None
        self.background_nmarkers = None

        self.effective_X = None
        self.effective_G = None
        self.effective_K = None

        self.S = None
        self.Q = None

    def __str__(self):
        t = []
        t += self.phenotype_info.get_info()
        if self.background_markers_user_provided:
            t.append(['Background data', 'provided via markers'])
            t.append(['# background markers', self.background_nmarkers])
            t.append([
                '# const background markers', self.nconst_background_markers
            ])
        else:
            t.append(['Background data', 'provided via Kinship matrix'])

        t.append(['Kinship diagonal mean', self.kinship_diagonal_mean])

        if self.covariates_user_provided:
            t.append(['Covariates', 'provided by user'])
        else:
            t.append(['Covariates', 'a single column of ones'])

        t.append(['Kinship rank', self.kinship_rank])
        t.append(['# candidate markers', self.candidate_nmarkers])
        return tabulate(t, tablefmt='plain')

def tuple_it(GK):
    r = []
    for GKi in GK:
        if isinstance(GKi, tuple):
            r.append(GKi)
        else:
            r.append((GKi, False))
    return tuple(r)

def normalize_covariance_list(GK):
    if not isinstance(GK, (list, tuple, dict)):
        GK = (GK, )

    GK = tuple_it(GK)

    if not isinstance(GK, dict):
        GK = [('K%d' % i, GK[i]) for i in range(len(GK))]
        GK = OrderedDict(GK)

    return GK

def preprocess(GK, covariates, input_info):
    logger = logging.getLogger(__name__)

    input_info.covariates_user_provided = covariates is not None

    for (name, GKi) in iter(GK.items()):
        if GKi[1]:
            logger.info('Covariace matrix normalization on %s.', name)
            K = asarray(GKi[0], dtype=float)
            K = gower_normalization(K)
            GK[name] = (K, True)
        else:
            logger.info('Genetic markers normalization on %s.', name)
            G = asarray(GKi[0], dtype=float)
            G = stdnorm(G, 0)
            G /= sqrt(G.shape[1])
            GK[name] = (G, False)

    input_info.effective_GK = GK

def normal_decomposition(y, GK, covariates=None, progress=True):
    logger = logging.getLogger(__name__)
    logger.info('Normal variance decomposition scan has started.')
    y = asarray(y, dtype=float)

    ii = InputInfo()
    # ii.phenotype_info = NormalPhenotypeInfo(y)

    GK = normalize_covariance_list(GK)
    preprocess(GK, covariates, ii)

    vd = NormalVarDec(
        y, ii.effective_GK, covariates=covariates, progress=progress)

    vd.learn()
    # genetic_preprocess(X, G, K, covariates, ii)
    #
    # lrt = NormalLRT(y, ii.Q[0], ii.Q[1], ii.S[0], covariates=covariates,
    #                 progress=progress)
    # lrt.candidate_markers = ii.effective_X
    # lrt.pvals()
    # return lrt
    return vd

def _offset_covariate(covariates, n):
    return ones((n, 1)) if covariates is None else covariates

class VarDec(object):
    def __init__(self, K, covariates=None, progress=True):
        self._logger = logging.getLogger(__name__)

        self._progress = progress
        self._X = None
        self._K = K
        n = list(K.items())[0][1][0].shape[0]
        self._covariates = _offset_covariate(covariates, n)

    def learn(self):
        self._logger.info('Variance decomposition computation: has started.')
        self._learn(progress=False)

class NormalVarDec(VarDec):
    def __init__(self, y, K, covariates=None, progress=True):
        super(NormalVarDec, self).__init__(
            K, covariates=covariates, progress=progress)
        self._y = y

        mean = LinearMean(self._covariates.shape[1])
        mean.set_data(self._covariates)

        covs = []
        for Ki in iter(K.items()):
            c = LinearCov()
            if Ki[1][1]:
                G = economic_svd(Ki[1][0])
            else:
                G = Ki[1][0]

            c.set_data((G, G))
            covs.append(c)

        cov = SumCov(covs)

        self._lmm = SlowLMM(y, mean, cov)

    def _learn(self, progress):
        self._lmm.feed().maximize()


text:
package com.github.anba.es6draft.runtime.internal;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 *
 */
public final class CompoundIterator<E> implements Iterator<E> {
    private final Iterator<? extends E> firstIterator;
    private final Iterator<? extends E> secondIterator;

    public CompoundIterator(Iterator<? extends E> firstIterator, Iterator<? extends E> secondIterator) {
        this.firstIterator = firstIterator;
        this.secondIterator = secondIterator;
    }

    @Override
    public boolean hasNext() {
        return firstIterator.hasNext() || secondIterator.hasNext();
    }

    @Override
    public E next() {
        if (firstIterator.hasNext()) {
            return firstIterator.next();
        }
        if (secondIterator.hasNext()) {
            return secondIterator.next();
        }
        throw new NoSuchElementException();
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('news', '0007_auto_20170923_2259'),
    ]

    operations = [
        migrations.AlterField(
            model_name='event',
            name='description',
            field=models.TextField(blank=True, null=True, verbose_name='description'),
        ),
        migrations.AlterField(
            model_name='news',
            name='description',
            field=models.TextField(blank=True, null=True, verbose_name='description'),
        ),
    ]


text:
<?xml version="1.0" encoding="utf-8"?>
<PRONOM-Report xmlns="http://pronom.nationalarchives.gov.uk">
  <report_format_detail>
    <FileFormat>
      <FormatID>1485</FormatID>
      <FormatName>Vectorworks</FormatName>
      <FormatVersion>2010</FormatVersion>
      <FormatAliases>
      </FormatAliases>
      <FormatFamilies>
      </FormatFamilies>
      <FormatTypes>Model</FormatTypes>
      <FormatDisclosure>
      </FormatDisclosure>
      <FormatDescription>Vectorworks is a proprietary Computer Aided Design and Building Information Modelling software program for both Mac and Windows operating systems. This software was previously called MiniCAD from 1985 - 1998 and  Vectorworks from 1999.</FormatDescription>
      <BinaryFileFormat>
      </BinaryFileFormat>
      <ByteOrders>
      </ByteOrders>
      <ReleaseDate>
      </ReleaseDate>
      <WithdrawnDate>
      </WithdrawnDate>
      <ProvenanceSourceID>1</ProvenanceSourceID>
      <ProvenanceName>Digital Preservation Department / The National Archives</ProvenanceName>
      <ProvenanceSourceDate>06 Nov 2014</ProvenanceSourceDate>
      <ProvenanceDescription>
      </ProvenanceDescription>
      <LastUpdatedDate>06 Nov 2014</LastUpdatedDate>
      <FormatNote>
      </FormatNote>
      <FormatRisk>
      </FormatRisk>
      <TechnicalEnvironment>
      </TechnicalEnvironment>
      <FileFormatIdentifier>
        <Identifier>application/vnd.vectorworks</Identifier>
        <IdentifierType>MIME</IdentifierType>
      </FileFormatIdentifier>
      <FileFormatIdentifier>
        <Identifier>fmt/686</Identifier>
        <IdentifierType>PUID</IdentifierType>
      </FileFormatIdentifier>
      <Developers>
        <DeveloperID>211</DeveloperID>
        <DeveloperName>Nemetschek Vectorworks</DeveloperName>
        <OrganisationName>Nemetschek Vectorworks</OrganisationName>
        <DeveloperCompoundName>Nemetschek Vectorworks / Nemetschek Vectorworks</DeveloperCompoundName>
      </Developers>
      <Support>
        <SupportID>211</SupportID>
        <SupportName>Nemetschek Vectorworks</SupportName>
        <OrganisationName>Nemetschek Vectorworks</OrganisationName>
        <SupportCompoundName>Nemetschek Vectorworks / Nemetschek Vectorworks</SupportCompoundName>
      </Support>
      <ExternalSignature>
        <ExternalSignatureID>1555</ExternalSignatureID>
        <Signature>vwx</Signature>
        <SignatureType>File extension</SignatureType>
      </ExternalSignature>
      <InternalSignature>
        <SignatureID>1013</SignatureID>
        <SignatureName>Vectorworks 2010</SignatureName>
        <SignatureNote>BOF: …X.......". VW15.0{0-3}VW15.0{0-29}VectorWorks</SignatureNote>
        <ByteSequence>
          <ByteSequenceID>1255</ByteSequenceID>
          <PositionType>Absolute from BOF</PositionType>
          <Offset>0</Offset>
          <MaxOffset>0</MaxOffset>
          <IndirectOffsetLocation>
          </IndirectOffsetLocation>
          <IndirectOffsetLength>
          </IndirectOffsetLength>
          <Endianness>
          </Endianness>
          <ByteSequenceValue>0000085800000000000000940020565731352E30{0-3}565731352E30{0-29}566563746F72576F726B73</ByteSequenceValue>
        </ByteSequence>
      </InternalSignature>
      <RelatedFormat>
        <RelationshipType>Is subsequent version of</RelationshipType>
        <RelatedFormatID>1238</RelatedFormatID>
        <RelatedFormatName>VectorWorks</RelatedFormatName>
        <RelatedFormatVersion>2009</RelatedFormatVersion>
      </RelatedFormat>
    </FileFormat>
    <SearchCriteria>Criteria</SearchCriteria>
  </report_format_detail>
</PRONOM-Report>


text:
require 'rainbow'
require 'rainbow/ext/string'
require 'crabfarm/support/webdriver_factory'
require 'crabfarm/crabtrap_runner'

module Crabfarm
  module Modes
    module Recorder
      module Memento
        extend self

        def start(_target, _replay=false)
          return puts "Must provide a recording target" unless _target.is_a? String

          target_path = Utils::Resolve.memento_path _target
          return puts "Memento file does not exist: #{target_path}" if _replay and not File.exist? target_path

          start_crabtrap _replay, target_path

          begin
            driver = build_driver Crabfarm.config.recorder_driver
            return puts "Invalid recorder_driver name '#{Crabfarm.config.recorder_driver}'" if driver.nil?

            begin
              puts "Press Ctrl-C or close browser to stop #{_replay ? 'playback' : 'capturing'}."
              loop do
                driver.window_handle
                sleep 1.0
              end
            rescue SystemExit, Interrupt
              # Nothing for now
            rescue Exception => e
              # Nothing for now
              # puts e.class.to_s
              # puts e.backtrace
            end

            puts "Releasing crawling context".color(:green)
            driver.quit rescue nil
          ensure
            crabtrap.stop
          end
        end

      private

        def start_crabtrap(_replay, _target_path)
          crabtrap_config = Crabfarm.config.crabtrap_config
          crabtrap_config[:mode] = _replay ? :replay : :capture
          crabtrap_config[:port] = Utils::PortDiscovery.find_available_port
          crabtrap_config[:bucket_path] = _target_path

          @crabtrap = CrabtrapRunner.new crabtrap_config
          @crabtrap.start
        end

        def crabtrap
          @crabtrap
        end

        def build_driver(_name)
          case _name.to_sym
          when :firefox
            Crabfarm::Support::WebdriverFactory.build_firefox_driver driver_config
          when :chrome
            Crabfarm::Support::WebdriverFactory.build_chrome_driver driver_config
          else return nil end
        end

        def driver_config
          {
            proxy: "127.0.0.1:#{crabtrap.port}",
            window_width: Crabfarm.config.webdriver_window_width,
            window_height: Crabfarm.config.webdriver_window_height
          }
        end

      end
    end
  end
end


text:
/*
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

#include "stdafx.h"

#include "MediaFormatAudio.h"

using namespace Nequeo::Net::PjSip;

/// <summary>
/// This structure describe detail information about an audio media.
/// </summary>
MediaFormatAudio::MediaFormatAudio()
{
}

/// <summary>
/// Gets or sets the audio clock rate in samples or Hz.
/// </summary>
unsigned MediaFormatAudio::ClockRate::get()
{
	return _clockRate;
}

/// <summary>
/// Gets or sets the audio clock rate in samples or Hz.
/// </summary>
void MediaFormatAudio::ClockRate::set(unsigned value)
{
	_clockRate = value;
}

/// <summary>
/// Gets or sets the number of channels.
/// </summary>
unsigned MediaFormatAudio::ChannelCount::get()
{
	return _channelCount;
}

/// <summary>
/// Gets or sets the number of channels.
/// </summary>
void MediaFormatAudio::ChannelCount::set(unsigned value)
{
	_channelCount = value;
}

/// <summary>
/// Gets or sets the frame interval, in microseconds.
/// </summary>
unsigned MediaFormatAudio::FrameTimeUsec::get()
{
	return _frameTimeUsec;
}

/// <summary>
/// Gets or sets the frame interval, in microseconds.
/// </summary>
void MediaFormatAudio::FrameTimeUsec::set(unsigned value)
{
	_frameTimeUsec = value;
}

/// <summary>
/// Gets or sets the number of bits per sample.
/// </summary>
unsigned MediaFormatAudio::BitsPerSample::get()
{
	return _bitsPerSample;
}

/// <summary>
/// Gets or sets the number of bits per sample.
/// </summary>
void MediaFormatAudio::BitsPerSample::set(unsigned value)
{
	_bitsPerSample = value;
}

/// <summary>
/// Gets or sets the average bitrate.
/// </summary>
unsigned MediaFormatAudio::AvgBps::get()
{
	return _avgBps;
}

/// <summary>
/// Gets or sets the average bitrate.
/// </summary>
void MediaFormatAudio::AvgBps::set(unsigned value)
{
	_avgBps = value;
}

/// <summary>
/// Gets or sets the maximum bitrate.
/// </summary>
unsigned MediaFormatAudio::MaxBps::get()
{
	return _maxBps;
}

/// <summary>
/// Gets or sets the maximum bitrate.
/// </summary>
void MediaFormatAudio::MaxBps::set(unsigned value)
{
	_maxBps = value;
}


text:
package org.apache.hadoop.hdfs.security.token.block;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.EnumSet;

import org.apache.hadoop.hdfs.security.token.block.BlockTokenSecretManager.AccessMode;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableUtils;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.TokenIdentifier;

public class BlockTokenIdentifier extends TokenIdentifier {
  static final Text KIND_NAME = new Text("HDFS_BLOCK_TOKEN");

  private long expiryDate;
  private int keyId;
  private String userId;
  private long blockId;
  private EnumSet<AccessMode> modes;

  private byte [] cache;

  public BlockTokenIdentifier() {
    this(null, 0l, EnumSet.noneOf(AccessMode.class));
  }

  public BlockTokenIdentifier(String userId, long blockId,
      EnumSet<AccessMode> modes) {
    this.cache = null;
    this.userId = userId;
    this.blockId  = blockId;
    this.modes = modes == null ? EnumSet.noneOf(AccessMode.class) : modes;
  }

  @Override
  public Text getKind() {
    return KIND_NAME;
  }

  @Override
  public UserGroupInformation getUser() {
    if (userId == null || "".equals(userId)) {
      return UserGroupInformation.createRemoteUser(Long.toString(blockId));
    }
    return UserGroupInformation.createRemoteUser(userId);
  }

  public long getExpiryDate() {
    return expiryDate;
  }

  public void setExpiryDate(long expiryDate) {
    cache = null;
    this.expiryDate = expiryDate;
  }

  public int getKeyId() {
    return this.keyId;
  }

  public void setKeyId(int keyId) {
    cache = null;
    this.keyId = keyId;
  }

  public String getUserId() {
    return userId;
  }

  public long getBlockId() {
    return blockId;
  }

  public EnumSet<AccessMode> getAccessModes() {
    return modes;
  }

  @Override
  public String toString() {
    return "block_token_identifier (expiryDate=" + this.getExpiryDate()
        + ", keyId=" + this.getKeyId() + ", userId=" + this.getUserId()
        + ", blockIds=" + blockId + ", access modes="
        + this.getAccessModes() + ")";
  }

  static boolean isEqual(Object a, Object b) {
    return a == null ? b == null : a.equals(b);
  }

  /** {@inheritDoc} */
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj instanceof BlockTokenIdentifier) {
      BlockTokenIdentifier that = (BlockTokenIdentifier) obj;
      return this.expiryDate == that.expiryDate && this.keyId == that.keyId
          && isEqual(this.userId, that.userId)
          && this.blockId == that.blockId
          && isEqual(this.modes, that.modes);
    }
    return false;
  }

  /** {@inheritDoc} */
  public int hashCode() {
    return (int) expiryDate ^ keyId ^ (int)blockId ^ modes.hashCode()
        ^ (userId == null ? 0 : userId.hashCode());
  }

  public void readFields(DataInput in) throws IOException {
    cache = null;
    expiryDate = WritableUtils.readVLong(in);
    keyId = WritableUtils.readVInt(in);
    userId = WritableUtils.readString(in);
    blockId = WritableUtils.readVLong(in);
    int length = WritableUtils.readVInt(in);
    for (int i = 0; i < length; i++) {
      modes.add(WritableUtils.readEnum(in, AccessMode.class));
    }
  }

  public void write(DataOutput out) throws IOException {
    WritableUtils.writeVLong(out, expiryDate);
    WritableUtils.writeVInt(out, keyId);
    WritableUtils.writeString(out, userId);
    WritableUtils.writeVLong(out, blockId);
    WritableUtils.writeVInt(out, modes.size());
    for (AccessMode aMode : modes) {
      WritableUtils.writeEnum(out, aMode);
    }
  }

  @Override
  public byte[] getBytes() {
    if(cache == null) cache = super.getBytes();

    return cache;
  }
}


text:
/*
Script: Collapsable.js
	Enables a dom element to, when clicked, hide or show (it toggles) another dom element. Kind of an Accordion for one item.

License:
	http://www.clientcide.com/wiki/cnet-libraries#license
*/
var Collapsable = new Class({
	Extends: Fx.Reveal,
	initialize: function(clicker, section, options) {
		this.clicker = document.id(clicker);
		this.section = document.id(section);
		this.parent(this.section, options);
		this.addEvents();
	},
	addEvents: function(){
		this.clicker.addEvent('click', this.toggle.bind(this));
	}
});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta name="google-site-verification" content="JEiMBjgvX1yE8Sx9S-0eAmQjvEF-qZM5BS2yrv0drAw" />
<title>Computer & Information Sciences at UD: Research - Laboratories - Artificial Intelligence</title>

Research

Laboratories - Artificial Intelligence

Learn about Artificial Intelligence Research

Human Language Technologies Laboratory

100 Elkton Road, Professors Sandra Carberry and Kathy McCoy.

The Human Language Technology Laboratory is an umbrella for two language-related laboratories: disabilities technology and discourse. The laboratory closely collaborates with the Statistical Information Retrieval Laboratory and the Text Mining Laboratory.

The Disabilities Technology Laboratory, directed by Kathy McCoy, develops intelligent interfaces for people with disabilities that affect their ability to communicate. The ICICLE System is an intelligent English grammar checker and tutor for people who are deaf. Other projects assist people who have special communication needs. We make "talking with" a computer faster and more natural. Another project is to help a person who has visual impairments "scan" a text to find the area relevant to answering a question.

The Discourse Laboratory, under the direction of Sandra Carberry, addresses problems related to discourse and dialogue. The Graphs project treats information graphics (bar charts, line graphs, etc.) as a form of discourse with a communicative goal. We are applying language understanding and generation techniques to index, store, and retrieve graphics from a digital library, to develop an interactive dialogue system that conveys the content of graphics via speech to individuals with sight impairments, and to develop an interactive graph design assistant that will critique graphs with the objective of improving them so that they achieve their communicative goal. Current collaborators include Dr. Stephanie Elzer (Millersville University), Dr. Dan Chester, and graduate students.

Statistical Information Retrieval Laboratory

77/79 East Delaware Ave, Professor Ben Carterette.

The Statistical Information Retrieval Laboratory pursues novel models of information organization, storage, access, retrieval, and integration using statistical and information-theoretic approaches. One of the key problems in developing such models is that optimizing and evaluating their utility requires human input. We aim to minimize the human cost, or to accomplish much more with an allotted cost, thereby allowing research and development to proceed much faster.

Multi Agent Systems Laboratory (MAS Lab)

447 Smith Hall, Professor Keith Decker.

An agent is a computer system capable of flexible, autonomous action in dynamic multi-agent environments. The success of the Internet has shown that computing is no longer only about fast numerical calculation, or isolated information processing. It is now also about interaction and coordination amongst machines, and between machines and people. The MAS laboratory focuses on the science of coordination in applications ranging from distributed energy management and emergency response support to scientific information gathering.

VIMS Vision Laboratory

212 Smith Hall, Professor Chandra Kambhametu.

VIMS (Video/Image Modeling and Synthesis) Lab encompasses research in areas related to computer vision and graphics. Our current research topics include camera systems, structure and motion recovery, stereo vision, facial image analysis, medical image analysis, object recognition and scene understanding, scientific visualization. Work done at VIMS explores solutions to challenging real-world problems such as Arctic ice motion and thickness studies, medical diagnosis and assistive robotics.

Text Mining Laboratory

102 Smith Hall, Professor Vijay Shanker.

The Text Mining Laboratory, directed by Vijay Shanker, is concerned with the development of language technology algorithms to assist scientists to rapidly access relevant information from research literature. Projects include the extraction of targeted information, retrieval of relevant textual passages, and assistance in the knowledge discovery process. A related project involves rapid adaptation of language processing tools that were developed for a general domain to be used in a specific domain. A third project involves multi-disciplinary effort that integrates natural language cues found in large software programs and program analysis for multiple software development and maintenance tasks.


text:
package alg

// Histogram handling and pretty printing.
// This originated in pbflint, but it turns out to be generally useful
// for debugging and gathering quick statistics.

import (
	"fmt"
	"sort"
)

type Histogram struct {
	Name string
	Data map[string] int
}

// Interface for sorting

type Sample struct {
	Frequency int
	Name      string
}

type Samples []Sample

func (s Samples) Len() int {
	return len(s)
}

func (s Samples) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s Samples) Less(i, j int) bool {
	// Sort in descending order.
	return s[j].Frequency < s[i].Frequency
}

func NewHistogram(name string) *Histogram {
	return &Histogram{
		Name: name,
		Data: map[string] int {},
	}
}

func (h *Histogram) Add(sample string) {
	if _, ok := h.Data[sample]; ok {
		h.Data[sample]++
	} else {
		h.Data[sample] = 1
	}
}

func (h *Histogram) Samples() Samples {
	var s Samples = make([]Sample, 0)
	for key, frequency := range h.Data {
		s = append(s, Sample{frequency, key})
	}
	sort.Sort(s)
	return s
}

func (h *Histogram) Print() {
	fmt.Printf("Histogram for %s:\n", h.Name)
	total := 0
	for _, frequency := range h.Data {
		total += frequency
	}
	fmt.Printf(" - Sample Count: %d\n", total)
	fmt.Printf("=========================\n")
	samples := h.Samples()
	maxLen  := 1
	for _, sample := range samples {
		if len(sample.Name) > maxLen {
			maxLen = len(sample.Name)
		}
	}
	format := fmt.Sprintf(" %%%ds: %%d\n", maxLen)
	for _, sample := range samples {
		key := sample.Name
		frequency := sample.Frequency
		fmt.Printf(format, key, frequency)
	}
}


text:
int
pthread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void))
{
	return 0;
}


text:
<DOCTYPE! html>

	<title>Week 3 Group Project Reflections</title>
	<link rel="stylesheet" href="stylesheets/group_project.css">
	<link href='http://fonts.googleapis.com/css?family=Black+Ops+One' rel='stylesheet' type='text/css'>

Week 3 Group Project Reflections

Treehouse

CodeAcademy

W3Schools

Relaxation

A.  What was this experience like?

I found it to be quite different not having a finger in each piece of the pie.  It was mostly a relief knowing that I was working this out with others and that I had a very specific part of the puzzle.

B.  Was your group successful in passing the tests?

We were successful.  Still awaiting the last step in the sequence, but time draws nigh.

C.  What did you learn about writing user stories, pseudocoding, writing code, refactoring, etc.?

The code that was handed to me was already very well written.  There were only a couple very minor syntax issues.

I enjoyed writing the user stories by interpreting the purpose of the code and its output.

1.  What parts of your strategy worked? What problems did you face?

I moved information through the code to see if it worked and then looked for any ways to reduce the amount of code.  This seemed to really make me productive.

2.  What questions did you have while coding? What resources did you find to help you answer them?

I really didn't have any questions other than reading through the code and making sure that it worked and looking for logical repeats of code.

3.  What concepts are you having trouble with, or did you just figure something out? If so, what?

This process did not seem too difficult.  I feel like I was successful.

4.  Did you learn any new skills or tricks?

I felt more that skills I have and knowledge I have was solidified.

5.  How confident are you with each of the Learning Competencies?

I am quite confident of this portion of JavaScript.

6.  Which parts of the challenge did you enjoy?

I really enjoyed looking through the code to see if it worked and to look for places to reduce/refactor.  I also enjoyed writing the user story.

7.  Which parts of the challenge did you find tedious?

I did not find any of it tedious.

2014, Adverture Sundays SSR *


text:
#include "tensorflow/compiler/jit/xla_compilation_cache.h"

#include "tensorflow/compiler/jit/flags.h"
#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/xla/client/client_library.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"

namespace tensorflow {
namespace {

using SignatureHash = XlaCompilationCache::Signature::Hash;

TEST(XlaCompilationCacheTest, SignatureEquality) {
  NameAttrList fn;
  fn.set_name("afunction");
  std::vector<XlaCompiler::Argument> args(1);
  args[0].kind = XlaCompiler::Argument::kConstant;
  args[0].type = DT_INT32;
  args[0].shape = TensorShape({4, 0});
  args[0].constant_value = Tensor(DT_INT32, {4, 0});
  TF_ASSERT_OK_AND_ASSIGN(XlaCompilationCache::Signature s1,
                          XlaCompilationCache::BuildSignature(fn, args));

  args[0].type = DT_FLOAT;
  args[0].constant_value = Tensor(DT_FLOAT, {4, 0});
  TF_ASSERT_OK_AND_ASSIGN(XlaCompilationCache::Signature s2,
                          XlaCompilationCache::BuildSignature(fn, args));

  args[0].shape = TensorShape({0, 4});
  args[0].constant_value = Tensor(DT_FLOAT, {0, 4});
  TF_ASSERT_OK_AND_ASSIGN(XlaCompilationCache::Signature s3,
                          XlaCompilationCache::BuildSignature(fn, args));

  std::vector<XlaCompilationCache::Signature> signatures = {s1, s2, s3};
  for (int i = 0; i < signatures.size(); ++i) {
    for (int j = 0; j < signatures.size(); ++j) {
      EXPECT_EQ(i == j, signatures[i] == signatures[j])
          << "s1: " << signatures[i].HumanString() << "\n"
          << "s2: " << signatures[j].HumanString();
      EXPECT_EQ(i == j,
                signatures[i].HumanString() == signatures[j].HumanString())
          << "s1: " << signatures[i].HumanString() << "\n"
          << "s2: " << signatures[j].HumanString();
      EXPECT_EQ(i == j, SignatureHash()(signatures[i]) ==
                            SignatureHash()(signatures[j]))
          << "s1: " << signatures[i].HumanString() << "\n"
          << "s1_hash: " << SignatureHash()(signatures[i]) << "\n"
          << "s2: " << signatures[j].HumanString() << "\n"
          << "s2_hash: " << SignatureHash()(signatures[j]);
    }
  }
}

TEST(XlaCompilationCacheTest, SignatureUniqueness) {
  NameAttrList fn;
  fn.set_name("afunction");
  std::vector<XlaCompiler::Argument> args(2);
  args[0].kind = XlaCompiler::Argument::kConstant;
  args[0].type = DT_INT32;
  args[0].constant_value = Tensor(DT_INT32, {4, 0});

  args[1].kind = XlaCompiler::Argument::kParameter;
  args[1].type = DT_INT32;
  args[1].shape = TensorShape({4, 0});

  TF_ASSERT_OK_AND_ASSIGN(XlaCompilationCache::Signature s1,
                          XlaCompilationCache::BuildSignature(fn, args));

  using std::swap;  // go/using-std-swap
  swap(args[0], args[1]);
  TF_ASSERT_OK_AND_ASSIGN(XlaCompilationCache::Signature s2,
                          XlaCompilationCache::BuildSignature(fn, args));

  EXPECT_NE(s1.HumanString(), s2.HumanString());
  EXPECT_NE(SignatureHash()(s1), SignatureHash()(s2));
  EXPECT_FALSE(s1 == s2);
}

void BM_BuildSignature(::testing::benchmark::State& state) {
  const int n_args = state.range(0);

  NameAttrList fn;
  fn.set_name("afunction");
  for (int i = 0; i < n_args; i++) {
    (*fn.mutable_attr())[absl::StrCat("T", i)].set_type(DT_FLOAT);
  }
  std::vector<XlaCompiler::Argument> args(n_args);
  for (int i = 0; i < n_args; i++) {
    args[i].kind = (((i % 3) == 0) ? XlaCompiler::Argument::kConstant
                                   : XlaCompiler::Argument::kParameter);
    args[i].type = DT_INT32;
    args[i].shape = TensorShape({4, 0});
    args[i].constant_value = Tensor(DT_INT32, {4, 0});
  }

  for (auto i : state) {
    StatusOr<XlaCompilationCache::Signature> s =
        XlaCompilationCache::BuildSignature(fn, args);
    CHECK(s.ok());
    XlaCompilationCache::Signature sig = std::move(s.value());
  }
}
BENCHMARK(BM_BuildSignature)->Arg(0)->Arg(1)->Arg(2)->Arg(5)->Arg(10);

TEST(GetExecutableOptionTest, Basic) {
  XlaCompiler::Options options;
  options.device_ordinal = 0;
  options.alias_passthrough_params = true;
  options.detailed_logging = true;
  XlaCompiler::CompilationResult result;
  xla::Shape xla_output_shape;
  result.xla_output_shape = xla_output_shape;

  auto build_option =
      GetExecutableBuildOptions(options, result, /*default_device_ordinal=*/-1);

  EXPECT_EQ(build_option.device_ordinal(), 0);
  EXPECT_EQ(build_option.result_layout()->ToString(),
            xla_output_shape.ToString());
  EXPECT_EQ(build_option.alias_passthrough_params(), true);
  EXPECT_EQ(build_option.debug_options().xla_detailed_logging_and_dumping(),
            true);
  LOG(ERROR) << build_option.ToString();
}

TEST(GetExecutableOptionTest, DefaultDeviceOrdinal) {
  XlaCompiler::Options options;
  XlaCompiler::CompilationResult result;

  auto build_option =
      GetExecutableBuildOptions(options, result, /*default_device_ordinal=*/0);

  EXPECT_EQ(build_option.device_ordinal(), 0);
}

TEST(GetExecutableOptionTest, DeviceOrdinalNotSet) {
  XlaCompiler::Options options;
  XlaCompiler::CompilationResult result;

  auto build_option =
      GetExecutableBuildOptions(options, result, /*default_device_ordinal=*/-1);

  EXPECT_EQ(build_option.device_ordinal(), -1);
}

}  // namespace
}  // namespace tensorflow


text:
package dojo

import _root_.play.api.libs.functional.syntax._
import _root_.play.api.libs.json.Format
import _root_.play.api.libs.json.Json
import _root_.play.api.libs.json.Reads
import _root_.play.api.libs.json.Writes
import _root_.play.api.libs.json._

package object etcd {

  case class NodeResponse(key: String,
                          dir: Option[Boolean],
                          value: Option[String],
                          nodes: Option[List[NodeResponse]])

  case class EtcdResponse(action: String,
                          node: NodeResponse,
                          prevNode: Option[NodeResponse])

  val nodeResponseReads: Reads[NodeResponse] = (
    (__ \ "key").read[String] and
      (__ \ "dir").readNullable[Boolean] and
      (__ \ "value").readNullable[String] and
      (__ \ "nodes").lazyReadNullable(Reads.list(nodeResponseReads))
    )(NodeResponse)

  val nodeResponseWrites: Writes[NodeResponse] = (
    (__ \ "key").write[String] and
      (__ \ "dir").writeNullable[Boolean] and
      (__ \ "value").writeNullable[String] and
      (__ \ "nodes").lazyWriteNullable(Writes.list(nodeResponseWrites))
    )(unlift(NodeResponse.unapply))

  implicit val nodeResponseFormat = Format(nodeResponseReads, nodeResponseWrites)

  implicit val etcdResponseFormat = Json.format[EtcdResponse]
}


text: Sourfen für ein Kurseinteilungsprogramm