text:
package org.apache.myfaces.trinidadinternal.style.cache;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.faces.context.FacesContext;

import org.apache.myfaces.trinidad.context.AccessibilityProfile;
import org.apache.myfaces.trinidad.context.LocaleContext;
import org.apache.myfaces.trinidad.context.RenderingContext;
import org.apache.myfaces.trinidad.logging.TrinidadLogger;
import org.apache.myfaces.trinidad.skin.Icon;
import org.apache.myfaces.trinidad.skin.Skin;
import org.apache.myfaces.trinidadinternal.agent.TrinidadAgent;
import org.apache.myfaces.trinidadinternal.renderkit.core.CoreRenderKit;
import org.apache.myfaces.trinidadinternal.renderkit.core.CoreRenderingContext;
import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.SkinSelectors;
import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.StyleSheetRenderer;
import org.apache.myfaces.trinidadinternal.share.io.CachingNameResolver;
import org.apache.myfaces.trinidadinternal.share.io.DefaultNameResolver;
import org.apache.myfaces.trinidadinternal.share.io.InputStreamProvider;
import org.apache.myfaces.trinidadinternal.share.io.NameResolver;
import org.apache.myfaces.trinidadinternal.share.xml.JaxpXMLProvider;
import org.apache.myfaces.trinidadinternal.share.xml.XMLProvider;
import org.apache.myfaces.trinidadinternal.style.CSSStyle;
import org.apache.myfaces.trinidadinternal.style.Style;
import org.apache.myfaces.trinidadinternal.style.StyleContext;
import org.apache.myfaces.trinidadinternal.style.StyleMap;
import org.apache.myfaces.trinidadinternal.style.StyleProvider;
import org.apache.myfaces.trinidadinternal.style.util.CSSGenerationUtils;
import org.apache.myfaces.trinidadinternal.style.util.NameUtils;
import org.apache.myfaces.trinidadinternal.style.util.StyleWriterFactory;
import org.apache.myfaces.trinidadinternal.style.xml.StyleSheetDocumentUtils;
import org.apache.myfaces.trinidadinternal.style.xml.parse.IconNode;
import org.apache.myfaces.trinidadinternal.style.xml.parse.PropertyNode;
import org.apache.myfaces.trinidadinternal.style.xml.parse.SkinPropertyNode;
import org.apache.myfaces.trinidadinternal.style.xml.parse.StyleNode;
import org.apache.myfaces.trinidadinternal.style.xml.parse.StyleSheetDocument;
import org.apache.myfaces.trinidadinternal.style.xml.parse.StyleSheetNode;
import org.apache.myfaces.trinidadinternal.util.nls.LocaleUtils;

import org.xml.sax.SAXException;

/**
 * The FileSystemStyleCache is a StyleProvider implementation which
 * caches generated CSS style sheets on the file system.
 *
 * Note that StyleProviders are responsible for providing access
 * both to style information (eg. getStyleSheetURI(), getStyleMap()) as
 * well as to icons registered via style sheets (see getIcons()).
 *
 * @see org.apache.myfaces.trinidadinternal.style.StyleProvider
 * @see org.apache.myfaces.trinidadinternal.skin.SkinStyleProvider
 *
 * @version $Name:  $ ($Revision: adfrt/faces/adf-faces-impl/src/main/java/oracle/adfinternal/view/faces/style/cache/FileSystemStyleCache.java#0 $) $Date: 10-nov-2005.18:58:54 $
 */
// -= Simon Lessard =-
// TODO: Synchronization does not seem to be needed since there's
//       synchronized blocks in the code, using HashMap hence
//       looks like a better choice than Hashtable.
public class FileSystemStyleCache implements StyleProvider
{
  /**
   * Returns the mime type for the styles provided by this
   * FileSystemStyleCache - "text/css".
   */
  public String getContentStyleType(StyleContext context)
  {
    return "text/css";
  }

  /**
   * Creates a FileSystemStyleCache.
   *
   * @param source The path of the source XSS document.  The
   *   specified file must be a valid XSS document.  If the specified
   *   file does not exists, an IllegalArgumentException is thrown.
   * @param target The path of the target directory.  Generated
   *   CSS files are stored in this directory.  If the directory
   *   does not exist and can not be created, an IllegalArgumentException
   *   is thrown.
   */
  protected FileSystemStyleCache(String source, String target)
  {
    // The source arg may actually be null if we are using a
    // SkinStyleProvider with no custom style sheet.
    if (source != null)
    {
      File sourceFile = new File(source);

      if (!sourceFile.exists())
        throw new IllegalArgumentException(
        "\nRequired XSS file " +
        source +
        " does not exist.");
      _sourceFile = sourceFile;

      // Get the base file name: name minus the extension
      String baseName = sourceFile.getName();
      int dotIndex = baseName.indexOf('.');
      if (dotIndex != -1)
        baseName = baseName.substring(0, dotIndex);
      _baseName = baseName;
    }

    // If the target directory does not exist, create it now.
    // Note: If we can't create the target directory, we just
    // plug along anyway instead of throwing an IllegalArgumentException.
    // That way, we can still use the StyleMap for this style sheet
    // even if the style sheet isn't generated.
    File targetDirectory = new File(target);
    if (!targetDirectory.exists())
      targetDirectory.mkdirs();

    _targetPath = target;
  }

  /**
   * Implementation of StyleCache.getStyleSheetURI().
   */
  public List<String> getStyleSheetURIs(StyleContext context)
  {
    Entry entry = _getEntry(context);

    if (entry == null)
    {
      return null;
    }

    return entry.uris;
  }

  /**
   * Implementation of StyleProvider.getStyleMap().
   */
  public StyleMap getStyleMap(StyleContext context)
  {

    Entry entry = _getEntry(context);

    if (entry == null)
      return null;

    return entry.map;
  }

  /**
   * Implementation of StyleProvider.getSkinProperties()
   */
  public ConcurrentMap<Object, Object> getSkinProperties(StyleContext context)
  {

    Entry entry = _getEntry(context);

    if (entry == null)
      return null;

    return entry.skinProperties;
  }

  /**
   * Implementation of StyleProvider.getIcons()
   */
  public ConcurrentMap<String, Icon> getIcons(StyleContext context)
  {

    Entry entry = _getEntry(context);

    if (entry == null)
      return null;

    return entry.icons;
  }

  /**
   * Returns a Map which maps style class names to
   * equivalent shorter names.
   *

   * FileSystemStyleCache automatically generates short versions
   * of every style class that is found the the underlying XSS
   * document.  FileSystemStyleCache clients can reduce the
   * size of generated content by using this method to obtain
   * short versions of any rendered style classes.
   *

   * Note: The returned Map uses String keys to represent
   * the full class names.  However, the short style class values
   * may not necessarily be type java.lang.String.  Clients must
   * avoid explicitly casting the values contained in the Map
   * to type String.  Instead, such values should be passed directly
   * to the ResponseWriter API to be rendered.  Or, if the String
   * representation is required, toString() should be called on
   * the value.
   *
   * @param context The StyleContext
   *
   * @return A Map which maps the full style class names to
   *   the shorter equivalents.
   */
  public Map<String, String> getShortStyleClasses(StyleContext context)
  {
    return _shortStyleClassMap;
  }

  /**
   * Creates the StyleSheetDocument for this StyleProvider.
   * @param context The StyleContext
   *                (not needed here, but is needed in  subclass)
   * @return The StyleSheetDocument which defines the styles
   *         for this StyleProvider.
   */
  protected StyleSheetDocument createStyleSheetDocument(
    StyleContext context
    )
  {
    // If we don't have a sourceFile, we don't have a StyleSheetDocument
    if (_sourceFile == null)
      return null;

    StyleSheetDocument document = null;

    // Get the XML Provider
    XMLProvider provider = new JaxpXMLProvider();

    try
    {
      document = StyleSheetDocumentUtils.createStyleSheetDocument(
                                                        provider,
                                                        _resolver,
                                                        _sourceFile.getPath());
    }
    catch (SAXException e)
    {
      // The error is logged by the TreeBuilder
      ;
    }
    catch (IOException e)
    {
      if (_LOG.isWarning())
        _LOG.warning("IOEXCEPTION_IN_PHASE", _sourceFile);
        _LOG.warning(e);
    }

    return document;
  }

  /**
   * Tests whether the source style sheet files have been modified
   * since the last call to createStyleSheetDocument().
   * @return true if the underlying source style sheets have been
   *              modified, false otherwise.
   */
  protected boolean hasSourceDocumentChanged(StyleContext context)
  {
    // If we haven't parsed yet, don't bother checking the time stamp
    if (_document == null)
      return true;

    InputStreamProvider provider = _getInputStreamProvider();
    if (provider != null)
      return provider.hasSourceChanged();

    // Couldn't get an InputStreamProvider, what to do?
    return false;
  }

  /**
   * Returns the name to use for the generated style sheet file .
   *
   * @param context The StyleContext
   * @param document The StyleSheetDocument which provides the styles
   */
  protected String getTargetStyleSheetName(
    StyleContext       context,
    StyleSheetDocument document
    )
  {
    StringBuffer buffer = new StringBuffer();

    String baseName = _baseName;
    if (baseName != null)
      buffer.append(baseName);

    String contextName = NameUtils.getContextName(context, document);
    if ((contextName != null) && contextName.length() > 0)
    {
      if (baseName != null)
        buffer.append(_NAME_SEPARATOR);

      buffer.append(contextName);
    }

    if (_isCompressStyles(null))
    {
      if (baseName != null || contextName != null)
        buffer.append(_NAME_SEPARATOR);
      buffer.append(_COMPRESSED);
    }

    buffer.append(_CSS_EXTENSION);

    return buffer.toString();
  }

  // Returns the current StyleSheetDocument - used by StyleMapImpl only
  StyleSheetDocument __getStyleSheetDocument()
  {
    return _document;
  }

  // Gets the entry for the specified StyleContext, creating it if
  // necessary. Part of creating an entry is creating the style sheet file itself.
  // And Entry contains the style sheet URI.
  private Entry _getEntry(StyleContext context)
  {
    Hashtable<Key, Entry> cache = null;
    Hashtable<Object, Entry> entryCache = null;
    StyleSheetDocument document = null;
    Map<String, String> shortStyleClassMap = null;
    String[] namespacePrefixes = null;

    boolean checkModified  = context.checkStylesModified();

    // Synchronize while set up the _cache, _entryCache, _document, etc...
    synchronized (this)
    {
      // Before we do anything, set up the NameResolver and
      // InputStreamProvider.   _getEntry() is the single entry point
      // through which all calls into the FileSystemStyleCache flow.
      // So, by initializing the NameResolver/InputStreamProvider
      // here, we know they will always be available to other code.
      _initResolver();

      // If checking for modified files, then check to see if the XSS or CSS
      // document has been modified.  If so, we dump our in-memory style cache.
      if (checkModified && hasSourceDocumentChanged(context))
      {
        _cache = null;
        _entryCache = null;
        _document = null;
        _shortStyleClassMap = null;
        _namespacePrefixes  = null;
      }

      // We get references to our two caches (the "normal" cache,
      // and the cache of shared Entry objects) up front.  We do
      // this because the actual caches could change at any time.
      // (The caches get reallocated if the source document is
      // modified.)  We need to use a consistent set of caches
      // throughout the entire request, to avoid adding bogus entries
      // to a new re-allocated cache.
      // Note: It would probably make sense to use Map for the
      // cache type in our vars and method prototypes.  We explicitly
      // use Hashtable, because our implementation relies on the
      // synchronization provided by Hashtable.  If we change the
      // cache data structure, we might need to re-code to add
      // synchronization.  Thus the somewhat ugly explicit references
      // to Hashtable everywhere.
      if (_cache == null)
        _cache = new Hashtable<Key, Entry>();
      if (_entryCache == null)
        _entryCache = new Hashtable<Object, Entry>(19);

      cache = _cache;
      entryCache = _entryCache;

      // Get the document up front too.
      // Returns the StyleSheetDocument, parsing the source file if necessary
      // this sets up _shortStyleClassMap and _namespacePrefixes
      document = _getStyleSheetDocument(context);
      if (document == null)
        return null;

      shortStyleClassMap = _shortStyleClassMap;
      namespacePrefixes = _namespacePrefixes;
    }

    // Look up the style sheet
    // The Key class is a private static class that is used for hashing. It implements
    // hashCode and equals which are based on locale, direction, browser, version, platform.
    Key key = new Key(context);
    Entry entry = _getEntry(cache, key, checkModified);
    if (entry != null)
      return entry;

    // Next see if this is an entry which is compatible with this request
    entry = _getCompatibleEntry(context, document, cache, key, entryCache, checkModified);

    if (entry != null)
      return entry;

    // If we didn't find an entry in the cache, create a new entry
    // This generates the CSS file.
    return _createEntry(context,
                        document,
                        cache,
                        key,
                        entryCache,
                        shortStyleClassMap,
                        namespacePrefixes,
                        checkModified);
  }

