text:
using System;
using Newtonsoft.Json;

namespace CurrencyCloud.Entity
{
    public class PaymentDeliveryDates : Entity
    {
        [JsonConstructor]
        public PaymentDeliveryDates() { }

        public PaymentDeliveryDates(DateTime paymentDate, string paymentType, string currency, string bankCountry)
        {
            this.PaymentDate = paymentDate;
            this.PaymentType = paymentType;
            this.Currency = currency;
            this.BankCountry = bankCountry;
        }

        [Param]
        public DateTime? PaymentDate { get; set; }

        [Param]
        public string PaymentType { get; set; }

        [Param]
        public string Currency { get; set; }

        [Param]
        public string BankCountry { get; set; }

        public DateTime? PaymentDeliveryDate { get; set; }

        public DateTime? PaymentCutoffTime { get; set; }

        public string ToJSON()
        {
            var obj = new[]
            {
                new
                {
                    PaymentDate,
                    PaymentDeliveryDate,
                    PaymentCutoffTime,
                    PaymentType,
                    Currency,
                    BankCountry
                }
            };
            return JsonConvert.SerializeObject(obj);
        }

        public override bool Equals(object obj)
        {
            if (!(obj is PaymentDeliveryDates))
            {
                return false;
            }

            var paymentDeliveryDates = obj as PaymentDeliveryDates;

            return PaymentDate == paymentDeliveryDates.PaymentDate &&
                   PaymentDeliveryDate == paymentDeliveryDates.PaymentDate &&
                   PaymentCutoffTime == paymentDeliveryDates.PaymentCutoffTime &&
                   PaymentType == paymentDeliveryDates.PaymentType &&
                   Currency == paymentDeliveryDates.Currency &&
                   BankCountry == paymentDeliveryDates.BankCountry;
        }

        public override int GetHashCode()
        {
            return PaymentDate.GetHashCode() ^
                   PaymentDeliveryDate.GetHashCode() ^
                   PaymentType.GetHashCode() ^
                   Currency.GetHashCode() ^
                   BankCountry.GetHashCode();
        }
    }
}


