text:
package org.apache.cassandra.cli;

import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.config.ConfigurationException;
import org.apache.cassandra.config.Schema;
import org.apache.cassandra.service.EmbeddedCassandraService;
import org.apache.cassandra.thrift.*;
import org.apache.thrift.TException;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.regex.Pattern;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class CliTest extends SchemaLoader
{
    // please add new statements here so they could be auto-runned by this test.
    private String[] statements = {
        "use TestKeySpace;",
        "create column family 123 with comparator=UTF8Type and column_metadata=[{ column_name:world, validation_class:IntegerType, index_type:0, index_name:IdxName }, " +
                                                                               "{ column_name:world2, validation_class:LongType, index_type:KEYS, index_name:LongIdxName}, " +
                                                                               "{ column_name:617070, validation_class:UTF8Type, index_type:KEYS }, " +
                                                                               "{ column_name:28292, validation_class:UTF8Type, index_type:CUSTOM, index_options:{class_name:'org.apache.cassandra.db.index.keys.KeysIndex', foo:bar}}," +
                                                                               "{ column_name:'-617071', validation_class:UTF8Type, index_type:KEYS }," +
                                                                               "{ column_name:time_spent_uuid, validation_class:TimeUUIDType}] and default_validation_class=UTF8Type;",
        "assume 123 keys as utf8;",
        "set 123[hello][world] = 123848374878933948398384;",
        "set 123[hello][test_quote] = 'value\\'';",
        "set 123['k\\'ey'][VALUE] = 'VAL';",
        "set 123['k\\'ey'][VALUE] = 'VAL\\'';",
        "set 123[hello][-31337] = 'some string value';",
        "list 123;",
        "list 123[:];",
        "list 123[456:];",
        "list 123 limit 5",
        "list 123[12:15] limit 20",
        "get 123[hello][-31337];",
        "get 123[hello][world];",
        "get 123[hello][test_quote];",
        "get 123['k\\'ey'][VALUE]",
        "set 123[hello][-31337] = -23876;",
        "set 123[hello][world2] = 15;",
        "get 123 where world2 = long(15);",
        "get 123 where world2 = long(15);",
        "get 123 where world2 = long(15);",
        "del 123[utf8('hello')][utf8('world')];",
        "del 123[hello][world2];",
        "set 123['hello'][time_spent_uuid] = timeuuid(a8098c1a-f86e-11da-bd1a-00112444be1e);",
        "create column family CF2 with comparator=IntegerType and default_validation_class=AsciiType;",
        "assume CF2 keys as utf8;",
        "set CF2['key'][98349387493847748398334] = 'some text';",
        "get CF2['key'][98349387493847748398334];",
        "set CF2['key'][98349387493] = 'some text other';",
        "get CF2['key'][98349387493];",
        "create column family CF3 with comparator=UTF8Type and column_metadata=[{column_name:'big world', validation_class:LongType, index_type:KEYS, index_name:WorldIdx}];",
        "assume CF3 keys as utf8;",
        "set CF3['hello']['big world'] = 3748;",
        "get CF3['hello']['big world'];",
        "list CF3;",
        "list CF3[:];",
        "list CF3[h:];",
        "list CF3 limit 10;",
        "list CF3[h:] limit 10;",
        "create column family CF4 with comparator=IntegerType and column_metadata=[{column_name:9999, validation_class:LongType}];",
        "assume CF4 keys as utf8;",
        "set CF4['hello'][9999] = 1234;",
        "get CF4['hello'][9999];",
        "get CF4['hello'][9999] as Long;",
        "get CF4['hello'][9999] as Bytes;",
        "set CF4['hello'][9999] = Long(1234);",
        "get CF4['hello'][9999];",
        "get CF4['hello'][9999] as Long;",
        "del CF4['hello'][9999];",
        "get CF4['hello'][9999];",
        "create column family sCf1 with column_type=Super and comparator=IntegerType and subcomparator=LongType and column_metadata=[{column_name:9999, validation_class:LongType}];",
        "assume sCf1 keys as utf8;",
        "set sCf1['hello'][1][9999] = 1234;",
        "get sCf1['hello'][1][9999];",
        "get sCf1['hello'][1][9999] as Long;",
        "get sCf1['hello'][1][9999] as Bytes;",
        "set sCf1['hello'][1][9999] = Long(1234);",
        "set sCf1['hello'][-1][-12] = Long(5678);",
        "get sCf1['hello'][-1][-12];",
        "set sCf1['hello'][-1][-12] = -340897;",
        "set sCf1['hello'][-1][-12] = integer(-340897);",
        "get sCf1['hello'][1][9999];",
        "get sCf1['hello'][1][9999] as Long;",
        "del sCf1['hello'][1][9999];",
        "get sCf1['hello'][1][9999];",
        "set sCf1['hello'][1][9999] = Long(1234);",
        "del sCf1['hello'][9999];",
        "get sCf1['hello'][1][9999];",
        "create column family 'Counter1' with comparator=UTF8Type and default_validation_class=CounterColumnType;",
        "assume Counter1 keys as utf8;",
        "incr Counter1['hello']['cassandra'];",
        "incr Counter1['hello']['cassandra'] by 3;",
        "incr Counter1['hello']['cassandra'] by -2;",
        "decr Counter1['hello']['cassandra'];",
        "decr Counter1['hello']['cassandra'] by 3;",
        "decr Counter1['hello']['cassandra'] by -2;",
        "get Counter1['hello']['cassandra'];",
        "get Counter1['hello'];",
        "truncate 123;",
        "drop index on '123'.world2;",
        "drop index on '123'.617070;",
        "drop index on '123'.'-617071';",
        "drop index on CF3.'big world';",
        "update keyspace TestKeySpace with durable_writes = false;",
        "assume 123 comparator as utf8;",
        "assume 123 sub_comparator as integer;",
        "assume 123 validator as lexicaluuid;",
        "assume 123 keys as timeuuid;",
        "create column family CF7;",
        "assume CF7 keys as utf8;",
        "set CF7[1][timeuuid()] = utf8(test1);",
        "set CF7[2][lexicaluuid()] = utf8('hello world!');",
        "set CF7[3][lexicaluuid(550e8400-e29b-41d4-a716-446655440000)] = utf8(test2);",
        "set CF7[key2][timeuuid()] = utf8(test3);",
        "assume CF7 comparator as lexicaluuid;",
        "assume CF7 keys as utf8;",
        "list CF7;",
        "get CF7[3];",
        "get CF7[3][lexicaluuid(550e8400-e29b-41d4-a716-446655440000)];",
        "get sCf1['hello'][1][9999];",
        "set sCf1['hello'][1][9999] = 938;",
        "set sCf1['hello'][1][9999] = 938 with ttl = 30;",
        "set sCf1['hello'][1][9999] = 938 with ttl = 560;",
        "count sCf1[hello];",
        "count sCf1[utf8('hello')];",
        "count sCf1[utf8('hello')][integer(1)];",
        "count sCf1[hello][1];",
        "list sCf1;",
        "del sCf1['hello'][1][9999];",
        "assume sCf1 comparator as utf8;",
        "create column family CF8;",
        "drop column family cF8;",
        "create keyspace TESTIN;",
        "drop keyspace tesTIN;",
        "update column family 123 with comparator=UTF8Type and column_metadata=[];",
        "drop column family 123;",
        "create column family myCF with column_type='Super' and comparator='UTF8Type' AND subcomparator='UTF8Type' AND default_validation_class=AsciiType;",
        "assume myCF keys as utf8;",
        "create column family Countries with comparator=UTF8Type and column_metadata=[ {column_name: name, validation_class: UTF8Type} ];",
        "set Countries[11][name] = USA;",
        "get Countries[11][name];",
        "update column family Countries with compaction_strategy = 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy';",
        "create column family Cities with compaction_strategy = 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy' and compaction_strategy_options = {min_sstable_size:1024};",
        "set myCF['key']['scName']['firstname'] = 'John';",
        "get myCF['key']['scName']",
        "assume CF3 keys as utf8;",
        "use TestKEYSpace;",
        "update keyspace TestKeySpace with placement_strategy='org.apache.cassandra.locator.NetworkTopologyStrategy';",
        "update keyspace TestKeySpace with strategy_options=[{DC1:3, DC2:4, DC5:1}];",
        "describe cluster;",
        "help describe cluster;",
        "show cluster name",
        "show api version",
        "help help",
        "help connect",
        "help use",
        "help describe",
        "HELP exit",
        "help QUIT",
        "help show cluster name",
        "help show keyspaces",
        "help show schema",
        "help show api version",
        "help create keyspace",
        "HELP update KEYSPACE",
        "HELP CREATE column FAMILY",
        "HELP UPDATE COLUMN family",
        "HELP drop keyspace",
        "help drop column family",
        "HELP GET",
        "HELP set",
        "HELP DEL",
        "HELP count",
        "HELP list",
        "HELP TRUNCATE",
        "help assume",
        "HELP",
        "?",
        "show schema",
        "show schema TestKeySpace"
    };

    @Test
    public void testCli() throws IOException, TException, ConfigurationException, ClassNotFoundException, TimedOutException, NotFoundException, SchemaDisagreementException, NoSuchFieldException, InvalidRequestException, UnavailableException, InstantiationException, IllegalAccessException
    {
        Schema.instance.clear(); // Schema are now written on disk and will be reloaded
        new EmbeddedCassandraService().start();

        // new error/output streams for CliSessionState
        ByteArrayOutputStream errStream = new ByteArrayOutputStream();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();

        // checking if we can connect to the running cassandra node on localhost
        CliMain.connect("127.0.0.1", 9170);

        // setting new output stream
        CliMain.sessionState.setOut(new PrintStream(outStream));
        CliMain.sessionState.setErr(new PrintStream(errStream));

        // re-creating keyspace for tests
        try
        {
            // dropping in case it exists e.g. could be left from previous run
            CliMain.processStatement("drop keyspace TestKeySpace;");
        }
        catch (Exception e)
        {
            // TODO check before drop so we don't have this fragile ignored exception block
        }
        CliMain.processStatement("create keyspace TestKeySpace;");

        for (String statement : statements)
        {
            errStream.reset();
            // System.out.println("Executing statement: " + statement);
            CliMain.processStatement(statement);
            String result = outStream.toString();
            // System.out.println("Result:\n" + result);
            assertEquals(errStream.toString() + " processing " + statement, "", errStream.toString());
            if (statement.startsWith("drop ") || statement.startsWith("create ") || statement.startsWith("update "))
            {
                assert Pattern.compile("(.{8})-(.{4})-(.{4})-(.{4})-(.{12}).*", Pattern.DOTALL).matcher(result).matches()
                       : String.format("\"%s\" failed: %s", statement, result);
            }
            else if (statement.startsWith("set "))
            {
                 assertTrue(result.contains("Value inserted."));
                 assertTrue(result.contains("Elapsed time:"));
            }
            else if (statement.startsWith("incr "))
            {
                 assertTrue(result.contains("Value incremented."));
            }
            else if (statement.startsWith("decr "))
            {
                 assertTrue(result.contains("Value decremented."));
            }
            else if (statement.startsWith("get "))
            {
                if (statement.contains("where"))
                {
                    assertTrue(result.startsWith("-------------------" + System.getProperty("line.separator") + "RowKey:"));
                }
                else if (statement.contains("Counter"))
                {
                    assertTrue(result.startsWith("=> (counter=") || result.startsWith("Value was not found"));
                }
                else
                {
                    assertTrue(result.startsWith("=> (column=") || result.startsWith("Value was not found"));
                }
                assertTrue(result.contains("Elapsed time:"));
            }
            else if (statement.startsWith("truncate "))
            {
                assertTrue(result.contains(" truncated."));
            }
            else if (statement.startsWith("assume "))
            {
                assertTrue(result.contains("successfully."));
            }

            outStream.reset(); // reset stream so we have only output from next statement all the time
            errStream.reset(); // no errors to the end user.
        }
    }

    @Test
    public void testEscape()
    {
        //escaped is the string read from the cli.
        String escaped = "backspace \\b tab \\t linefeed \\n form feed \\f carriage return \\r duble quote \\\" " +
                "single quote \\' backslash \\\\";
        String unescaped = "backspace \b tab \t linefeed \n form feed \f carriage return \r duble quote \" " +
                "single quote ' backslash \\";
        // when read from the cli may have single quotes around it
        assertEquals(unescaped, CliUtils.unescapeSQLString("'" + escaped + "'"));
        assertEquals(escaped, CliUtils.escapeSQLString(unescaped));
    }
}