  private Entry _getEntry(
    Map<?, Entry> cache,
    Object        key,
    boolean       checkModified
    )
  {
    Entry entry = cache.get(key);
    if (entry == null)
    {
      return null;
    }

    if (checkModified)
    {
      List<String> uris = entry.uris;
      assert uris != null && !uris.isEmpty();

      boolean valid = true;
      List<File> existing = new LinkedList<File>();
      // Make sure the entry's file exists.  If it no longer
      // exists, we remove the entry from the cache
      for (String name : uris)
      {
        File file = new File(_targetPath, name);
        if (file.exists())
        {
          existing.add(file);
        }
        else
        {
          valid = false;
        }
      }

      if (!valid)
      {
        _deleteAll(existing);

        synchronized (cache)
        {
          if (cache.get(key) == entry)
          {
            cache.remove(key);
          }
        }

        return null;
      }
    }

    return entry;
  }

  /**
   * Creates and caches an Entry for the specified StyleContext
   * This generates a style sheet for the specific StyleContext
   * (locale, direction, etc), and puts that style sheet's uri in the Entry.
   * It also caches it in the "normal" cache (the one that is based on the StyleContext),
   * and the entry cache (the one that is based on the StyleSheetNodes)
   */
  private Entry _createEntry(
    StyleContext             context,
    StyleSheetDocument       document,
    Hashtable<Key, Entry>    cache,
    Key                      key,
    Hashtable<Object, Entry> entryCache,
    Map<String, String>      shortStyleClassMap,
    String[]                 namespacePrefixes,
    boolean                  checkModified
    )
  {
    // Next, get the fully resolved styles for this context. This will be
    // those StyleNodes that match the locale, direction, browser, etc -- the
    // info that is in the StyleContext.
    StyleNode[] styles = _getStyleContextResolvedStyles(context, document);
    if (styles == null)
      return null;

    // Generate the style sheet file, if it isn't already generated,
    // and return the uri.
    List<String> uris = _createStyleSheetFiles(context,
                                       document,
                                       styles,
                                       shortStyleClassMap,
                                       namespacePrefixes,
                                                   checkModified);

    _LOG.fine("Finished processing stylesheet {0}", uris);

    // Next, get the fully resolved icons and skin properties for this context.
    // This will be those Icons and Skin Properties that match the locale, direction,
    // browser, etc -- the info that is in the StyleContext
    ConcurrentMap<String, Icon> icons =
      _getStyleContextResolvedIcons(context, document);
    ConcurrentMap<Object, Object> skinProperties =
      _getStyleContextResolvedSkinProperties(context, document);

    // Create a new entry and cache it in the "normal" cache. The "normal" cache is one
    // where the key is the Key object which is built based on information from the StyleContext,
    // like browser, agent, locale, direction.
    Entry entry = new Entry(uris, new StyleMapImpl(), icons, skinProperties);
    cache.put(key, entry);

    // Also, cache the new entry in the entry cache
    DerivationKey derivationKey = _getDerivationKey(context, document);
    entryCache.put(derivationKey, entry);

    return entry;
  }

  /**
   * Look in the entry cache for a compatible entry.
   * A compatible entry is one with the same DerivationKey, which is essentially the
   * same StyleSheetNodes.
   */
  private Entry _getCompatibleEntry(
    StyleContext             context,
    StyleSheetDocument       document,
    Map<Key, Entry>    cache,
    Key                      key,
    Map<Object, Entry> entryCache,
    boolean                  checkModified
    )
  {
    DerivationKey derivationKey = _getDerivationKey(context, document);
    Entry entry = _getEntry(entryCache, derivationKey, checkModified);
    if (entry != null)
    {
      // If we've got a compatible entry, cache it
      cache.put(key, entry);
    }
    return entry;
  }