text:
[![Build Status](https://travis-ci.org/ckaatz-here/container.svg?branch=master)](https://travis-ci.org/ckaatz-here/container)

Container is a library that allows you to specify  dependencies, and then invoke functions that can use any of those previously specified dependencies. Dependencies are matched through the argument names of the function that is invoked.

__Table of content__

- [Install](#install)
- [Usage Examples](#usage-examples)
- [API](#api)

## Install

**node.js**:

```bash
npm install cntnr --save
```

## Usage Examples

Dependencies can have dependencies of themselves, see the example below:

```
var Container = require('cntnr').Container;
var container = new Container();

container.add('settings', {
	logFile: '/var/log/mylog.log'
});
container.add('logger', function(settings, callback) {
	var Logger = require('logger');
	return callback(null, new Logger(settings.logFile));
});

container.invoke(function(logger) {
	logger.info('inside invoked function');
});
```

### creating a container
To start using dependency injection, the first thing to do is to create a container to add all your dependencies to.

```
var Container = require('cntnr').Container;
var container = new Container();
```

### adding dependencies

Once having a container, you can add dependencies using ```container.add(name, value)```.

### Invoking functions
order is not important, matching of arguments is done only by name, optional arguments have the postfix \_optional. This means no error will be thrown when the argument name without the _optional postfix is not present in the container.

## API

### Container.add(name, value)
Add a value to the container with ```name```. ```value``` can be a *creator function* that returns the dependency value through a callback. The argument has to be called callback, and the creator function can specify any number of other arguments that should match other dependencies in the container. In other words, creator functions are also dependency injected, with a special extra argument called callback.

The callback accepts to arguments, the first being an error if one occured or null if not, and the second one the value of the dependency if no error occurred.

```
container.add('a', function(anotherDependency, callback) {
	callback(null, 4);
});
```

If ```value``` is not a function, the given value will be returned when the dependency is requested.

```
container.add('port', 8080);
container.add('encryptionKey', 'asd8f9asf787s8dff9s8d');
container.add('today', new Date(1918, 10, 11));
```

### Container.addAll(obj)
Add multiple values to the container giving an object where each property is added to the container with the given name and value. Example:

```
container.addAll({
	a: 5,
	b: 3
});
```

### Container.addPath(name, path)
Add a given filepath to be hooked up to the container

```
container.addPath("module", "path/to/module.js");
```

### Container.get(name, callback)
retrieve a previously added dependency before running a callback function
Example:

```
container.get('neededDependency', function(err, neededDependency) {
    if(err) {
        return err;
    }
    container.on('error', function(err) {
        console.log('ERROR in DI container: ' + err.stack);
    });
});
```
### Container.invoke(fn [, extraArguments], callback)
invoke a function handing in a needed dependency
Example:

```
container.invoke(function(neededDependency) {
    a(neededDependency);
}, callback);
```
### Container.invokeAll(obj [, extraArguments], callback)
invoke several dependencies at once to be able to use it in the callback
```
container.invokeAll({
		a: 5,
		b: 3
	},callback);
```

### Container.bind(fn [, extraArguments], callback)
### Container.bindAll(obj [, extraArguments], callback)
### Container.create(path, callback)
### Container.createAll(obj, callback)

### error event on container

### circular reference detection
Detects circular references and throws an error then

## Future plans
   * add way to obtain dependency graph so it can be drawn in a diagram.

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by ramos on 29/12/14.
 */
'use strict';
/**
 * Default return API
 * @type {{status: {}, date: Date, data: Array}}
 */
var result = {

    status:{},
    date:new Date(),
    data:[]

};
module.exports = result;


text:
package com.google.api.ads.adwords.jaxws.v201406.o;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             A {@link SearchParameter} that specifies the level of search volume expected in results,
 *             and it has a direct relationship to
 *             {@link com.google.ads.api.services.targetingideas.external.AttributeType#SEARCH_VOLUME}.
 *             Absence of a {@link SearchVolumeSearchParameter} in a
 *             {@link com.google.ads.api.services.targetingideas.TargetingIdeaSelector} is
 *             equivalent to having no constraint on search volume specified.
 *
This element is supported by following {@link IdeaType}s: KEYWORD.
 *
This element is supported by following {@link RequestType}s: IDEAS, STATS.
 *
 *
 *
Java class for SearchVolumeSearchParameter complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="SearchVolumeSearchParameter">
 *   <complexContent>
 *     <extension base="{https://adwords.google.com/api/adwords/o/v201406}SearchParameter">
 *       <sequence>
 *         <element name="operation" type="{https://adwords.google.com/api/adwords/o/v201406}LongComparisonOperation" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SearchVolumeSearchParameter", propOrder = {
    "operation"
})
public class SearchVolumeSearchParameter
    extends SearchParameter
{

    protected LongComparisonOperation operation;

    /**
     * Gets the value of the operation property.
     *
     * @return
     *     possible object is
     *     {@link LongComparisonOperation }
     *
     */
    public LongComparisonOperation getOperation() {
        return operation;
    }

    /**
     * Sets the value of the operation property.
     *
     * @param value
     *     allowed object is
     *     {@link LongComparisonOperation }
     *
     */
    public void setOperation(LongComparisonOperation value) {
        this.operation = value;
    }

}


text:
var logger = {};
var DEBUG_LEVEL = 5;
logger.trace = function(str) {
  if (DEBUG_LEVEL >= 6) {
    console.log(str);
  }
}

logger.debug = function(str) {
  if (DEBUG_LEVEL >= 5) {
    console.log(str);
  }
}

logger.info = function(str) {
  if (DEBUG_LEVEL >= 4) {
    console.log(str);
  }
}

// Create logging panel on the left


text:
package org.apache.activemq;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.security.KeyStore;
import java.security.SecureRandom;

import javax.jms.JMSException;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import org.apache.activemq.broker.SslContext;
import org.apache.activemq.transport.Transport;
import org.apache.activemq.util.JMSExceptionSupport;

/**
 * An ActiveMQConnectionFactory that allows access to the key and trust managers
 * used for SslConnections. There is no reason to use this class unless SSL is
 * being used AND the key and trust managers need to be specified from within
 * code. In fact, if the URI passed to this class does not have an "ssl" scheme,
 * this class will pass all work on to its superclass.
 *
 * There are two alternative approaches you can use to provide X.509
 * certificates for the SSL connections:
 *
 * Call setTrustStore, setTrustStorePassword,
 * setKeyStore, and setKeyStorePassword.
 *
 * Call setKeyAndTrustManagers.
 *
 * @author sepandm@gmail.com
 */
public class ActiveMQSslConnectionFactory extends ActiveMQConnectionFactory {

    // The key and trust managers used to initialize the used SSLContext.
    protected KeyManager[] keyManager;
    protected TrustManager[] trustManager;
    protected SecureRandom secureRandom;
    protected String trustStoreType = KeyStore.getDefaultType();
    protected String trustStore;
    protected String trustStorePassword;
    protected String keyStoreType = KeyStore.getDefaultType();
    protected String keyStore;
    protected String keyStorePassword;
    protected String keyStoreKeyPassword;

    public ActiveMQSslConnectionFactory() {
        super();
    }

    public ActiveMQSslConnectionFactory(String brokerURL) {
        super(brokerURL);
    }

    public ActiveMQSslConnectionFactory(URI brokerURL) {
        super(brokerURL);
    }

    /**
     * Sets the key and trust managers used when creating SSL connections.
     *
     * @param km
     *            The KeyManagers used.
     * @param tm
     *            The TrustManagers used.
     * @param random
     *            The SecureRandom number used.
     */
    public void setKeyAndTrustManagers(final KeyManager[] km, final TrustManager[] tm, final SecureRandom random) {
        keyManager = km;
        trustManager = tm;
        secureRandom = random;
    }

    /**
     * Overriding to make special considerations for SSL connections. If we are
     * not using SSL, the superclass's method is called. If we are using SSL, an
     * SslConnectionFactory is used and it is given the needed key and trust
     * managers.
     *
     * @author sepandm@gmail.com
     */
    @Override
    protected Transport createTransport() throws JMSException {
        SslContext existing = SslContext.getCurrentSslContext();
        try {
            if (keyStore != null || trustStore != null) {
                keyManager = createKeyManager();
                trustManager = createTrustManager();
            }
            if (keyManager != null || trustManager != null) {
                SslContext.setCurrentSslContext(new SslContext(keyManager, trustManager, secureRandom));
            }
            return super.createTransport();
        } catch (Exception e) {
            throw JMSExceptionSupport.create("Could not create Transport. Reason: " + e, e);
        } finally {
            SslContext.setCurrentSslContext(existing);
        }
    }

    protected TrustManager[] createTrustManager() throws Exception {
        TrustManager[] trustStoreManagers = null;
        KeyStore trustedCertStore = KeyStore.getInstance(getTrustStoreType());

        if (trustStore != null) {
            try(InputStream tsStream = getInputStream(trustStore)) {

                trustedCertStore.load(tsStream, trustStorePassword.toCharArray());
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

                tmf.init(trustedCertStore);
                trustStoreManagers = tmf.getTrustManagers();
            }
        }
        return trustStoreManagers;
    }

    protected KeyManager[] createKeyManager() throws Exception {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        KeyStore ks = KeyStore.getInstance(getKeyStoreType());
        KeyManager[] keystoreManagers = null;
        if (keyStore != null) {
            byte[] sslCert = loadClientCredential(keyStore);

            if (sslCert != null && sslCert.length > 0) {
                try(ByteArrayInputStream bin = new ByteArrayInputStream(sslCert)) {
                    ks.load(bin, keyStorePassword.toCharArray());
                    kmf.init(ks, keyStoreKeyPassword !=null ? keyStoreKeyPassword.toCharArray() : keyStorePassword.toCharArray());
                    keystoreManagers = kmf.getKeyManagers();
                }
            }
        }
        return keystoreManagers;
    }

    protected byte[] loadClientCredential(String fileName) throws IOException {
        if (fileName == null) {
            return null;
        }
        try(InputStream in = getInputStream(fileName);
            ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            byte[] buf = new byte[512];
            int i = in.read(buf);
            while (i > 0) {
                out.write(buf, 0, i);
                i = in.read(buf);
            }
            return out.toByteArray();
        }
    }

    protected InputStream getInputStream(String urlOrResource) throws IOException {
        try {
            File ifile = new File(urlOrResource);
            // only open the file if and only if it exists
            if (ifile.exists()) {
                return new FileInputStream(ifile);
            }
        } catch (Exception e) {
        }

        InputStream ins = null;

        try {
            URL url = new URL(urlOrResource);
            ins = url.openStream();
            if (ins != null) {
                return ins;
            }
        } catch (MalformedURLException ignore) {
        }

        // Alternatively, treat as classpath resource
        if (ins == null) {
            ins = Thread.currentThread().getContextClassLoader().getResourceAsStream(urlOrResource);
        }

        if (ins == null) {
            throw new IOException("Could not load resource: " + urlOrResource);
        }

        return ins;
    }

    public String getTrustStoreType() {
        return trustStoreType;
    }

    public void setTrustStoreType(String type) {
        trustStoreType = type;
    }

    public String getTrustStore() {
        return trustStore;
    }

    /**
     * The location of a keystore file (in jks format) containing
     * one or more trusted certificates.
     *
     * @param trustStore
     *            If specified with a scheme, treat as a URL, otherwise treat as
     *            a classpath resource.
     */
    public void setTrustStore(String trustStore) throws Exception {
        this.trustStore = trustStore;
        trustManager = null;
    }

    public String getTrustStorePassword() {
        return trustStorePassword;
    }

    /**
     * The password to match the trust store specified by {@link setTrustStore}.
     *
     * @param trustStorePassword
     *            The password used to unlock the keystore file.
     */
    public void setTrustStorePassword(String trustStorePassword) {
        this.trustStorePassword = trustStorePassword;
    }

    public String getKeyStoreType() {
        return keyStoreType;
    }

    public void setKeyStoreType(String type) {
        keyStoreType = type;
    }

    public String getKeyStore() {
        return keyStore;
    }

    /**
     * The location of a keystore file (in jks format) containing a
     * certificate and its private key.
     *
     * @param keyStore
     *            If specified with a scheme, treat as a URL, otherwise treat as
     *            a classpath resource.
     */
    public void setKeyStore(String keyStore) throws Exception {
        this.keyStore = keyStore;
        keyManager = null;
    }

    public String getKeyStorePassword() {
        return keyStorePassword;
    }

    /**
     * The password to match the key store specified by {@link setKeyStore}.
     *
     * @param keyStorePassword
     *            The password, which is used both to unlock the keystore file
     *            and as the pass phrase for the private key stored in the
     *            keystore.
     */
    public void setKeyStorePassword(String keyStorePassword) {
        this.keyStorePassword = keyStorePassword;
    }

    public String getKeyStoreKeyPassword() {
        return keyStoreKeyPassword;
    }

    /**
     * The password to match the key from the keyStore.
     *
     * @param keyStoreKeyPassword
     *            The password for the private key stored in the
     *            keyStore if different from keyStorePassword.
     */
    public void setKeyStoreKeyPassword(String keyStoreKeyPassword) {
        this.keyStoreKeyPassword = keyStoreKeyPassword;
    }

}


text:
body {color: #463E21; background: #4d4d4d}

table.site_header {
  border-top : 8px solid #FFFFFF;
  border-left : 8px solid #FFFFFF;
  border-right: 5px solid #FFFFFF;
  border-bottom: 3px solid #FFFFFF;
  background-color: #BDC49A;
}

input:hover, select:hover, textarea:hover {
  background-color: #DCE0CA;
}

.mainBC {height: 0px;}

.mainBR {background-image: url(/images/box_bottom.jpg);background-repeat: no-repeat;background-position: center; height: 14px;width: 165px;border-right:5px solid #FFFFFF;border-left:5px solid #FFFFFF;}

.blocks {background-color: #BEC49E;}

.cornerTL {background-image: url(/images/rounded/top_left.jpg); width:11px; height: 14px;background-repeat: no-repeat;}
.cornerTC {background-image: url(/images/rounded/top_side.jpg); background-repeat: repeat-x;}
.cornerTR {background-image: url(/images/rounded/top_right.jpg); background-repeat: no-repeat; width:14px; height: 14px;
           border-right: 4px solid white;}
.cornerBL {background-image: url(/images/rounded/bottom_left.jpg);height: 12px;width: 11px; /*background-repeat: no-repeat;*/}
.cornerBC {background-image: url(/images/rounded/bottom_side.jpg);background-repeat: repeat-x; height:12px}
.cornerBR {background-image: url(/images/rounded/bottom_right.jpg);height: 12px;width: 14px; /*background-repeat: no-repeat;*/ border-right: 4px solid white;}
.cornerCL {background-image: url(/images/rounded/left_side.jpg);background-repeat: repeat-y; background-position: left;width: 11px;}
/*.cornerCC {background-image: url(/images/centre_05.gif);background-repeat: repeat-x;
background-position: top;} */
.cornerCR {background-image: url(/images/rounded/right_side.jpg);background-repeat: repeat-y; background-position: right;width: 13px; border-right: 4px solid white; }

/* top page */

td#leftcolumn {background-image: url(/images/box_bg.jpg);border-left: 5px solid #FFFFFF;border-right: 2px solid #FFFFFF; border-top: 2px solid #ffffff;}
td#leftcolumn div.blockTitle {padding: 3px; background-image: url(/images/bullet1.gif);padding-left: 25px;background-repeat: no-repeat; color: #463E21; font-weight: bold;font-size: 120%}

#centercolumn {font-size: 12px;}
#centercolumn th {background-color: #A2AD6A; color: #FFFFFF; vertical-align: middle;}
#centercolumn .blockTitle, #bottomCcolumn .blockTitle {padding: 1px; color: #408a1c; font-weight: bold; margin-top: 0px; margin-right: 0px;  margin-left: 0px;font-size: 115%}
#centercolumn .blockContent, #bottomCcolumn .blockContent {padding: 3px; margin-right: 0px;  margin-left: 0px; margin-bottom: 2px; line-height: 130%;}

/* forums */
.head {background-color: #B6BF8A; }
.even {background-color: #E9EBDE; }
.odd {background-color: #DEE1CE; }
.foot {background-color: #C8CDAE; }
tr.even td {background-color: #E9EBDE; }
tr.odd td {background-color: #DEE1CE; }

/* account pages */
#account_content {
  background-color: #727E49;
}


text:
BBCODEPY
========

bbcodepy is a fast Python BBCode parser and renderer.

Usage
-----

All common BBCode tags are supported by default.

``` python
import bbcodepy
print bbcodepy.Parser().to_html('[b]Hello![/b]')
```

Easily add new tags!

``` python
import bbcodepy

class YoutubeTag(bbcodepy.Tag):
    def to_html(self):
        attributes = {
            'src': self.get_content(True).strip(),
            'width': self.params.get('width', 420),
            'height': self.params.get('height', 315)
        }

        return '<iframe %s frameborder="0" allowfullscreen></iframe>' % self.renderer.html_attributes(attributes)

parser = bbcodepy.Parser()
parser.register_tag('youtube', YoutubeTag)

print parser.to_html('[youtube width=420 height=315]http://www.youtube.com/embed/rWTa6OKgWlM[/youtube]')
```


text:
<!DOCTYPE html>

    <title>
    For Relaxing Times, Make It Coding Time
    </title>
    <link rel="stylesheet" type="text/css" href="index.css">

Home

About

Blog

Archive

Projects

Post

          Cultural

            Right Questions for the Right Answer

by Santa Maria, Steven * September 6, 2015

          As I dive deeper into my development career, I'm starting to realize the value and importance of the online community to get things done. What I mean by this is that I probably would have been stuck on a coding challenge if it hadn't been for others who asked questions on Quora or Stack Overflow and had them answered.

          We can't however pose a question willy-nilly. There's a considered methodology of sorts that can make our questions more understandable and the answers we receive more helpful. Here are some tips I compiled that can help us with this:

In the question header, describe the problem concisely

Introduce the problem before any code

Post only the most relevant part of your code

Employ tags (of posts) to help describe and archive your question

Proof-read

Respond to feedback

          With these tips in mind, we can help make the development community more productive not just for everybody else but for yourself too!

  <button>View More Posts</button>


text:
import { useEffect, useRef } from 'react';

const events = ['mousedown', 'touchstart'] as const;

const clickedScrollbar = (evt: MouseEvent) =>
  document.documentElement.clientWidth <= evt.clientX ||
  document.documentElement.clientHeight <= evt.clientY;

export const useClickOutside = (onClickOutside: () => void) => {
  const ref = useRef<HTMLDivElement>(null);
  const fnRef = useRef(onClickOutside);
  fnRef.current = onClickOutside;

  useEffect(() => {
    const handle = (e: MouseEvent | TouchEvent) => {
      if (clickedScrollbar(e as MouseEvent)) {
        return;
      }

      if (!ref.current?.contains(e.target as Node)) {
        fnRef.current();
      }
    };

    events.forEach((eventName) => document.addEventListener(eventName, handle, true));

    return () => {
      events.forEach((eventName) => document.removeEventListener(eventName, handle, true));
    };
  }, []);

  return ref;
};


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

#define  ACE_BUILD_SVC_DLL
#include "ace/Log_Msg.h"
#include "Adaptive_Lock_Performance_Test_Base.h"
#include "ace/Semaphore.h"
#include "ace/Lock_Adapter_T.h"

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

#if defined (ACE_HAS_THREADS)

class ACE_Svc_Export Adaptive_Sema_Test : public Adaptive_Lock_Performance_Test_Base
{
public:
  virtual int init (int, ACE_TCHAR *[]);

private:
  static ACE_Semaphore sema;
};

ACE_Semaphore Adaptive_Sema_Test::sema (1);

int
Adaptive_Sema_Test::init (int, ACE_TCHAR *[])
{
  ACE_Lock *lock;
  ACE_NEW_RETURN (lock,
                  ACE_Lock_Adapter<ACE_Semaphore> (Adaptive_Sema_Test::sema),
                  -1);

  return this->set_lock (lock);
}

ACE_SVC_FACTORY_DECLARE (Adaptive_Sema_Test)
ACE_SVC_FACTORY_DEFINE  (Adaptive_Sema_Test)

#endif /* ACE_HAS_THREADS */


text:
package org.wikimedia.wikibase.entitysuggester.client.servlets.ingest;

import javax.servlet.annotation.WebServlet;
import org.wikimedia.wikibase.entitysuggester.client.EntityType;

/**
 * Source reference property dataset trainer Servlet
 *
 * @author Nilesh Chakraborty
 */
@WebServlet(
        name = "RefPropertyIngestServlet",
        displayName = "Sourceref Property Dataset Trainer",
        urlPatterns = "/ingest/refprops/*",
        loadOnStartup = 1
)
public class RefPropertyIngestServlet extends AbstractIngestServlet {

    /**
     * @return EntityType - the type of entity suggester this Servlet trains.
     */
    @Override
    protected EntityType getEntityType() {
        return EntityType.REF_PROPERTY;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<resource xmlns="http://datacite.org/schema/kernel-3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://datacite.org/schema/kernel-3 http://schema.datacite.org/meta/kernel-3/metadata.xsd">
  <identifier identifierType="DOI"/>
  <creators>
    <creator>
      <creatorName>Baldassare, Mark</creatorName>
    </creator>
  </creators>
  <titles>
    <title>Special Survey of Orange County 2001</title>
  </titles>
  <publisher>UC Irvine</publisher>
  <publicationYear>2014</publicationYear>
  <subjects>
    <subject>Consumer Confidence</subject>
    <subject>Traffic</subject>
    <subject>Growth</subject>
    <subject>Government</subject>
    <subject>Transportation</subject>
    <subject>Economy</subject>
    <subject>El Toro Airport</subject>
    <subject>Great Park</subject>
    <subject>Gray Davis</subject>
    <subject>George W. Bush</subject>
    <subject>Politics</subject>
  </subjects>
  <contributors>
    <contributor contributorType="DataManager">
      <contributorName>McKinley, Matthew J.</contributorName>
    </contributor>
    <contributor contributorType="Funder">
      <contributorName>University of California, Irvine</contributorName>
    </contributor>
  </contributors>
  <relatedIdentifiers>
    <relatedIdentifier relatedIdentifierType="URL" relationType="IsSupplementedBy">http://data.lib.uci.edu/ocs/</relatedIdentifier>
  </relatedIdentifiers>
  <resourceType resourceTypeGeneral="Dataset">Dataset</resourceType>
  <sizes>
    <size>694516</size>
  </sizes>
  <rightsList>
    <rights rightsURI="https://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International (CC-BY 4.0)</rights>
  </rightsList>
  <descriptions>
    <description descriptionType="Abstract">The Orange County Survey - a collaborative effort of the Public Policy Institute of California and the School of Social Ecology at the University of California, Irvine - is a special edition of the PPIC Statewide Survey. This is the first of an annual series of PPIC surveys of Orange County. The purpose of this study is to inform policymakers by providing timely, accurate, and objective information about policy preferences and economic, social, and political trends. The sample size is 2,004 Orange County adult residents.

Online data analysis & additional documentation in Link below.</description>
    <description descriptionType="Methods">The Orange County Survey is a special edition of the PPIC Statewide
Survey, which is directed by Mark Baldassare, a senior fellow at the
Public Policy Institute of California, with research assistance from Lisa
Cole and Eric McGhee. The survey was conducted in collaboration with the
School of Social Ecology at the University of California, Irvine; however, the survey methodology and questions and the content of this report were solely determined by Mark Baldassare.

The findings of this survey are based on a telephone survey of 2,004 Orange County adult residents interviewed from August 20 to August 31, 2001. Interviewing took place on weekend days and weekday nights, using a computer-generated random sample of telephone numbers, ensuring that both listed and unlisted telephone numbers were called. All telephone exchanges in Orange County were eligible for calling. Telephone numbers in the survey sample were called up to five times to increase the likelihood of reaching eligible households. Once a household was reached, an adult respondent (18 or older) was randomly chosen for interviewing by using the "last birthday method" to avoid biases in age and gender.

Each interview took an average of 20 minutes to complete. Interviewing was conducted in English or Spanish.

We used recent U.S. Census and state figures to compare the demographic characteristics of the survey sample with characteristics of Orange
County's adult population. The survey sample was closely comparable to the census and state figures.

The survey data in this report were statistically weighted to account for any demographic differences.

The sampling error for the total sample of 2,004 adults is +/- 2 percent at the 95 percent confidence level. This means that 95 times out of 100, the results will be within 2 percentage points of what they would be if all Orange County adults were interviewed. The sampling error for subgroups is larger. Sampling error is just one type of error to which surveys are subject.

Results may also be affected by factors such as question wording, question order, and survey timing.

Throughout the report, we refer to two geographic regions. North County refers to cities and communities north of the 55 Freeway, including
Anaheim, Orange, Villa Park, La Habra, Brea, Buena Park, Fullerton, Placentia, Yorba Linda, La Palma, Cypress, Los Alamitos, Rossmoor, Seal Beach, Westminster, Midway City, Stanton, Fountain Valley, Huntington Beach, Santa Ana, Garden Grove, Tustin, Tustin Foothills, and Costa Mesa. South County refers to cities and communities south of the 55 Freeway, including Newport Beach, Irvine, Lake Forest, Newport Coast, Aliso Viejo, Laguna Hills, Laguna Niguel, Laguna Woods, Mission Viejo, Portola Hills, Rancho Santa Margarita, Foothill Ranch, Coto de Caza, Trabuco, Laguna Beach, Dana Point, San Clemente, Capistrano Beach, and San Juan Capistrano. In the analysis of questions on the proposed El Toro airport, we include Newport Beach in the North County.

We also present results for non-Hispanic whites (referred to in the tables as "whites"), Latinos, and Asians because each group accounts for a substantial number of the county's adult population. We also contrast the opinions of Democrats and Republicans with "other" or "independent" registered voters. This third category includes those who are registered to vote as "decline to state" as well as a fewer number who say they are members of other political parties.

In some cases, we compare the Orange County Survey responses to responses in the 1982-2000 Orange County Annual Surveys at the University of California, Irvine, the PPIC Statewide Surveys, and national surveys by the University of Michigan and CBS/New York Times.</description>
  </descriptions>
  <geoLocations>
    <geoLocation>
      <geoLocationPlace>Orange County (Calif.)</geoLocationPlace>
    </geoLocation>
  </geoLocations>
</resource>


text:
from __future__ import unicode_literals
from __future__ import absolute_import

from .. import unittest
import mock

import docker
from docker.utils import LogConfig

from compose.service import Service
from compose.container import Container
from compose.const import LABEL_SERVICE, LABEL_PROJECT, LABEL_ONE_OFF
from compose.service import (
    ConfigError,
    NeedsBuildError,
    NoSuchImageError,
    build_port_bindings,
    build_volume_binding,
    get_container_data_volumes,
    merge_volume_bindings,
    parse_repository_tag,
    parse_volume_spec,
    split_port,
)

class ServiceTest(unittest.TestCase):

    def setUp(self):
        self.mock_client = mock.create_autospec(docker.Client)

    def test_name_validations(self):
        self.assertRaises(ConfigError, lambda: Service(name='', image='foo'))

        self.assertRaises(ConfigError, lambda: Service(name=' ', image='foo'))
        self.assertRaises(ConfigError, lambda: Service(name='/', image='foo'))
        self.assertRaises(ConfigError, lambda: Service(name='!', image='foo'))
        self.assertRaises(ConfigError, lambda: Service(name='\xe2', image='foo'))

        Service('a', image='foo')
        Service('foo', image='foo')
        Service('foo-bar', image='foo')
        Service('foo.bar', image='foo')
        Service('foo_bar', image='foo')
        Service('_', image='foo')
        Service('___', image='foo')
        Service('-', image='foo')
        Service('--', image='foo')
        Service('.__.', image='foo')

    def test_project_validation(self):
        self.assertRaises(ConfigError, lambda: Service('bar'))
        self.assertRaises(ConfigError, lambda: Service(name='foo', project='>', image='foo'))

        Service(name='foo', project='bar.bar__', image='foo')

    def test_containers(self):
        service = Service('db', self.mock_client, 'myproject', image='foo')
        self.mock_client.containers.return_value = []
        self.assertEqual(service.containers(), [])

    def test_containers_with_containers(self):
        self.mock_client.containers.return_value = [
            dict(Name=str(i), Image='foo', Id=i) for i in range(3)
        ]
        service = Service('db', self.mock_client, 'myproject', image='foo')
        self.assertEqual([c.id for c in service.containers()], range(3))

        expected_labels = [
            '{0}=myproject'.format(LABEL_PROJECT),
            '{0}=db'.format(LABEL_SERVICE),
            '{0}=False'.format(LABEL_ONE_OFF),
        ]

        self.mock_client.containers.assert_called_once_with(
            all=False,
            filters={'label': expected_labels})

    def test_container_without_name(self):
        self.mock_client.containers.return_value = [
            {'Image': 'foo', 'Id': '1', 'Name': '1'},
            {'Image': 'foo', 'Id': '2', 'Name': None},
            {'Image': 'foo', 'Id': '3'},
        ]
        service = Service('db', self.mock_client, 'myproject', image='foo')

        self.assertEqual([c.id for c in service.containers()], ['1'])
        self.assertEqual(service._next_container_number(), 2)
        self.assertEqual(service.get_container(1).id, '1')

    def test_get_volumes_from_container(self):
        container_id = 'aabbccddee'
        service = Service(
            'test',
            image='foo',
            volumes_from=[mock.Mock(id=container_id, spec=Container)])

        self.assertEqual(service._get_volumes_from(), [container_id])

    def test_get_volumes_from_service_container_exists(self):
        container_ids = ['aabbccddee', '12345']
        from_service = mock.create_autospec(Service)
        from_service.containers.return_value = [
            mock.Mock(id=container_id, spec=Container)
            for container_id in container_ids
        ]
        service = Service('test', volumes_from=[from_service], image='foo')

        self.assertEqual(service._get_volumes_from(), container_ids)

    def test_get_volumes_from_service_no_container(self):
        container_id = 'abababab'
        from_service = mock.create_autospec(Service)
        from_service.containers.return_value = []
        from_service.create_container.return_value = mock.Mock(
            id=container_id,
            spec=Container)
        service = Service('test', image='foo', volumes_from=[from_service])

        self.assertEqual(service._get_volumes_from(), [container_id])
        from_service.create_container.assert_called_once_with()

    def test_split_port_with_host_ip(self):
        internal_port, external_port = split_port("127.0.0.1:1000:2000")
        self.assertEqual(internal_port, "2000")
        self.assertEqual(external_port, ("127.0.0.1", "1000"))

    def test_split_port_with_protocol(self):
        internal_port, external_port = split_port("127.0.0.1:1000:2000/udp")
        self.assertEqual(internal_port, "2000/udp")
        self.assertEqual(external_port, ("127.0.0.1", "1000"))

    def test_split_port_with_host_ip_no_port(self):
        internal_port, external_port = split_port("127.0.0.1::2000")
        self.assertEqual(internal_port, "2000")
        self.assertEqual(external_port, ("127.0.0.1", None))

    def test_split_port_with_host_port(self):
        internal_port, external_port = split_port("1000:2000")
        self.assertEqual(internal_port, "2000")
        self.assertEqual(external_port, "1000")

    def test_split_port_no_host_port(self):
        internal_port, external_port = split_port("2000")
        self.assertEqual(internal_port, "2000")
        self.assertEqual(external_port, None)

    def test_split_port_invalid(self):
        with self.assertRaises(ConfigError):
            split_port("0.0.0.0:1000:2000:tcp")

    def test_build_port_bindings_with_one_port(self):
        port_bindings = build_port_bindings(["127.0.0.1:1000:1000"])
        self.assertEqual(port_bindings["1000"], [("127.0.0.1", "1000")])

    def test_build_port_bindings_with_matching_internal_ports(self):
        port_bindings = build_port_bindings(["127.0.0.1:1000:1000", "127.0.0.1:2000:1000"])
        self.assertEqual(port_bindings["1000"], [("127.0.0.1", "1000"), ("127.0.0.1", "2000")])

    def test_build_port_bindings_with_nonmatching_internal_ports(self):
        port_bindings = build_port_bindings(["127.0.0.1:1000:1000", "127.0.0.1:2000:2000"])
        self.assertEqual(port_bindings["1000"], [("127.0.0.1", "1000")])
        self.assertEqual(port_bindings["2000"], [("127.0.0.1", "2000")])

    def test_split_domainname_none(self):
        service = Service('foo', image='foo', hostname='name', client=self.mock_client)
        self.mock_client.containers.return_value = []
        opts = service._get_container_create_options({'image': 'foo'}, 1)
        self.assertEqual(opts['hostname'], 'name', 'hostname')
        self.assertFalse('domainname' in opts, 'domainname')

    def test_memory_swap_limit(self):
        service = Service(name='foo', image='foo', hostname='name', client=self.mock_client, mem_limit=1000000000, memswap_limit=2000000000)
        self.mock_client.containers.return_value = []
        opts = service._get_container_create_options({'some': 'overrides'}, 1)
        self.assertEqual(opts['host_config']['MemorySwap'], 2000000000)
        self.assertEqual(opts['host_config']['Memory'], 1000000000)

    def test_log_opt(self):
        log_opt = {'address': 'tcp://192.168.0.42:123'}
        service = Service(name='foo', image='foo', hostname='name', client=self.mock_client, log_driver='syslog', log_opt=log_opt)
        self.mock_client.containers.return_value = []
        opts = service._get_container_create_options({'some': 'overrides'}, 1)

        self.assertIsInstance(opts['host_config']['LogConfig'], LogConfig)
        self.assertEqual(opts['host_config']['LogConfig'].type, 'syslog')
        self.assertEqual(opts['host_config']['LogConfig'].config, log_opt)

    def test_split_domainname_fqdn(self):
        service = Service(
            'foo',
            hostname='name.domain.tld',
            image='foo',
            client=self.mock_client)
        self.mock_client.containers.return_value = []
        opts = service._get_container_create_options({'image': 'foo'}, 1)
        self.assertEqual(opts['hostname'], 'name', 'hostname')
        self.assertEqual(opts['domainname'], 'domain.tld', 'domainname')

    def test_split_domainname_both(self):
        service = Service(
            'foo',
            hostname='name',
            image='foo',
            domainname='domain.tld',
            client=self.mock_client)
        self.mock_client.containers.return_value = []
        opts = service._get_container_create_options({'image': 'foo'}, 1)
        self.assertEqual(opts['hostname'], 'name', 'hostname')
        self.assertEqual(opts['domainname'], 'domain.tld', 'domainname')

    def test_split_domainname_weird(self):
        service = Service(
            'foo',
            hostname='name.sub',
            domainname='domain.tld',
            image='foo',
            client=self.mock_client)
        self.mock_client.containers.return_value = []
        opts = service._get_container_create_options({'image': 'foo'}, 1)
        self.assertEqual(opts['hostname'], 'name.sub', 'hostname')
        self.assertEqual(opts['domainname'], 'domain.tld', 'domainname')

    def test_get_container_not_found(self):
        self.mock_client.containers.return_value = []
        service = Service('foo', client=self.mock_client, image='foo')

        self.assertRaises(ValueError, service.get_container)

    @mock.patch('compose.service.Container', autospec=True)
    def test_get_container(self, mock_container_class):
        container_dict = dict(Name='default_foo_2')
        self.mock_client.containers.return_value = [container_dict]
        service = Service('foo', image='foo', client=self.mock_client)

        container = service.get_container(number=2)
        self.assertEqual(container, mock_container_class.from_ps.return_value)
        mock_container_class.from_ps.assert_called_once_with(
            self.mock_client, container_dict)

    @mock.patch('compose.service.log', autospec=True)
    def test_pull_image(self, mock_log):
        service = Service('foo', client=self.mock_client, image='someimage:sometag')
        service.pull()
        self.mock_client.pull.assert_called_once_with(
            'someimage',
            tag='sometag',
            stream=True)
        mock_log.info.assert_called_once_with('Pulling foo (someimage:sometag)...')

    def test_pull_image_no_tag(self):
        service = Service('foo', client=self.mock_client, image='ababab')
        service.pull()
        self.mock_client.pull.assert_called_once_with(
            'ababab',
            tag='latest',
            stream=True)

    @mock.patch('compose.service.Container', autospec=True)
    def test_recreate_container(self, _):
        mock_container = mock.create_autospec(Container)
        service = Service('foo', client=self.mock_client, image='someimage')
        service.image = lambda: {'Id': 'abc123'}
        new_container = service.recreate_container(mock_container)

        mock_container.stop.assert_called_once_with(timeout=10)
        self.mock_client.rename.assert_called_once_with(
            mock_container.id,
            '%s_%s' % (mock_container.short_id, mock_container.name))

        new_container.start.assert_called_once_with()
        mock_container.remove.assert_called_once_with()

    @mock.patch('compose.service.Container', autospec=True)
    def test_recreate_container_with_timeout(self, _):
        mock_container = mock.create_autospec(Container)
        self.mock_client.inspect_image.return_value = {'Id': 'abc123'}
        service = Service('foo', client=self.mock_client, image='someimage')
        service.recreate_container(mock_container, timeout=1)

        mock_container.stop.assert_called_once_with(timeout=1)

    def test_parse_repository_tag(self):
        self.assertEqual(parse_repository_tag("root"), ("root", ""))
        self.assertEqual(parse_repository_tag("root:tag"), ("root", "tag"))
        self.assertEqual(parse_repository_tag("user/repo"), ("user/repo", ""))
        self.assertEqual(parse_repository_tag("user/repo:tag"), ("user/repo", "tag"))
        self.assertEqual(parse_repository_tag("url:5000/repo"), ("url:5000/repo", ""))
        self.assertEqual(parse_repository_tag("url:5000/repo:tag"), ("url:5000/repo", "tag"))

    @mock.patch('compose.service.Container', autospec=True)
    def test_create_container_latest_is_used_when_no_tag_specified(self, mock_container):
        service = Service('foo', client=self.mock_client, image='someimage')
        images = []

        def pull(repo, tag=None, **kwargs):
            self.assertEqual('someimage', repo)
            self.assertEqual('latest', tag)
            images.append({'Id': 'abc123'})
            return []

        service.image = lambda *args, **kwargs: mock_get_image(images)
        self.mock_client.pull = pull

        service.create_container()
        self.assertEqual(1, len(images))

    def test_create_container_with_build(self):
        service = Service('foo', client=self.mock_client, build='.')

        images = []
        service.image = lambda *args, **kwargs: mock_get_image(images)
        service.build = lambda: images.append({'Id': 'abc123'})

        service.create_container(do_build=True)
        self.assertEqual(1, len(images))

    def test_create_container_no_build(self):
        service = Service('foo', client=self.mock_client, build='.')
        service.image = lambda: {'Id': 'abc123'}

        service.create_container(do_build=False)
        self.assertFalse(self.mock_client.build.called)

    def test_create_container_no_build_but_needs_build(self):
        service = Service('foo', client=self.mock_client, build='.')
        service.image = lambda *args, **kwargs: mock_get_image([])

        with self.assertRaises(NeedsBuildError):
            service.create_container(do_build=False)

    def test_build_does_not_pull(self):
        self.mock_client.build.return_value = [
            '{"stream": "Successfully built 12345"}',
        ]

        service = Service('foo', client=self.mock_client, build='.')
        service.build()

        self.assertEqual(self.mock_client.build.call_count, 1)
        self.assertFalse(self.mock_client.build.call_args[1]['pull'])

def mock_get_image(images):
    if images:
        return images[0]
    else:
        raise NoSuchImageError()

class ServiceVolumesTest(unittest.TestCase):

    def setUp(self):
        self.mock_client = mock.create_autospec(docker.Client)

    def test_parse_volume_spec_only_one_path(self):
        spec = parse_volume_spec('/the/volume')
        self.assertEqual(spec, (None, '/the/volume', 'rw'))

    def test_parse_volume_spec_internal_and_external(self):
        spec = parse_volume_spec('external:interval')
        self.assertEqual(spec, ('external', 'interval', 'rw'))

    def test_parse_volume_spec_with_mode(self):
        spec = parse_volume_spec('external:interval:ro')
        self.assertEqual(spec, ('external', 'interval', 'ro'))

        spec = parse_volume_spec('external:interval:z')
        self.assertEqual(spec, ('external', 'interval', 'z'))

    def test_parse_volume_spec_too_many_parts(self):
        with self.assertRaises(ConfigError):
            parse_volume_spec('one:two:three:four')

    def test_build_volume_binding(self):
        binding = build_volume_binding(parse_volume_spec('/outside:/inside'))
        self.assertEqual(binding, ('/inside', '/outside:/inside:rw'))

    def test_get_container_data_volumes(self):
        options = [
            '/host/volume:/host/volume:ro',
            '/new/volume',
            '/existing/volume',
        ]

        self.mock_client.inspect_image.return_value = {
            'ContainerConfig': {
                'Volumes': {
                    '/mnt/image/data': {},
                }
            }
        }
        container = Container(self.mock_client, {
            'Image': 'ababab',
            'Volumes': {
                '/host/volume': '/host/volume',
                '/existing/volume': '/var/lib/docker/aaaaaaaa',
                '/removed/volume': '/var/lib/docker/bbbbbbbb',
                '/mnt/image/data': '/var/lib/docker/cccccccc',
            },
        }, has_been_inspected=True)

        expected = {
            '/existing/volume': '/var/lib/docker/aaaaaaaa:/existing/volume:rw',
            '/mnt/image/data': '/var/lib/docker/cccccccc:/mnt/image/data:rw',
        }

        binds = get_container_data_volumes(container, options)
        self.assertEqual(binds, expected)

    def test_merge_volume_bindings(self):
        options = [
            '/host/volume:/host/volume:ro',
            '/host/rw/volume:/host/rw/volume',
            '/new/volume',
            '/existing/volume',
        ]

        self.mock_client.inspect_image.return_value = {
            'ContainerConfig': {'Volumes': {}}
        }

        intermediate_container = Container(self.mock_client, {
            'Image': 'ababab',
            'Volumes': {'/existing/volume': '/var/lib/docker/aaaaaaaa'},
        }, has_been_inspected=True)

        expected = [
            '/host/volume:/host/volume:ro',
            '/host/rw/volume:/host/rw/volume:rw',
            '/var/lib/docker/aaaaaaaa:/existing/volume:rw',
        ]

        binds = merge_volume_bindings(options, intermediate_container)
        self.assertEqual(set(binds), set(expected))

    def test_mount_same_host_path_to_two_volumes(self):
        service = Service(
            'web',
            image='busybox',
            volumes=[
                '/host/path:/data1',
                '/host/path:/data2',
            ],
            client=self.mock_client,
        )

        self.mock_client.inspect_image.return_value = {
            'Id': 'ababab',
            'ContainerConfig': {
                'Volumes': {}
            }
        }

        create_options = service._get_container_create_options(
            override_options={},
            number=1,
        )

        self.assertEqual(
            set(create_options['host_config']['Binds']),
            set([
                '/host/path:/data1:rw',
                '/host/path:/data2:rw',
            ]),
        )

    def test_different_host_path_in_container_json(self):
        service = Service(
            'web',
            image='busybox',
            volumes=['/host/path:/data'],
            client=self.mock_client,
        )

        self.mock_client.inspect_image.return_value = {
            'Id': 'ababab',
            'ContainerConfig': {
                'Volumes': {
                    '/data': {},
                }
            }
        }

        self.mock_client.inspect_container.return_value = {
            'Id': '123123123',
            'Image': 'ababab',
            'Volumes': {
                '/data': '/mnt/sda1/host/path',
            },
        }

        create_options = service._get_container_create_options(
            override_options={},
            number=1,
            previous_container=Container(self.mock_client, {'Id': '123123123'}),
        )

        self.assertEqual(
            create_options['host_config']['Binds'],
            ['/mnt/sda1/host/path:/data:rw'],
        )

    def test_create_with_special_volume_mode(self):
        self.mock_client.inspect_image.return_value = {'Id': 'imageid'}

        create_calls = []

        def create_container(*args, **kwargs):
            create_calls.append((args, kwargs))
            return {'Id': 'containerid'}

        self.mock_client.create_container = create_container

        volumes = ['/tmp:/foo:z']

        Service(
            'web',
            client=self.mock_client,
            image='busybox',
            volumes=volumes,
        ).create_container()

        self.assertEqual(len(create_calls), 1)
        self.assertEqual(create_calls[0][1]['host_config']['Binds'], volumes)


text:
package com.blazeroni.reddit.util;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

import android.os.Handler;
import android.util.Log;

/**
 * A class similar but unrelated to android's {@link android.os.AsyncTask}.
 *
 * Unlike AsyncTask, this class properly propagates exceptions.
 *
 * If you're familiar with AsyncTask and are looking for {@link android.os.AsyncTask#doInBackground(Object[])},
 * we've named it {@link #call()} here to conform with java 1.5's {@link java.util.concurrent.Callable} interface.
 *
 * Current limitations: does not yet handle progress, although it shouldn't be
 * hard to add.
 *
 * Borrowed from Roboguice.
 *
 * @param <T>
 */
public abstract class SafeAsyncTask<T> implements Callable<T> {

    private static final ThreadFactory THREAD_FACTORY = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r) {
            return new Thread(r, "SafeAsyncTask #" + this.mCount.getAndIncrement());
        }
    };
    private static final ExecutorService POOL = Executors.newCachedThreadPool(THREAD_FACTORY);

    private Handler handler;
    private FutureTask<T> future = new FutureTask<T>(newTask());

    public SafeAsyncTask() {
        this.handler = new Handler();
    }

    public SafeAsyncTask(Handler handler) {
        this.handler = handler;
    }

    public void execute() {
        POOL.execute(this.future);
    }

    public boolean cancel(boolean mayInterruptIfRunning) {
        return this.future != null && this.future.cancel(mayInterruptIfRunning);
    }

    /**
     * @throws Exception, captured on passed to onException() if present.
     */
    protected void onPreExecute() throws Exception {}

    /**
     * @param t the result of {@link #call()}
     * @throws Exception, captured on passed to onException() if present.
     */
    protected void onSuccess(T t) throws Exception {}

    /**
     * Called when the thread has been interrupted, likely because
     * the task was canceled.
     *
     * By default, calls {@link #onException(Exception)}, but this method
     * may be overridden to handle interruptions differently than other
     * exceptions.
     *
     * @param e the exception thrown from {@link #onPreExecute()}, {@link #call()}, or {@link #onSuccess(Object)}
     */
    protected void onInterrupted(InterruptedException e) {
        onException(e);
    }

    /**
     * Logs the exception as an Error by default, but this method may
     * be overridden by subclasses.
     *
     * @param e the exception thrown from {@link #onPreExecute()}, {@link #call()}, or {@link #onSuccess(Object)}
     * @throws RuntimeException, ignored
     */
    protected void onException( Exception e ) throws RuntimeException {
        Log.e("Redditastic", "Exception caught during background processing", e);
    }

    /**
     * @throws RuntimeException, ignored
     */
    protected void onFinally() throws RuntimeException {}

    protected Task newTask() {
        return new Task();
    }

    protected class Task implements Callable<T> {
        public T call() throws Exception {
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
            try {
                doPreExecute();
                doSuccess(doCall());
                return null;

            } catch( final Exception e ) {
                try {
                    doException(e);
                } catch( Exception f ) {
                    // ignored, throw original instead
                }
                throw e;

            } finally {
                doFinally();
            }
        }

        protected void doPreExecute() throws Exception {
            postToUiThreadAndWait( new Callable<Object>() {
                public Object call() throws Exception {
                    onPreExecute();
                    return null;
                }
            });
        }

        protected T doCall() throws Exception {
            return SafeAsyncTask.this.call();
        }

        protected void doSuccess( final T r ) throws Exception {
            postToUiThreadAndWait( new Callable<Object>() {
                public Object call() throws Exception {
                    onSuccess(r);
                    return null;
                }
            });
        }

        protected void doException( final Exception e ) throws Exception {
            postToUiThreadAndWait( new Callable<Object>() {
                public Object call() throws Exception {
                    if( e instanceof InterruptedException ) {
                        onInterrupted((InterruptedException)e);
                    }
                    else {
                        onException(e);
                    }
                    return null;
                }
            });
        }

        protected void doFinally() throws Exception {
            postToUiThreadAndWait( new Callable<Object>() {
                public Object call() throws Exception {
                    onFinally();
                    return null;
                }
            });
        }

        /**
         * Posts the specified runnable to the UI thread using a handler,
         * and waits for operation to finish.  If there's an exception,
         * it captures it and rethrows it.
         * @param c the callable to post
         * @throws Exception on error
         */
        protected void postToUiThreadAndWait( final Callable<?> c ) throws Exception {
            final CountDownLatch latch = new CountDownLatch(1);
            final Exception[] exceptions = new Exception[1];

            // Execute onSuccess in the UI thread, but wait
            // for it to complete.
            // If it throws an exception, capture that exception
            // and rethrow it later.
            SafeAsyncTask.this.handler.post( new Runnable() {
               public void run() {
                   try {
                       c.call();
                   } catch( Exception e ) {
                       exceptions[0] = e;
                   } finally {
                       latch.countDown();
                   }
               }
            });

            // Wait for onSuccess to finish
            latch.await();

            if( exceptions[0] != null ) {
                throw exceptions[0];
            }
        }
    }
}


text:
import { forwardRef } from "react";

import { FontIcon, FontIconProps } from "@react-md/icon";

export const ImageAspectRatioFontIcon = forwardRef<HTMLElement, FontIconProps>(
  function ImageAspectRatioFontIcon(props, ref) {
    return (
      <FontIcon {...props} ref={ref}>
        image_aspect_ratio
      </FontIcon>
    );
  }
);


text:
set -e
set -x

usage() {
    echo "run_ctverif.sh install_dir part?"
    exit 1
}

runSingleTest() {
    cd "${BASE_S2N_DIR}/tests/sidetrail/working/${1}"
    ./copy_as_needed.sh
    make clean

    #run the test.  We expect both to pass, and none to fail
    FAILED=0
    EXPECTED_PASS=1
    EXPECTED_FAIL=0
    make 2>&1 | ../../count_success.pl $EXPECTED_PASS $EXPECTED_FAIL || FAILED=1

    if [ $FAILED == 1 ];
    then
	printf "\\033[31;1mFAILED ctverif\\033[0m\\n"
	exit -1
    else
	printf "\\033[32;1mPASSED ctverif\\033[0m\\n"
    fi
}

if [[ "$#" -ne "1" && "$#" -ne "2" ]]; then
    usage
fi

INSTALL_DIR=$1
SMACK_DIR="${1}/smack"

#Put the dependencies on the path

# Disabling ShellCheck using https://github.com/koalaman/shellcheck/wiki/Directive
# Turn of Warning in one line as https://github.com/koalaman/shellcheck/wiki/SC1090
# shellcheck disable=SC1090
source "${INSTALL_DIR}/smack.environment"
export PATH="${SMACK_DIR}/bin:${SMACK_DIR}/build:${PATH}"
#Test that they are really there
which smack || echo "can't find smack"
which boogie || echo "can't find z3"
which llvm2bpl || echo "can't find llvm2bpl"
which clang
clang --version

if [[ "$2" == "" || "$2" == "1" ]]; then
    runSingleTest "s2n-cbc"
    runSingleTest "s2n-record-read-aead"
fi

if [[ "$2" == "" || "$2" == "2" ]]; then
    runSingleTest "s2n-record-read-cbc"
    runSingleTest "s2n-record-read-composite"
    runSingleTest "s2n-record-read-stream"
fi


text:
package com.feedback.mongo;

import com.feedback.config.Constants;
import com.feedback.util.Util;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;

import java.util.Arrays;

/**
 * Created by Samarth Bhargav on 30/6/15.
 */
public enum MongoConnector
{
    INSTANCE;

    private final MongoClient client;

    private MongoConnector()
    {
        if ( Util.isNullOrEmpty( Constants.MONGO.USERNAME ) ) {
            client = new MongoClient( Constants.MONGO.HOST, Constants.MONGO.PORT );
        } else {
            final MongoCredential credential = MongoCredential
                .createCredential( Constants.MONGO.USERNAME, Constants.MONGO.AUTH_DB, Constants.MONGO.PASSWORD.toCharArray() );
            client = new MongoClient( new ServerAddress( Constants.MONGO.HOST, Constants.MONGO.PORT ),
                Arrays.asList( credential ) );
        }
    }

    public static MongoDatabase getDB( String dbName )
    {
        return INSTANCE.client.getDatabase( dbName );
    }

}


text:
<?php

declare(strict_types=1);

namespace OpenCFP\Test\Integration\Http\Action;

use OpenCFP\Domain\Model\Talk;
use OpenCFP\Domain\Model\User;
use OpenCFP\Domain\Services\AccountManagement;
use OpenCFP\Domain\Services\Authentication;
use OpenCFP\Domain\Services\IdentityProvider;
use OpenCFP\Test\Helper\MockAuthentication;
use OpenCFP\Test\Helper\MockIdentityProvider;
use OpenCFP\Test\Integration\TransactionalTestCase;
use OpenCFP\Test\Integration\WebTestCase;

final class DashboardActionTest extends WebTestCase implements TransactionalTestCase
{
    /**
     * Test that the index page returns a list of talks associated
     * with a specific user and information about that user as well
     *
     * @test
     */
    public function indexDisplaysUserAndTalks()
    {
        $accounts = self::$container->get(AccountManagement::class);

        $user = $accounts->create('someone@example.com', 'some password', [
            'first_name' => 'Test',
            'last_name'  => 'User',
        ]);
        $accounts->activate($user->getLogin());
        $accounts->promoteToAdmin($user->getLogin());

        Talk::create([
            'title'       => 'Test Title',
            'description' => 'A good one!',
            'type'        => 'regular',
            'level'       => 'entry',
            'category'    => 'api',
            'user_id'     => $user->getId(),
        ]);

        /** @var MockAuthentication $authentication */
        $authentication = self::$container->get(Authentication::class);
        $authentication->overrideUser($user);

        /** @var MockIdentityProvider $identityProvider */
        $identityProvider = self::$container->get(IdentityProvider::class);
        $identityProvider->overrideCurrentUser(new User([
            'id'         => $user->getId(),
            'first_name' => 'Test',
            'last_name'  => 'User',
        ]));

        $this->callForPapersIsOpen();

        $response = $this->get('/dashboard');

        $this->assertResponseIsSuccessful($response);
        $this->assertResponseBodyContains('Test Title', $response);
        $this->assertResponseBodyContains('Test User', $response);
    }

    /**
     * @test
     */
    public function it_hides_transportation_and_hotel_when_doing_an_online_conference()
    {
        $accounts = self::$container->get(AccountManagement::class);

        $user = $accounts->create('another.one@example.com', 'some password', [
            'first_name' => 'Test',
            'last_name'  => 'User',
        ]);
        $accounts->activate($user->getLogin());

        /** @var MockAuthentication $authentication */
        $authentication = self::$container->get(Authentication::class);
        $authentication->overrideUser($user);

        /** @var MockIdentityProvider $identityProvider */
        $identityProvider = self::$container->get(IdentityProvider::class);
        $identityProvider->overrideCurrentUser(new User([
            'id'         => $user->getId(),
            'first_name' => 'Test',
            'last_name'  => 'User',
        ]));

        $response = $this
            ->callForPapersIsOpen()
            ->isOnlineConference()
            ->get('/dashboard');

        $this->assertResponseBodyNotContains('Need Transportation', $response);
        $this->assertResponseBodyNotContains('Need Hotel', $response);
    }
}


text:
package services

import (
	"fmt"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"

	"github.com/spf13/viper"
	gorp "github.com/topfreegames/extensions/v9/gorp/interfaces"
	"github.com/topfreegames/khan/log"
	"github.com/topfreegames/khan/models"
	"github.com/uber-go/zap"
)

// EncryptionScript is a struct that represents a Khan API Application
type EncryptionScript struct {
	Debug         bool
	ConfigPath    string
	Config        *viper.Viper
	Logger        zap.Logger
	EncryptionKey []byte
	db            gorp.Database
}

// GetEncryptionScript returns a new Khan API Application
func GetEncryptionScript(configPath string, debug bool, logger zap.Logger) *EncryptionScript {
	app := &EncryptionScript{
		ConfigPath: configPath,
		Config:     viper.New(),
		Debug:      debug,
		Logger:     logger,
	}

	app.Configure()
	return app
}

// Configure instantiates the required dependencies for Khan Api Application
func (app *EncryptionScript) Configure() {
	app.setConfigurationDefaults()
	app.loadConfiguration()
	app.connectDatabase()
}

func (app *EncryptionScript) setConfigurationDefaults() {
	logger := app.Logger.With(
		zap.String("source", "app"),
		zap.String("operation", "setConfigurationDefaults"),
	)
	app.Config.SetDefault("graceperiod.ms", 500)
	app.Config.SetDefault("postgres.host", "localhost")
	app.Config.SetDefault("postgres.user", "khan")
	app.Config.SetDefault("postgres.dbName", "khan")
	app.Config.SetDefault("postgres.port", 5432)
	app.Config.SetDefault("postgres.sslMode", "disable")
	app.Config.SetDefault("security.encryptionKey", "00000000000000000000000000000000")
	app.Config.SetDefault("script.tick", "1s")
	app.Config.SetDefault("script.playerAmount", "500")

	log.D(logger, "Configuration defaults set.")
}

func (app *EncryptionScript) loadConfiguration() {
	logger := app.Logger.With(
		zap.String("source", "app"),
		zap.String("operation", "loadConfiguration"),
		zap.String("configPath", app.ConfigPath),
	)

	app.Config.SetConfigType("yaml")
	app.Config.SetConfigFile(app.ConfigPath)
	app.Config.SetEnvPrefix("khan")
	app.Config.AddConfigPath(".")
	app.Config.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	app.Config.AutomaticEnv()

	log.D(logger, "Loading configuration file...")
	if err := app.Config.ReadInConfig(); err == nil {
		log.I(logger, "Loaded config file successfully.")
	} else {
		log.P(logger, "Config file failed to load.")
	}

	app.EncryptionKey = []byte(app.Config.GetString("security.encryptionKey"))
}

func (app *EncryptionScript) connectDatabase() {
	host := app.Config.GetString("postgres.host")
	user := app.Config.GetString("postgres.user")
	dbName := app.Config.GetString("postgres.dbname")
	password := app.Config.GetString("postgres.password")
	port := app.Config.GetInt("postgres.port")
	sslMode := app.Config.GetString("postgres.sslMode")

	logger := app.Logger.With(
		zap.String("source", "app"),
		zap.String("operation", "connectDatabase"),
		zap.String("host", host),
		zap.String("user", user),
		zap.String("dbName", dbName),
		zap.Int("port", port),
		zap.String("sslMode", sslMode),
	)

	log.D(logger, "Connecting to database...")

	db, err := models.GetDB(host, user, port, sslMode, dbName, password)

	if err != nil {
		log.P(logger, "Could not connect to postgres...", func(cm log.CM) {
			cm.Write(zap.String("error", err.Error()))
		})
	}

	_, err = db.SelectInt("select count(*) from games")
	if err != nil {
		log.P(logger, "Could not connect to postgres...", func(cm log.CM) {
			cm.Write(zap.String("error", err.Error()))
		})
	}

	log.I(logger, "Connected to database successfully.")
	app.db = db
}

// Start starts listening for web requests at specified host and port
func (app *EncryptionScript) Start() {
	logger := app.Logger.With(
		zap.String("source", "app"),
		zap.String("operation", "Start"),
	)

	sg := make(chan os.Signal)
	stopScript := make(chan bool, 1)
	signal.Notify(sg, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL, syscall.SIGTERM)

	go app.executeScript(stopScript)

	// stop server
	select {
	case s := <-sg:
		graceperiod := app.Config.GetInt("graceperiod.ms")
		log.I(logger, "shutting down", func(cm log.CM) {
			cm.Write(zap.String("signal", fmt.Sprintf("%v", s)),
				zap.Int("graceperiod", graceperiod))
		})
		stopScript <- true
		time.Sleep(time.Duration(graceperiod) * time.Millisecond)
	}
	log.I(logger, "app stopped")
}

func (app *EncryptionScript) executeScript(stopChan chan bool) {
	ticker := time.NewTicker(app.Config.GetDuration("script.tick"))
	for {
		select {
		case <-stopChan:
			log.I(app.Logger, "Finishing script")
		case <-ticker.C:
			app.encryptPlayers()
		}
	}
}

func (app *EncryptionScript) encryptPlayers() {
	logger := app.Logger.With(
		zap.String("source", "app"),
		zap.String("operation", "executeScript"),
	)

	amount := app.Config.GetInt("script.playerAmount")

	initTime := time.Now()

	players, err := models.GetPlayersToEncrypt(app.db, app.EncryptionKey, amount)
	if err != nil {
		log.E(logger, "error on get players to encrypt", func(cm log.CM) {
			cm.Write(zap.Error(err))
		})
		return
	}

	if len(players) == 0 {
		logger.Warn("FINISHED, there is no player to encrypt")
		return
	}

	err = models.ApplySecurityChanges(app.db, app.EncryptionKey, players)
	if err != nil {
		log.E(logger, "error on update players", func(cm log.CM) {
			cm.Write(zap.Error(err))
		})
		return
	}

	app.Logger.Debug("encryption done", zap.String("spent time", time.Since(initTime).String()))
}


text:
<ipojo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="org.apache.felix.ipojo http://felix.apache.org/ipojo/schemas/CURRENT/core.xsd"
	xmlns="org.apache.felix.ipojo">

	<handler name="transaction" namespace="org.apache.felix.ipojo.transaction"
		classname="org.apache.felix.ipojo.transaction.TransactionHandler">
		<requires field="m_transactionManager">
			<callback type="bind" method="bind"/>
			<callback type="unbind" method="unbind"/>
		</requires>
	</handler>

</ipojo>


text:
"""Evaluates the baseline performance of grid1 without RL control.

Baseline is an actuated traffic light provided by SUMO.
"""

import numpy as np
from flow.core.experiment import Experiment
from flow.core.params import InitialConfig
from flow.core.params import TrafficLightParams
from flow.benchmarks.grid1 import flow_params
from flow.benchmarks.grid1 import N_ROWS
from flow.benchmarks.grid1 import N_COLUMNS

def grid1_baseline(num_runs, render=True):
    """Run script for the grid1 baseline.

    Parameters
    ----------
        num_runs : int
            number of rollouts the performance of the environment is evaluated
            over
        render: bool, optional
            specifies whether to the gui during execution

    Returns
    -------
        flow.core.experiment.Experiment
            class needed to run simulations
    """
    exp_tag = flow_params['exp_tag']
    sim_params = flow_params['sim']
    vehicles = flow_params['veh']
    env_params = flow_params['env']
    net_params = flow_params['net']
    initial_config = flow_params.get('initial', InitialConfig())

    # define the traffic light logic
    tl_logic = TrafficLightParams(baseline=False)
    phases = [{'duration': '31', 'minDur': '5', 'maxDur': '45',
               "state": "GrGr"},
              {'duration': '2', 'minDur': '2', 'maxDur': '2',
               "state": "yryr"},
              {'duration': '31', 'minDur': '5', 'maxDur': '45',
               "state": "rGrG"},
              {'duration': '2', 'minDur': '2', 'maxDur': '2',
               "state": "ryry"}]
    for i in range(N_ROWS*N_COLUMNS):
        tl_logic.add('center'+str(i), tls_type='actuated', phases=phases,
                     programID=1)

    # modify the rendering to match what is requested
    sim_params.render = render

    # set the evaluation flag to True
    env_params.evaluate = True

    # import the scenario class
    module = __import__('flow.scenarios', fromlist=[flow_params['scenario']])
    scenario_class = getattr(module, flow_params['scenario'])

    # create the scenario object
    scenario = scenario_class(
        name=exp_tag,
        vehicles=vehicles,
        net_params=net_params,
        initial_config=initial_config,
        traffic_lights=tl_logic
    )

    # import the environment class
    module = __import__('flow.envs', fromlist=[flow_params['env_name']])
    env_class = getattr(module, flow_params['env_name'])

    # create the environment object
    env = env_class(env_params, sim_params, scenario)

    exp = Experiment(env)

    results = exp.run(num_runs, env_params.horizon)
    total_delay = np.mean(results['returns'])

    return total_delay

if __name__ == '__main__':
    runs = 1  # number of simulations to average over
    res = grid1_baseline(num_runs=runs, render=False)

    print('---------')
    print('The total delay across {} runs is {}'.format(runs, res))


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class CollectionActionResult
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class CollectionActionResult
   ">
    <meta name="generator" content="docfx 2.16.2.2">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

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

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class CollectionActionResult

The result of an operation on a collection

Inheritance

Object

ActionResult

CollectionActionResult

Inherited Members

                  ActionResult.Status

                  ActionResult.Target

                  ActionResult.Href

                  ActionResult.Exception

                  ActionResult.FailedProperties

                  ActionResult.IsFailure

                  Object.Equals(Object)

                  Object.Equals(Object, Object)

                  Object.GetHashCode()

                  Object.GetType()

                  Object.MemberwiseClone()

                  Object.ReferenceEquals(Object, Object)

                  Object.ToString()

Namespace:FubarDev.WebDavServer.Engines

Assembly:FubarDev.WebDavServer.dll

Syntax

public class CollectionActionResult : ActionResult

Constructors

                |
                <a href="https://github.com/FubarDevelopment/WebDavServer/new/master/apiSpec/new?filename=FubarDev_WebDavServer_Engines_CollectionActionResult__ctor_FubarDev_WebDavServer_Engines_ActionStatus_FubarDev_WebDavServer_Engines_ITarget_.md&value=---%0Auid%3A%20FubarDev.WebDavServer.Engines.CollectionActionResult.%23ctor(FubarDev.WebDavServer.Engines.ActionStatus%2CFubarDev.WebDavServer.Engines.ITarget)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

                View Source

CollectionActionResult(ActionStatus, ITarget)

Initializes a new instance of the CollectionActionResult class.

Declaration

public CollectionActionResult(ActionStatus status, ITarget target)

Parameters

                    Type
                    Name
                    Description

                    ActionStatus
                    status

The status of the operation

                    ITarget
                    target

The target of the operation

Properties

                |
                Improve this Doc

                View Source

CollectionActionResults

Gets or sets the action results of the sub-collections of this collection

Declaration

public IReadOnlyCollection<CollectionActionResult> CollectionActionResults { get; set; }

Property Value

                    Type
                    Description

                    IReadOnlyCollection<CollectionActionResult>

                |
                Improve this Doc

                View Source

DocumentActionResults

Gets or sets the action results of the documents of this collection

Declaration

public IReadOnlyCollection<ActionResult> DocumentActionResults { get; set; }

Property Value

                    Type
                    Description

                    IReadOnlyCollection<ActionResult>

Methods

                |
                Improve this Doc

                View Source

Flatten()

Returns a flat list of action results

Declaration

public IEnumerable<ActionResult> Flatten()

Returns

                    Type
                    Description

                    IEnumerable<ActionResult>

The flat list of action results

Remarks

This returns all action results for all sub-collections, documents and their child elements.

Extension Methods

                  CollectionActionResultExtensions.Evaluate(CollectionActionResult, IWebDavContext)

                    Improve this Doc

                    View Source

              Back to top

            Copyright © 2016-2017 Fubar Development Junker
Generated by DocFX


text:
#include "usb_device_config.h"
#include "usb.h"
#include "usb_device.h"

#include "usb_device_class.h"
#include "usb_device_hid.h"

#include "usb_device_ch9.h"
#include "usb_device_descriptor.h"

#include "composite.h"

#include "hid_keyboard.h"
#include "hid_mouse.h"

#include "fsl_device_registers.h"
#include "clock_config.h"
#include "board.h"
#include "fsl_debug_console.h"

#include <stdio.h>
#include <stdlib.h>
#if (defined(FSL_FEATURE_SOC_MPU_COUNT) && (FSL_FEATURE_SOC_MPU_COUNT > 0U))
#include "fsl_mpu.h"
#endif /* FSL_FEATURE_SOC_MPU_COUNT */
#if defined(USB_DEVICE_CONFIG_EHCI) && (USB_DEVICE_CONFIG_EHCI > 0U)
#include "usb_phy.h"
#endif

#if (USB_DEVICE_CONFIG_HID < 2U)
#error USB_DEVICE_CONFIG_HID need to > 1U, Please change the MARCO USB_DEVICE_CONFIG_HID in file "usb_device_config.h".
#endif

#include "pin_mux.h"
/*******************************************************************************
 * Definitions
 ******************************************************************************/
/* USB clock source and frequency*/
#define USB_FS_CLK_SRC kCLOCK_UsbSrcIrc48M
#define USB_FS_CLK_FREQ 48000000U
#define USB_HS_PHY_CLK_SRC kCLOCK_UsbPhySrcExt
#define USB_HS_PHY_CLK_FREQ BOARD_XTAL0_CLK_HZ
#define USB_HS_CLK_SRC kCLOCK_UsbSrcUnused
#define USB_HS_CLK_FREQ 0U

/*******************************************************************************
 * Prototypes
 ******************************************************************************/
void BOARD_InitHardware(void);

static usb_status_t USB_DeviceCallback(usb_device_handle handle, uint32_t event, void *param);
static void USB_DeviceApplicationInit(void);

/*******************************************************************************
 * Variables
 ******************************************************************************/

extern usb_device_class_struct_t g_UsbDeviceHidMouseConfig;
extern usb_device_class_struct_t g_UsbDeviceHidKeyboardConfig;

static usb_device_composite_struct_t g_UsbDeviceComposite;

/* Set class configurations */
usb_device_class_config_struct_t g_CompositeClassConfig[USB_COMPOSITE_INTERFACE_COUNT] = {
    {
        USB_DeviceHidKeyboardCallback, /* HID keyboard class callback pointer */
        (class_handle_t)NULL,          /* The HID class handle, This field is set by USB_DeviceClassInit */
        &g_UsbDeviceHidKeyboardConfig, /* The HID keyboard configuration, including class code, subcode, and protocol,
                                  class
                                  type, transfer type, endpoint address, max packet size, etc.*/
    },
    {
        USB_DeviceHidMouseCallback, /* HID mouse class callback pointer */
        (class_handle_t)NULL,       /* The HID class handle, This field is set by USB_DeviceClassInit */
        &g_UsbDeviceHidMouseConfig, /* The HID mouse configuration, including class code, subcode, and protocol, class
                               type,
                               transfer type, endpoint address, max packet size, etc.*/
    }};

/* Set class configuration list */
usb_device_class_config_list_struct_t g_UsbDeviceCompositeConfigList = {
    g_CompositeClassConfig,        /* Class configurations */
    USB_DeviceCallback,            /* Device callback pointer */
    USB_COMPOSITE_INTERFACE_COUNT, /* Class count */
};

/*******************************************************************************
 * Code
 ******************************************************************************/

/* The Device callback */
static usb_status_t USB_DeviceCallback(usb_device_handle handle, uint32_t event, void *param)
{
    usb_status_t error = kStatus_USB_Error;
    uint16_t *temp16 = (uint16_t *)param;
    uint8_t *temp8 = (uint8_t *)param;

    switch (event)
    {
        case kUSB_DeviceEventBusReset:
        {
            /* USB bus reset signal detected */
            g_UsbDeviceComposite.attach = 0U;
            error = kStatus_USB_Success;
#if defined(USB_DEVICE_CONFIG_EHCI) && (USB_DEVICE_CONFIG_EHCI > 0U)
            /* Get USB speed to configure the device, including max packet size and interval of the endpoints. */
            if (kStatus_USB_Success == USB_DeviceClassGetSpeed(CONTROLLER_ID, &g_UsbDeviceComposite.speed))
            {
                USB_DeviceSetSpeed(handle, g_UsbDeviceComposite.speed);
            }
#endif
        }
        break;
        case kUSB_DeviceEventSetConfiguration:
            if (param)
            {
                /* Set device configuration request */
                g_UsbDeviceComposite.attach = 1U;
                g_UsbDeviceComposite.currentConfiguration = *temp8;
                USB_DeviceHidMouseSetConfigure(g_UsbDeviceComposite.hidMouseHandle, *temp8);
                USB_DeviceHidKeyboardSetConfigure(g_UsbDeviceComposite.hidKeyboardHandle, *temp8);
                error = kStatus_USB_Success;
            }
            break;
        case kUSB_DeviceEventSetInterface:
            if (g_UsbDeviceComposite.attach)
            {
                /* Set device interface request */
                uint8_t interface = (uint8_t)((*temp16 & 0xFF00U) >> 0x08U);
                uint8_t alternateSetting = (uint8_t)(*temp16 & 0x00FFU);
                if (interface < USB_COMPOSITE_INTERFACE_COUNT)
                {
                    g_UsbDeviceComposite.currentInterfaceAlternateSetting[interface] = alternateSetting;
                    USB_DeviceHidMouseSetInterface(g_UsbDeviceComposite.hidMouseHandle, interface, alternateSetting);
                    USB_DeviceHidKeyboardSetInterface(g_UsbDeviceComposite.hidKeyboardHandle, interface,
                                                      alternateSetting);
                    error = kStatus_USB_Success;
                }
            }
            break;
        case kUSB_DeviceEventGetConfiguration:
            if (param)
            {
                /* Get current configuration request */
                *temp8 = g_UsbDeviceComposite.currentConfiguration;
                error = kStatus_USB_Success;
            }
            break;
        case kUSB_DeviceEventGetInterface:
            if (param)
            {
                /* Get current alternate setting of the interface request */
                uint8_t interface = (uint8_t)((*temp16 & 0xFF00U) >> 0x08U);
                if (interface < USB_COMPOSITE_INTERFACE_COUNT)
                {
                    *temp16 = (*temp16 & 0xFF00U) | g_UsbDeviceComposite.currentInterfaceAlternateSetting[interface];
                    error = kStatus_USB_Success;
                }
                else
                {
                    error = kStatus_USB_InvalidRequest;
                }
            }
            break;
        case kUSB_DeviceEventGetDeviceDescriptor:
            if (param)
            {
                /* Get device descriptor request */
                error = USB_DeviceGetDeviceDescriptor(handle, (usb_device_get_device_descriptor_struct_t *)param);
            }
            break;
        case kUSB_DeviceEventGetConfigurationDescriptor:
            if (param)
            {
                /* Get device configuration descriptor request */
                error = USB_DeviceGetConfigurationDescriptor(handle,
                                                             (usb_device_get_configuration_descriptor_struct_t *)param);
            }
            break;
        case kUSB_DeviceEventGetStringDescriptor:
            if (param)
            {
                /* Get device string descriptor request */
                error = USB_DeviceGetStringDescriptor(handle, (usb_device_get_string_descriptor_struct_t *)param);
            }
            break;
        case kUSB_DeviceEventGetHidDescriptor:
            if (param)
            {
                /* Get hid descriptor request */
                error = USB_DeviceGetHidDescriptor(handle, (usb_device_get_hid_descriptor_struct_t *)param);
            }
            break;
        case kUSB_DeviceEventGetHidReportDescriptor:
            if (param)
            {
                /* Get hid report descriptor request */
                error =
                    USB_DeviceGetHidReportDescriptor(handle, (usb_device_get_hid_report_descriptor_struct_t *)param);
            }
            break;
        case kUSB_DeviceEventGetHidPhysicalDescriptor:
            if (param)
            {
                /* Get hid physical descriptor request */
                error = USB_DeviceGetHidPhysicalDescriptor(handle,
                                                           (usb_device_get_hid_physical_descriptor_struct_t *)param);
            }
            break;
        default:
            break;
    }

    return error;
}

#if defined(USB_DEVICE_CONFIG_EHCI) && (USB_DEVICE_CONFIG_EHCI > 0U)
void USBHS_IRQHandler(void)
{
    USB_DeviceEhciIsrFunction(g_UsbDeviceComposite.deviceHandle);
}
#endif
#if defined(USB_DEVICE_CONFIG_KHCI) && (USB_DEVICE_CONFIG_KHCI > 0U)
void USB0_IRQHandler(void)
{
    USB_DeviceKhciIsrFunction(g_UsbDeviceComposite.deviceHandle);
}
#endif
#if defined(USB_DEVICE_CONFIG_LPCIP3511FS) && (USB_DEVICE_CONFIG_LPCIP3511FS > 0U)
void USB0_IRQHandler(void)
{
    USB_DeviceLpcIp3511IsrFunction(g_UsbDeviceComposite.deviceHandle);
}
#endif

/* Application initialization */
static void USB_DeviceApplicationInit(void)
{
    uint8_t irqNumber;
#if defined(USB_DEVICE_CONFIG_EHCI) && (USB_DEVICE_CONFIG_EHCI > 0U)
    uint8_t usbDeviceEhciIrq[] = USBHS_IRQS;
    irqNumber = usbDeviceEhciIrq[CONTROLLER_ID - kUSB_ControllerEhci0];

    CLOCK_EnableUsbhs0PhyPllClock(USB_HS_PHY_CLK_SRC, USB_HS_PHY_CLK_FREQ);
    CLOCK_EnableUsbhs0Clock(USB_HS_CLK_SRC, USB_HS_CLK_FREQ);
    USB_EhciPhyInit(CONTROLLER_ID, BOARD_XTAL0_CLK_HZ);
#endif
#if defined(USB_DEVICE_CONFIG_KHCI) && (USB_DEVICE_CONFIG_KHCI > 0U)
    uint8_t usbDeviceKhciIrq[] = USB_IRQS;
    irqNumber = usbDeviceKhciIrq[CONTROLLER_ID - kUSB_ControllerKhci0];

    SystemCoreClockUpdate();

    CLOCK_EnableUsbfs0Clock(USB_FS_CLK_SRC, USB_FS_CLK_FREQ);
#endif

#if defined(USB_DEVICE_CONFIG_LPCIP3511FS) && (USB_DEVICE_CONFIG_LPCIP3511FS > 0U)
    uint8_t usbDeviceIP3511Irq[] = USB_IRQS;
    irqNumber = usbDeviceIP3511Irq[CONTROLLER_ID - kUSB_ControllerLpcIp3511Fs0];

    /* enable USB IP clock */
    CLOCK_EnableUsbfs0Clock(USB_FS_CLK_SRC, USB_FS_CLK_FREQ);
#endif

#if (defined(FSL_FEATURE_SOC_MPU_COUNT) && (FSL_FEATURE_SOC_MPU_COUNT > 0U))
    MPU_Enable(MPU, 0);
#endif /* FSL_FEATURE_SOC_MPU_COUNT */

/*
 * If the SOC has USB KHCI dedicated RAM, the RAM memory needs to be clear after
 * the KHCI clock is enabled. When the demo uses USB EHCI IP, the USB KHCI dedicated
 * RAM can not be used and the memory can't be accessed.
 */
#if (defined(FSL_FEATURE_USB_KHCI_USB_RAM) && (FSL_FEATURE_USB_KHCI_USB_RAM > 0U))
#if (defined(FSL_FEATURE_USB_KHCI_USB_RAM_BASE_ADDRESS) && (FSL_FEATURE_USB_KHCI_USB_RAM_BASE_ADDRESS > 0U))
    for (int i = 0; i < FSL_FEATURE_USB_KHCI_USB_RAM; i++)
    {
        ((uint8_t *)FSL_FEATURE_USB_KHCI_USB_RAM_BASE_ADDRESS)[i] = 0x00U;
    }
#endif /* FSL_FEATURE_USB_KHCI_USB_RAM_BASE_ADDRESS */
#endif /* FSL_FEATURE_USB_KHCI_USB_RAM */

    /* Set composite device to default state */
    g_UsbDeviceComposite.speed = USB_SPEED_FULL;
    g_UsbDeviceComposite.attach = 0U;
    g_UsbDeviceComposite.hidMouseHandle = (class_handle_t)NULL;
    g_UsbDeviceComposite.hidKeyboardHandle = (class_handle_t)NULL;
    g_UsbDeviceComposite.deviceHandle = NULL;

    if (kStatus_USB_Success !=
        USB_DeviceClassInit(CONTROLLER_ID, &g_UsbDeviceCompositeConfigList, &g_UsbDeviceComposite.deviceHandle))
    {
        usb_echo("USB device composite demo init failed\r\n");
        return;
    }
    else
    {
        usb_echo("USB device composite demo\r\n");
        /* Get the HID keyboard class handle */
        g_UsbDeviceComposite.hidKeyboardHandle = g_UsbDeviceCompositeConfigList.config[0].classHandle;
        /* Get the HID mouse class handle */
        g_UsbDeviceComposite.hidMouseHandle = g_UsbDeviceCompositeConfigList.config[1].classHandle;

        USB_DeviceHidKeyboardInit(&g_UsbDeviceComposite);
        USB_DeviceHidMouseInit(&g_UsbDeviceComposite);
    }

    /* Install isr, set priority, and enable IRQ. */
    NVIC_SetPriority((IRQn_Type)irqNumber, USB_DEVICE_INTERRUPT_PRIORITY);
    NVIC_EnableIRQ((IRQn_Type)irqNumber);

    /* Start the device function */
    USB_DeviceRun(g_UsbDeviceComposite.deviceHandle);
}

#if defined(__CC_ARM) || defined(__GNUC__)
int main(void)
#else
void main(void)
#endif
{
    BOARD_InitPins();
    BOARD_BootClockRUN();
    BOARD_InitDebugConsole();

    USB_DeviceApplicationInit();

    while (1U)
    {
#if USB_DEVICE_CONFIG_USE_TASK
#if defined(USB_DEVICE_CONFIG_EHCI) && (USB_DEVICE_CONFIG_EHCI > 0U)
        USB_DeviceEhciTaskFunction(g_UsbDeviceComposite.deviceHandle);
#endif
#if defined(USB_DEVICE_CONFIG_KHCI) && (USB_DEVICE_CONFIG_KHCI > 0U)
        USB_DeviceKhciTaskFunction(g_UsbDeviceComposite.deviceHandle);
#endif
#if defined(USB_DEVICE_CONFIG_LPCIP3511FS) && (USB_DEVICE_CONFIG_LPCIP3511FS > 0U)
        USB_DeviceLpcIp3511TaskFunction(g_UsbDeviceComposite.deviceHandle);
#endif
#endif
    }
}


text:
/*
* Load Google Maps Asynchronous
* via appending script
* Don't forget the key: https://console.developers.google.com/flows/enableapi?apiid=maps_backend&keyType=CLIENT_SIDE&reusekey=true&pli=1
* Choose web API
*/
(function(){
    var key = 'AIzaSyDSlUp7PDxUqo4LwAP3mi_6y6uAk55D8OY';//Eigen Key Gebruiken!!!

    //Load Google Maps Async
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp'
        + '&key=' + key
        + '&callback=initGoogleMaps';
    document.body.appendChild(script);

    this.initGoogleMaps = function(){
        this._googleMapsInitialized = true;
    };

})();

var GMap = {
    init:function(container) {
        var mapOptions = {
            zoom:13,
            center: new google.maps.LatLng(51.048017, 3.727666)
        }
        this._map = new google.maps.Map(document.querySelector('#' + container), mapOptions);
        google.maps.visualRefresh = true;
        google.maps.event.trigger(this._map, 'resize');
        this._geoLocationMarker = null;
        this._markersTreesInventory = [];
        this._markerClusterTreesInventory = null;
    },
    addMarkerGeoLocation: function(geoLocation) {
        this._geoLocationMarker = new google.maps.Marker({
            position: new google.maps.LatLng(geoLocation.coords.latitude, geoLocation.coords.longitude),
            title:"My location",
            icon:'images/markers/home.png'
        });// Create a Google Maps Marker

        this._geoLocationMarker.setMap(this._map);// Add Marker to Map
        this._map.setCenter(new google.maps.LatLng(geoLocation.coords.latitude, geoLocation.coords.longitude));// Set center of the map to my geolocation
    },
    addMarkersForTreesInventory: function(trees){
        if(this._markersTreesInventory.length == 0) {
            var marker = null, self = this;

            _.each(trees, function(tree){
                marker = new google.maps.Marker({
                    position:new google.maps.LatLng(tree.geolocation.lat, tree.geolocation.lng),
                    title:tree.name,
                    icon:'images/markers/tree.png'
                });// Create a Google Maps Marker

                marker.setMap(self._map);// Add Marker to Map

                self._markersTreesInventory.push(marker);
            });

            this._markerClusterTreesInventory = new MarkerClusterer(this._map, this._markersTreesInventory);
        }
    },
    hideMarkers: function(arrMarkers, hide){
        var self = this;

        _.each(arrMarkers, function(marker){
            if(hide){
                marker.setMap(null);
            }else{
                marker.setMap(self.map);
            }
        });
    },
    refresh: function() {
        google.maps.visualRefresh = true;
        google.maps.event.trigger(this.map,'resize');
    }
};


text:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <soap:Body xmlns:t="urn:TaniumSOAP" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <t:return>
      <command>GetObject</command>
      <session>1-690-aca01e9daeadf9306aa409bf425fda9269b6325f7c5dc87de878dd8216f93a13a1bb02ba01b1fee42a8b28c4cfe6c87ed9dea1dae2a3001f427639b2859dd517</session>
      <server_version>6.5.314.4301</server_version>
      <ID></ID>
      <IDType></IDType>
      <ContextID></ContextID>
      <result_object>
        <sensors>
          <sensor>
            <id>3</id>
            <name>Computer Name</name>
            <hash>3409330187</hash>
            <string_count>5</string_count>
            <category>Reserved</category>
            <description>The assigned name of the client machine.
Example: workstation-1.company.com</description>
            <queries>
              <query>
                <platform>Windows</platform>
                <script>select CSName from win32_operatingsystem</script>
                <script_type>WMIQuery</script_type>
              </query>
            </queries>
            <source_id>0</source_id>
            <parameter_definition></parameter_definition>
            <value_type>String</value_type>
            <max_age_seconds>86400</max_age_seconds>
            <ignore_case_flag>1</ignore_case_flag>
            <hidden_flag>0</hidden_flag>
            <exclude_from_parse_flag>0</exclude_from_parse_flag>
            <delimiter></delimiter>
          </sensor>
        </sensors>
      </result_object>
      <ResultXML></ResultXML>
      <options>
        <include_hidden_flag>0</include_hidden_flag>
        <suppress_object_list>1</suppress_object_list>
      </options>
    </t:return>
  </soap:Body>
</soap:Envelope>


text:
<?php

/**
 * Flag Tree Test Fixture
 *
 * Like Number Tree, but uses a flag for testing scope parameters
 *
 * @package       Cake.Test.Fixture
 */
class FlagTreeFixture extends CakeTestFixture {

/**
 * name property
 *
 * @var string 'FlagTree'
 */
	public $name = 'FlagTree';

/**
 * fields property
 *
 * @var array
 */
	public $fields = array(
		'id' => array('type' => 'integer','key' => 'primary'),
		'name' => array('type' => 'string','null' => false),
		'parent_id' => 'integer',
		'lft' => array('type' => 'integer','null' => false),
		'rght' => array('type' => 'integer','null' => false),
		'flag' => array('type' => 'integer','null' => false, 'length' => 1, 'default' => 0)
	);
}