text:
## SYNOPSIS
Returns the forest object for the current (or specified) forest.

Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: ConvertTo-SID

## SYNTAX

```
Get-Forest [[-Forest] <String>] [-Credential <PSCredential>]
```

## DESCRIPTION
Returns a System.DirectoryServices.ActiveDirectory.Forest object for the current
forest or the forest specified with -Forest X.

## EXAMPLES

### -------------------------- EXAMPLE 1 --------------------------
```
Get-Forest -Forest external.domain
```

### -------------------------- EXAMPLE 2 --------------------------
```
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
```

$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)
Get-Forest -Credential $Cred

## PARAMETERS

### -Forest
The forest name to query for, defaults to the current forest.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: 1
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```

### -Credential
A \[Management.Automation.PSCredential\] object of alternate credentials
for connection to the target forest.

```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```

## INPUTS

## OUTPUTS

### System.Management.Automation.PSCustomObject

Outputs a PSObject containing System.DirectoryServices.ActiveDirectory.Forest in addition
to the forest root domain SID.

## NOTES

## RELATED LINKS

redpajama_set_name: RedPajamaGithub


text:
package common

import (
	"bytes"
	"encoding/binary"
)

// Converts Big Endian binary format of a 4 byte integer to uint32
func toUInt32(b []byte) (uint32, error) {
	var result uint32
	buf := bytes.NewReader(b)
	err := binary.Read(buf, binary.BigEndian, &result)
	return result, err
}

// Converts Big Endian binary format of a 4 byte integer to uint16
func toUInt16(b []byte) (uint16, error) {
	var result uint16
	buf := bytes.NewReader(b)
	err := binary.Read(buf, binary.BigEndian, &result)
	return result, err
}

// Converts an uint32 to a 4 byte Big Endian binary format
func int32ToByteArr(i uint32) ([]byte, error) {
	buf := new(bytes.Buffer)
	err := binary.Write(buf, binary.BigEndian, i)
	return buf.Bytes(), err
}

// Converts an uint16 to a 4 byte Big Endian binary format
func uint16ToByteArr(i uint16) ([]byte, error) {
	buf := new(bytes.Buffer)
	err := binary.Write(buf, binary.BigEndian, i)
	return buf.Bytes(), err
}


text:
package github

import (
	"context"
	"fmt"
)

// ListAssignees fetches all available assignees (owners and collaborators) to
// which issues may be assigned.
//
// GitHub API docs: https://developer.github.com/v3/issues/assignees/#list-assignees
func (s *IssuesService) ListAssignees(ctx context.Context, owner, repo string, opts *ListOptions) ([]*User, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/assignees", owner, repo)
	u, err := addOptions(u, opts)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}
	var assignees []*User
	resp, err := s.client.Do(ctx, req, &assignees)
	if err != nil {
		return nil, resp, err
	}

	return assignees, resp, nil
}

// IsAssignee checks if a user is an assignee for the specified repository.
//
// GitHub API docs: https://developer.github.com/v3/issues/assignees/#check-if-a-user-can-be-assigned
func (s *IssuesService) IsAssignee(ctx context.Context, owner, repo, user string) (bool, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/assignees/%v", owner, repo, user)
	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return false, nil, err
	}
	resp, err := s.client.Do(ctx, req, nil)
	assignee, err := parseBoolResponse(err)
	return assignee, resp, err
}

// AddAssignees adds the provided GitHub users as assignees to the issue.
//
// GitHub API docs: https://developer.github.com/v3/issues/assignees/#add-assignees-to-an-issue
func (s *IssuesService) AddAssignees(ctx context.Context, owner, repo string, number int, assignees []string) (*Issue, *Response, error) {
	users := &struct {
		Assignees []string `json:"assignees,omitempty"`
	}{Assignees: assignees}
	u := fmt.Sprintf("repos/%v/%v/issues/%v/assignees", owner, repo, number)
	req, err := s.client.NewRequest("POST", u, users)
	if err != nil {
		return nil, nil, err
	}

	issue := &Issue{}
	resp, err := s.client.Do(ctx, req, issue)
	return issue, resp, err
}

// RemoveAssignees removes the provided GitHub users as assignees from the issue.
//
// GitHub API docs: https://developer.github.com/v3/issues/assignees/#remove-assignees-from-an-issue
func (s *IssuesService) RemoveAssignees(ctx context.Context, owner, repo string, number int, assignees []string) (*Issue, *Response, error) {
	users := &struct {
		Assignees []string `json:"assignees,omitempty"`
	}{Assignees: assignees}
	u := fmt.Sprintf("repos/%v/%v/issues/%v/assignees", owner, repo, number)
	req, err := s.client.NewRequest("DELETE", u, users)
	if err != nil {
		return nil, nil, err
	}

	issue := &Issue{}
	resp, err := s.client.Do(ctx, req, issue)
	return issue, resp, err
}


text:
package io.pravega.segmentstore.storage.cache;

import io.pravega.common.util.BufferView;
import io.pravega.segmentstore.storage.CacheException;
import java.util.function.Supplier;
import lombok.NonNull;

/**
 * Defines a generic, non-associative, block-based Cache Storage.
 */
public interface CacheStorage extends AutoCloseable {
    /**
     * Gets a value representing a "null" address.
     */
    int NO_ADDRESS = CacheLayout.NO_ADDRESS;

    /**
     * Gets a value representing the size of one block. For efficiency purposes, it is highly recommended that all inserted
     * data align to this value (i.e., have a length that is a multiple of this value).
     *
     * @return The block alignment, in bytes.
     */
    int getBlockAlignment();

    /**
     * Gets a value representing the maximum size of an entry that can be stored in this {@link CacheStorage}.
     *
     * @return The maximum size, in bytes.
     */
    int getMaxEntryLength();

    /**
     * Inserts a new entry into this {@link CacheStorage}.
     *
     * @param data A {@link BufferView} representing the entry to insert. May be empty. Must have {@link BufferView#getLength()}
     *             less than or equal to {@link #getMaxEntryLength()}.
     * @return An integer representing the address where this data was inserted at. This can be used to invoke {@link #append},
     * {@link #get}, {@link #delete} or {@link #replace}.
     * @throws CacheFullException If there is no more capacity in the {@link CacheStorage} to accomodate this entry.
     */
    int insert(@NonNull BufferView data);

    /**
     * Replaces the entry at the given address with new content.
     *
     * @param address The address to replace. May be obtained via {@link #insert} or {@link #replace}. If there is no
     *                entry with this address, this method will act like {@link #insert}.
     * @param data    A {@link BufferView} representing the new contents of the entry. May be empty. Must have
     *                {@link BufferView#getLength()} less than or equal to {@link #getMaxEntryLength()}.
     * @return An integer representing the address where this data now resides. Depending on the implementation, this may
     * or may not be equal to `address`. This can be used to invoke {@link #append}, {@link #get} or {@link #delete}.
     * @throws CacheFullException If there is no more capacity in the {@link CacheStorage} to accommodate this entry.
     * @throws CacheException     If another unexpected exception occurred.
     */
    int replace(int address, @NonNull BufferView data);

    /**
     * Gets the number of bytes that can be appended to an entry that has the given length.
     *
     * @param currentLength The current length of the entry.
     * @return An non-negative integer representing the number of bytes that can be appended.
     */
    int getAppendableLength(int currentLength);

    /**
     * Performs an atomic compare-and-appends of data at the end of an entry. This operation will only take effect if
     * the current length of the entry matches the argument `expectedLength` and both the entry's length and contents
     * will be updated atomically.
     *
     * @param address        An integer representing the address to append to.
     * @param expectedLength The currently known length of this entry.
     * @param data           A {@link BufferView} representing the data to append.
     * @return An integer representing the number of bytes that were appended. If 0, then the entry at the given address
     * is already at its max capacity (its length equals {@link #getMaxEntryLength()}.
     * @throws IncorrectCacheEntryLengthException If `expectedLength` does not match the current length of the entry.
     * @throws IllegalArgumentException If address does not point to a valid entry or the given {@link BufferView} is
     * too long to fit into the given entry (use {@link #getAppendableLength} to determine maximum length).
     */
    int append(int address, int expectedLength, @NonNull BufferView data);

    /**
     * Deletes the entry at the given address. If this address does not currently map to an entry, this operation will have
     * no effect.
     *
     * @param address An integer representing the address to delete.
     */
    void delete(int address);

    /**
     * Retrieves the contents of an entry with the given address.
     *
     * @param address An integer representing the address to retrieve.
     * @return A read-only {@link BufferView} that can be used to access the data, or null if no entry is mapped to this
     * address.
     */
    BufferView get(int address);

    /**
     * Returns a {@link CacheState} representing the current state of the {@link CacheStorage}.
     *
     * @return A new {@link CacheState} instance.
     */
    CacheState getState();

    /**
     * Sets a callback that will be invoked during {@link #insert} if there is insufficient capacity to add more entries.
     *
     * @param cacheFullCallback    The callback to invoke. This should return `true` if a cache cleanup was performed, and
     *                             `false` otherwise.
     * @param retryDelayBaseMillis The amount of time to wait between retries if cacheFullCallback returns `false`.
     */
    void setCacheFullCallback(@NonNull Supplier<Boolean> cacheFullCallback, int retryDelayBaseMillis);

    /**
     * Closes this {@link CacheStorage} instance and releases all resources used by it.
     */
    @Override
    void close();
}


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using GeoChallenger.Database;
using GeoChallenger.Search.Documents;
using GeoChallenger.Search.Providers;
using GeoChallenger.Search.Providers.Interfaces;
using Mehdime.Entity;
using NLog;

namespace GeoChallenger.Services.Core
{
    public class SearchIndexer : ISearchIndexer
    {
        private readonly ILogger _log = LogManager.GetCurrentClassLogger();
        private readonly IDbContextScopeFactory _dbContextScopeFactory;

        public SearchIndexer(IDbContextScopeFactory dbContextScopeFactory)
        {
            if (dbContextScopeFactory == null) {
                throw new ArgumentNullException(nameof(dbContextScopeFactory));
            }
            _dbContextScopeFactory = dbContextScopeFactory;
        }

        // TODO: write unittests.
        public async Task UpdateSearchIndexAsync<TDomain, TDocument>(
            Expression<Func<TDomain, bool>> where,
            Expression<Func<TDomain, int>> order,
            Func<TDomain, Task<TDocument>> documentFactoryAsync,
            IDocumentsSearchProvider<TDocument> searchProvider
            )
            where TDomain: class
            where TDocument: BaseDocument
        {
            const int PAGE_SIZE = 1000;

            using (var dbContextScope = _dbContextScopeFactory.CreateReadOnly()) {
                var context = dbContextScope.DbContexts.Get<GeoChallengerContext>();

                var documentCounts = await context.Set<TDomain>()
                    .Where(where)
                    .CountAsync();

                for (int i = 0; i < documentCounts; i = i + PAGE_SIZE) {
                    var domains = await context.Set<TDomain>()
                        .Where(where)
                        .OrderBy(order)
                        .Skip(i)
                        .Take(PAGE_SIZE)
                        .ToListAsync();

                    // Maps teams document.
                    // NOTE: we can't map list to list since data will be overridden.
                    var documents = new List<TDocument>();
                    foreach (var domain in domains) {
                        documents.Add(await documentFactoryAsync(domain));
                    }

                    await searchProvider.IndexAsync(documents);
                }

                _log.Info($"Indexed {documentCounts} documents of type {typeof(TDocument)}");
            }
        }
    }
}


text:
import EmberObject from '@ember/object';
import { resolve } from 'rsvp';
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, settled } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import DS from 'ember-data';

const { PromiseArray } = DS;

module('Integration | Component | pending single user update', function(hooks) {
  setupRenderingTest(hooks);

  test('it renders', async function(assert) {
    // Set any properties with this.set('myProperty', 'value');
    // Handle any actions with this.on('myAction', function(val) { ... });"

    let updates = [
      {
        type: 'emailMismatch',
        value: 'directory-email',
      }
    ];
    let user = EmberObject.create({
      pendingUserUpdates: PromiseArray.create({
        promise: resolve(updates)
      }),
      email: 'user-email'
    });
    updates[0].user = user;

    this.set('user', user);
    await render(hbs`{{pending-single-user-update user=user}}`);

    return settled().then(() => {
      assert.equal(this.element.textContent.trim().search(/The email address in the directory \(directory-email\) does not match the email in ilios \(user-email\)/), 0);
    });
  });
});


text:
package uk.ac.open.kmi.iserve.sal.manager;

import uk.ac.open.kmi.iserve.sal.exception.UserException;

import java.net.URI;

/**
 * Class Description
 *
 * TODO: Complete
 *
 * @author Carlos Pedrinaci (Knowledge Media Institute - The Open University)
 */
public interface UserManager {

//	public abstract User getUser(URI openId) throws UserException;

//	public abstract User getUser(String userName) throws UserException;

    public abstract URI addUser(URI foafId, URI openId, String userName,
                                String password) throws UserException;

//	public abstract URI addUser(User user) throws UserException;

    public abstract boolean removeUser(URI foafId) throws UserException;

    public abstract boolean removeUser(String userName) throws UserException;

//	public abstract URI updateUser(User user) throws UserException;

//	// TODO: should not be here
//	public RDFRepositoryConnector getUsersRepositoryConnector();

}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @typedef {{
 *   overrideCwsContainerUrlForTest: (string|undefined),
 *   overrideCwsContainerOriginForTest: (string|undefined)
 * }}
 */
var SuggestAppDialogState;

/**
 * @param {!Object} unformatted Unformatted option.
 * @constructor
 * @struct
 */
function LaunchParam(unformatted) {
  /**
   * @type {DialogType}
   * @const
   */
  this.type = unformatted['type'] || DialogType.FULL_PAGE;

  /**
   * @type {string}
   * @const
   */
  this.action = unformatted['action'] ? unformatted['action'] : '';

  /**
   * @type {string}
   * @const
   */
  this.currentDirectoryURL = unformatted['currentDirectoryURL'] ?
      unformatted['currentDirectoryURL'] : '';

  /**
   * @type {string}
   * @const
   */
  this.selectionURL =
      unformatted['selectionURL'] ? unformatted['selectionURL'] : '';

  /**
   * @type {string}
   * @const
   */
  this.targetName = unformatted['targetName'] ? unformatted['targetName'] : '';

  /**
   * @type {!Array<!Object>}
   * @const
   */
  this.typeList = unformatted['typeList'] ? unformatted['typeList'] : [];

  /**
   * @type {boolean}
   * @const
   */
  this.includeAllFiles = !!unformatted['includeAllFiles'];

  /**
   * @type {!AllowedPaths}
   * @const
   */
  this.allowedPaths = unformatted['allowedPaths'] ?
      unformatted['allowedPaths'] : AllowedPaths.ANY_PATH;

  /**
   * @type {!SuggestAppDialogState}
   * @const
   */
  this.suggestAppsDialogState =
      unformatted['suggestAppsDialogState'] ?
      unformatted['suggestAppsDialogState'] :
      {
        overrideCwsContainerUrlForTest: '',
        overrideCwsContainerOriginForTest: ''
      };
}


text:
"""Google PageSpeed

This check uses the Google PageSpeed API to run various test to collect metrics for how
a website is performing.

Official page: https://developers.google.com/speed/pagespeed/

API key required.
"""
import json
import sys

from bs4 import BeautifulSoup

import _privatekeys as privatekeys
import helper

def google_pagespeed_check(check_url, strategy='mobile'):
    """Checks the Pagespeed Insights with Google
    In addition to the 'mobile' strategy there is also 'desktop' aimed at the desktop user's preferences
    Returns a dictionary of the results.

    attributes: check_url, strategy
    """
    check_url = check_url.strip()

    # urlEncodedURL = parse.quote_plus(check_url)	# making sure no spaces or other weird characters f*cks up the request, such as HTTP 400
    pagespeed_api_request = 'https://www.googleapis.com/pagespeedonline/v4/runPagespeed?url={}&strategy={}&key={}'.format(
        check_url, strategy, privatekeys.googlePageSpeedApiKey)
    # print('HTTP request towards GPS API: {}'.format(pagespeed_api_request))

    responsecontents = ""
    get_content = ""

    try:
        get_content = helper.httpRequestGetContent(pagespeed_api_request)
        get_content = BeautifulSoup(get_content, "html.parser")
        get_content = str(get_content.encode("ascii"))
    except:  # breaking and hoping for more luck with the next URL
        print(
            'Error! Unfortunately the request for URL "{0}" failed, message:\n{1}'.format(
                check_url, sys.exc_info()[0]))
        pass
    # try:
    get_content = get_content[2:][:-1]  # removes two first chars and the last one
    get_content = get_content.replace('\\n', '\n').replace("\\'",
                                                           "\'")  # .replace('"', '"') #.replace('\'', '\"')
    get_content = get_content.replace('\\\\"', '\\"').replace('""', '"')

    json_content = ''
    try:
        json_content = json.loads(get_content)
    except:  # might crash if checked resource is not a webpage
        print('Error! JSON failed parsing for the URL "{0}"\nMessage:\n{1}'.format(
            check_url, sys.exc_info()[0]))
        pass

    return_dict = {}
    try:
        # overall score
        for key in json_content['ruleGroups'].keys():
            # print('Key: {0}, value {1}'.format(key, json_content['ruleGroups'][key]['score']))
            return_dict[key] = json_content['ruleGroups'][key]['score']

        # page statistics
        for key in json_content['pageStats'].keys():
            # print('Key: {0}, value {1}'.format(key, json_content['pageStats'][key]))
            return_dict[key] = json_content['pageStats'][key]

        # page potential
        for key in json_content['formattedResults']['ruleResults'].keys():
            # print('Key: {0}, value {1}'.format(key, json_content['formattedResults']['ruleResults'][key]['ruleImpact']))
            return_dict[key] = json_content['formattedResults']['ruleResults'][key]['ruleImpact']
        return return_dict
    except:
        print('Error! Request for URL "{0}" failed.\nMessage:\n{1}'.format(check_url,
                                                                           sys.exc_info()[
                                                                               0]))
        pass

def check_lighthouse(url, strategy='mobile', category='performance'):
    """
    perf = https://www.googleapis.com/pagespeedonline/v5/runPagespeed?category=performance&strategy=mobile&url=YOUR-SITE&key=YOUR-KEY
    a11y = https://www.googleapis.com/pagespeedonline/v5/runPagespeed?category=accessibility&strategy=mobile&url=YOUR-SITE&key=YOUR-KEY
    practise = https://www.googleapis.com/pagespeedonline/v5/runPagespeed?category=best-practices&strategy=mobile&url=YOUR-SITE&key=YOUR-KEY
    pwa = https://www.googleapis.com/pagespeedonline/v5/runPagespeed?category=pwa&strategy=mobile&url=YOUR-SITE&key=YOUR-KEY
    seo = https://www.googleapis.com/pagespeedonline/v5/runPagespeed?category=seo&url=YOUR-SITE&key=YOUR-KEY
    """
    check_url = url.strip()

    pagespeed_api_request = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?category={0}&url={1}&key={2}'.format(category, check_url, privatekeys.googlePageSpeedApiKey)

    get_content = ''

    try:
        get_content = helper.httpRequestGetContent(pagespeed_api_request)
    except:  # breaking and hoping for more luck with the next URL
        print(
            'Error! Unfortunately the request for URL "{0}" failed, message:\n{1}'.format(
                check_url, sys.exc_info()[0]))
        pass

    #print('Checked \'{0}\' successfully against Google\'s API!'.format(pagespeed_api_request))
    json_content = ''

    try:
        json_content = json.loads(get_content)
    except:  # might crash if checked resource is not a webpage
        print('Error! JSON failed parsing for the URL "{0}"\nMessage:\n{1}'.format(
            check_url, sys.exc_info()[0]))
        pass

    #print(json_content)

    return_dict = {}
    return_dict = json_content['lighthouseResult']['audits']['metrics']['details']['items'][0]

    for item in json_content['lighthouseResult']['audits'].keys():
        try:
            return_dict[item] = json_content['lighthouseResult']['audits'][item]['numericValue']
        except:
            # has no 'numericValue'
            #print(item, 'har inget värde')
            pass

    return return_dict


text:
package org.robolectric.shadows;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.R;
import org.robolectric.TestRunners;
import org.robolectric.util.Transcript;

import static org.junit.Assert.*;
import static org.robolectric.Robolectric.shadowOf;

@RunWith(TestRunners.WithDefaults.class)
public class DialogFragmentTest {

    private FragmentActivity activity;
    private TestDialogFragment dialogFragment;
    private FragmentManager fragmentManager;

    @Before
    public void setUp() throws Exception {
        activity = new FragmentActivity();
        dialogFragment = new TestDialogFragment();
        fragmentManager = activity.getSupportFragmentManager();
        shadowOf(activity).callOnCreate(null);
        shadowOf(activity).callOnStart();
        shadowOf(activity).callOnResume();
    }

    @Test
    public void show_shouldCallLifecycleMethods() throws Exception {
        dialogFragment.show(fragmentManager, "this is a tag");

        dialogFragment.transcript.assertEventsSoFar(
                "onAttach",
                "onCreate",
                "onCreateDialog",
                "onCreateView",
                "onViewCreated",
                "onActivityCreated",
                "onStart",
                "onResume"
        );

        assertNotNull(dialogFragment.getActivity());
        assertSame(activity, dialogFragment.onAttachActivity);
    }

    @Test
    public void show_whenPassedATransaction_shouldCallShowWithManager() throws Exception {
        dialogFragment.show(fragmentManager.beginTransaction(), "this is a tag");

        dialogFragment.transcript.assertEventsSoFar(
                "onAttach",
                "onCreate",
                "onCreateDialog",
                "onCreateView",
                "onViewCreated",
                "onActivityCreated",
                "onStart",
                "onResume"
        );

        assertNotNull(dialogFragment.getActivity());
        assertSame(activity, dialogFragment.onAttachActivity);
    }

    @Test
    public void show_shouldShowDialogThatWasReturnedFromOnCreateDialog_whenOnCreateDialogReturnsADialog() throws Exception {
        Dialog dialogFromOnCreateDialog = new Dialog(activity);
        dialogFragment.returnThisDialogFromOnCreateDialog(dialogFromOnCreateDialog);
        dialogFragment.show(fragmentManager, "this is a tag");

        Dialog dialog = ShadowDialog.getLatestDialog();
        assertSame(dialogFromOnCreateDialog, dialog);
        assertSame(dialogFromOnCreateDialog, dialogFragment.getDialog());
        assertSame(dialogFragment, fragmentManager.findFragmentByTag("this is a tag"));
    }

    @Test
    public void show_shouldShowDialogThatWasAutomaticallyCreated_whenOnCreateDialogReturnsNull() throws Exception {
        dialogFragment.show(fragmentManager, "this is a tag");

        Dialog dialog = ShadowDialog.getLatestDialog();
        assertNotNull(dialog);
        assertSame(dialog, dialogFragment.getDialog());
        assertNotNull(dialog.findViewById(R.id.title));
        assertSame(dialogFragment, fragmentManager.findFragmentByTag("this is a tag"));
    }

    @Ignore("needs some work") @Test
    public void dismiss_shouldDismissTheDialog() throws Exception {
        dialogFragment.show(fragmentManager, "tag");

        dialogFragment.dismiss();

        Dialog dialog = ShadowDialog.getLatestDialog();
        assertFalse(dialog.isShowing());
        assertTrue(shadowOf(dialog).hasBeenDismissed());

        assertNull(fragmentManager.findFragmentByTag("tag"));
    }

    @Test
    public void removeUsingTransaction_shouldDismissTheDialog() throws Exception {
        dialogFragment.show(fragmentManager, null);

        FragmentTransaction t = fragmentManager.beginTransaction();
        t.remove(dialogFragment);
        t.commit();

        Dialog dialog = ShadowDialog.getLatestDialog();
        assertFalse(dialog.isShowing());
        assertTrue(shadowOf(dialog).hasBeenDismissed());
    }

    private class TestDialogFragment extends DialogFragment {
        final Transcript transcript = new Transcript();
        Activity onAttachActivity;
        private Dialog returnThisDialogFromOnCreateDialog;

        @Override
        public void onAttach(Activity activity) {
            transcript.add("onAttach");
            onAttachActivity = activity;
            super.onAttach(activity);
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            transcript.add("onCreate");
            super.onCreate(savedInstanceState);
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            transcript.add("onCreateDialog");
            return returnThisDialogFromOnCreateDialog == null
                    ? super.onCreateDialog(savedInstanceState)
                    : returnThisDialogFromOnCreateDialog;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            transcript.add("onCreateView");
            return inflater.inflate(R.layout.main, null);
        }

        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            transcript.add("onViewCreated");
            super.onViewCreated(view, savedInstanceState);
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            transcript.add("onActivityCreated");
            super.onActivityCreated(savedInstanceState);
        }

        @Override
        public void onStart() {
            transcript.add("onStart");
            super.onStart();
        }

        @Override
        public void onResume() {
            transcript.add("onResume");
            super.onResume();
        }

        public void returnThisDialogFromOnCreateDialog(Dialog dialog) {
            returnThisDialogFromOnCreateDialog = dialog;
        }
    }
}


text:
extern "C" {
#include "caffe2/utils/cblas.h"
}

#ifdef CAFFE2_USE_ACCELERATE
#include <Accelerate/Accelerate.h>
#endif // CAFFE2_USE_ACCELERATE

#include "caffe2/core/common.h"
#include "caffe2/core/types.h"

#ifndef __CUDACC__
#include "Eigen/Core"
#include "Eigen/Dense"
#endif

namespace caffe2 {

// An empty class as a placeholder for a math function that has no specific
// engine specified.
class DefaultEngine {};

#ifndef __CUDACC__
// Common Eigen types that we will often use
template <typename T>
using EigenMatrixMap =
    Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> >;
template <typename T>
using EigenArrayMap =
    Eigen::Map<Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> >;
template <typename T>
using EigenVectorMap = Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1> >;
template <typename T>
using EigenVectorArrayMap = Eigen::Map<Eigen::Array<T, Eigen::Dynamic, 1> >;
template <typename T>
using ConstEigenMatrixMap =
    Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> >;
template <typename T>
using ConstEigenArrayMap =
    Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> >;
template <typename T>
using ConstEigenVectorMap =
    Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, 1> >;
template <typename T>
using ConstEigenVectorArrayMap =
    Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, 1> >;
#endif

namespace math {

template <typename T, class Context>
void Exp(const int N, const T* x, T* y, Context* context);
template <typename T, class Context>
void Log(const int N, const T* x, T* y, Context* context);
template <typename T, class Context>
void Sqr(const int N, const T* x, T* y, Context* context);

template <typename T, class Context>
void Not(const int N, const T* x, T* y, Context* context);

template <typename T, class Context>
void Powx(const int N, const T* a, const T b, T* y, Context* context);

#define CAFFE2_DECLARE_BINARY_OP_BINARY_RESULT(name)                         \
  template <typename T, class Context>                                       \
  void name(const int N, const T* a, const T* b, bool* y, Context* context); \
  template <typename T, class Context>                                       \
  void name##ToRow(                                                          \
      const int M,                                                           \
      const int N,                                                           \
      const T* a,                                                            \
      const T* b,                                                            \
      bool* y,                                                               \
      Context* context);

CAFFE2_DECLARE_BINARY_OP_BINARY_RESULT(LT);
CAFFE2_DECLARE_BINARY_OP_BINARY_RESULT(LE);
CAFFE2_DECLARE_BINARY_OP_BINARY_RESULT(GT);
CAFFE2_DECLARE_BINARY_OP_BINARY_RESULT(GE);

CAFFE2_DECLARE_BINARY_OP_BINARY_RESULT(And);
CAFFE2_DECLARE_BINARY_OP_BINARY_RESULT(Or);
CAFFE2_DECLARE_BINARY_OP_BINARY_RESULT(Xor);

#undef CAFFE2_DECLARE_BINARY_OP_BINARY_RESULT

#define CAFFE2_DECLARE_BINARY_OP(name)                                    \
  template <typename T, class Context>                                    \
  void name(const int N, const T* a, const T* b, T* y, Context* context); \
  template <typename T, class Context>                                    \
  void name##ToRow(                                                       \
      const int M,                                                        \
      const int N,                                                        \
      const T* a,                                                         \
      const T* b,                                                         \
      T* y,                                                               \
      Context* context);                                                  \
  template <typename T, class Context>                                    \
  void name##ToRow(                                                       \
      const int M, const int N, const T* x, T* y, Context* context);      \
  template <typename T, class Context>                                    \
  void name##ToCol(                                                       \
      const int M, const int N, const T* x, T* y, Context* context);

CAFFE2_DECLARE_BINARY_OP(Add);
CAFFE2_DECLARE_BINARY_OP(Sub);
CAFFE2_DECLARE_BINARY_OP(Mul);
CAFFE2_DECLARE_BINARY_OP(Div);

#undef CAFFE2_DECLARE_BINARY_OP

// Adds batch sub-tensors elementwise to output. Stripe is the stripe length
// and N is the number of elements to add (size of Y).
template <typename T, class Context>
void AddStripedBatch(
    const int N,
    const T* first,
    T* y,
    const int stripe,
    const int batch,
    Context* context);

// Compute the row-wise max of a N*D matrix X, and write it to a N
// dimensional vector y.
template <typename T, class Context>
void RowwiseMax(const int N, const int D, const T* x, T* y,
                Context* context);

// Compute the column-wise max of a N*D matrix X, and write it to a D
// dimensional vector y.
template <typename T, class Context>
void ColwiseMax(const int N, const int D, const T* x, T* y,
                Context* context);

// Decaf gemm provides a simpler interface to the gemm functions, with the
// limitation that the data has to be contiguous in memory.
template <typename T, class Context, class Engine = DefaultEngine>
void Gemm(
    const CBLAS_TRANSPOSE TransA,
    const CBLAS_TRANSPOSE TransB,
    const int M,
    const int N,
    const int K,
    const float alpha,
    const T* A,
    const T* B,
    const float beta,
    T* C,
    Context* context,
    TensorProto::DataType math_type = TensorProto_DataType_FLOAT);

// We also provide a gemm that has explicit lda, ldb and ldc specified.
// In most cases you probably want to use the function above, though.
template <typename T, class Context, class Engine = DefaultEngine>
void GemmEx(
    const CBLAS_TRANSPOSE TransA,
    const CBLAS_TRANSPOSE TransB,
    const int M,
    const int N,
    const int K,
    const T alpha,
    const T* A,
    const int lda,
    const T* B,
    const int ldb,
    const T beta,
    T* C,
    const int ldc,
    Context* context);

// Gemv always takes in a M*N matrix A, and depending on whether we set TransA
// to Trans, the output is:
// CblasNoTrans: x is an N dim vector and y is an M dim vector.
// CblasTrans:   x is an M dim vector and y is an N dim vector.
template <typename T, class Context, class Engine = DefaultEngine>
void Gemv(
    const CBLAS_TRANSPOSE TransA,
    const int M,
    const int N,
    const float alpha,
    const T* A,
    const T* x,
    const float beta,
    T* y,
    Context* context,
    TensorProto::DataType math_type = TensorProto_DataType_FLOAT);

template <typename T, class Context>
void Set(const TIndex N, const T alpha, T* X, Context* context);

template <typename T, class Context>
void RandUniform(const int n, const T a, const T b, T* r,
                 Context* context);

template <typename T, class Context>
void RandUniformUnique(
    const size_t n,
    const T a,
    const T b,
    T* r,
    const size_t m,
    const T* avoid,
    Context* context);

template <typename T, class Context>
void RandGaussian(
    const int n,
    const T mean,
    const T std,
    T* r,
    Context* context);

// Dot matrix of vector a and b, and writes the result to a single value y.
template <typename T, class Context>
void Dot(const int N, const T* a, const T* b, T* y, Context* context);

// Sum of vector x, and writes the result to a single value y.
template <typename T, class Context>
void Sum(const int N, const T* x, T* y, Context* context);

// Sum of squares of vector x, and writes the result to a single value y.
template <typename T, class Context>
void SumSqr(const int N, const T* x, T* y, Context* context);

// Select does index selection of the rows a N*D matrix x, and gives the N
// dimensional vector y that contains the selected data.
template <typename T, class Context>
void Select(const int N, const int D, const T* x, const int* idx, T* y,
            Context* context);

template <typename T, class Context>
void Scale(const int N, const float alpha, const T* x, T* y, Context* context);

// Different from the Scale function above, if alpha is passed in
// as a pointer, we will assume that it lives on the Context device,
// for example on GPU.
template <typename T, class Context>
void Scale(const int N, const float* alpha, const T* x, T* y, Context* context);

template <typename T, class Context>
void Axpy(const int N, const float alpha, const T* x, T* y, Context* context);

// Different from the Axpy function above, if alpha is passed in
// as a pointer, we will assume that it lives on the Context device,
// for example on GPU.
template <typename T, class Context>
void Axpy(const int N, const float* alpha, const T* x, T* y, Context* context);

template <typename T, class Context>
void Axpby(
    const int N,
    const float alpha,
    const T* x,
    const T b,
    T* y,
    Context* context);

template <typename T, class Context, int order>
void Im2colNd(
    const T* data_img,
    const int* im_shape,
    const int* col_shape,
    const int img_size,
    const int col_size,
    const int* kernel_shape,
    const int* stride,
    const int* dilation,
    const int* pad,
    const int N,
    T* data_col,
    Context* context,
    bool accumulate_output = false);

template <typename T, class Context, int order>
void Col2imNd(
    const T* data_col,
    const int* img_shape,
    const int* col_shape,
    const int img_size,
    const int col_size,
    const int* kernel_shape,
    const int* stride,
    const int* dilation,
    const int* pad,
    const int N,
    T* data_img,
    Context* context);

template <typename T, class Context, int order>
void Im2col(
    const T* data_im,
    const int channels,
    const int height,
    const int width,
    const int kernel_h,
    const int kernel_w,
    const int dilation_h,
    const int dilation_w,
    const int pad_t,
    const int pad_l,
    const int pad_b,
    const int pad_r,
    const int stride_h,
    const int stride_w,
    T* data_col,
    Context* context);

template <typename T, class Context, int order>
void Col2im(
    const T* data_col,
    const int channels,
    const int height,
    const int width,
    const int patch_h,
    const int patch_w,
    const int dilation_h,
    const int dilation_w,
    const int pad_t,
    const int pad_l,
    const int pad_b,
    const int pad_r,
    const int stride_h,
    const int stride_w,
    T* data_im,
    Context* context);

// Applies a per-channel bias value to each channel of the input
// image. image_size is H * W
template <typename T, class Context>
void BiasCHW(
  const T* bias,
  const int bias_channels,
  const int image_size,
  T* image,
  Context* context);

template <class Context>
void CopyMatrix(const size_t item_size, const int M, const int N, const void* A,
                const int lda, void* B, const int ldb, Context* context);

uint32_t randomNumberSeed();

// Function uses casting from int to unsigned to compare if value of
// parameter a is greater or equal to zero and lower than value of
// parameter b. The b parameter is of type signed and is always
// positive,
// therefore its value is always lower than 0x800... where casting
// negative value of a parameter converts it to value higher than
// 0x800...
// The casting allows to use one condition instead of two.
inline bool is_a_ge_zero_and_a_lt_b(int a, int b) {
  return static_cast<unsigned>(a) < static_cast<unsigned>(b);
}

// Calculates ceil(a / b). User must be careful to ensure that there
// is no overflow or underflow in the calculation.
template <typename T>
inline T divUp(T a, T b) {
  return (a + b - (T) 1) / b;
}

// Rounds a up to the next highest multiple of b. User must be careful
// to ensure that there is no overflow or underflow in the calculation
// of divUp.
template <typename T>
inline T roundUp(T a, T b) {
  return divUp<T>(a, b) * b;
}

}  // namespace math
}  // namespace caffe2

#include "caffe2/utils/math-detail.h"
#endif  // CAFFE2_UTILS_MATH_H_


text:
(function(){
  Backbone.Plugins = Backbone.Plugins || {};
  Backbone.Plugins.ScrollableFilterableView = Backbone.Plugins.FilterableView.extend({
    viewportEl: ".viewport",
    spacerTagName: "div",
    listTagName: "ul",
    itemTemplate: _.template("<%collection.each(function(i){%>
<%=i.cid%>
<%});%>"),

    _configure: function(options) {
      console.log("scrollable configure")
      Backbone.Plugins.ScrollableFilterableView.__super__._configure.call(this, options);
      this._scrollState = new Backbone.Model({
        top: 0,
        length: options.length || 10,
        height: 0
      });
      _.bindAll(this, 'render', 'refilter', 'rescroll', 'scroll');
    },
    _ensureElement: function() {
      console.log("scrollable ensure")
      Backbone.Plugins.ScrollableFilterableView.__super__._ensureElement.call(this);
      if (_.isString(this.viewportEl)) {
        this.viewportEl = $(this.viewportEl);
      }
      this.spacerEl = this.make(this.spacerTagName);
      this.listEl = this.make(this.listTagName);
      this.viewportEl.prepend(this.spacerEl).append(this.listEl).scroll(this.scroll);
      this._scrollState.set({ height: this.getSize() });
      this._scrollState.bind('change:top', this.rescroll);
      this._scrollState.bind('change:length', this.rescroll);
      this._scrollState.bind('change', this.render);
    },
    refilter: function() {
      console.log("scrollable refilter")
      Backbone.Plugins.ScrollableFilterableView.__super__.refilter.call(this);
      this.viewportEl.scrollTop(0);
    },
    rescroll: function() {
      console.log("scrollable rescroll")
      var height = this._scrollState.get('height'),
          top = this._scrollState.get('top'),
          filtered = this._filterState.get('filtered').length;

      this.viewportEl.height(height * Math.min(filtered, this._scrollState.get('length')));
      this.spacerEl.height(top * height);
      this.listEl.height(height * (filtered - top));
    },
    scroll: function(e) {
      console.log("scrollable rescroll")
      this._scrollState.set({
        top: Math.floor(e.target.scrollTop / this._scrollState.get('height'))
      });
    },
    render: function() {
      Backbone.Plugins.ScrollableFilterableView.__super__.render.call(this);
      var length = this._scrollState.get('length'),
          from = this._scrollState.get('top'),
          filtered = this._filterState.get('filtered'),
          to = Math.min(filtered.length, top + length + 1),
          sliced = filtered.slice(from, to),
          templated = this.itemTemplate({
            collection: _(sliced)
          });

      console.log("scrollable render with", this.listEl, sliced, templated)
      $(this.listEl).html(templated);
    },
    getSize: function() {
      console.log("scrollable getSize")
      var h = $(this.listEl).html(this.itemTemplate({
                               collection: _([ new Backbone.Model({}) ])
                             }))
                            .select("> *:first")
                            .height();
      $(this.listEl).empty();
      return h;
    }
  });
})();


text:
void RunANSICBasics01(void);
void RunANSICBasics02(void);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta name="description" content="High-performance VPS servers, Managed DNS services, and server monitoring tools for your most demanding applications...">
    <meta name="keywords" content="VPS hosting, VPS servers, virtual server hosting, virutal private servers, web hosting, managed DNS hosting, DNS hosting, managed DNS services, DNS services, DNS tools, domain monitoring, cloud computing, cloud servers, linux hosting, ubuntu hosting, debian hosting, centos hosting, fedora hosting, fedora core hosting, pods, watchdog, hosting services, iaas, saas, grid computing">
  <title>REST API v1.1 (current) | Zerigo DNS | Support | Zerigo</title>
  <link href="api_11_files/black_packaged.css" media="all" rel="stylesheet" type="text/css">

Home

Services

Support

Blog

Contact Us

Manage Account

Zerigo

Accounts/Billing

DNS

Servers

Watchdog

Support - Zerigo DNS

REST API v1.1 (current)

Zerigo DNS supports a fairly standard REST API for full creation,
modification, and deletion of domain (zone) and host records. It is
easy and straightforward to work with.

Note that in the context of the API, domains are always referred to
as zones. Additionally note that current API support is for standard
domains and their hosts, not domain templates and their hosts. If you
need API support for templates, email support.

API status

This is the current version of the API. All new development should
use this version. Additionally, users of an older version of the API
should plan to upgrade to the latest version. See the documentation for
the older versions for sunset dates.

REST API Basics

REST runs on top of HTTP. It uses standard GET, POST, PUT, and
DELETE methods for HTTP along with XML document bodies. Authentication
is sent as an HTTP basic auth header.

Authentication

Authentication for all API requests is done via a standard Basic
HTTP Auth header. The username is your email address and the password
is the dynamic update token available in Manage Account -> DNS -> Preferences. You must enable dynamic updates to use the API.

Content types

A Content-Type header is required for all POST or PUT requests. If your content is sent as XML (recommended), you must send Content-Type: application/xml. All examples within our documentation are XML and must use the application/xml mime-type. A Content-Type header must not be sent with GET or DELETE requests.

You may also send standard web-form content with the application/x-www-form-urlencoded mime-type. Parameters should be translated like this: <zone><domain>example.com</domain><ns-type>pri_sec</ns-type></zone> becomes zone[domain]=example.com&zone[ns_type]=pri_sec.
Note that ns-type became ns_type. The rule is this: use hyphens for XML
node names and use underscores for web-form content or URL query
parameters.

If your HTTP client cannot sent PUT and DELETE verbs, you may
substitute the parameter _method=put along with a POST request. This
only works for web-form content and the _method parameter must be in
the POST body, not in the query string. It is recommended that you use
an HTTP client capable of using PUT and DELETE verbs.

API URL

The URL path for every API call begins with
http://ns.zerigo.com/api/1.1/ .

Listing All Zones

Request: GET /api/1.1/zones.xml

There are two optional parameters: page=# and per_page=#. page
defaults to 1 (and starts at 1, not 0). per_page defaults to 100 but
should be specified exactly if a change of the default value will cause
your application to fail. The maximum value for per_page is 1000.
Example:

GET /api/1.1/zones.xml?per_page=25&page=2

Response Header:

X-Query-Count: 12

Response Body:

<zones type="array">
  <zone>
    <created-at type="datetime">2008-12-07T02:40:02Z</created-at>
    <custom-nameservers nil="true"/>
    <custom-ns type="boolean">false</custom-ns>
    <default-ttl type="integer">600</default-ttl>
    <domain>example.com</domain>
    <hostmaster nil="true"/>
    <id type="integer">959</id>
    <ns1 nil="true"/>
    <ns2 nil="true"/>
    <ns3 nil="true"/>
    <ns-type>pri_sec</ns-type>
    <nx-ttl nil="true"/>
    <slave-nameservers nil="true"/>
    <updated-at type="datetime">2008-12-07T02:40:02Z</updated-at>
  </zone>
</zones>

X-Query-Count will contain the total number of results, including those that didn't fit inside this response. For example,
  if there are 12 results and per_page (above) is 10, only 10 entries will be returned but X-Query-Count will show 12 so that
  you know there are more results remaining.

default-ttl is in seconds.

ns-type has three valid values: 'pri_sec', 'pri', and 'sec'. They
are: Standard service (normal), Standard service with Master support,
and Slave only service respectively.

The value of ns-type will determine whether ns1 or slave-nameservers
are used. If ns-type is 'pri', then slave-nameservers should be used to
provide a comma-separated list of slave nameservers (eg:
"ns1.some-slave.com,ns2.some-slave.com"). If ns-type is 'sec', then ns1
is used to designate the master nameserver. Both ns1 and
slave-nameservers should be left blank when using the 'pri-sec' service.

ns2 and ns3 (along with ns1, which had dual-use) used to hold the
slave nameservers for 'pri' service. ns2 and ns3 are now fully
deprecated and should no longer be used or even included in any POST OR
PUT requests. They will be removed in the next version of the API. For
backwards compatibility in this version, when ns-type is 'pri', ns1,
ns2, and ns3 will contain the first 3 values from slave-nameservers.

custom-ns indicated if custom (vanity) nameservers are enabled for
this domain. Only allowed if the account's service plan support custom
nameservers.

custom-nameservers is a comma-separated list of custom nameservers.
If nil, the domain will use Zerigo's default list of servers. Only
valid for domains with custom-ns enabled.

hostmaster is the email of the DNS administrator or hostmaster. A
nil value will default to Zerigo's hostmaster address. Note that this
is publicly visible in the domain records. Only valid for domains with
custom-ns enabled.

Counting All Zones

Request: GET /api/1.1/zones/count.xml

Response:

<count>12</count>

This is the total number of zones available. It is the same result as provided in the X-Query-Count header above.

Listing a Specific Zone

Request: GET /api/1.1/zones/[zone_id].xml

Alternate: GET /api/1.1/zones/example.com.xml (to retrieve the record for example.com)

Response:

<zone>
  <created-at type="datetime">2008-12-07T02:40:02Z</created-at>
  <custom-nameservers>ns1.example.com,ns2.example.com</custom-nameservers>
  <custom-ns type="boolean">true</custom-ns>
  <default-ttl type="integer">600</default-ttl>
  <domain>example.com</domain>
  <hostmaster>dnsadmin@example.com</hostmaster>
  <id type="integer">959</id>
  <ns1 nil="true"/>
  <ns2 nil="true"/>
  <ns3 nil="true"/>
  <ns-type>pri_sec</ns-type>
  <nx-ttl nil="true"></nx-ttl>
  <slave-nameservers nil="true"/>
  <updated-at type="datetime">2008-12-07T02:40:02Z</updated-at>
  <hosts-count>1</hosts-count>
  <hosts type="array">
    <host>
      <created-at type="datetime">2008-12-07T02:51:13Z</created-at>
      <data>172.16.16.1</data>
      <fqdn>example.com</fqdn>
      <host-type>A</host-type>
      <hostname nil="true"/>
      <id type="integer">2499</id>
      <priority type="integer" nil="true"/>
      <ttl type="integer" nil="true"/>
      <updated-at type="datetime">2008-12-07T02:51:13Z</updated-at>
      <zone-id type="integer">959</zone-id>
    </host>
  </hosts>
</zone>

This response is similar to Listing All Zones, with the addition of
hosts-count and possibly hosts. As long as there are no more than 300
hosts, they will be returned. If there are more, the hosts array will
be left out. hosts-count will always be returned. Information on the
fields for the hosts are below under Listing All Hosts for a Zone.

Getting a Blank Zone

Request: GET /api/1.1/zones/new.xml

Response:

<zone>
  <custom-ns type="boolean">false</custom-ns>
  <default-ttl type="integer">600</default-ttl>
  <domain nil="true"/>
  <ns1 nil="true"/>
  <ns-type>pri_sec</ns-type>
  <nx-ttl nil="true"/>
  <slave-nameservers nil="true"/>
</zone>

This response may be useful to obtain a blank zone, suitable for use
as a template or retrieving default values for included fields.

Creating a New Zone

Request: POST /api/1.1/zones.xml

<zone>
  <default-ttl type="integer">600</default-ttl>
  <domain>example.com</domain>
  <ns1 nil="true"/>
  <ns2 nil="true"/>
  <ns3 nil="true"/>
  <ns-type>pri_sec</ns-type>
  <nx-ttl type="integer">900</nx-ttl>
  <slave-nameservers nil="true"/>
</zone>

Response: If successful, a copy of the new zone along with an HTTP
201 Created status. If unsuccessful, an HTTP 422 Unprocessable Entity
status and a list of errors:

<errors>
  <error>Domain is invalid</error>
  <error>Domain is too short (minimum is 4 characters)</error>
</errors>

ns1 should be left out unless ns-type is 'sec'. slave-nameservers
should be left out unless ns-type is 'pri'. See more details under
Listing All Zones.

Updating an Existing Zone

Request: PUT /api/1.1/zones/[zone_id].xml

<zone>
  <default-ttl type="integer">600</default-ttl>
  <domain>example.com</domain>
  <ns1 nil="true"/>
  <ns-type>pri_sec</ns-type>
  <slave-nameservers nil="true"/>
</zone>

ns1 should be left out unless ns-type is 'sec'. slave-nameservers
should be left out unless ns-type is 'pri'. See more details under
Listing All Zones.

Response: If successful, simply an HTTP 200 OK status. If
unsuccessful, an HTTP 422 Unprocessable Entity status and a list of
errors:

<errors>
  <error>Domain is invalid</error>
  <error>Domain is too short (minimum is 4 characters)</error>
</errors>

Deleting a Zone

Request: DELETE /api/1.1/zones/[zone_id].xml

Response: If successful, an HTTP 200 OK status.

Listing All Hosts

Request: GET /api/1.1/zones/[zone_id]/hosts.xml

Alternate: GET /api/1.1/hosts.xml?zone_id=#

There are two optional parameters: page=# and per_page=#. page
defaults to 1 (and starts at 1, not 0). per_page defaults to 100 but
should be specified exactly if a change of the default value will cause
your application to fail. The maximum value for per_page is 1000.
Example:

GET /api/1.1/zones/[zone_id]/hosts.xml?per_page=25&page=2

It is possible to search by hostname to limit the result set.
Searches are based on the FQDN (fully qualified domain name) which is
the combination of the hostname (if any) and the zone/domain name. An
example search request would be:

GET /api/1.1/zones/[zone_id]/hosts.xml?fqdn=www.example.com

This example would return all host records, regardless of host-type,
with a hostname of 'www' attached to [zone_id]. Note that the
referenced zone's domain must be 'example.com'. If the parameter was
fqdn=example.com, it would search for a hostname of nil.

Lastly, because the zone_id may not always be known, it is possible
to skip it when using the fqdn parameter. The zone id will be returned
in the response. Example:

GET /api/1.1/hosts.xml?fqdn=www.example.com

Response Header:

X-Query-Count: 4

Response Body:

<hosts type="array">
  <host>
    <created-at type="datetime">2008-12-07T02:51:13Z</created-at>
    <data>172.16.16.1</data>
    <fqdn>example.com</fqdn>
    <host-type>A</host-type>
    <hostname nil="true"/>
    <id type="integer">2499</id>
    <priority type="integer" nil="true"/>
    <ttl type="integer" nil="true"/>
    <updated-at type="datetime">2008-12-07T02:51:13Z</updated-at>
    <zone-id type="integer">959</zone-id>
  </host>
</hosts>

X-Query-Count will contain the total number of results, including those that didn't fit inside this response. For example,
  if there are 12 results and per_page (above) is 10, only 10 entries will be returned but X-Query-Count will show 12 so that
  you know there are more results remaining.

This is very similar to the response given in Listing a Specific
Zone except that it's only the hosts information, excluding the zone
fields.

hostname is any part of a domain in front of the domain itself. For
example, for a fully qualified domain name of 'www.example.com', where
the zone domain is 'example.com', the hostname would be 'www'. If there
isn't any hostname in front of the domain name, this should be set as
nil or left out.

host-type is the type of host record. Valid values are A, AAAA,
CNAME, MX, NS, SRV, and TXT. Note that NS is only for delegating DNS
for subdomains; non-subdomain NS records cannot be set this way. For
reverse domains, the only valid value is PTR.

host-type should be 'A' to set an Address record. This points a full
hostname (www.example.com) to a specific IP address (172.16.16.1) which
should be in the data field.

host-type should be 'MX' to set a Mail eXchange record. This
indicates where email for a full hostname (www.example.com) should be
delivered -- by using a hostname in the data field (mail.example.com).
Also see the priority field below.

host-type should be 'CNAME' to create a Canonical Name record. This
points one hostname as an alias to another which should be entered as a
hostname in the data field (othername.example.com).

host-type should be 'TXT' to configure a text record. The text
itself should be entered in the data field. A common use of this is
setting an SPF record for a domain.

priority indicates the relative priority of two or more MX records.
For example, this may be set to 10 for a primary mail server and 20 for
a backup server.

ttl is in seconds. If it is nil, the record uses the default-ttl value from the zone.

Counting All Hosts

Request: GET /api/1.1/zones/[zone_id]/hosts/count.xml

Alternate: GET /api/1.1/hosts/count.xml?zone_id=#

Response:

<count>12</count>

This is the total number of hosts available for zone [zone_id]. It
is the same result as provided in the X-Query-Count header above.

Listing a Specific Host

Request: GET /api/1.1/hosts/[host_id].xml

Response:

<host>
  <created-at type="datetime">2008-12-07T02:51:13Z</created-at>
  <data>172.16.16.1</data>
  <fqdn>example.com</fqdn>
  <host-type>A</host-type>
  <hostname nil="true"/>
  <id type="integer">2499</id>
  <priority type="integer" nil="true"/>
  <ttl type="integer" nil="true"/>
  <updated-at type="datetime">2008-12-07T02:51:13Z</updated-at>
  <zone-id type="integer">959</zone-id>
</host>

Getting a Blank Host

Request: GET /api/1.1/zones/[zone_id]/hosts/new.xml

Alternate: GET /api/1.1/hosts/new.xml?zone_id=#

Alternate: GET /api/1.1/hosts/new.xml

Response:

<host>
  <data nil="true"/>
  <host-type>A</host-type>
  <hostname nil="true"/>
  <priority type="integer" nil="true"/>
  <ttl type="integer" nil="true"/>
</host>

This response may be useful to obtain a blank host, suitable for use
as a template or retrieving default values for included fields. zone_id
will be populated only if provided.

Creating a New Host

Request: POST /api/1.1/zones/[zone_id]/hosts.xml

Alternate: POST /api/1.1/hosts.xml?zone_id=?

<host>
  <data>172.16.16.2</data>
  <host-type>A</host-type>
  <hostname>www</hostname>
  <priority type="integer" nil="true"/>
  <ttl type="integer" nil="true"/>
</host>

Response: If successful, a copy of the new host along with an HTTP
201 Created status. If unsuccessful, an HTTP 422 Unprocessable Entity
status and a list of errors:

<errors>
  <error>Data must be an IP</error>
</errors>

Note that priority or ttl can be left out entirely if their value is nil.

Updating an Existing Host

Request: PUT /api/1.1/hosts/[host_id].xml

<host>
  <data>172.16.16.2</data>
  <host-type>A</host-type>
  <hostname>www</hostname>
  <priority type="integer" nil="true"/>
  <ttl type="integer" nil="true"/>
</host>

Response: If successful, simply an HTTP 200 OK status. If
unsuccessful, an HTTP 422 Unprocessable Entity status and a list of
errors:

<errors>
  <error>Data must be an IP</error>
</errors>

Deleting a Host

Request: DELETE /api/1.1/hosts/[host_id].xml

Response: If successful, an HTTP 200 OK status.

Getting the current public IP

If you're doing development or production behind NAT devices, it may be helpful to retrieve your current public IP address.

Request: GET /api/1.1/tools/public_ipv4.xml

Response:

<ipv4>64.27.57.4</ipv4>

Home

Services

About Us

Support

Blog

Contact Us

      Contact Us. 1-888-9-ZERIGO or support@zerigo.com

      Copyright © 2009 Zerigo, Inc.; all rights reserved.


text:
"""View DICOM images using Python image Library (PIL)

Usage:
>>> import dicom
>>> from dicom.contrib.pydicom_PIL import show_PIL
>>> ds = dicom.read_file("filename")
>>> show_PIL(ds)

Requires Numpy:  http://numpy.scipy.org/
and Python Imaging Library:   http://www.pythonware.com/products/pil/

"""
# Copyright (c) 2009 Darcy Mason, Adit Panchal
# This file is part of pydicom, relased under an MIT license.
#    See the file license.txt included with this distribution, also
#    available at http://pydicom.googlecode.com

# Based on image.py from pydicom version 0.9.3,
#    LUT code added by Adit Panchal
# Tested on Python 2.5.4 (32-bit) on Mac OS X 10.6
#    using numpy 1.3.0 and PIL 1.1.7b1

have_PIL=True
try:
    import PIL.Image
except:
    have_PIL = False

have_numpy=True
try:
    import numpy as np
except:
    have_numpy = False

have_numpy=True
try:
    import numpy as np
except:
    have_numpy = False

def get_LUT_value(data, window, level):
    """Apply the RGB Look-Up Table for the given data and window/level value."""
    if not have_numpy:
        raise ImportError("Numpy is not available. See http://numpy.scipy.org/ to download and install")

    return np.piecewise(data,
        [data <= (level - 0.5 - (window-1)/2),
            data > (level - 0.5 + (window-1)/2)],
            [0, 255, lambda data: ((data - (level - 0.5))/(window-1) + 0.5)*(255-0)])

def get_LUT_value(data, window, level):
    """Apply the RGB Look-Up Table for the given data and window/level value."""
    if not have_numpy:
        raise ImportError("Numpy is not available. See http://numpy.scipy.org/ to download and install")

    return np.piecewise(data,
        [data <= (level - 0.5 - (window-1)/2),
            data > (level - 0.5 + (window-1)/2)],
            [0, 255, lambda data: ((data - (level - 0.5))/(window-1) + 0.5)*(255-0)])

# Display an image using the Python Imaging Library (PIL)
def show_PIL(dataset):
    if not have_PIL:
        raise ImportError("Python Imaging Library is not available. See http://www.pythonware.com/products/pil/ to download and install")
    if ('PixelData' not in dataset):
        raise TypeError("Cannot show image -- DICOM dataset does not have pixel data")
    if ('WindowWidth' not in dataset) or ('WindowCenter' not in dataset): # can only apply LUT if these values exist
        bits = dataset.BitsAllocated
        samples = dataset.SamplesPerPixel
        if bits == 8 and samples == 1:
            mode = "L"
        elif bits == 8 and samples == 3:
            mode = "RGB"
        elif bits == 16:
            mode = "I;16" # not sure about this -- PIL source says is 'experimental' and no documentation. Also, should bytes swap depending on endian of file and system??
        else:
            raise TypeError("Don't know PIL mode for %d BitsAllocated and %d SamplesPerPixel" % (bits, samples))

        # PIL size = (width, height)
        size = (dataset.Columns, dataset.Rows)

        im = PIL.Image.frombuffer(mode, size, dataset.PixelData, "raw", mode, 0, 1) # Recommended to specify all details by http://www.pythonware.com/library/pil/handbook/image.htm

    else:
        image = get_LUT_value(dataset.pixel_array, dataset.WindowWidth, dataset.WindowCenter)
        im = PIL.Image.fromarray(image).convert('L') # Convert mode to L since LUT has only 256 values: http://www.pythonware.com/library/pil/handbook/image.htm

    im.show()


text:
import config from './config'
import * as data from './data'

export default {
	name: "mk-app-portal-about",
	version: "1.0.0",
	description: "mk-app-portal-about",
	meta: data.getMeta(),
	components: [],
	config: config,
	load: (cb) => {
		require.ensure([], require => {
			cb(require('./component'), require('./action'), require('./reducer'))
		}, "mk-app-portal-about")
	}
}


text:
// $Id: barrier1.cpp 80826 2008-03-04 14:51:23Z wotte $

// This test program illustrates how the ACE barrier synchronization
// mechanisms work.

#include "ace/OS_main.h"
#include "ace/Barrier.h"
#include "ace/Thread_Manager.h"
#include "ace/Service_Config.h"

ACE_RCSID(Threads, barrier1, "$Id: barrier1.cpp 80826 2008-03-04 14:51:23Z wotte $")

#if defined (ACE_HAS_THREADS)

struct Tester_Args
  // = TITLE
  //     These arguments are passed into each test thread.
{
  Tester_Args (ACE_Barrier &tb, int i)
    : tester_barrier_ (tb),
      n_iterations_ (i) {}

  ACE_Barrier &tester_barrier_;
  // Reference to the tester barrier.  This controls each miteration of
  // the tester function running in every thread.

  int n_iterations_;
  // Number of iterations to run.
};

// Iterate <n_iterations> time printing off a message and "waiting"
// for all other threads to complete this iteration.

static void *
tester (Tester_Args *args)
{
  for (int iterations = 1;
       iterations <= args->n_iterations_;
       iterations++)
    {
      ACE_DEBUG ((LM_DEBUG, "(%t) in iteration %d\n", iterations));

      // Block until all other threads have waited, then continue.
      args->tester_barrier_.wait ();
    }

  return 0;
}

// Default number of threads to spawn.
static const int DEFAULT_ITERATIONS = 5;

int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  ACE_Service_Config daemon (argv[0]);

  int n_threads = argc > 1 ? ACE_OS::atoi (argv[1]) : ACE_DEFAULT_THREADS;
  int n_iterations = argc > 2 ? ACE_OS::atoi (argv[2]) : DEFAULT_ITERATIONS;

  ACE_Barrier tester_barrier (n_threads);

  Tester_Args args (tester_barrier, n_iterations);

  if (ACE_Thread_Manager::instance ()->spawn_n
      (int(n_threads), ACE_THR_FUNC (tester),
       (void *) &args, THR_NEW_LWP | THR_DETACHED) == -1)
    ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "spawn_n"), 1);

  // Wait for all the threads to reach their exit point.
  ACE_Thread_Manager::instance ()->wait ();

  ACE_DEBUG ((LM_DEBUG, "(%t) done\n"));
  return 0;
}
#else
int
ACE_TMAIN (int, ACE_TCHAR *[])
{
  ACE_ERROR ((LM_ERROR, "threads not supported on this platform\n"));
  return 0;
}
#endif /* ACE_HAS_THREADS */


text:
package com.bignerdranch.android.criminalintent;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class CrimeListFragment extends Fragment {
    private RecyclerView mCrimeRecyclerView;
    private CrimeAdapter mAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_crime_list, container, false);

        mCrimeRecyclerView = (RecyclerView) view
                .findViewById(R.id.crime_recycler_view);
        mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        updateUI();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    private void updateUI() {
        CrimeLab crimeLab = CrimeLab.get(getActivity());
        List<Crime> crimes = crimeLab.getCrimes();

        if (mAdapter == null) {
            mAdapter = new CrimeAdapter(crimes);
            mCrimeRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    private class CrimeHolder extends RecyclerView.ViewHolder
            implements View.OnClickListener {

        private Crime mCrime;

        private TextView mTitleTextView;
        private TextView mDateTextView;
        private ImageView mSolvedImageView;

        public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
            super(inflater.inflate(R.layout.list_item_crime, parent, false));
            itemView.setOnClickListener(this);

            mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
            mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
            mSolvedImageView = (ImageView) itemView.findViewById(R.id.crime_solved);
        }

        public void bind(Crime crime) {
            mCrime = crime;
            mTitleTextView.setText(mCrime.getTitle());
            mDateTextView.setText(mCrime.getDate().toString());
            mSolvedImageView.setVisibility(crime.isSolved() ? View.VISIBLE : View.GONE);
        }

        @Override
        public void onClick(View view) {
            Intent intent = CrimeActivity.newIntent(getActivity(), mCrime.getId());
            startActivity(intent);
        }
    }

    private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {

        private List<Crime> mCrimes;

        public CrimeAdapter(List<Crime> crimes) {
            mCrimes = crimes;
        }

        @Override
        public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            return new CrimeHolder(layoutInflater, parent);
        }

        @Override
        public void onBindViewHolder(CrimeHolder holder, int position) {
            Crime crime = mCrimes.get(position);
            holder.bind(crime);
        }

        @Override
        public int getItemCount() {
            return mCrimes.size();
        }
    }
}


text:
require 'rails_helper'

feature 'Root Page' do
  before(:all) do
    @habit = create(:capybara_habit)
  end
  after(:all) do
    @habit.destroy
  end
  scenario 'visit' do
    visit '/habitable'
    expect(page).to have_title "Habitable"
    #Navbar
      expect(page).to have_css "a", text: "Habitable"
      expect(page).to have_css "a", text: "New Habit"
    expect(page).to have_css "h1", text: "Habits"
    expect(page).to have_content "Apply sunscreen"
  end

  scenario 'submit form with good status' do
    visit '/habitable'
    fill_in 'habit_log_status', :with => "1"
    click_button "Send"
    expect(page).to have_content("Habit logged!")
    @habit.reload
    expect(@habit.streak).to eq(100)
  end

  scenario 'submit form with empty status' do
    visit '/habitable'
    fill_in 'habit_log_status', :with => ""
    click_button "Send"
    expect(page).to have_content("Status can't be blank")
  end

  scenario "submit form with status == 0" do
    visit '/habitable'
    fill_in 'habit_log_status', :with => "0"
    click_button "Send"
    @habit.reload
    expect(@habit.streak).to eq(0)
  end

  scenario "delete a habit" do
    visit '/habitable'
    find('.delete-btn', visible: false).click
    expect(page).to have_content("Habit deleted!")
  end
end


text:
from chars import Char  # Get Char class from chars

class Layout(object):  # Class to create layout
    def __init__(self):
        self.c = Char()  # Get characters from the chars page

        # Page header - Doctype through end of body header
        self.header = '''<!DOCTYPE HTML>

            <title>The New Freedom League</title>
            <link rel="stylesheet" href="css/style.css">

Claremont Academy Admin Zone

Team Roster: Freedom League

                    Admin HQ
                    More Teams

        '''

        # Content Frame - Title panel and start charList class
        self.content = '''

The Freedom League has long been established as the mascot of Freedom City, Texas.
            With an ever-changing roster of super heroes willing to sacrifice their time, energy, and even lives,
            they have earned the respect and love of the city they defend.

        '''

        # Footer - Close charList, wrapper, body, and full footer, end HTML
        self.footer = '''

Background image from MorgueFile.

All other images created by Harmony for Claremont Academy 2014©

         '''

    # Print Layout to Page
    def print_layout(self):
        # Page layout is header, content, filler, and footer
        page = self.header + self.content + self.filler_content() + self.footer
        # Return it all, with locals filled in
        return page.format(**locals())

    # Set filler content
    def filler_content(self):
        formatted = ""  # Empty Format container
        # Cycle through every character in list
        for x in self.c.chars_list:
            # Set up the buttons
            buttons = '''

{x.code_name}

{x.descrip}

Name: {x.name}

Age: {x.age}

Total Missions: {x.missions}

Total Victories: {x.victory}

Success Rate: {x.success_rate}%

Status: {x.get_status}

            '''
            # Format it all with the locals
            formatted += buttons.format(**locals())
        # Return the formatted stuff
        return formatted


text:
html.apfm-open,
html.apfm-open > body {
	width: 100%;
	height: 100%;
}

html.apfm-open > body {
	overflow: hidden;
}

.apfm-container {
	position: fixed;
	z-index: -1;
	visibility: hidden;
	opacity: 0;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	width: 100%;
	height: 100%;
	overflow-y: scroll;
	overflow-x: hidden;

	-webkit-transform: scale(0.8);
	-moz-transform: scale(0.8);
	-ms-transform: scale(0.8);
	-o-transform: scale(0.8);
	transform: scale(0.8);

}

.apfm-container.apfm-opening,
.apfm-container.apfm-closing {
	visibility: visible;
	z-index: 99999;

}

.apfm-container.apfm-open {
	visibility: visible;
	z-index: 99999;

	/* for iOS momentum/inertia scrolling */
	/* Must be put here and not in original .apfm-container class because
	   else scrolling on main page is buggy */
	-webkit-overflow-scrolling: touch;

	/* These attributes are animated: */
	opacity: 1;
	-webkit-transform: scale(1);
	-moz-transform: scale(1);
	-ms-transform: scale(1);
	-o-transform: scale(1);
	transform: scale(1);
}

.apfm-container .apfm-wrapper {
	position: relative;
}

.apfm-container .apfm-close-button {
	position: absolute;
	z-index: 1000;
	top: 20px;
	right: 20px;
	width: 50px;
	height: 50px;
	cursor: pointer;

	/* No blue selection when clicking on the cross */
	-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
	-webkit-tap-highlight-color: transparent;
	-webkit-touch-callout: none;
	-webkit-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	user-select: none;
}

.apfm-container .apfm-close-button::before,
.apfm-container .apfm-close-button::after {
	content: "";
	position: absolute;
	left: 0;
	top: 50%;
	width: 100%;
	height: 2px;
	background-color: #bbb;

	-webkit-transform: rotate(45deg);
	-moz-transform: rotate(45deg);
	-ms-transform: rotate(45deg);
	-o-transform: rotate(45deg);
	transform: rotate(45deg);

	-webkit-transition: background-color .2s;
	-moz-transition: background-color .2s;
	-ms-transition: background-color .2s;
	-o-transition: background-color .2s;
	transition: background-color .2s;
}

.apfm-container .apfm-close-button::after {
	-webkit-transform: rotate(-45deg);
	-moz-transform: rotate(-45deg);
	-ms-transform: rotate(-45deg);
	-o-transform: rotate(-45deg);
	transform: rotate(-45deg);
}

.apfm-container .apfm-close-button:hover::before,
.apfm-container .apfm-close-button:hover::after {
	background-color: #555;
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Br. mycol. Soc. 89(3): 350 (1987)

#### Original name
Fusarium bugnicourtii Brayford, 1987

### Remarks
null


text:
package com.intellij.psi.util.proximity;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.util.NullableLazyKey;
import com.intellij.psi.*;
import com.intellij.psi.util.ProximityLocation;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.NullableFunction;
import org.jetbrains.annotations.NotNull;

/**
 * @author peter
*/
public class ExplicitlyImportedWeigher extends ProximityWeigher {
  private static final NullableLazyKey<PsiPackage, ProximityLocation>
    PLACE_PACKAGE = NullableLazyKey.create("placePackage", new NullableFunction<ProximityLocation, PsiPackage>() {
    @Override
    public PsiPackage fun(ProximityLocation location) {
      return PsiTreeUtil.getContextOfType(location.getPosition(), PsiPackage.class, false);
    }
  });

  public Comparable weigh(@NotNull final PsiElement element, @NotNull final ProximityLocation location) {
    final PsiElement position = location.getPosition();
    if (position == null){
      return null;
    }

    final PsiFile elementFile = element.getContainingFile();
    final PsiFile positionFile = position.getContainingFile();
    if (positionFile != null && elementFile != null && positionFile.getOriginalFile().equals(elementFile.getOriginalFile())) {
      return true;
    }

    if (element instanceof PsiClass) {
      final String qname = ((PsiClass) element).getQualifiedName();
      if (qname != null) {
        final PsiJavaFile psiJavaFile = PsiTreeUtil.getContextOfType(position, PsiJavaFile.class, false);
        if (psiJavaFile != null) {
          final PsiImportList importList = psiJavaFile.getImportList();
          if (importList != null) {
            for (final PsiImportStatement importStatement : importList.getImportStatements()) {
              final boolean onDemand = importStatement.isOnDemand();
              final String imported = importStatement.getQualifiedName();
              if (onDemand && qname.startsWith(imported + ".") || !onDemand && qname.equals(imported)) {
                return true;
              }
            }
          }
        }
      }

    }
    if (element instanceof PsiMember) {
      final PsiPackage placePackage = PLACE_PACKAGE.getValue(location);
      if (placePackage == null) {
        return false;
      }

      Module elementModule = ModuleUtil.findModuleForPsiElement(element);
      return location.getPositionModule() == elementModule &&
             placePackage.equals(PsiTreeUtil.getContextOfType(element, PsiPackage.class, false));
    }
    return false;
  }
}