  /**
   * Returns the derivation key that would be used for entries
   * based on the provided context
   */
  private DerivationKey _getDerivationKey(
    StyleContext context,
    StyleSheetDocument document
    )
  {
    // Entries with the same style sheet derivation are compatible.
    // Get the style sheet derivation list.
    Iterator


text:
from nose.tools import assert_raises

from ad.test.base import BaseTest
from ad.core.object import activate
from ad.core.client import Client
from ad.core.locate import Locator
from ad.core.constant import *
from ad.core.creds import Creds
from ad.core.exception import Error as ADError, LDAPError

class TestADClient(BaseTest):
    """Test suite for ADClient"""

    def test_search(self):
        self.require(ad_user=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_user_account(), self.ad_user_password())
        activate(creds)
        client = Client(domain)
        result = client.search('(objectClass=user)')
        assert len(result) > 1

    def _delete_user(self, client, name, server=None):
        # Delete any user that may conflict with a newly to be created user
        filter = '(|(cn=%s)(sAMAccountName=%s)(userPrincipalName=%s))' % \
                 (name, name, '%s@%s' % (name, client.domain().upper()))
        result = client.search('(&(objectClass=user)(sAMAccountName=%s))' % name,
                               server=server)
        for res in result:
            client.delete(res[0], server=server)

    def _create_user(self, client, name, server=None):
        attrs = []
        attrs.append(('cn', [name]))
        attrs.append(('sAMAccountName', [name]))
        attrs.append(('userPrincipalName', ['%s@%s' % (name, client.domain().upper())]))
        ctrl = AD_USERCTRL_ACCOUNT_DISABLED | AD_USERCTRL_NORMAL_ACCOUNT
        attrs.append(('userAccountControl', [str(ctrl)]))
        attrs.append(('objectClass', ['user']))
        dn = 'cn=%s,cn=users,%s' % (name, client.dn_from_domain_name(client.domain()))
        self._delete_user(client, name, server=server)
        client.add(dn, attrs, server=server)
        return dn

    def _delete_obj(self, client, dn, server=None):
        try:
            client.delete(dn, server=server)
        except (ADError, LDAPError):
            pass

    def _create_ou(self, client, name, server=None):
        attrs = []
        attrs.append(('objectClass', ['organizationalUnit']))
        attrs.append(('ou', [name]))
        dn = 'ou=%s,%s' % (name, client.dn_from_domain_name(client.domain()))
        self._delete_obj(client, dn, server=server)
        client.add(dn, attrs, server=server)
        return dn

    def test_add(self):
        self.require(ad_admin=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_admin_account(), self.ad_admin_password())
        activate(creds)
        client = Client(domain)
        user = self._create_user(client, 'test-usr')
        self._delete_obj(client, user)

    def test_delete(self):
        self.require(ad_admin=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_admin_account(), self.ad_admin_password())
        activate(creds)
        client = Client(domain)
        dn = self._create_user(client, 'test-usr')
        client.delete(dn)

    def test_modify(self):
        self.require(ad_admin=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_admin_account(), self.ad_admin_password())
        activate(creds)
        client = Client(domain)
        user = self._create_user(client, 'test-usr')
        mods = []
        mods.append(('replace', 'sAMAccountName', ['test-usr-2']))
        client.modify(user, mods)
        self._delete_obj(client, user)

    def test_modrdn(self):
        self.require(ad_admin=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_admin_account(), self.ad_admin_password())
        activate(creds)
        client = Client(domain)
        result = client.search('(&(objectClass=user)(sAMAccountName=test-usr))')
        if result:
            client.delete(result[0][0])
        user = self._create_user(client, 'test-usr')
        client.modrdn(user, 'cn=test-usr2')
        result = client.search('(&(objectClass=user)(cn=test-usr2))')
        assert len(result) == 1

    def test_rename(self):
        self.require(ad_admin=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_admin_account(), self.ad_admin_password())
        activate(creds)
        client = Client(domain)
        result = client.search('(&(objectClass=user)(sAMAccountName=test-usr))')
        if result:
            client.delete(result[0][0])
        user = self._create_user(client, 'test-usr')
        client.rename(user, 'cn=test-usr2')
        result = client.search('(&(objectClass=user)(cn=test-usr2))')
        assert len(result) == 1
        user = result[0][0]
        ou = self._create_ou(client, 'test-ou')
        client.rename(user, 'cn=test-usr', ou)
        newdn = 'cn=test-usr,%s' % ou
        result = client.search('(&(objectClass=user)(cn=test-usr))')
        assert len(result) == 1
        assert result[0][0].lower() == newdn.lower()

    def test_forest(self):
        self.require(ad_user=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_user_account(), self.ad_user_password())
        activate(creds)
        client = Client(domain)
        forest = client.forest()
        assert forest
        assert forest.isupper()

    def test_domains(self):
        self.require(ad_user=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_user_account(), self.ad_user_password())
        activate(creds)
        client = Client(domain)
        domains = client.domains()
        for domain in domains:
            assert domain
            assert domain.isupper()

    def test_naming_contexts(self):
        self.require(ad_user=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_user_account(), self.ad_user_password())
        activate(creds)
        client = Client(domain)
        naming_contexts = client.naming_contexts()
        assert len(naming_contexts) >= 3

    def test_search_all_domains(self):
        self.require(ad_user=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_user_account(), self.ad_user_password())
        activate(creds)
        client = Client(domain)
        domains = client.domains()
        for domain in domains:
            base = client.dn_from_domain_name(domain)
            result = client.search('(objectClass=*)', base=base, scope='base')
            assert len(result) == 1

    def test_search_schema(self):
        self.require(ad_user=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_user_account(), self.ad_user_password())
        activate(creds)
        client = Client(domain)
        base = client.schema_base()
        result = client.search('(objectClass=*)', base=base, scope='base')
        assert len(result) == 1

    def test_search_configuration(self):
        self.require(ad_user=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_user_account(), self.ad_user_password())
        activate(creds)
        client = Client(domain)
        base = client.configuration_base()
        result = client.search('(objectClass=*)', base=base, scope='base')
        assert len(result) == 1

    def _delete_group(self, client, dn, server=None):
        try:
            client.delete(dn, server=server)
        except (ADError, LDAPError):
            pass

    def _create_group(self, client, name, server=None):
        attrs = []
        attrs.append(('cn', [name]))
        attrs.append(('sAMAccountName', [name]))
        attrs.append(('objectClass', ['group']))
        dn = 'cn=%s,cn=Users,%s' % (name, client.dn_from_domain_name(client.domain()))
        self._delete_group(client, dn, server=server)
        client.add(dn, attrs, server=server)
        return dn

    def _add_user_to_group(self, client, user, group):
        mods = []
        mods.append(('delete', 'member', [user]))
        try:
            client.modify(group, mods)
        except (ADError, LDAPError):
            pass
        mods = []
        mods.append(('add', 'member', [user]))
        client.modify(group, mods)

    def test_incremental_retrieval_of_multivalued_attributes(self):
        self.require(ad_admin=True, expensive=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_admin_account(), self.ad_admin_password())
        activate(creds)
        client = Client(domain)
        user = self._create_user(client, 'test-usr')
        groups = []
        for i in range(2000):
            group = self._create_group(client, 'test-grp-%04d' % i)
            self._add_user_to_group(client, user, group)
            groups.append(group)
        result = client.search('(sAMAccountName=test-usr)')
        assert len(result) == 1
        dn, attrs = result[0]
        assert attrs.has_key('memberOf')
        assert len(attrs['memberOf']) == 2000
        self._delete_obj(client, user)
        for group in groups:
            self._delete_group(client, group)

    def test_paged_results(self):
        self.require(ad_admin=True, expensive=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_admin_account(), self.ad_admin_password())
        activate(creds)
        client = Client(domain)
        users = []
        for i in range(2000):
            user = self._create_user(client, 'test-usr-%04d' % i)
            users.append(user)
        result = client.search('(cn=test-usr-*)')
        assert len(result) == 2000
        for user in users:
            self._delete_obj(client, user)

    def test_search_rootdse(self):
        self.require(ad_user=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_user_account(), self.ad_user_password())
        activate(creds)
        locator = Locator()
        server = locator.locate(domain)
        client = Client(domain)
        result = client.search(base='', scope='base', server=server)
        assert len(result) == 1
        dns, attrs = result[0]
        assert attrs.has_key('supportedControl')
        assert attrs.has_key('supportedSASLMechanisms')

    def test_search_server(self):
        self.require(ad_user=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_user_account(), self.ad_user_password())
        activate(creds)
        locator = Locator()
        server = locator.locate(domain)
        client = Client(domain)
        result = client.search('(objectClass=user)', server=server)
        assert len(result) > 1

    def test_search_gc(self):
        self.require(ad_user=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_user_account(), self.ad_user_password())
        activate(creds)
        client = Client(domain)
        result = client.search('(objectClass=user)', scheme='gc')
        assert len(result) > 1
        for res in result:
            dn, attrs = res
            # accountExpires is always set, but is not a GC attribute
            assert 'accountExpires' not in attrs

    def test_set_password(self):
        self.require(ad_admin=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_admin_account(), self.ad_admin_password())
        activate(creds)
        client = Client(domain)
        user = self._create_user(client, 'test-usr-1')
        principal = 'test-usr-1@%s' % domain
        client.set_password(principal, 'Pass123')
        mods = []
        ctrl = AD_USERCTRL_NORMAL_ACCOUNT
        mods.append(('replace', 'userAccountControl', [str(ctrl)]))
        client.modify(user, mods)
        creds = Creds(domain)
        creds.acquire('test-usr-1', 'Pass123')
        assert_raises(ADError, creds.acquire, 'test-usr-1', 'Pass321')
        self._delete_obj(client, user)

    def test_set_password_target_pdc(self):
        self.require(ad_admin=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_admin_account(), self.ad_admin_password())
        activate(creds)
        client = Client(domain)
        locator = Locator()
        pdc = locator.locate(domain, role='pdc')
        user = self._create_user(client, 'test-usr-2', server=pdc)
        principal = 'test-usr-2@%s' % domain
        client.set_password(principal, 'Pass123', server=pdc)
        mods = []
        ctrl = AD_USERCTRL_NORMAL_ACCOUNT
        mods.append(('replace', 'userAccountControl', [str(ctrl)]))
        client.modify(user, mods, server=pdc)
        creds = Creds(domain)
        creds.acquire('test-usr-2', 'Pass123', server=pdc)
        assert_raises(ADError, creds.acquire, 'test-usr-2','Pass321',
                      server=pdc)
        self._delete_obj(client, user, server=pdc)

    def test_change_password(self):
        self.require(ad_admin=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_admin_account(), self.ad_admin_password())
        activate(creds)
        client = Client(domain)
        user = self._create_user(client, 'test-usr-3')
        principal = 'test-usr-3@%s' % domain
        client.set_password(principal, 'Pass123')
        mods = []
        ctrl = AD_USERCTRL_NORMAL_ACCOUNT
        mods.append(('replace', 'userAccountControl', [str(ctrl)]))
        mods.append(('replace', 'pwdLastSet', ['0']))
        client.modify(user, mods)
        client.change_password(principal, 'Pass123', 'Pass456')
        creds = Creds(domain)
        creds.acquire('test-usr-3', 'Pass456')
        assert_raises(ADError, creds.acquire, 'test-usr-3', 'Pass321')
        self._delete_obj(client, user)

    def test_change_password_target_pdc(self):
        self.require(ad_admin=True)
        domain = self.domain()
        creds = Creds(domain)
        creds.acquire(self.ad_admin_account(), self.ad_admin_password())
        activate(creds)
        client = Client(domain)
        locator = Locator()
        pdc = locator.locate(domain, role='pdc')
        user = self._create_user(client, 'test-usr-4', server=pdc)
        principal = 'test-usr-4@%s' % domain
        client.set_password(principal, 'Pass123', server=pdc)
        mods = []
        ctrl = AD_USERCTRL_NORMAL_ACCOUNT
        mods.append(('replace', 'userAccountControl', [str(ctrl)]))
        mods.append(('replace', 'pwdLastSet', ['0']))
        client.modify(user, mods, server=pdc)
        client.change_password(principal, 'Pass123', 'Pass456', server=pdc)
        creds = Creds(domain)
        creds.acquire('test-usr-4', 'Pass456', server=pdc)
        assert_raises(ADError, creds.acquire, 'test-usr-4', 'Pass321',
                             server=pdc)
        self._delete_obj(client, user, server=pdc)

redpajama_set_name: RedPajamaGithub


text:
"use strict";

var config = require('./config');
var spraitinator = require('./spritinator/lib/bin');
var del = require('del');

module.exports = function (gulp, plugins, options) {
  return function (cb) {
    del.sync(config.sprite.out);
  	spraitinator.generate({
      iconsPathSvg: config.sprite.iconsPathSvg,
      out: config.sprite.out,
      scssPath: config.sprite.scssPath,
      cssSpritePath: config.sprite.cssSpritePath,
      spritePath: config.sprite.spritePath
    }, function (error) {
      if(cb){
        cb(error);
      }
    });
  };
};


text:
function RectangularGravityField(x, y, w, h, gx, gy) {
	// basics
	this.type = 'RectangularGravityField';
	this.locked = false;

	// definition
	this.tl = {x: x, y: y};
	this.tr = {x: x + w, y: y};
	this.br = {x: x + w, y: y + h};
	this.bl = {x: x, y: y + h};
	this.w = w;
	this.h = h;

	// drawing
	this.fillR = 0;
	this.fillG = 0;
	this.fillB = 0;
	this.fillA = 0;

	this.hasDots = true;
	this.dotColors = [
		{
			r: 64,
			g: 255,
			b: 160
		},
		{
			r: 0,
			g: 160,
			b: 255
		},
		{
			r: 255,
			g: 160,
			b: 255
		}
	];

	this.dotDensity = 0.1; // per second per unit length of diagonal in appropriate direction
	this.dotDiagonalLR = 0; // left/right component of diagonal
	this.dotDiagonalTB = 0; // top/bottom component of diagonal
	this.dotDiagonal = 0; // is set during setup; the cross-section of rectangle normal to gravity direction
	this.dotsPerFrame = 0; // is set during setup
	this.dotRadius = 1;
	this.dotsFromTop = false;
	this.dotsFromBottom = false;
	this.dotsFromLeft = false;
	this.dotsFromRight = false;
	this.dotOffset = undefined; // is set during setup; how far new dots are offset from edge (vector)
	this.dotLeadTime = 0.1; // in seconds, how long dots take to enter field once generated

	this.dots = []; // get generated with a color chosen at random from the list, a random a for that color, and random position offscreen
	this.dotsThisFrame = 0; // number of dots this frame still to draw; draws a dot only if >= 1;

	// physics
	this.g = { // acceleration in pixels/s^2
		x: gx,
		y: gy
	};
	this.n = { // normal to gravity
		x: gy,
		y: -gx
	}

	this.setupDotGeometry();
}
RectangularGravityField.prototype = new GameObject();

RectangularGravityField.prototype.setupDotGeometry = function () {
	if (this.g.x === 0 && this.g.y === 0) { // no gravity, no dots
		this.hasDots = false;
		return;
	}

	// figure out where dots are coming from
	if (this.g.x > 0) this.dotsFromLeft = true;
	if (this.g.x < 0) this.dotsFromRight = true;
	if (this.g.y > 0) this.dotsFromTop = true;
	if (this.g.y < 0) this.dotsFromBottom = true;

	this.dotDiagonalLR = Math.abs(projectionLength({x: 0, y: this.h}, this.n));
	this.dotDiagonalTB = Math.abs(projectionLength({x: this.w, y: 0}, this.n));
	this.dotDiagonal = this.dotDiagonalLR + this.dotDiagonalTB;

	var g = Math.sqrt(this.g.x*this.g.x + this.g.y*this.g.y);
	var offsetDistance = 0.5*g*this.dotLeadTime*this.dotLeadTime + 2*this.dotRadius;
	this.dotOffset = {
		x: -this.g.x*offsetDistance/g,
		y: -this.g.y*offsetDistance/g
	}

	var dotsPerSecond = this.dotDiagonal * this.dotDensity;
	this.dotsPerFrame = dotsPerSecond*globalOptions.mspf/1000.0;
};

RectangularGravityField.prototype.generateDot = function () {
	if (!this.hasDots) return;

	var pos = Math.random()*this.dotDiagonal; // position along diagonal
	var dot = {
		velocity: {
			x: 0,
			y: 0
		}
	};
	var entryX = 0; // if from left
	var entryY = 0; // if from top
	if (pos < this.dotDiagonalLR) { // without loss of generality assume that lower numbers go on L/R and higher on T/B
		entryY = (pos/this.dotDiagonalLR)*this.h;
		if (this.dotsFromRight) {
			entryX = this.w;
		}
	} else {
		entryX = ((pos - this.dotDiagonalLR)/this.dotDiagonalTB)*this.w;
		if (this.dotsFromBottom) {
			entryY = this.h;
		}
	}
	var colorIndex = Math.floor(Math.random()*this.dotColors.length);
	var dot = {
		position: {
			x: entryX + this.dotOffset.x,
			y: entryY + this.dotOffset.y
		},
		velocity: {
			x: 0,
			y: 0
		},
		color: {
			r: this.dotColors[colorIndex].r,
			g: this.dotColors[colorIndex].g,
			b: this.dotColors[colorIndex].b,
			a: Math.random()
		}
	};
	this.dots.push(dot);
};

RectangularGravityField.prototype.draw = function (f) {
	gameCtx.save();
	gameCtx.rect(this.tl.x, this.tl.y, this.w, this.h);
	gameCtx.clip();

	gameCtx.fillStyle = rgba(this.fillR,this.fillG,this.fillB,this.fillA*f);
	gameCtx.fillRect(this.tl.x, this.tl.y, this.w, this.h);

	for (var d = 0; d < this.dots.length; d++) {
		/*gameCtx.fillStyle = rgba(this.dots[d].color.r, this.dots[d].color.g, this.dots[d].color.b, this.dots[d].color.a*f);
		gameCtx.beginPath();
		gameCtx.arc(this.dots[d].position.x, this.dots[d].position.y, this.dotRadius, 0, 2*Math.PI, true);
		gameCtx.fill();*/
		gameCtx.strokeStyle = rgba(this.dots[d].color.r, this.dots[d].color.g, this.dots[d].color.b, this.dots[d].color.a*f);
		gameCtx.lineWidth = this.dotRadius;
		gameCtx.beginPath();
		gameCtx.moveTo(this.dots[d].position.x, this.dots[d].position.y);
		gameCtx.lineTo(this.dots[d].position.x + 0.05*this.dots[d].velocity.x, this.dots[d].position.y + 0.05*this.dots[d].velocity.y);
		gameCtx.stroke();
	}

	gameCtx.restore();
};

RectangularGravityField.prototype.update = function () {
	if (!this.hasDots) return;
	this.dotsThisFrame += this.dotsPerFrame;

	while (this.dotsThisFrame >= 1) {
		this.generateDot();
		this.dotsThisFrame--;
	}

	for (var d = 0; d < this.dots.length; d++) {
		this.dots[d].velocity.x += this.g.x*globalOptions.mspf/1000.0;
		this.dots[d].velocity.y += this.g.y*globalOptions.mspf/1000.0;
		this.dots[d].position.x += this.dots[d].velocity.x*globalOptions.mspf/1000.0;
		this.dots[d].position.y += this.dots[d].velocity.y*globalOptions.mspf/1000.0;
		if ((this.dotsFromTop && this.dots[d].position.y > this.h + this.dotRadius) ||
			(this.dotsFromBottom && this.dots[d].position.y < -this.dotRadius) ||
			(this.dotsFromLeft && this.dots[d].position.x > this.w + this.dotRadius) ||
			(this.dotsFromRight && this.dots[d].position.y < -this.dotRadius)) {
			this.dots.splice(d, 1);
			d--;
		}
	}
};


text:
Ti=Personal Information Security Practices

Intro.sec=Reflecting the schema of the EU "Model Clauses" of technical and organizational, and covering with an umbrella of policy.

Policy.=[GHx/KantaraInitiative/MBP/Sec/Policy_v0.md]

Tech.=[GHx/KantaraInitiative/MBP/Sec/Technical_v0.md]

Organize.=[GHx/KantaraInitiative/MBP/Sec/Organizational_v0.md]

Model.Root={Ti}
{Intro.sec}

{Policy.Sec}
{Tech.Sec}
{Organize.Sec}


text:
<?php
///VALIDATE USER
function Send_Validation($user){
global $OK_Button, $link, $Validation_Failed, $Validation_Success;
$null_key = "00000000-0000-0000-0000-000000000000";
$name_seg=explode(' ',$user);
if(empty($name_seg[1])){$user=$user." resident";}
$escapename=urlencode($user);
$uuid="";
$searchurl = "http://secondlife.com/app/search/search?q=" . str_replace(" ", "+", $user);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $searchurl);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$site = curl_exec($ch);
curl_close($ch);
$search = "http://world.secondlife.com/resident/";
if (substr_count($site, $search) ==1){
	$keypos = strpos($site, $search) + strlen($search);
	$uuid = substr($site, $keypos, 36);
	if($uuid!=$null_key&&!empty($uuid)){$found_key=true;}
}
if(!$found_key){
	$url="http://w-hat.com/name2key?terse=1&name=$escapename";
	$h = fopen($url, "r");
	if($h){
		$uuid = fread($h, 100);
		fclose($h);
		if($uuid!=$null_key&&!empty($uuid)){$found_key=true;}
	}
}
if($OK_Button!=""){
	if(!$found_key){Show_Popup("Validation Failed",$Validation_Failed.$OK_Button,false);}
	else{Set_Account($user,$uuid);Show_Popup("Validation Link Sent In-World",$Validation_Success.$OK_Button,false);}
}
else{
	if(!$found_key){die("error: unable to validate user");}
	else{Set_Account($user,$uuid);die("error: user not validated. validation link sent to user ($user) in-world");}
}
}
?>


text:
/**
 * Created by at15 on 2016/4/8.
 */
import {Component} from 'angular2/core';

@Component({
    selector: 'bform-user-dashboard',
    styleUrls: ['./assets/user/user.dashboard.css'],
    templateUrl: './assets/user/user.dashboard.html'
})
export class UserDashboardComponent {

}


text:
package org.loon.framework.javase.game.core.graphics.component.awt;

import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.util.StringTokenizer;

import org.loon.framework.javase.game.utils.GraphicsUtils;

public class AWTLabel extends Canvas {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private String[] lines;

	private int numlines, width = 6, height = 6;

	private int line_height, line;

	private int[] line_widths;

	private int min_width, max_width;

	public AWTLabel(String label) {
		this(label, 0);
	}

	public AWTLabel(String label, int width) {
		StringTokenizer t = new StringTokenizer(label, "\n");
		this.numlines = t.countTokens();
		this.lines = new String[numlines];
		this.line_widths = new int[numlines];
		for (int i = 0; i < numlines; i++) {
			lines[i] = t.nextToken();
		}
		this.min_width = width;
	}

	protected void treatment() {
		FontMetrics fm = this.getFontMetrics(this.getFont());
		if (fm == null)
			return;
		line_height = fm.getHeight();
		line = fm.getAscent();
		max_width = 0;
		for (int i = 0; i < numlines; i++) {
			line_widths[i] = fm.stringWidth(lines[i]);
			if (line_widths[i] > max_width) {
				max_width = line_widths[i];
			}
		}
	}

	public void setFont(Font f) {
		super.setFont(f);
		treatment();
		repaint();
	}

	public void addNotify() {
		super.addNotify();
		treatment();
	}

	public Dimension getPreferredSize() {
		return new Dimension(Math.max(min_width, max_width + 2 * width),
				numlines * line_height + 2 * height);
	}

	public Dimension getMinimumSize() {
		return new Dimension(Math.max(min_width, max_width), numlines
				* line_height);
	}

	/**
	 * 绘制文字
	 */
	public void paint(Graphics g) {
		int x, y;
		Dimension d = this.getSize();
		y = line + (d.height - numlines * line_height) / 2;
		GraphicsUtils.setAntialias(g, true);
		for (int i = 0; i < numlines; i++, y += line_height) {
			x = width;
			g.drawString(lines[i], x, y);
		}
		GraphicsUtils.setAntialias(g, false);
	}

}


text:
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}

{-|

Types and functions for working with JOSE header parameters.

-}
module Crypto.JOSE.Header
  (
  -- * Defining header data types
    HeaderParam(..)
  , ProtectionIndicator(..)
  , Protection(..)
  , protection
  , isProtected
  , param

  -- * Defining header parsers
  -- $parsing
  , HasParams(..)
  , headerRequired
  , headerRequiredProtected
  , headerOptional
  , headerOptional'
  , headerOptionalProtected

  -- * Parsing headers
  , parseParams
  , parseCrit

  -- * Encoding headers
  , protectedParamsEncoded
  , unprotectedParams

  -- * Header fields shared by JWS and JWE
  , HasAlg(..)
  , HasJku(..)
  , HasJwk(..)
  , HasKid(..)
  , HasX5u(..)
  , HasX5c(..)
  , HasX5t(..)
  , HasX5tS256(..)
  , HasTyp(..)
  , HasCty(..)
  , HasCrit(..)
  ) where

import qualified Control.Monad.Fail as Fail
import Data.Kind (Type)
import Data.List.NonEmpty (NonEmpty)
import Data.Monoid ((<>))
import Data.Proxy (Proxy(..))

import Control.Lens (Lens', Getter, review, to)
import Data.Aeson (FromJSON(..), Object, Value, encode, object)
import Data.Aeson.Types (Pair, Parser)
import qualified Data.Aeson.Key as Key
import qualified Data.Aeson.KeyMap as M
import qualified Data.ByteString.Lazy as L
import qualified Data.Text as T

import qualified Crypto.JOSE.JWA.JWS as JWA.JWS
import Crypto.JOSE.JWK (JWK)
import Crypto.JOSE.Types.Internal (base64url)
import qualified Crypto.JOSE.Types as Types

-- | A thing with parameters.
--
class HasParams (a :: Type -> Type) where
  -- | Return a list of parameters,
  -- each paired with whether it is protected or not.
  params :: ProtectionIndicator p => a p -> [(Bool, Pair)]

  -- | List of "known extensions", i.e. keys that may appear in the
  -- "crit" header parameter.
  extensions :: Proxy a -> [T.Text]
  extensions = const []

  parseParamsFor
    :: (HasParams b, ProtectionIndicator p)
    => Proxy b -> Maybe Object -> Maybe Object -> Parser (a p)

-- | Parse a pair of objects (protected and unprotected header)
--
-- This internally invokes 'parseParamsFor' applied to a proxy for
-- the target type.  (This allows the parsing of the "crit" parameter
-- to access "known extensions" understood by the target type.)
--
parseParams
  :: forall a p. (HasParams a, ProtectionIndicator p)
  => Maybe Object -- ^ protected header
  -> Maybe Object -- ^ unprotected header
  -> Parser (a p)
parseParams = parseParamsFor (Proxy :: Proxy a)

protectedParams
  :: (HasParams a, ProtectionIndicator p)
  => a p -> Maybe Value {- ^ Object -}
protectedParams h =
  case (map snd . filter fst . params) h of
    [] -> Nothing
    xs -> Just (object xs)

-- | Return the base64url-encoded protected parameters
--
protectedParamsEncoded
  :: (HasParams a, ProtectionIndicator p)
  => a p -> L.ByteString
protectedParamsEncoded =
  maybe mempty (review base64url . encode) . protectedParams

-- | Return unprotected params as a JSON 'Value' (always an object)
--
unprotectedParams
  :: (HasParams a, ProtectionIndicator p)
  => a p -> Maybe Value {- ^ Object -}
unprotectedParams h =
  case (map snd . filter (not . fst) . params) h of
    [] -> Nothing
    xs -> Just (object xs)

-- | Whether a header is protected or unprotected
--
data Protection = Protected | Unprotected
  deriving (Eq, Show)

class Eq a => ProtectionIndicator a where
  -- | Get a value for indicating protection.
  getProtected :: a

  -- | Get a 'Just' a value for indicating no protection, or 'Nothing'
  -- if the type does not support unprotected headers.
  getUnprotected :: Maybe a

instance ProtectionIndicator Protection where
  getProtected = Protected
  getUnprotected = Just Unprotected

instance ProtectionIndicator () where
  getProtected = ()
  getUnprotected = Nothing

-- | A header value, along with a protection indicator.
--
data HeaderParam p a = HeaderParam p a
  deriving (Eq, Show)

instance Functor (HeaderParam p) where
  fmap f (HeaderParam p a) = HeaderParam p (f a)

-- | Lens for the 'Protection' of a 'HeaderParam'
protection :: Lens' (HeaderParam p a) p
protection f (HeaderParam p v) = fmap (\p' -> HeaderParam p' v) (f p)
{-# ANN protection "HLint: ignore Avoid lambda using `infix`" #-}

-- | Lens for a 'HeaderParam' value
param :: Lens' (HeaderParam p a) a
param f (HeaderParam p v) = fmap (\v' -> HeaderParam p v') (f v)
{-# ANN param "HLint: ignore Avoid lambda" #-}

-- | Getter for whether a parameter is protected
isProtected :: (ProtectionIndicator p) => Getter (HeaderParam p a) Bool
isProtected = protection . to (== getProtected)

{- $parsing

The 'parseParamsFor' function defines the parser for a header type.

@
'parseParamsFor'
  :: ('HasParams' a, HasParams b)
  => Proxy b -> Maybe Object -> Maybe Object -> 'Parser' a
@

It is defined over two objects: the /protected header/ and the
/unprotected header/.  The following functions are provided for
parsing header parameters:

['headerOptional']
  An optional parameter that may be protected or unprotected.
['headerRequired']
  A required parameter that may be protected or unprotected.
['headerOptionalProtected']
  An optional parameter that, if present, MUST be carried in the protected header.
['headerRequiredProtected']
  A required parameter that, if present, MUST be carried in the protected header.

Duplicate headers are forbidden.  The above functions all perform
duplicate header detection.  If you do not use them, be sure to
perform this detection yourself!

An example parser:

@
instance HasParams ACMEHeader where
  'parseParamsFor' proxy hp hu = ACMEHeader
    \<$> 'parseParamsFor' proxy hp hu
    \<*> 'headerRequiredProtected' "nonce" hp hu
@

-}

-- | Parse an optional parameter that may be carried in either
-- the protected or the unprotected header.
--
headerOptional
  :: (FromJSON a, ProtectionIndicator p)
  => T.Text
  -> Maybe Object
  -> Maybe Object
  -> Parser (Maybe (HeaderParam p a))
headerOptional = headerOptional' parseJSON

-- | Parse an optional parameter that may be carried in either
-- the protected or the unprotected header.  Like 'headerOptional',
-- but with an explicit argument for the parser.
--
headerOptional'
  :: (ProtectionIndicator p)
  => (Value -> Parser a)
  -> T.Text
  -> Maybe Object
  -> Maybe Object
  -> Parser (Maybe (HeaderParam p a))
headerOptional' parser kText hp hu = case (hp >>= M.lookup k, hu >>= M.lookup k) of
  (Just _, Just _)    -> fail $ "duplicate header " ++ show kText
  (Just v, Nothing)   -> Just . HeaderParam getProtected <$> parser v
  (Nothing, Just v)   -> maybe
    (fail "unprotected header not supported")
    (\p -> Just . HeaderParam p <$> parser v)
    getUnprotected
  (Nothing, Nothing)  -> pure Nothing
  where
    k = Key.fromText kText

-- | Parse an optional parameter that, if present, MUST be carried
-- in the protected header.
--
headerOptionalProtected
  :: FromJSON a
  => T.Text
  -> Maybe Object
  -> Maybe Object
  -> Parser (Maybe a)
headerOptionalProtected kText hp hu = case (hp >>= M.lookup k, hu >>= M.lookup k) of
  (Just _, Just _)    -> fail $ "duplicate header " ++ show kText
  (_, Just _) -> fail $ "header must be protected: " ++ show kText
  (Just v, _) -> Just <$> parseJSON v
  _           -> pure Nothing
  where
    k = Key.fromText kText

-- | Parse a required parameter that may be carried in either
-- the protected or the unprotected header.
--
headerRequired
  :: (FromJSON a, ProtectionIndicator p)
  => T.Text
  -> Maybe Object
  -> Maybe Object
  -> Parser (HeaderParam p a)
headerRequired kText hp hu = case (hp >>= M.lookup k, hu >>= M.lookup k) of
  (Just _, Just _)    -> fail $ "duplicate header " ++ show kText
  (Just v, Nothing)   -> HeaderParam getProtected <$> parseJSON v
  (Nothing, Just v)   -> maybe
    (fail "unprotected header not supported")
    (\p -> HeaderParam p <$> parseJSON v)
    getUnprotected
  (Nothing, Nothing)  -> fail $ "missing required header " ++ show k
  where
    k = Key.fromText kText

-- | Parse a required parameter that MUST be carried
-- in the protected header.
--
headerRequiredProtected
  :: FromJSON a
  => T.Text
  -> Maybe Object
  -> Maybe Object
  -> Parser a
headerRequiredProtected kText hp hu = case (hp >>= M.lookup k, hu >>= M.lookup k) of
  (Just _, Just _)    -> fail $ "duplicate header " ++ show kText
  (_, Just _) -> fail $ "header must be protected: " <> show kText
  (Just v, _) -> parseJSON v
  _           -> fail $ "missing required protected header: " <> show kText
  where
    k = Key.fromText kText

critObjectParser
  :: (Foldable t0, Foldable t1, Fail.MonadFail m)
  => t0 T.Text -> t1 T.Text -> Object -> T.Text -> m T.Text
critObjectParser reserved exts o s
  | s `elem` reserved         = Fail.fail "crit key is reserved"
  | s `notElem` exts          = Fail.fail "crit key is not understood"
  | not (Key.fromText s `M.member` o) = Fail.fail "crit key is not present in headers"
  | otherwise                 = pure s

-- | Parse a "crit" header param
--
-- Fails if:
--
-- * any reserved header appears in "crit" header
-- * any value in "crit" is not a recognised extension
-- * any value in "crit" does not have a corresponding key in the object
--
parseCrit
  :: (Foldable t0, Foldable t1, Traversable t2, Traversable t3, Fail.MonadFail m)
  => t0 T.Text -- ^ reserved header parameters
  -> t1 T.Text -- ^ recognised extensions
  -> Object    -- ^ full header (union of protected and unprotected headers)
  -> t2 (t3 T.Text) -- ^ crit header
  -> m (t2 (t3 T.Text))
parseCrit reserved exts o = mapM (mapM (critObjectParser reserved exts o))
  -- TODO fail on duplicate strings

class HasAlg a where
  alg :: Lens' (a p) (HeaderParam p JWA.JWS.Alg)

class HasJku a where
  jku :: Lens' (a p) (Maybe (HeaderParam p Types.URI))

class HasJwk a where
  jwk :: Lens' (a p) (Maybe (HeaderParam p JWK))

class HasKid a where
  kid :: Lens' (a p) (Maybe (HeaderParam p T.Text))

class HasX5u a where
  x5u :: Lens' (a p) (Maybe (HeaderParam p Types.URI))

class HasX5c a where
  x5c :: Lens' (a p) (Maybe (HeaderParam p (NonEmpty Types.SignedCertificate)))

class HasX5t a where
  x5t :: Lens' (a p) (Maybe (HeaderParam p Types.Base64SHA1))

class HasX5tS256 a where
  x5tS256 :: Lens' (a p) (Maybe (HeaderParam p Types.Base64SHA256))

class HasTyp a where
  typ :: Lens' (a p) (Maybe (HeaderParam p T.Text))

class HasCty a where
  cty :: Lens' (a p) (Maybe (HeaderParam p T.Text))

class HasCrit a where
  crit :: Lens' (a p) (Maybe (NonEmpty T.Text))


text:
package lv.srolanh.ornamenti;

import android.content.Context;
import android.os.SystemClock;
import android.view.animation.Interpolator;
import android.view.animation.DecelerateInterpolator;

/**
 * Created by srolanh on 16.1.7.
 */
public class ZoomWidget {

    private Interpolator interpolator;
    private int animationLength;
    private long zoomStartTimestamp;
    private boolean zoomFinished = true;
    private float currentZoom, destZoom;

    ZoomWidget(Context context) {
        interpolator = new DecelerateInterpolator();
        animationLength = context.getResources().getInteger(android.R.integer.config_shortAnimTime);
    }

    public void forceFinish(boolean finish) {
        zoomFinished = finish;
    }

    public void abortAnimation() {
        zoomFinished = true;
        currentZoom = destZoom;
    }

    public void startZoom(float dest) {
        zoomStartTimestamp = SystemClock.elapsedRealtime();
        destZoom = dest;
        zoomFinished = false;
        currentZoom = 1.0f;
    }

    public boolean computeZoomActiveState() {
        if (zoomFinished) {
            return false;
        }
        long zoomTimeElapsed = SystemClock.elapsedRealtime() - zoomStartTimestamp;
        if (zoomTimeElapsed >= animationLength) {
            zoomFinished = true;
            currentZoom = destZoom;
            return false;
        }
        float interpolatorTime = zoomTimeElapsed * 1.0f / animationLength;
        currentZoom = destZoom * interpolator.getInterpolation(interpolatorTime);
        return true;
    }

    public float getCurrentZoomLevel() {
        return currentZoom;
    }
}


text:
package com.andreid278.shootit.client.gui;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import com.andreid278.shootit.ShootIt;
import com.andreid278.shootit.client.Resources;
import com.andreid278.shootit.common.MCData;
import com.andreid278.shootit.common.PhotosData;
import com.andreid278.shootit.common.item.Camera;
import com.andreid278.shootit.common.network.MessageCameraToServer;
import com.andreid278.shootit.common.network.MessageDeletePhotoRequest;
import com.andreid278.shootit.common.network.MessageRequestForPhoto;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.renderer.vertex.VertexBuffer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IContainerListener;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.NonNullList;
import net.minecraft.util.text.TextFormatting;

public class CameraGui extends GuiContainer implements IContainerListener {
	public int curShader;

	public int curPhoto;
	public int maxPhoto;

	public CameraGui(Container inventorySlotsIn) {
		super(inventorySlotsIn);
		xSize = 352;
		ySize = 210;
	}

	public void initGui() {
		super.initGui();

		this.inventorySlots.removeListener(this);
		this.inventorySlots.addListener(this);

		buttonList.add(new TrueButtonGui(0, width / 2 - 72, height / 2 - 10, 10, 20, "<"));
		buttonList.add(new TrueButtonGui(1, width / 2 + 150, height / 2 - 10, 10, 20, ">"));
		buttonList.add(new TrueButtonGui(2, width / 2 + 140, height / 2 - 90, 20, 20, Resources.DELETE, 64, 192));

		curShader = 0;
		ItemStack item = mc.player.getHeldItemMainhand();
		if(item.getItem() instanceof Camera)
			if(item.hasTagCompound())
				curShader = item.getTagCompound().getInteger("shader");
	}

	@Override
	public void drawScreen(int mouseX, int mouseY, float partialTicks) {
		super.drawScreen(mouseX, mouseY, partialTicks);
		this.renderHoveredToolTip(mouseX, mouseY);
	}

	@Override
	protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
		this.mc.renderEngine.bindTexture(Resources.CAMERA_GUI);
		int x = (width - xSize) / 2;
		int y = (height - ySize) / 2;
		this.drawTexturedModalRect(x, y, 0, 0, xSize, ySize, 1, 1);

		ItemStack item = mc.player.getHeldItemMainhand();
		if(item.getItem() instanceof Camera) {
			if(item.hasTagCompound()) {
				curPhoto = 0;
				maxPhoto = 0;
				NBTTagCompound nbt = item.getTagCompound();

				if(nbt.getBoolean("hasMemoryCard")) {
					int[] indexes = nbt.getIntArray("indexes");
					curPhoto = nbt.getInteger("curPhoto");
					maxPhoto = indexes.length;
					if(indexes.length > 0) {
						if(curPhoto < indexes.length) {
							if(PhotosData.photos.containsKey(indexes[curPhoto]))
								mc.renderEngine.bindTexture(PhotosData.photos.get(indexes[curPhoto]));
							else {
								if(MCData.imageIDToLoadFromServer == 0 && !Minecraft.getMinecraft().isSingleplayer()) {
									MCData.imageIDToLoadFromServer = indexes[curPhoto];
									ShootIt.network.sendToServer(new MessageRequestForPhoto(indexes[curPhoto]));
								}
								else if(Minecraft.getMinecraft().isSingleplayer()) {
									File file = new File(MCData.photosFolderPathClient + "/" + indexes[curPhoto] + ".png");
									if(file.exists())
										PhotosData.addPhoto(indexes[curPhoto]);
									else PhotosData.addEmptyPhoto(indexes[curPhoto]);
								}
								Minecraft.getMinecraft().getTextureManager().bindTexture(Resources.LOADING);
							}
						}
						else {
							nbt.setInteger("curPhoto", 0);
							item.setTagCompound(nbt);
							ShootIt.network.sendToServer(new MessageCameraToServer((byte)2));
						}
					}
					else {
						Minecraft.getMinecraft().getTextureManager().bindTexture(Resources.NO_PHOTOS);
					}
				}
				else {
					Minecraft.getMinecraft().getTextureManager().bindTexture(Resources.NO_MEMORY_CARD);
				}
				int bx1 = (int)(100 * width / xSize);
				int bx2 = (int)(339 * width / xSize);
				int by1 = (int)(12 * height / ySize);
				int by2 = (int)(196 * height / ySize);
				drawTexturedModalRect(width / 2 - 76, height / 2 - 93, 0, 0, 240, 185, 1, 1);
				if(maxPhoto > 0) {
					drawCenteredStringWithoutShadow(mc.fontRenderer, (curPhoto + 1) + "/" + maxPhoto, (int)(width / 2 + 44), (int)(height / 2 - 90), 16777215);
				}
			}
		}
	}

	public void drawTexturedModalRect(double x, double y, double textureX, double textureY, double width, double height, double textureWidth, double textureHeight) {
		Tessellator tessellator = Tessellator.getInstance();
		BufferBuilder vertexbuffer = tessellator.getBuffer();
		vertexbuffer.begin(7, DefaultVertexFormats.POSITION_TEX);
		vertexbuffer.pos(x + 0, y + height, (double)this.zLevel).tex(textureX, textureY + textureHeight).endVertex();
		vertexbuffer.pos(x + width, y + height, (double)this.zLevel).tex(textureX + textureWidth, textureY + textureHeight).endVertex();
		vertexbuffer.pos(x + width, y + 0, (double)this.zLevel).tex(textureX + textureWidth, textureY).endVertex();
		vertexbuffer.pos(x + 0, y + 0, (double)this.zLevel).tex(textureX, textureY).endVertex();
		tessellator.draw();
	}

	public void drawCenteredStringWithoutShadow(FontRenderer fontRendererIn, String text, int x, int y, int color) {
		fontRendererIn.drawString(text, (float)(x - fontRendererIn.getStringWidth(text) / 2), (float)y, color, false);
	}

	public void onGuiClosed() {
		super.onGuiClosed();
	}

	protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
		if(getSlotUnderMouse() != null) {
			int slot = getSlotUnderMouse().slotNumber;
			if(slot == 36 && !getSlotUnderMouse().getHasStack())
				drawHoveringText(Arrays.asList(TextFormatting.ITALIC + "Memory card"), mouseX - guiLeft, mouseY - guiTop);
		}

		if(buttonList.get(2).isMouseOver()) {
			drawHoveringText(Arrays.asList("Ctrl + Click to delete only from this memory card", "Ctrl + Alt + Click to delete from everywhere (forever)"), mouseX - guiLeft, mouseY - guiTop);
		}
	}

	protected boolean checkHotbarKeys(int keyCode) {
		return false;
	}

	@Override
	public void sendAllContents(Container containerToSend, NonNullList<ItemStack> itemsList) {
		// TODO Auto-generated method stub
		//this.sendSlotContents(containerToSend, 36, containerToSend.getSlot(36).getStack());

	}

	@Override
	public void sendSlotContents(Container containerToSend, int slotInd, ItemStack stack) {
		// TODO Auto-generated method stub
		if(slotInd == mc.player.inventory.currentItem) {
			ItemStack item = mc.player.getHeldItemMainhand();
			if(item.getItem() instanceof Camera) {
				item.setTagCompound(stack.getTagCompound());
			}
		}
	}

	@Override
	public void sendWindowProperty(Container containerIn, int varToUpdate, int newValue) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sendAllWindowProperties(Container containerIn, IInventory inventory) {
		// TODO Auto-generated method stub

	}

	protected void actionPerformed(GuiButton button) throws IOException {
		switch (button.id) {
		case 0:
			ShootIt.network.sendToServer(new MessageCameraToServer((byte)0, false));
			break;
		case 1:
			ShootIt.network.sendToServer(new MessageCameraToServer((byte)0, true));
			break;
		case 2:
			ItemStack item = mc.player.getHeldItemMainhand();
			if(item.getItem() instanceof Camera)
				if(item.hasTagCompound()) {
					NBTTagCompound nbt = item.getTagCompound();
					if(nbt.getBoolean("hasMemoryCard")) {
						int[] indexes = nbt.getIntArray("indexes");
						int curPhoto = nbt.getInteger("curPhoto");
						if(indexes.length > 0 && curPhoto < indexes.length) {
							if(isCtrlKeyDown() && isAltKeyDown())
								ShootIt.network.sendToServer(new MessageDeletePhotoRequest(indexes[curPhoto], true));
							else if(isCtrlKeyDown())
								ShootIt.network.sendToServer(new MessageDeletePhotoRequest(indexes[curPhoto], false));
						}
					}
				}
			break;
		}
	}
}


text:
from deepctr.models import DeepFM
from deepctr.feature_column import SparseFeat, VarLenSparseFeat, get_feature_names
import numpy as np
import pandas as pd
from tensorflow.python.keras.preprocessing.sequence import pad_sequences

try:
    import tensorflow.compat.v1 as tf
except ImportError as e:
    import tensorflow as tf

if __name__ == "__main__":
    data = pd.read_csv("./movielens_sample.txt")
    sparse_features = ["movie_id", "user_id",
                       "gender", "age", "occupation", "zip", ]

    data[sparse_features] = data[sparse_features].astype(str)
    target = ['rating']

    # 1.Use hashing encoding on the fly for sparse features,and process sequence features

    genres_list = list(map(lambda x: x.split('|'), data['genres'].values))
    genres_length = np.array(list(map(len, genres_list)))
    max_len = max(genres_length)

    # Notice : padding=`post`
    genres_list = pad_sequences(genres_list, maxlen=max_len, padding='post', dtype=object, value=0).astype(str)
    # 2.set hashing space for each sparse field and generate feature config for sequence feature

    fixlen_feature_columns = [SparseFeat(feat, data[feat].nunique() * 5, embedding_dim=4, use_hash=True,
                                         vocabulary_path='./movielens_age_vocabulary.csv' if feat == 'age' else None,
                                         dtype='string')
                              for feat in sparse_features]
    varlen_feature_columns = [
        VarLenSparseFeat(SparseFeat('genres', vocabulary_size=100, embedding_dim=4,
                                    use_hash=True, dtype="string"),
                         maxlen=max_len, combiner='mean',
                         )]  # Notice : value 0 is for padding for sequence input feature
    linear_feature_columns = fixlen_feature_columns + varlen_feature_columns
    dnn_feature_columns = fixlen_feature_columns + varlen_feature_columns
    feature_names = get_feature_names(linear_feature_columns + dnn_feature_columns)

    # 3.generate input data for model
    model_input = {name: data[name] for name in feature_names}
    model_input['genres'] = genres_list

    # 4.Define Model,compile and train
    model = DeepFM(linear_feature_columns, dnn_feature_columns, task='regression')
    model.compile("adam", "mse", metrics=['mse'], )
    if not hasattr(tf, 'version') or tf.version.VERSION < '2.0.0':
        with tf.Session() as sess:
            sess.run(tf.tables_initializer())
            history = model.fit(model_input, data[target].values,
                                batch_size=256, epochs=10, verbose=2, validation_split=0.2, )
    else:
        history = model.fit(model_input, data[target].values,
                            batch_size=256, epochs=10, verbose=2, validation_split=0.2, )


text:
import Vue from 'vue';
import store from './store';

let notification = new Vue({
  store,

  vuex: {
    getters: {
      currentTrack: ({player}) => player.currentTrack,
      apiUrl: ({player}) => player.apiUrl
    }
  },

  methods: {
    songPlayed () {
      let vm = this;
      let oldTrackTitle = vm.currentTrack.title;
      setTimeout(function () {
        if (vm.$store.state.player.currentTrack.title === oldTrackTitle) {
          vm.notify(
              `♫ ${vm.currentTrack.title}`,
              `By: ${vm.currentTrack.username} on ${vm.currentTrack.genre}`
          );
        }
      }, 5000);
    },

    notify(title, body, silent = true, icon = require('../img/logo.png')) {
      return new Notification(
        title,
        {
          icon,
          body,
          silent
        }
      );
    }
  }
});

export default notification;


text:
The OAuthEvent class
====================

When a user accepts to share his data with a client, it's a nice idea to save this state.
By default, the FOSOAuthServerBundle will always show the authorization page to the user
when an access token is asked. As an access token has a lifetime, it can be annoying for your
users to always accept a client.

Thanks to the [Event Dispatcher](http://symfony.com/doc/current/components/event_dispatcher.html),
you can listen before, and after the authorization form process. So, you can save the user's choice,
and even by pass the authorization pass. Let's an example.

Assuming we have a _Many to Many_ relation between clients, and users. An `OAuthEvent` contains
a `ClientInterface` instance, a `UserInterface` instance (coming from the [Security Component](http://symfony.com/doc/current/book/security.html)),
and a flag to determine whether the client has been accepted, or not.

The following class shows a Propel implementation of a basic listener:

``` php
<?php

namespace Acme\DemoBundle\EventListener;

use FOS\OAuthServerBundle\Event\OAuthEvent;

class OAuthEventListener
{
    public function onPreAuthorizationProcess(OAuthEvent $event)
    {
        if ($user = $this->getUser($event)) {
            $event->setAuthorizedClient(
                $user->isAuthorizedClient($event->getClient())
            );
        }
    }

    public function onPostAuthorizationProcess(OAuthEvent $event)
    {
        if ($event->isAuthorizedClient()) {
            if (null !== $client = $event->getClient()) {
                $user = $this->getUser($event);
                $user->addClient($client);
                $user->save();
            }
        }
    }

    protected function getUser(OAuthEvent $event)
    {
        return UserQuery::create()
            ->filterByUsername($event->getUser()->getUsername())
            ->findOne();
    }
}
```

The `$user` variable has a method `isAuthorizedClient()` which contains your logic to determine whether
the given client (`ClientInterface`) is allowed by the user, or not. This `$user` is part of your
own model layer, and loaded using the `username` property (see `getUser()`).

### Registering the listener

``` yaml
services:
    oauth_event_listener:
        class:  Acme\DemoBundle\EventListener\OAuthEventListener
        tags:
            - { name: kernel.event_listener, event: fos_oauth_server.pre_authorization_process, method: onPreAuthorizationProcess }
            - { name: kernel.event_listener, event: fos_oauth_server.post_authorization_process, method: onPostAuthorizationProcess }
```

### Next?

You can build a panel for your users displaying this list. If they remove an entry from this list,
then the authorization page will be displayed to the user like the first time. And, if the user
accepts the client, then the system will save this client to the user's list once again.

[Back to index](index.md)


text:
package com.ly.hi.lbs.http.params;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import com.ly.hi.lbs.common.BizInterface;

/**
 * ÇëÇóµÄ»ù´¡²ÎÊý
 */
public class BaseRequestParams {
    //½Ó¿Ú°æ±¾ºÅ
    protected String ak;      //ÃÜÔ¿

    public BaseRequestParams() {
        this.ak = BizInterface.BAIDU_LBS_AK;
    }

	public String getAk() {
		return ak;
	}

	public void setAk(String ak) {
		this.ak = ak;
	}

}


text:
Public Class clsURLScrub
    Inherits System.Web.UI.Page

    Public Function URLScrub(ByVal strURLTest As String)
        Dim valid As New Boolean
        Dim blacklist As New Collection
        Dim spacelist As New Collection
        'Dim investlist As New Collection

        strURLTest = LCase(strURLTest)

        valid = True
        If Len(strURLTest) > 0 Then

            ' Commented out because spaces were used in OLD RAD TreeView
            ' check url for space of any kind, a space is not allowed
            spacelist.Add("%20") 'hex space
            'spacelist.Add("")   'oct space
            spacelist.Add("chr(32)") 'html space
            For Each itm As String In spacelist
                If strURLTest.IndexOf(itm) <> -1 Then
                    'bad string found
                    valid = False
                    Exit For
                End If
            Next
        End If
        If valid = True Then
            'Fill out blacklist with words in lower case only
            blacklist.Add("--")
            blacklist.Add("+")  'new 03-06-09 JMT
            blacklist.Add(":")
            blacklist.Add("%3a") ' url encode for :
            blacklist.Add(";")
            blacklist.Add("%3b") ' url encode for ;
            blacklist.Add("@@")
            blacklist.Add("'")
            blacklist.Add("%27")  'url encode for '
            blacklist.Add("|")
            blacklist.Add("^")
            blacklist.Add("~")
            blacklist.Add("%7e")  'url encode for ~
            blacklist.Add("<>")
            blacklist.Add("!")
            blacklist.Add("/")
            blacklist.Add("%2F")  'url encode for /
            blacklist.Add(")")
            blacklist.Add("%29")  'url encode for )
            blacklist.Add("/*")
            blacklist.Add("*/")
            blacklist.Add("%22")  ' url encode for "
            blacklist.Add("""")
            blacklist.Add("all_")
            blacklist.Add("alter%20database")
            blacklist.Add("alter%20function")
            blacklist.Add("alter%20procedure")
            blacklist.Add("alter%20table")
            blacklist.Add("alter%20trigger")
            blacklist.Add("alter%20view")
            blacklist.Add("appl_")
            blacklist.Add("ascii(")
            blacklist.Add("auth_")
            blacklist.Add("bcp")
            blacklist.Add("begin%20distributed%20transaction")
            blacklist.Add("begin%20transaction")
            blacklist.Add("binary_checksum")
            blacklist.Add("bulk")
            blacklist.Add("bulk%20insert")
            blacklist.Add("charindex")
            blacklist.Add("cert_")
            blacklist.Add("checkpoint")
            blacklist.Add("checksum")
            blacklist.Add("checksum_agg")
            blacklist.Add("cmdshell")
            blacklist.Add("coalesce")
            blacklist.Add("collate")
            blacklist.Add("collationproperty")
            blacklist.Add("col_length")
            blacklist.Add("col_name")
            blacklist.Add("columnproperty")
            blacklist.Add("commit%20transaction")
            blacklist.Add("commit%20work")
            blacklist.Add("containstable")
            blacklist.Add("content_")
            blacklist.Add("count_big")
            blacklist.Add("create%20database")
            blacklist.Add("create%20function")
            blacklist.Add("create%20index")
            blacklist.Add("create%20procedure")
            blacklist.Add("create%20rule")
            blacklist.Add("create%20schema")
            blacklist.Add("create%20statistics")
            blacklist.Add("create%20table")
            blacklist.Add("create%20trigger")
            blacklist.Add("create%20view")
            blacklist.Add("current_timestamp")
            blacklist.Add("current_user")
            blacklist.Add("cursor_status")
            blacklist.Add("databaseproperty")
            blacklist.Add("databasepropertyex")
            blacklist.Add("datalength")
            blacklist.Add("dateadd")
            blacklist.Add("datediff")
            blacklist.Add("datename")
            blacklist.Add("datepart")
            blacklist.Add("db_id")
            blacklist.Add("dbcc")
            blacklist.Add("declare @")
            blacklist.Add("drop%20database")
            blacklist.Add("drop%20default")
            blacklist.Add("drop%20function")
            blacklist.Add("drop%20index")
            blacklist.Add("drop%20procedure")
            blacklist.Add("drop%20rule")
            blacklist.Add("drop%20statistics")
            blacklist.Add("drop%20table")
            blacklist.Add("drop%20trigger")
            blacklist.Add("drop%20view")
            blacklist.Add("dump")
            blacklist.Add("exec")
            blacklist.Add("file_id")
            blacklist.Add("file_name")
            blacklist.Add("filegroup_id")
            blacklist.Add("filegroup_name")
            blacklist.Add("filegroupproperty")
            blacklist.Add("fileproperty")
            blacklist.Add("fn_helpcollations")
            blacklist.Add("fn_listextendedproperty")
            blacklist.Add("fn_servershareddrives")
            blacklist.Add("fn_trace_geteveninfo")
            blacklist.Add("fn_trace_getfilterinfo")
            blacklist.Add("fn_trace_getinfo")
            blacklist.Add("fn_trace_gettable")
            blacklist.Add("fn_virtualfilestats")
            blacklist.Add("fn_virtualservernodes")
            blacklist.Add("formatmessage")
            blacklist.Add("freetext")
            blacklist.Add("freetexttable")
            blacklist.Add("fulltextcatalogproperty")
            blacklist.Add("fulltextserviceproperty")
            blacklist.Add("gateway_")
            blacklist.Add("getansinull")
            blacklist.Add("group bye")
            blacklist.Add("has_dbaccess")
            blacklist.Add("host_id")
            blacklist.Add("host_name")
            blacklist.Add("http_")
            blacklist.Add("https_")
            blacklist.Add("ident_current")
            blacklist.Add("ident_incr")
            blacklist.Add("ident_seed")
            blacklist.Add("in(")
            blacklist.Add("indexkey_property")
            blacklist.Add("indexproperty")
            blacklist.Add("index_col")
            blacklist.Add("information_schema")
            blacklist.Add("instance_")
            blacklist.Add("is_member")
            blacklist.Add("is_srvrolemember")
            blacklist.Add("is[not]null")
            blacklist.Add("isnull")
            blacklist.Add("is%20null")
            blacklist.Add("left(")
            blacklist.Add("len(")
            blacklist.Add("local_")
            blacklist.Add("logon_")
            blacklist.Add("lower(")
            blacklist.Add("ltrim(")
            blacklist.Add("max(")
            blacklist.Add("min(")
            blacklist.Add("month(")
            blacklist.Add("nchar(")
            blacklist.Add("newid")
            blacklist.Add("nullif")
            blacklist.Add("object_id")
            blacklist.Add("object_name")
            blacklist.Add("objectproperty")
            blacklist.Add("opendatasource")
            blacklist.Add("openquery")
            blacklist.Add("openrowset")
            blacklist.Add("openxml")
            blacklist.Add("order%20by")
            blacklist.Add("parsename")
            blacklist.Add("path_")
            blacklist.Add("patindex")
            blacklist.Add("query_")
            blacklist.Add("quotename")
            blacklist.Add("raiserror")
            blacklist.Add("reconfigure")
            blacklist.Add("remote_")
            blacklist.Add("replicate(")
            blacklist.Add("request_")
            blacklist.Add("restore%20filelistonly")
            blacklist.Add("restore%20headeronly")
            blacklist.Add("restore%20labelonly")
            blacklist.Add("restore%20verifyonly")
            blacklist.Add("reverse(")
            blacklist.Add("revoke all")
            blacklist.Add("right(")
            blacklist.Add("rollback%20transaction")
            blacklist.Add("rollback%20work")
            blacklist.Add("rowcount_big")
            blacklist.Add("rtrim(")
            blacklist.Add("save%20transaction")
            blacklist.Add("scope_identity")
            blacklist.Add("script_")
            blacklist.Add("server_")
            blacklist.Add("serverproperty")
            blacklist.Add("session_user")
            blacklist.Add("sessionproperty")
            blacklist.Add("setuser")
            blacklist.Add("shutdown")
            blacklist.Add("sp_")
            blacklist.Add("space(")
            blacklist.Add("sql_variant_property")
            blacklist.Add("stats_date")
            blacklist.Add("substring")
            blacklist.Add("suser_id")
            blacklist.Add("suser_name")
            blacklist.Add("suser_sid")
            blacklist.Add("suser_sname")
            blacklist.Add("syscolumns")
            blacklist.Add("sysobjects")
            blacklist.Add("system_user")
            blacklist.Add("textptr")
            blacklist.Add("textvalid")
            blacklist.Add("trigger_nestlevel")
            blacklist.Add("truncate%20table")
            blacklist.Add("typeproperty")
            blacklist.Add("update%20statistics")
            blacklist.Add("updatetext")
            blacklist.Add("upper(")
            blacklist.Add("waitfor")
            blacklist.Add("writetext")
            blacklist.Add("xp_")
            'check url for + and if there is a plus next to our investigate list
            'blacklist.Add("having")
            'blacklist.Add("or")
            'blacklist.Add("url")
            'blacklist.Add("select")
            'blacklist.Add("grant")
            blacklist.Add("@")

            For Each itm As String In blacklist
                If strURLTest.IndexOf(itm) <> -1 Then
                    'bad string found
                    valid = False
                    Exit For
                End If
            Next
        End If
        'Dim intLength As Integer
        'intLength = Len(strURLTest)
        'Dim intX As Integer
        'intX = 0

        'While intX < intLength
        '    If intX = 0 Then
        '        intX = strURLTest.IndexOf("+")
        '        If intX = -1 Then
        '            Exit While
        '        End If
        '    Else
        '        intX = strURLTest.IndexOf("+", intX)
        '        If intX = -1 Then
        '            Exit While
        '        End If
        '    End If

        '    Dim intLengthItem As Integer

        '    'loops through all the investigate word list
        '    For Each itm As String In investlist
        '        intLengthItem = Len(itm)
        '        If strURLTest.IndexOf(itm, intX - intLengthItem, intLengthItem) <> -1 Then
        '            'if the word is found it will return the position of the first occurence starting at intX.
        '            'see if the plus then investigate word ie. having+
        '            Dim strPartWord As String
        '            strPartWord = Mid(strURLTest, intX - (intLengthItem - 1), intLengthItem)
        '            If strPartWord = itm Then
        '                'invalid word found before the + exit
        '                valid = False
        '                Exit For
        '            End If
        '        End If
        '    Next
        '    intX = intX + 1
        'End While

        If valid = False Then
            System.Web.HttpContext.Current.Response.Redirect("/ErrorPage.aspx")
            Return False
        Else
            Return True
        End If

    End Function

End Class


text:
<?php

/**
 * Sets the client character set
 *
 * @phpstub
 *
 * @param string $charset
 * @param resource $link_identifier
 *
 * @return bool
 */
function mysql_set_charset($charset, $link_identifier = NULL)
{
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Beco</tipo><logradouro>Noel</logradouro><bairro>Maré</bairro><cidade>Rio de Janeiro</cidade><uf>RJ</uf><cep>21042014</cep></feed>


text:
package uk.gov.ida.dropwizard.logstash.support;

import com.fasterxml.jackson.annotation.JsonProperty;

public class LogFormat {

    @JsonProperty("@timestamp")
    public String timestamp;

    @JsonProperty("@version")
    public String version;

    public String message;

    public String logger_name;

    public String thread_name;

    public String level;

    public String level_value;

    public String tags;

    private LogFormat() {

    }

    public LogFormat(String timestamp, String version, String message, String logger_name, String thread_name, String level, String level_value, String tags) {
        this.timestamp = timestamp;
        this.version = version;
        this.message = message;
        this.logger_name = logger_name;
        this.thread_name = thread_name;
        this.level = level;
        this.level_value = level_value;
        this.tags = tags;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public String getVersion() {
        return version;
    }

    public String getMessage() {
        return message;
    }

    public String getLoggerName() {
        return logger_name;
    }

    public String getThreadName() {
        return thread_name;
    }

    public String getLevel() {
        return level;
    }

    public String getLevelValue() {
        return level_value;
    }

    public String getTags() {
        return tags;
    }

}


text:
:- module('more_specific.simple',['more_specific.simple:more_specific_transformation'/1]).

%:- dynamic more_specific_transformation/1.

:- set_prolog_flag(multi_arity_warnings,off).
%:- set_prolog_flag(discontiguous_warnings,off).
:- set_prolog_flag(single_var_warnings,off).

:- use_module(library(lists)).

:- use_module('../bimtools').
:- use_module('../calc_chtree').

:- use_module( mst ).

/* instantiates goals during the unfolding process to more specific versions */

'more_specific.simple:more_specific_transformation'([]).
'more_specific.simple:more_specific_transformation'([CH|T]) :-
	peel_off_calls(CH,H),
	mst_instantiate_atom(H),!,
	'more_specific.simple:more_specific_transformation'(T).


text:
package com.codebullets.external.party.simulator.connections;

/**
 * Represents a connection, can either be inbound or outbound.<p/>
 * Implementations of this interface are expected to have a constructor with with an
 * empty argument list.
 */
public interface Connection {
    /**
     * Called when it is time for the connection to be established.
     */
    void start(ConnectionConfig config);

    /**
     * Called by the simulator service. The methods on the injected monitor
     * need to be called to trigger actions inside the service.
     */
    void setMonitor(ConnectionMonitor monitor);

    /**
     * Sends a single text string over the connection.
     */
    void send(String text);

    /**
     * Sends a single text string over the connection. This
     * message is sent as part of a specific context. For example sending
     * a message back only a single client attached to single connection.
     */
    void send(ConnectionContext context, String text);

    /**
     * Sends a buffer of bytes over the connection.
     */
    void send(byte[] buffer);

    /**
     * Sends a buffer of bytes over the connection. This
     * message is sent as part of a specific context. For example sending
     * a message back only a single client attached to single connection.
     */
    void send(ConnectionContext context, byte[] buffer);

    /**
     * Sends any kind of object over the connection.
     */
    void send(Object object);

    /**
     * Sends any kind of object over the connection. This
     * message is sent as part of a specific context. For example sending
     * a message back only a single client attached to single connection.
     */
    void send(ConnectionContext context, Object object);
}


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

#pragma once

//+-----------------------------------------------Terminology---------------------------------------------+
//|                                                                                |
//| CPU Reset:    Reset CPU core only, once reset done, CPU will execute from reset vector                |
//|                                                                                |
//| Core Reset:   Reset the whole digital system except RTC sub-system                                    |
//|                                                                                |
//| System Reset: Reset the whole digital system, including RTC sub-system                                |
//|                                                                                |
//| Chip Reset:   Reset the whole chip, including the analog part                                         |
//|                                                                                |
//+-------------------------------------------------------------------------------------------------------+

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @brief Naming conventions: RESET_REASON_{reset level}_{reset reason}
 * @note refer to TRM: <Reset and Clock> chapter
 */
typedef enum {
    RESET_REASON_CHIP_POWER_ON   = 0x01, // Power on reset
    RESET_REASON_CHIP_BROWN_OUT  = 0x01, // VDD voltage is not stable and resets the chip
    RESET_REASON_CHIP_SUPER_WDT  = 0x01, // Super watch dog resets the chip
    RESET_REASON_CORE_SW         = 0x03, // Software resets the digital core by RTC_CNTL_SW_SYS_RST
    RESET_REASON_CORE_DEEP_SLEEP = 0x05, // Deep sleep reset the digital core
    RESET_REASON_CORE_MWDT0      = 0x07, // Main watch dog 0 resets digital core
    RESET_REASON_CORE_MWDT1      = 0x08, // Main watch dog 1 resets digital core
    RESET_REASON_CORE_RTC_WDT    = 0x09, // RTC watch dog resets digital core
    RESET_REASON_CPU0_MWDT0      = 0x0B, // Main watch dog 0 resets CPU 0
    RESET_REASON_CPU0_SW         = 0x0C, // Software resets CPU 0 by RTC_CNTL_SW_PROCPU_RST
    RESET_REASON_CPU0_RTC_WDT    = 0x0D, // RTC watch dog resets CPU 0
    RESET_REASON_SYS_BROWN_OUT   = 0x0F, // VDD voltage is not stable and resets the digital core
    RESET_REASON_SYS_RTC_WDT     = 0x10, // RTC watch dog resets digital core and rtc module
    RESET_REASON_CPU0_MWDT1      = 0x11, // Main watch dog 1 resets CPU 0
    RESET_REASON_SYS_SUPER_WDT   = 0x12, // Super watch dog resets the digital core and rtc module
    RESET_REASON_SYS_CLK_GLITCH  = 0x13, // Glitch on clock resets the digital core and rtc module
    RESET_REASON_CORE_EFUSE_CRC  = 0x14, // eFuse CRC error resets the digital core
    RESET_REASON_CORE_USB_UART   = 0x15, // USB UART resets the digital core
    RESET_REASON_CORE_USB_JTAG   = 0x16, // USB JTAG resets the digital core
    RESET_REASON_CORE_PWR_GLITCH = 0x17, // Glitch on power resets the digital core
} soc_reset_reason_t;

#ifdef __cplusplus
}
#endif


text:
<if expr="pp_ifdef('chromeos')">

        <select id="timezone-select" class="control" i18n-options="timezoneList"
            data-type="string" pref="cros.system.timezone"></select>

          <input id="use-24hour-clock" pref="settings.clock.use_24hour_clock"
              type="checkbox">

</if>

        <button id="privacyContentSettingsButton"
            i18n-content="privacyContentSettingsButton"></button>
        <button id="privacyClearDataButton"
            i18n-content="privacyClearDataButton"></button>

          <input id="alternateErrorPagesEnabled"
              pref="alternate_error_pages.enabled"
              metric="Options_LinkDoctorCheckbox" type="checkbox">

          <input id="searchSuggestEnabled" pref="search.suggest_enabled"
              metric="Options_UseSuggestCheckbox" type="checkbox">

          <input id="dnsPrefetchingEnabled" pref="dns_prefetching.enabled"
              metric="Options_DnsPrefetchCheckbox" type="checkbox">

          <input id="safeBrowsingEnabled" pref="safebrowsing.enabled"
              metric="Options_SafeBrowsingCheckbox" type="checkbox">

<if expr="pp_ifdef('_google_chrome') and pp_ifdef('chromeos')">

          <input id="metricsReportingEnabled"
              pref="cros.metrics.reportingEnabled" type="checkbox">

</if>
<if expr="pp_ifdef('_google_chrome') and not pp_ifdef('chromeos')">

          <input id="metricsReportingEnabled" type="checkbox">

</if>

<if expr="pp_ifdef('chromeos')">

          <input type="checkbox" id="enable-bluetooth">

        <list id="bluetooth-paired-devices-list"></list>

        <button id="bluetooth-add-device"
            i18n-content="addBluetoothDevice" hidden></button>
        <button id="bluetooth-reconnect-device"
            i18n-content="bluetoothConnectDevice" disabled hidden></button>

</if>

      <input id="autofill-enabled" pref="autofill.enabled"
          metric="Options_FormAutofill" type="checkbox">

      <button id="autofill-settings" class="link-button"
          pref="autofill.enabled"
          i18n-content="manageAutofillSettings"></button>

      <input id="password-manager-enabled"
          pref="profile.password_manager_enabled"
          metric="Options_PasswordManager" type="checkbox">

      <button id="manage-passwords" class="link-button"
          i18n-content="managePasswords"
          pref="profile.password_manager_enabled"></button>

    <input name="password_allow_show_hidden" type="text"
        pref="profile.password_manager_allow_show_passwords" hidden>

          <select id="defaultFontSize">
            <option value="9" i18n-content="fontSizeLabelVerySmall">
            </option>
            <option value="12" i18n-content="fontSizeLabelSmall"></option>
            <option value="16" i18n-content="fontSizeLabelMedium"></option>
            <option value="20" i18n-content="fontSizeLabelLarge"></option>
            <option value="24" i18n-content="fontSizeLabelVeryLarge">
            </option>
          </select>

        <button id="fontSettingsCustomizeFontsButton"
            i18n-content="fontSettingsCustomizeFontsButton"></button>

          <select id="defaultZoomFactor" dataType="double"></select>

<if expr="not pp_ifdef('chromeos') or os == 'win32'">

</if>
<if expr="not pp_ifdef('chromeos') or os == 'win32'">

</if>
<if expr="os == 'darwin'">

          <input id="tabsToLinksPref" pref="webkit.webprefs.tabs_to_links"
              metric="Options_TabsToLinks" type="checkbox">

</if>

<if expr="not pp_ifdef('chromeos')">

        <button id="proxiesConfigureButton"
            i18n-content="proxiesConfigureButton"></button>

</if>

    <button id="language-button"
        i18n-content="languageAndSpellCheckSettingsButton"></button>

        <input id="enableTranslate" pref="translate.enabled"
            metric="Options_Translate" type="checkbox">

<if expr="not pp_ifdef('chromeos')">

          <input id="downloadLocationPath" class="weakrtl" type="text"
              pref="download.default_directory" size="36">

        <button id="downloadLocationChangeButton"
            pref="download.prompt_for_download"
            i18n-content="downloadLocationChangeButton"></button>

          <input type="checkbox"
              pref="download.prompt_for_download"
              metric="Options_AskForSaveLocation">

        <button id="autoOpenFileTypesResetToDefault"
            i18n-content="autoOpenFileTypesResetToDefault"></button>

</if>

          <button id="certificatesManageButton"
              i18n-content="certificatesManageButton"></button>

            <input id="sslCheckRevocation" type="checkbox">

<if expr="not pp_ifdef('chromeos')">

          <button id="cloudPrintConnectorSetupButton"
                  i18n-content="cloudPrintConnectorDisabledButton"></button>
          <button id="cloudPrintManageButton"
                  i18n-content="cloudPrintConnectorEnabledManageButton"></button>

</if>
<if expr="pp_ifdef('chromeos')">

        <button id="cloudPrintManageButton"
                i18n-content="cloudPrintChromeosOptionButton"></button>

            <input id="accessibility-spoken-feedback-check" type="checkbox">

            <input id="accessibility-high-contrast-check" type="checkbox">

            <input id="accessibility-screen-magnifier-check" type="checkbox">

            <input id="accessibility-virtual-keyboard-check" type="checkbox">

</if>
<if expr="os != 'darwin' and not pp_ifdef('chromeos')">

        <input id="backgroundModeCheckbox" type="checkbox">

</if>