text:
<!---
Copyright 2017 The AMP HTML Authors. All Rights Reserved.

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.
-->

# A8net

Serves ads from [a8.net](https://www.a8.net/).

## Example

### Normal ad

```html
<amp-ad
  width="300"
  height="250"
  type="a8"
  data-aid="170223075073"
  data-wid="001"
  data-eno="01"
  data-mid="s00000016751001031000"
  data-mat="2TCGYR-17GNXU-3L92-64Z8X"
  data-type="static"
>
</amp-ad>
```

## Configuration

For configuration details and to generate your tags, please contact https://support.a8.net/as/contact/form/conentry.php.

### Required parameters

-   `data-aid`

### Optional parameters

-   `data-wid`
-   `data-eno`
-   `data-mid`
-   `data-mat`
-   `data-type`


text:
title: Basic Commands
---
## Basic Commands

Here you will find a list of basic commands to start developing iOS and Android apps using React Native. If you don't have it installed yet, is highly recommended that you follow the [official guide](https://facebook.github.io/react-native/docs/getting-started.html).

### Starting a new project

There are different ways you can bootstrap a react native application. You can use **Expo** or `create-react-native-app`(which in turns uses Expo-Cli) to start your new project, but with this method you are in more control of what happend in your project and can communicate, tweak and write your own modules with native libraries for iOS and Android mobile platform.
```
react-native init [PROJECT-NAME]
cd [PROJECT-NAME]
```

**Run app in Android emulator**

This command is self explanatory and as it says it will start the Android emulator and install the app you just created. You need to be in the root of the project to run this command.
```
react-native run-android
```

**Run app in iOS emulator**

This command do exactly the same as `react-native run-android` but instead of the Android emulator, it opens the iPhone simulator.
```
react-native run-ios
```

**Link dependencies to native projects**

Some libraries have dependencies that need to be linked in the native code generated for React Native. If something doesn't work after you installed a new library, maybe is because you skip this step.
```
react-native link [LIBRARY-NAME]
```

**Clear bundle**

If something don't run as expected, maybe you need to clear and create a new bundle with this command.
```
watchman watch-del-all
```

**Support decorators**

JSX doesn't support decorators by default so you need to install the **Babel** plugin to make it work.
```
npm install babel-plugin-transform-decorators-legacy --save
npm install babel-plugin-transform-class-properties --save
```

### Export APK to run in device
With the following commands you will have and unsigned apk so you can install and share with your colleagues for testing purposes. Just remember that this apk is not ready to upload to the App Store or production.
You will find your fresh apk in *android/app/build/outputs/apk/app-debug.apk*

**1. Bundle debug build**
```
react-native bundle --dev false --platform android --entry-file index.android.js --bundle-output ./android/app/build/intermediates/assets/debug/index.android.bundle --assets-dest ./android/app/build/intermediates/res/merged/debug
```

**2. Create debug build**
```
cd android
./gradlew assembleDebug
```

redpajama_set_name: RedPajamaGithub


text:
"""WebKit Win implementation of the Port interface."""

import logging

from webkitpy.layout_tests.port.webkit import WebKitPort

_log = logging.getLogger("webkitpy.layout_tests.port.win")

class WinPort(WebKitPort):
    """WebKit Win implementation of the Port class."""

    def __init__(self, port_name=None, **kwargs):
        port_name = port_name or 'win'
        WebKitPort.__init__(self, port_name=port_name, **kwargs)
        self._version = 'win7'
        self._operating_system = 'win'

    def baseline_search_path(self):
        # Based on code from old-run-webkit-tests expectedDirectoryForTest()
        port_names = ["win", "mac-snowleopard", "mac"]
        return map(self._webkit_baseline_path, port_names)

    def _tests_for_other_platforms(self):
        # FIXME: This list could be dynamic based on platform name and
        # pushed into base.Port.
        # This really need to be automated.
        return [
            "platform/chromium",
            "platform/gtk",
            "platform/qt",
            "platform/mac",
        ]

    def _path_to_apache_config_file(self):
        return self._filesystem.join(self.layout_tests_dir(), 'http', 'conf',
                                     'cygwin-httpd.conf')

    def _shut_down_http_server(self, server_pid):
        """Shut down the httpd web server. Blocks until it's fully
        shut down.

        Args:
            server_pid: The process ID of the running server.
        """
        # Looks like we ignore server_pid.
        # Copy/pasted from chromium-win.
        self._executive.kill_all("httpd.exe")


text:
from __future__ import absolute_import

import os
import shutil
from collections import OrderedDict, defaultdict

from pex import hashing, resolver
from pex.auth import PasswordDatabase
from pex.common import pluralize, safe_mkdtemp
from pex.dist_metadata import DistMetadata, ProjectNameAndVersion
from pex.fetcher import URLFetcher
from pex.orderedset import OrderedSet
from pex.pep_503 import ProjectName
from pex.pip.download_observer import DownloadObserver
from pex.pip.tool import PackageIndexConfiguration
from pex.resolve import lock_resolver, locker, resolvers
from pex.resolve.configured_resolver import ConfiguredResolver
from pex.resolve.downloads import ArtifactDownloader
from pex.resolve.locked_resolve import (
    Artifact,
    FileArtifact,
    LocalProjectArtifact,
    LockConfiguration,
    LockedResolve,
    LockStyle,
    VCSArtifact,
)
from pex.resolve.locker import Locker
from pex.resolve.lockfile.download_manager import DownloadManager
from pex.resolve.lockfile.model import Lockfile
from pex.resolve.pep_691.fingerprint_service import FingerprintService
from pex.resolve.requirement_configuration import RequirementConfiguration
from pex.resolve.resolved_requirement import Pin, ResolvedRequirement
from pex.resolve.resolver_configuration import PipConfiguration
from pex.resolve.resolvers import Resolver
from pex.resolver import BuildRequest, Downloaded, ResolveObserver, WheelBuilder
from pex.result import Error, try_
from pex.targets import Target, Targets
from pex.tracer import TRACER
from pex.typing import TYPE_CHECKING
from pex.version import __version__

if TYPE_CHECKING:
    from typing import DefaultDict, Dict, Iterable, Mapping, Optional, Tuple, Union

    import attr  # vendor:skip

    from pex.hashing import HintedDigest
    from pex.requirements import ParsedRequirement
else:
    from pex.third_party import attr

class CreateLockDownloadManager(DownloadManager[Artifact]):
    @classmethod
    def create(
        cls,
        download_dir,  # type: str
        locked_resolves,  # type: Iterable[LockedResolve]
        pex_root=None,  # type: Optional[str]
    ):
        # type: (...) -> CreateLockDownloadManager

        file_artifacts_by_filename = {}  # type: Dict[str, FileArtifact]
        source_artifacts_by_pin = {}  # type: Dict[Pin, Union[LocalProjectArtifact, VCSArtifact]]
        for locked_resolve in locked_resolves:
            for locked_requirement in locked_resolve.locked_requirements:
                for artifact in locked_requirement.iter_artifacts():
                    if isinstance(artifact, FileArtifact):
                        file_artifacts_by_filename[artifact.filename] = artifact
                    else:
                        # N.B.: We know there is only ever one local project artifact for a given
                        # locked local project requirement and likewise only one VCS artifact for a
                        # given locked VCS requirement.
                        source_artifacts_by_pin[locked_requirement.pin] = artifact

        path_by_artifact_and_project_name = {}  # type: Dict[Tuple[Artifact, ProjectName], str]
        for root, _, files in os.walk(download_dir):
            for f in files:
                pin = Pin.canonicalize(ProjectNameAndVersion.from_filename(f))
                artifact = file_artifacts_by_filename.get(f) or source_artifacts_by_pin[pin]
                path_by_artifact_and_project_name[(artifact, pin.project_name)] = os.path.join(
                    root, f
                )

        return cls(
            path_by_artifact_and_project_name=path_by_artifact_and_project_name, pex_root=pex_root
        )

    def __init__(
        self,
        path_by_artifact_and_project_name,  # type: Mapping[Tuple[Artifact, ProjectName], str]
        pex_root=None,  # type: Optional[str]
    ):
        # type: (...) -> None
        super(CreateLockDownloadManager, self).__init__(pex_root=pex_root)
        self._path_by_artifact_and_project_name = path_by_artifact_and_project_name

    def store_all(self):
        # type: () -> None
        for artifact, project_name in self._path_by_artifact_and_project_name:
            self.store(artifact, project_name)

    def save(
        self,
        artifact,  # type: Artifact
        project_name,  # type: ProjectName
        dest_dir,  # type: str
        digest,  # type: HintedDigest
    ):
        # type: (...) -> Union[str, Error]
        src = self._path_by_artifact_and_project_name[(artifact, project_name)]
        filename = os.path.basename(src)
        dest = os.path.join(dest_dir, filename)
        shutil.move(src, dest)

        hashing.file_hash(dest, digest=digest)
        return filename

@attr.s(frozen=True)
class _LockAnalysis(object):
    target = attr.ib()  # type: Target
    analyzer = attr.ib()  # type: Locker
    download_dir = attr.ib()  # type: str

@attr.s(frozen=True)
class LockObserver(ResolveObserver):
    root_requirements = attr.ib()  # type: Tuple[ParsedRequirement, ...]
    lock_configuration = attr.ib()  # type: LockConfiguration
    resolver = attr.ib()  # type: Resolver
    wheel_builder = attr.ib()  # type: WheelBuilder
    package_index_configuration = attr.ib()  # type: PackageIndexConfiguration
    max_parallel_jobs = attr.ib(default=None)  # type: Optional[int]
    _analysis = attr.ib(factory=OrderedSet, eq=False)  # type: OrderedSet[_LockAnalysis]

    def observe_download(
        self,
        target,  # type: Target
        download_dir,  # type: str
    ):
        # type: (...) -> DownloadObserver
        patch = locker.patch(
            root_requirements=self.root_requirements,
            pip_version=self.package_index_configuration.pip_version,
            resolver=self.resolver,
            lock_configuration=self.lock_configuration,
            download_dir=download_dir,
            fingerprint_service=FingerprintService.create(
                url_fetcher=URLFetcher(
                    network_configuration=self.package_index_configuration.network_configuration,
                    password_entries=self.package_index_configuration.password_entries,
                ),
                max_parallel_jobs=self.max_parallel_jobs,
            ),
        )
        self._analysis.add(
            _LockAnalysis(target=target, analyzer=patch.analyzer, download_dir=download_dir)
        )
        return patch

    def lock(self, downloaded):
        # type: (Downloaded) -> Tuple[LockedResolve, ...]

        dist_metadatas_by_target = defaultdict(
            OrderedSet
        )  # type: DefaultDict[Target, OrderedSet[DistMetadata]]
        build_requests = OrderedSet()  # type: OrderedSet[BuildRequest]

        for local_distribution in downloaded.local_distributions:
            if local_distribution.is_wheel:
                dist_metadatas_by_target[local_distribution.target].add(
                    DistMetadata.load(local_distribution.path)
                )
            else:
                build_requests.add(
                    BuildRequest.create(
                        target=local_distribution.target, source_path=local_distribution.path
                    )
                )

        resolved_requirements_by_target = (
            OrderedDict()
        )  # type: OrderedDict[Target, Tuple[ResolvedRequirement, ...]]
        for analysis in self._analysis:
            lock_result = analysis.analyzer.lock_result
            build_requests.update(
                BuildRequest.create(target=analysis.target, source_path=local_project)
                for local_project in lock_result.local_projects
            )
            resolved_requirements_by_target[analysis.target] = lock_result.resolved_requirements

        with TRACER.timed(
            "Building {count} source {distributions} to gather metadata for lock.".format(
                count=len(build_requests), distributions=pluralize(build_requests, "distribution")
            )
        ):
            build_results = self.wheel_builder.build_wheels(
                build_requests=build_requests,
                max_parallel_jobs=self.max_parallel_jobs,
            )
            for install_requests in build_results.values():
                for install_request in install_requests:
                    dist_metadatas_by_target[install_request.target].add(
                        DistMetadata.load(install_request.wheel_path)
                    )

        return tuple(
            LockedResolve.create(
                resolved_requirements=resolved_requirements,
                dist_metadatas=dist_metadatas_by_target[target],
                fingerprinter=ArtifactDownloader(
                    resolver=self.resolver,
                    target=target,
                    package_index_configuration=self.package_index_configuration,
                    max_parallel_jobs=self.max_parallel_jobs,
                ),
                platform_tag=None
                if self.lock_configuration.style == LockStyle.UNIVERSAL
                else target.platform.tag,
            )
            for target, resolved_requirements in resolved_requirements_by_target.items()
        )

def create(
    lock_configuration,  # type: LockConfiguration
    requirement_configuration,  # type: RequirementConfiguration
    targets,  # type: Targets
    pip_configuration,  # type: PipConfiguration
):
    # type: (...) -> Union[Lockfile, Error]
    """Create a lock file for the given resolve configurations."""

    network_configuration = pip_configuration.network_configuration
    parsed_requirements = tuple(requirement_configuration.parse_requirements(network_configuration))
    constraints = tuple(
        parsed_constraint.requirement
        for parsed_constraint in requirement_configuration.parse_constraints(network_configuration)
    )

    package_index_configuration = PackageIndexConfiguration.create(
        pip_version=pip_configuration.version,
        resolver_version=pip_configuration.resolver_version,
        network_configuration=network_configuration,
        find_links=pip_configuration.repos_configuration.find_links,
        indexes=pip_configuration.repos_configuration.indexes,
        password_entries=PasswordDatabase.from_netrc()
        .append(pip_configuration.repos_configuration.password_entries)
        .entries,
    )

    configured_resolver = ConfiguredResolver(pip_configuration=pip_configuration)
    lock_observer = LockObserver(
        root_requirements=parsed_requirements,
        lock_configuration=lock_configuration,
        resolver=configured_resolver,
        wheel_builder=WheelBuilder(
            package_index_configuration=package_index_configuration,
            prefer_older_binary=pip_configuration.prefer_older_binary,
            use_pep517=pip_configuration.use_pep517,
            build_isolation=pip_configuration.build_isolation,
            pip_version=pip_configuration.version,
            resolver=configured_resolver,
        ),
        package_index_configuration=package_index_configuration,
        max_parallel_jobs=pip_configuration.max_jobs,
    )

    download_dir = safe_mkdtemp()

    if lock_configuration.style is LockStyle.UNIVERSAL:
        download_targets = (
            Targets(interpreters=(targets.interpreter,)) if targets.interpreter else Targets()
        )
    else:
        download_targets = targets

    try:
        downloaded = resolver.download(
            targets=download_targets,
            requirements=requirement_configuration.requirements,
            requirement_files=requirement_configuration.requirement_files,
            constraint_files=requirement_configuration.constraint_files,
            allow_prereleases=pip_configuration.allow_prereleases,
            transitive=pip_configuration.transitive,
            indexes=pip_configuration.repos_configuration.indexes,
            find_links=pip_configuration.repos_configuration.find_links,
            resolver_version=pip_configuration.resolver_version,
            network_configuration=network_configuration,
            password_entries=pip_configuration.repos_configuration.password_entries,
            build=pip_configuration.allow_builds,
            use_wheel=pip_configuration.allow_wheels,
            prefer_older_binary=pip_configuration.prefer_older_binary,
            use_pep517=pip_configuration.use_pep517,
            build_isolation=pip_configuration.build_isolation,
            max_parallel_jobs=pip_configuration.max_jobs,
            observer=lock_observer,
            dest=download_dir,
            preserve_log=pip_configuration.preserve_log,
            pip_version=pip_configuration.version,
            resolver=configured_resolver,
        )
    except resolvers.ResolveError as e:
        return Error(str(e))

    with TRACER.timed("Creating lock from resolve"):
        locked_resolves = lock_observer.lock(downloaded)

    with TRACER.timed("Indexing downloads"):
        create_lock_download_manager = CreateLockDownloadManager.create(
            download_dir=download_dir, locked_resolves=locked_resolves
        )
        create_lock_download_manager.store_all()

    lock = Lockfile.create(
        pex_version=__version__,
        style=lock_configuration.style,
        requires_python=lock_configuration.requires_python,
        target_systems=lock_configuration.target_systems,
        pip_version=pip_configuration.version,
        resolver_version=pip_configuration.resolver_version,
        requirements=parsed_requirements,
        constraints=constraints,
        allow_prereleases=pip_configuration.allow_prereleases,
        allow_wheels=pip_configuration.allow_wheels,
        allow_builds=pip_configuration.allow_builds,
        prefer_older_binary=pip_configuration.prefer_older_binary,
        use_pep517=pip_configuration.use_pep517,
        build_isolation=pip_configuration.build_isolation,
        transitive=pip_configuration.transitive,
        locked_resolves=locked_resolves,
    )

    if lock_configuration.style is LockStyle.UNIVERSAL and (
        targets.platforms or targets.complete_platforms
    ):
        check_targets = Targets(
            platforms=targets.platforms,
            complete_platforms=targets.complete_platforms,
            assume_manylinux=targets.assume_manylinux,
        )
        with TRACER.timed(
            "Checking lock can resolve for platforms: {targets}".format(targets=check_targets)
        ):
            try_(
                lock_resolver.resolve_from_lock(
                    targets=check_targets,
                    lock=lock,
                    resolver=configured_resolver,
                    indexes=pip_configuration.repos_configuration.indexes,
                    find_links=pip_configuration.repos_configuration.find_links,
                    resolver_version=pip_configuration.resolver_version,
                    network_configuration=network_configuration,
                    password_entries=pip_configuration.repos_configuration.password_entries,
                    build=pip_configuration.allow_builds,
                    use_wheel=pip_configuration.allow_wheels,
                    prefer_older_binary=pip_configuration.prefer_older_binary,
                    use_pep517=pip_configuration.use_pep517,
                    build_isolation=pip_configuration.build_isolation,
                    transitive=pip_configuration.transitive,
                    max_parallel_jobs=pip_configuration.max_jobs,
                    pip_version=pip_configuration.version,
                )
            )

    return lock


text:
SYNONYM

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

#### Published in
Meded. Bot. Mus. Herb. Rijks Univ. Utrecht 9: 122 (1933)

#### Original name
Boletus giganteus Schumach., 1803

### Remarks
null


text:
namespace Ui {
class PetriDesign;
}

class PetriDesign : public QWidget
{
    Q_OBJECT

public:
    explicit PetriDesign(QWidget *parent = 0);
    ~PetriDesign();

    bool isLocked();
    void setLocked(bool l);

    void close();
    void load(spnp::IData *data);

signals:
    void itemSelected(QGraphicsItem* item);

private slots:
    void on_bt_normal_clicked();

    void on_bt_place_clicked();

    void on_bt_fplace_clicked();

    void on_bt_ttrans_clicked();

    void on_bt_itrans_clicked();

    void on_bt_remove_clicked();

    void on_bt_arc_clicked();

    void on_bt_iarc_clicked();

    void on_bt_farc_clicked();

private slots:
    void afterClickAction();
    void afterSelectionAction(QGraphicsItem *item);

private:
    Ui::PetriDesign *ui;

    QButtonGroup *bGroup;

    void addButtonsToGroup();
};

#endif // PETRIDESIGN_H


text:
using RS.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RS.Reporting.Web.Controllers
{
    public class BaseController: Controller
    {
        private ConnectionData connectionData = new ConnectionData(Configuration.App.ConnectionString);

        private BL.Manager manager = null;
        public BL.Manager Manager { get { return manager ?? (manager = new BL.Manager(connectionData)); } }
    }
}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

Thank you for registering your new account!

You have successfully register. You may now login.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.IO;

namespace Trinity.Core.Lib
{
    /// <summary>
    /// A Helper class for manipulating blob related data structures.
    /// </summary>
    public unsafe partial class BitHelper
    {
        /// <summary>
        /// Returns the specified string as an array of bytes.
        /// </summary>
        /// <param name="value">The string to convert.</param>
        /// <returns>An array of bytes.</returns>
        public static byte[] GetBytes(string value)
        {
            int length = value.Length;
            byte[] buffer = new byte[length << 1];
            fixed (byte* bp = buffer)
            {
                byte* ptr = bp;
                for (int k = 0; k < length; k++)
                {
                    *((char*)(ptr)) = value[k];
                    ptr += 2;
                }
            }
            return buffer;
        }

        internal static byte[] GetAsciiCharArray(string value)
        {
            int length = value.Length;
            byte[] buffer = new byte[length];
            fixed (byte* bp = buffer)
            {
                byte* ptr = bp;
                for (int k = 0; k < length; k++)
                {
                    *ptr = (byte)value[k];
                    ptr++;
                }
            }
            return buffer;
        }

        /// <summary>
        /// Returns the specified string as an array of bytes with a header containing the string buffer length.
        /// </summary>
        /// <param name="value">The string to convert.</param>
        /// <returns>An array of bytes.</returns>
        public static byte[] GetBytesWithHeader(string value)
        {
            int length = value.Length;
            byte[] buffer = new byte[sizeof(int) + (length << 1)];
            fixed (byte* bp = buffer)
            {
                *(int*)bp = (length << 1);
                byte* ptr = bp + sizeof(int);
                for (int k = 0; k < length; k++)
                {
                    *((char*)(ptr)) = value[k];
                    ptr += 2;
                }
            }
            return buffer;
        }

        /// <summary>
        /// Write the specified value to the specified buffer starting from the given offset.
        /// </summary>
        /// <param name="value">The string value to write.</param>
        /// <param name="buffer">The buffer to write the string value in.</param>
        /// <param name="offset">The offset of the buffer to write; the offset is added (value.Length*2) after the writing.</param>
        public static void WriteString(string value, byte[] buffer, ref int offset)
        {
            int length = value.Length;
            fixed (byte* numRef = &(buffer[offset]))
            {
                byte* ptr = numRef;
                for (int k = 0; k < length; k++)
                {
                    *((short*)(ptr)) = (short)value[k];
                    ptr += 2;
                }
            }
            offset += (length << 1);
        }

        /// <summary>
        /// Write the specified value to the specified buffer.
        /// </summary>
        /// <param name="value">The string value to write.</param>
        /// <param name="buffer">The buffer to write the string value in.</param>
        public static void WriteString(string value, byte* buffer)
        {
            int length = value.Length;

            for (int k = 0; k < length; k++)
            {
                *((short*)(buffer)) = (short)value[k];
                buffer += 2;
            }
        }

        /// <summary>
        /// Gets the corresponding string from the specified buffer.
        /// </summary>
        /// <param name="buffer">The string buffer.</param>
        /// <returns>The corresponding string.</returns>
        public static string GetString(byte[] buffer)
        {
            int string_length = buffer.Length >> 1;
            char[] char_array = new char[string_length];
            fixed (byte* bp = buffer)
            {
                byte* ptr = bp;
                for (int k = 0; k < string_length; k++)
                {
                    char_array[k] = *((char*)(ptr));
                    ptr += 2;
                }
            }
            return new string(char_array);
        }

        /// <summary>
        /// Gets the corresponding string from the specified buffer starting from the given position.
        /// </summary>
        /// <param name="buffer">The string buffer.</param>
        /// <param name="startIndex">The zero-based byte offset into the buffer.</param>
        /// <param name="count">The number of bytes to convert.</param>
        /// <returns>The corresponding string.</returns>
        public static unsafe string GetString(byte[] buffer, int startIndex, int count)
        {
            fixed (byte* numRef = &(buffer[startIndex]))
            {
                return new string((char*)numRef, 0, count >> 1);
            }
        }

        /// <summary>
        ///  Gets the corresponding string from the specified buffer.
        /// </summary>
        /// <param name="buffer">The string buffer.</param>
        /// <param name="byteCount">The number of bytes to convert.</param>
        /// <returns>The corresponding string.</returns>
        public static unsafe string GetString(byte* buffer, int byteCount)
        {
            return new string((char*)buffer, 0, byteCount >> 1);
        }

        /// <summary>
        /// Gets the corresponding char array from the specified buffer starting from the given position.
        /// </summary>
        /// <param name="buffer">The string buffer.</param>
        /// <param name="startIndex">The zero-based byte offset into the buffer.</param>
        /// <param name="count">The number of bytes to convert.</param>
        /// <returns>The corresponding char array.</returns>
        public static unsafe char[] GetCharArray(byte[] buffer, int startIndex, int count)
        {
            int size = count >> 1;
            char[] array = new char[size];
            fixed (byte* numRef = &(buffer[startIndex]))
            {
                char* ptr = (char*)numRef;
                for (int k = 0; k < size; k++)
                {
                    array[k] = *ptr;
                    ptr++;
                }
            }
            return array;
        }

        /// <summary>
        /// Writes an IPEndPoint instance to the specified buffer.
        /// </summary>
        /// <param name="ipe">An IPEndPoint instance.</param>
        /// <param name="buffer">The buffer to write the ipe in.</param>
        public unsafe static void WriteIPEndPoint(IPEndPoint ipe, byte* buffer)
        {
            *(int*)buffer = BitHelper.ToInt32(ipe.Address.GetAddressBytes(), 0);
            *(int*)(buffer + 4) = ipe.Port;
        }

        /// <summary>
        /// Returns an IPAddress instance from eight bytes of the specified buffer.
        /// </summary>
        /// <param name="buffer">The buffer.</param>
        /// <param name="startIndex">A zero-based byte offset into the buffer.</param>
        /// <returns>An IPAddress instance.</returns>
        public static IPAddress ToIPAddress(byte* buffer, int startIndex)
        {
            Int64 m_address = (
                (
                ((buffer[startIndex + 3] << 0x18) | (buffer[startIndex + 2] << 0x10)) |
                (buffer[startIndex + 1] << 8)
                ) | buffer[startIndex]) & ((long)0xffffffffL);
            return new IPAddress(m_address);
        }

        /// <summary>
        /// Returns an IPEndPoint instance from eight bytes of the specified buffer.
        /// </summary>
        /// <param name="buffer">The buffer.</param>
        /// <returns>An IPEndPoint instance.</returns>
        public unsafe static IPEndPoint ToIPEndPoint(byte* buffer)
        {
            Int64 m_address = ((((*(buffer + 3) << 0x18) | (*(buffer + 2) << 0x10)) | (*(buffer + 1) << 8)) | *buffer) & ((long)0xffffffffL);
            return new IPEndPoint(m_address, *((int*)(buffer + 4)));
        }

        /// <summary>
        /// Returns a 32-bit signed integer converted from four bytes at a specified position in a byte array.
        /// </summary>
        /// <param name="buffer">An array of bytes</param>
        /// <param name="startIndex">The starting position within the byte array.</param>
        /// <returns>A 32-bit signed integer formed by four bytes beginning at startIndex.</returns>
        public static unsafe Int32 ToInt32(byte[] buffer, int startIndex)
        {
            fixed (byte* p = &(buffer[startIndex]))
            {
                return *(((int*)p));
            }
        }

        /// <summary>
        /// Returns a Boolean value converted from one byte at a specified position in a byte array.
        /// </summary>
        /// <param name="buffer">An array of bytes.</param>
        /// <param name="startIndex">The starting position within the byte of array.</param>
        /// <returns>true if the byte at startIndex in the byte array is nonzero; otherwise, false.</returns>
        public static unsafe bool ToBoolean(byte[] buffer, int startIndex)
        {
            return (buffer[startIndex] != 0);
        }

        /// <summary>
        /// Returns a 16-bit unsigned integer converted from two bytes at a specified position in a byte array.
        /// </summary>
        /// <param name="buffer">The array of bytes.</param>
        /// <param name="startIndex">The starting position within the byte array.</param>
        /// <returns>A 16-bit unsigned integer formed by two bytes beginning at startIndex.</returns>
        public static unsafe ushort ToUInt16(byte[] buffer, int startIndex)
        {
            fixed (byte* p = &(buffer[startIndex]))
            {
                return *(((ushort*)p));
            }
        }

        /// <summary>
        /// Returns a 16-bit signed integer converted from two bytes at a specified position in a byte array.
        /// </summary>
        /// <param name="buffer">The array of bytes.</param>
        /// <param name="startIndex">The starting position within the byte array.</param>
        /// <returns>A 16-bit signed integer formed by two bytes beginning at startIndex.</returns>
        public static unsafe short ToInt16(byte[] buffer, int startIndex)
        {
            fixed (byte* p = &(buffer[startIndex]))
            {
                return *(((short*)p));
            }
        }

        /// <summary>
        /// Returns a 64-bit signed integer converted from eight bytes at a specified position in a byte array.
        /// </summary>
        /// <param name="buffer">The array of bytes.</param>
        /// <param name="startIndex">The starting position within the byte array.</param>
        /// <returns>A 64-bit signed integer formed by eight bytes beginning at startIndex.</returns>
        public static unsafe Int64 ToInt64(byte[] buffer, int startIndex)
        {
            fixed (byte* p = &(buffer[startIndex]))
            {
                return *(((long*)p));
            }
        }

        /// <summary>
        /// Returns the specified decimal value as an array of bytes.
        /// </summary>
        /// <param name="value">The decimal number to convert.</param>
        /// <returns>An array of bytes with length 16.</returns>
        public static byte[] GetBytes(decimal value)
        {
            byte[] bytes = new byte[16];
            int[] int_array = Decimal.GetBits(value);
            for (int i = 0; i < 4; i++)
            {
                Memory.Copy(BitConverter.GetBytes(int_array[i]), 0, bytes, i << 2, 4);
            }
            return bytes;
        }

        /// <summary>
        /// Writes the specified decimal value to the specified buffer starting from the specified offset.
        /// </summary>
        /// <param name="value">The decimal value.</param>
        /// <param name="buffer">The memory buffer.</param>
        /// <param name="offset">The zero-based byte offset into the buffer; the offset is added 16 bytes after the writing.</param>
        public static void WriteDecimal(decimal value, byte[] buffer, ref int offset)
        {
            int[] int_array = Decimal.GetBits(value);
            for (int i = 0; i < 4; i++)
            {
                Memory.Copy(BitConverter.GetBytes(int_array[i]), 0, buffer, offset, 4);
                offset += 4;
            }
        }

        /// <summary>
        /// Returns a decimal value converted from 16 bytes at a specified position in a byte array.
        /// </summary>
        /// <param name="buffer">An array of bytes.</param>
        /// <param name="startIndex">The starting position within the buffer.</param>
        /// <returns>A decimal value.</returns>
        public static decimal GetDecimal(byte[] buffer, int startIndex)
        {
            int[] int_array = new int[4];
            for (int i = 0; i < 4; i++)
            {
                int_array[i] = BitHelper.ToInt32(buffer, startIndex + (i << 2));
            }
            return new decimal(int_array);
        }

        internal static uint CountOneBits(uint* array, int size)
        {
            int i, j, lim;
            uint s8, x;

            uint oneBitCount = 0;
            for (i = 0; i < size; i = i + 31)
            {
                lim = Math.Min(size, i + 31);
                s8 = 0;
                for (j = i; j < lim; j++)
                {
                    x = array[j];
                    x = x - ((x >> 1) & 0x55555555);
                    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
                    x = (x + (x >> 4)) & 0x0F0F0F0F;
                    s8 = s8 + x;
                }
                x = (s8 & 0x00FF00FF) + ((s8 >> 8) & 0x00FF00FF);
                x = (x & 0x0000ffff) + (x >> 16);
                oneBitCount = oneBitCount + x;
            }
            return oneBitCount;
        }

        /// <summary>
        /// Returns the Hamming distance of the two specified ulong array buffer.
        /// </summary>
        /// <param name="arrayA">The first ulong array buffer.</param>
        /// <param name="arrayB">The second ulong array buffer.</param>
        /// <param name="size">The number of ulong elements to compare.</param>
        /// <returns>The hamming distance between the two ulong array.</returns>
        public static uint HammingDistance(ulong* arrayA, ulong* arrayB, int size)
        {
            ulong[] buffer = new ulong[size];
            fixed (ulong* lp = buffer)
            {
                for (int i = 0; i < size; i++)
                {
                    lp[i] = arrayA[i] ^ arrayB[i];
                }
                uint* ip = (uint*)lp;
                return CountOneBits(ip, size << 1);
            }
        }
    }
}


text:
[中文文档](./README_ZH.md)

This sample is about using long polling and WebSocket to build a web-based chat room based on beego.

- [Documentation](http://beego.me/docs/examples/chat.md)


text:
<?php

namespace NEkman\ModelLogger;

use NEkman\ModelLogger\Contract\Logable;
use NEkman\ModelLogger\Exception\NoOldModelException;
use Illuminate\Database\Eloquent\Model as Eloquent;

/**
 * Package logic. Only used within the package
 *
 * @author Niklas Ekman <niklas.ekman@codr.se>
 */
class ModelLogger {

	const ACTION_DELETE = 'delete';
	const ACTION_UPDATE = 'update';
	const ACTION_INSERT = 'insert';

	/**
	 * For updating, get the old model
	 * @param \Eloquent $model
	 * @return type
	 * @throws \InvalidArgumentException
	 */
	public static function getOldModel(Eloquent $model) {
		$class = get_class($model);

		$oldModel = $class::find($model->id);
		if (empty($oldModel)) :
			throw new NoOldModelException("Could not find model with class {$class} and id {$model->id}");
		endif;

		return $oldModel;
	}

	/**
	 * Get the data needed to save an update post
	 * @param \Log\Logable $model
	 * @param \Log\Logable $oldModel
	 * @return array Array of datas
	 */
	public static function getDatas(Logable $model, Logable $oldModel) {
		$diff = self::getLogDifference($model, $oldModel);

		$datas = array();
		foreach ($diff as $key) :
			$datas[] = array(
			    'key' => $key,
			    'new' => $model->{$key},
			    'old' => $oldModel->{$key},
			);
		endforeach;

		return $datas;
	}

	/**
	 * Determine the difference between this model and another
	 * @param self $model
	 * @return array Keys that are different
	 */
	public static function getLogDifference(Eloquent $model, Eloquent $oldModel) {
		$attributes = $model->attributesToArray();
		$modelAttributes = $oldModel->attributesToArray();

		$diff = array();

		// Determine what values are not the same
		foreach ($attributes as $key => $value) :
			$other = $modelAttributes[$key];

			if ($value !== $other) :
				$diff[] = $key;
			endif;
		endforeach;

		return $diff;
	}

}


text:
package org.apache.commons.digester3.annotations.addressbook;

import org.apache.commons.digester3.annotations.rules.BeanPropertySetter;
import org.apache.commons.digester3.annotations.rules.ObjectCreate;

/**
 * @since 2.1
 */
@ObjectCreate( pattern = "address-book/person/address" )
public class Address
{

    @BeanPropertySetter( pattern = "address-book/person/address/type" )
    private String type;

    @BeanPropertySetter( pattern = "address-book/person/address/street" )
    private String street;

    @BeanPropertySetter( pattern = "address-book/person/address/city" )
    private String city;

    @BeanPropertySetter( pattern = "address-book/person/address/state" )
    private String state;

    @BeanPropertySetter( pattern = "address-book/person/address/zip" )
    private String zip;

    @BeanPropertySetter( pattern = "address-book/person/address/country" )
    private String country;

    public String getType()
    {
        return type;
    }

    public void setType( String type )
    {
        this.type = type;
    }

    public String getStreet()
    {
        return street;
    }

    public void setStreet( String street )
    {
        this.street = street;
    }

    public String getCity()
    {
        return city;
    }

    public void setCity( String city )
    {
        this.city = city;
    }

    public String getState()
    {
        return state;
    }

    public void setState( String state )
    {
        this.state = state;
    }

    public String getZip()
    {
        return zip;
    }

    public void setZip( String zip )
    {
        this.zip = zip;
    }

    public String getCountry()
    {
        return country;
    }

    public void setCountry( String country )
    {
        this.country = country;
    }

    @Override
    public boolean equals( Object obj )
    {
        if ( this == obj )
            return true;
        if ( obj == null )
            return false;
        if ( getClass() != obj.getClass() )
            return false;
        Address other = (Address) obj;
        if ( city == null )
        {
            if ( other.city != null )
                return false;
        }
        else if ( !city.equals( other.city ) )
            return false;
        if ( country == null )
        {
            if ( other.country != null )
                return false;
        }
        else if ( !country.equals( other.country ) )
            return false;
        if ( state == null )
        {
            if ( other.state != null )
                return false;
        }
        else if ( !state.equals( other.state ) )
            return false;
        if ( street == null )
        {
            if ( other.street != null )
                return false;
        }
        else if ( !street.equals( other.street ) )
            return false;
        if ( type == null )
        {
            if ( other.type != null )
                return false;
        }
        else if ( !type.equals( other.type ) )
            return false;
        if ( zip == null )
        {
            if ( other.zip != null )
                return false;
        }
        else if ( !zip.equals( other.zip ) )
            return false;
        return true;
    }

    @Override
    public String toString()
    {
        return "Address [city=" + city + ", country=" + country + ", state=" + state + ", street=" + street + ", type="
            + type + ", zip=" + zip + "]";
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <property name="LOG_PATTERN"
              value="%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%thread] %class:%line - %msg%n"/>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${LOG_PATTERN}</pattern>
        </encoder>
    </appender>
    <root level="DEBUG">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>


text:
"""
Pooled PostgreSQL database backend for Django.

Requires psycopg 2: http://initd.org/projects/psycopg2
"""
from django import get_version as get_django_version
from django.db.backends.postgresql_psycopg2.base import \
    DatabaseWrapper as OriginalDatabaseWrapper
from django.db.backends.signals import connection_created
from threading import Lock
import logging
import sys

try:
    import psycopg2 as Database
    import psycopg2.extensions
except ImportError, e:
    from django.core.exceptions import ImproperlyConfigured
    raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)

logger = logging.getLogger(__name__)

class PooledConnection():
    '''
    Thin wrapper around a psycopg2 connection to handle connection pooling.
    '''
    def __init__(self, pool, test_query=None):
        self._pool = pool

        # If passed a test query we'll run it to ensure the connection is available
        if test_query:
            self._wrapped_connection = None
            num_attempts = 0
            while self._wrapped_connection is None:
                num_attempts += 1;
                c = pool.getconn()
                try:
                    c.cursor().execute(test_query)
                except Database.Error:
                    pool.putconn(c, close=True)
                    if num_attempts > self._pool.maxconn:
                        logger.error("Unable to check out connection from pool %s" % self._pool)
                        raise;
                    else:
                        logger.info("Closing dead connection from pool %s" % self._pool,
                                    exc_info=sys.exc_info())
                else:
                    if not c.autocommit:
                        c.rollback()
                    self._wrapped_connection = c
        else:
            self._wrapped_connection = pool.getconn()

        logger.debug("Checked out connection %s from pool %s" % (self._wrapped_connection, self._pool))

    def close(self):
        '''
        Override to return the connection to the pool rather than closing it.
        '''
        if self._wrapped_connection and self._pool:
            logger.debug("Returning connection %s to pool %s" % (self._wrapped_connection, self._pool))
            self._pool.putconn(self._wrapped_connection)
            self._wrapped_connection = None

    def __getattr__(self, attr):
        '''
        All other calls proxy through to the "real" connection
        '''
        return getattr(self._wrapped_connection, attr)

'''
This holds our connection pool instances (for each alias in settings.DATABASES that
uses our PooledDatabaseWrapper.)
'''
connection_pools = {}
connection_pools_lock = Lock()

pool_config_defaults = {
    'MIN_CONNS': None,
    'MAX_CONNS': 1,
    'TEST_ON_BORROW': False,
    'TEST_ON_BORROW_QUERY': 'SELECT 1'
}

def _set_up_pool_config(self):
    '''
    Helper to configure pool options during DatabaseWrapper initialization.
    '''
    self._max_conns = self.settings_dict['OPTIONS'].get('MAX_CONNS', pool_config_defaults['MAX_CONNS'])
    self._min_conns = self.settings_dict['OPTIONS'].get('MIN_CONNS', self._max_conns)

    self._test_on_borrow = self.settings_dict["OPTIONS"].get('TEST_ON_BORROW',
                                                             pool_config_defaults['TEST_ON_BORROW'])
    if self._test_on_borrow:
        self._test_on_borrow_query = self.settings_dict["OPTIONS"].get('TEST_ON_BORROW_QUERY',
                                                                       pool_config_defaults['TEST_ON_BORROW_QUERY'])
    else:
        self._test_on_borrow_query = None

def _create_connection_pool(self, conn_params):
    '''
    Helper to initialize the connection pool.
    '''
    connection_pools_lock.acquire()
    try:
        # One more read to prevent a read/write race condition (We do this
        # here to avoid the overhead of locking each time we get a connection.)
        if (self.alias not in connection_pools or
            connection_pools[self.alias]['settings'] != self.settings_dict):
            logger.info("Creating connection pool for db alias %s" % self.alias)
            logger.info("  using MIN_CONNS = %s, MAX_CONNS = %s, TEST_ON_BORROW = %s" % (self._min_conns,
                                                                                self._max_conns,
                                                                                self._test_on_borrow))

            from psycopg2 import pool
            connection_pools[self.alias] = {
                'pool': pool.ThreadedConnectionPool(self._min_conns, self._max_conns, **conn_params),
                'settings': dict(self.settings_dict),
            }
    finally:
        connection_pools_lock.release()

'''
Simple Postgres pooled connection that uses psycopg2's built-in ThreadedConnectionPool
implementation.  In Django, use this by specifying MAX_CONNS and (optionally) MIN_CONNS
in the OPTIONS dictionary for the given db entry in settings.DATABASES.

MAX_CONNS should be equal to the maximum number of threads your app server is configured
for.  For example, if you are running Gunicorn or Apache/mod_wsgi (in a multiple *process*
configuration) MAX_CONNS should be set to 1, since you'll have a dedicated python
interpreter per process/worker.  If you're running Apache/mod_wsgi in a multiple *thread*
configuration set MAX_CONNS to the number of threads you have configured for each process.

By default MIN_CONNS will be set to MAX_CONNS, which prevents connections from being closed.
If your load is spikey and you want to recycle connections, set MIN_CONNS to something lower
than MAX_CONNS.   I suggest it should be no lower than your 95th percentile concurrency for
your app server.

If you wish to validate connections on each check out, specify TEST_ON_BORROW (set to True)
in the OPTIONS dictionary for the given db entry.  You can also provide an optional
TEST_ON_BORROW_QUERY, which is "SELECT 1" by default.
'''
class DatabaseWrapper16(OriginalDatabaseWrapper):
    '''
    For Django 1.6.x

    TODO: See https://github.com/django/django/commit/1893467784deb6cd8a493997e8bac933cc2e4af9
      but more importantly https://github.com/django/django/commit/2ee21d9f0d9eaed0494f3b9cd4b5bc9beffffae5

    This code may be no longer needed!
    '''
    set_up_pool_config = _set_up_pool_config
    create_connection_pool = _create_connection_pool

    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper16, self).__init__(*args, **kwargs)
        self.set_up_pool_config()

    def get_new_connection(self, conn_params):
        # Is this the initial use of the global connection_pools dictionary for
        # this python interpreter? Build a ThreadedConnectionPool instance and
        # add it to the dictionary if so.
        if self.alias not in connection_pools or connection_pools[self.alias]['settings'] != self.settings_dict:
            for extra in pool_config_defaults.keys():
                if extra in conn_params:
                    del conn_params[extra]

            self.create_connection_pool(conn_params)

        return PooledConnection(connection_pools[self.alias]['pool'], test_query=self._test_on_borrow_query)

class DatabaseWrapper14and15(OriginalDatabaseWrapper):
    '''
    For Django 1.4.x and 1.5.x
    '''
    set_up_pool_config = _set_up_pool_config
    create_connection_pool = _create_connection_pool

    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper14and15, self).__init__(*args, **kwargs)
        self.set_up_pool_config()

    def _cursor(self):
        settings_dict = self.settings_dict
        if self.connection is None or connection_pools[self.alias]['settings'] != settings_dict:
            # Is this the initial use of the global connection_pools dictionary for
            # this python interpreter? Build a ThreadedConnectionPool instance and
            # add it to the dictionary if so.
            if self.alias not in connection_pools or connection_pools[self.alias]['settings'] != settings_dict:
                if not settings_dict['NAME']:
                    from django.core.exceptions import ImproperlyConfigured
                    raise ImproperlyConfigured(
                        "settings.DATABASES is improperly configured. "
                        "Please supply the NAME value.")
                conn_params = {
                    'database': settings_dict['NAME'],
                }
                conn_params.update(settings_dict['OPTIONS'])
                for extra in ['autocommit'] + pool_config_defaults.keys():
                    if extra in conn_params:
                        del conn_params[extra]
                if settings_dict['USER']:
                    conn_params['user'] = settings_dict['USER']
                if settings_dict['PASSWORD']:
                    conn_params['password'] = force_str(settings_dict['PASSWORD'])
                if settings_dict['HOST']:
                    conn_params['host'] = settings_dict['HOST']
                if settings_dict['PORT']:
                    conn_params['port'] = settings_dict['PORT']

                self.create_connection_pool(conn_params)

            self.connection = PooledConnection(connection_pools[self.alias]['pool'],
                                               test_query=self._test_on_borrow_query)
            self.connection.set_client_encoding('UTF8')
            tz = 'UTC' if settings.USE_TZ else settings_dict.get('TIME_ZONE')
            if tz:
                try:
                    get_parameter_status = self.connection.get_parameter_status
                except AttributeError:
                    # psycopg2 < 2.0.12 doesn't have get_parameter_status
                    conn_tz = None
                else:
                    conn_tz = get_parameter_status('TimeZone')

                if conn_tz != tz:
                    # Set the time zone in autocommit mode (see #17062)
                    self.connection.set_isolation_level(
                            psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
                    self.connection.cursor().execute(
                            self.ops.set_time_zone_sql(), [tz])
            self.connection.set_isolation_level(self.isolation_level)
            self._get_pg_version()
            connection_created.send(sender=self.__class__, connection=self)
        cursor = self.connection.cursor()
        cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None
        return CursorWrapper(cursor)

class DatabaseWrapper13(OriginalDatabaseWrapper):
    '''
    For Django 1.3.x
    '''
    set_up_pool_config = _set_up_pool_config
    create_connection_pool = _create_connection_pool

    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper13, self).__init__(*args, **kwargs)
        self.set_up_pool_config()

    def _cursor(self):
        '''
        Override _cursor to plug in our connection pool code.  We'll return a wrapped Connection
        which can handle returning itself to the pool when its .close() method is called.
        '''
        from django.db.backends.postgresql.version import get_version

        new_connection = False
        set_tz = False
        settings_dict = self.settings_dict

        if self.connection is None or connection_pools[self.alias]['settings'] != settings_dict:
            new_connection = True
            set_tz = settings_dict.get('TIME_ZONE')

            # Is this the initial use of the global connection_pools dictionary for
            # this python interpreter? Build a ThreadedConnectionPool instance and
            # add it to the dictionary if so.
            if self.alias not in connection_pools or connection_pools[self.alias]['settings'] != settings_dict:
                if settings_dict['NAME'] == '':
                    from django.core.exceptions import ImproperlyConfigured
                    raise ImproperlyConfigured("You need to specify NAME in your Django settings file.")
                conn_params = {
                    'database': settings_dict['NAME'],
                }
                conn_params.update(settings_dict['OPTIONS'])
                for extra in ['autocommit'] + pool_config_defaults.keys():
                    if extra in conn_params:
                        del conn_params[extra]
                if settings_dict['USER']:
                    conn_params['user'] = settings_dict['USER']
                if settings_dict['PASSWORD']:
                    conn_params['password'] = settings_dict['PASSWORD']
                if settings_dict['HOST']:
                    conn_params['host'] = settings_dict['HOST']
                if settings_dict['PORT']:
                    conn_params['port'] = settings_dict['PORT']

                self.create_connection_pool(conn_params)

            self.connection = PooledConnection(connection_pools[self.alias]['pool'],
                                               test_query=self._test_on_borrow_query)
            self.connection.set_client_encoding('UTF8')
            self.connection.set_isolation_level(self.isolation_level)
            # We'll continue to emulate the old signal frequency in case any code depends upon it
            connection_created.send(sender=self.__class__, connection=self)
        cursor = self.connection.cursor()
        cursor.tzinfo_factory = None
        if new_connection:
            if set_tz:
                cursor.execute("SET TIME ZONE %s", [settings_dict['TIME_ZONE']])
            if not hasattr(self, '_version'):
                self.__class__._version = get_version(cursor)
            if self._version[0:2] < (8, 0):
                # No savepoint support for earlier version of PostgreSQL.
                self.features.uses_savepoints = False
            if self.features.uses_autocommit:
                if self._version[0:2] < (8, 2):
                    # FIXME: Needs extra code to do reliable model insert
                    # handling, so we forbid it for now.
                    from django.core.exceptions import ImproperlyConfigured
                    raise ImproperlyConfigured("You cannot use autocommit=True with PostgreSQL prior to 8.2 at the moment.")
                else:
                    # FIXME: Eventually we're enable this by default for
                    # versions that support it, but, right now, that's hard to
                    # do without breaking other things (#10509).
                    self.features.can_return_id_from_insert = True
        return CursorWrapper(cursor)

'''
Choose a version of the DatabaseWrapper class to use based on the Django
version.  This is a bit hacky, what's a more elegant way?
'''
django_version = get_django_version()
if django_version.startswith('1.3'):
    from django.db.backends.postgresql_psycopg2.base import CursorWrapper

    class DatabaseWrapper(DatabaseWrapper13):
        pass
elif django_version.startswith('1.4') or django_version.startswith('1.5'):
    from django.conf import settings
    from django.db.backends.postgresql_psycopg2.base import utc_tzinfo_factory, \
        CursorWrapper

    # The force_str call around the password seems to be the only change from
    # 1.4 to 1.5, so we'll use the same DatabaseWrapper class and make
    # force_str a no-op.
    try:
        from django.utils.encoding import force_str
    except ImportError:
        force_str = lambda x: x

    class DatabaseWrapper(DatabaseWrapper14and15):
        pass
elif django_version.startswith('1.6'):
    class DatabaseWrapper(DatabaseWrapper16):
        pass
else:
    raise ImportError("Unsupported Django version %s" % django_version)


text:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
using System.Threading.Tasks;
namespace ImageFinderOrganizer
{
	partial class MainForm : System.Windows.Forms.Form
	{

		//Form overrides dispose to clean up the component list.
		[System.Diagnostics.DebuggerNonUserCode()]
		protected override void Dispose(bool disposing)
		{
			try {
				if (disposing && components != null) {
					components.Dispose();
				}
			} finally {
				base.Dispose(disposing);
			}
		}

		//Required by the Windows Form Designer

		private System.ComponentModel.IContainer components;
		//NOTE: The following procedure is required by the Windows Form Designer
		//It can be modified using the Windows Form Designer.
		//Do not modify it using the code editor.
		[System.Diagnostics.DebuggerStepThrough()]
		private void InitializeComponent()
		{
            this.Label1 = new System.Windows.Forms.Label();
            this.TextBoxBaseSearch = new System.Windows.Forms.TextBox();
            this.ButtonChangeBaseSearch = new System.Windows.Forms.Button();
            this.ButtonChangeBaseOutput = new System.Windows.Forms.Button();
            this.TextBoxBaseOutput = new System.Windows.Forms.TextBox();
            this.Label2 = new System.Windows.Forms.Label();
            this.StatusStrip1 = new System.Windows.Forms.StatusStrip();
            this.ToolStripProgressBar1 = new System.Windows.Forms.ToolStripProgressBar();
            this.ToolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
            this.buttonStart = new System.Windows.Forms.Button();
            this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
            this.buttonCancel = new System.Windows.Forms.Button();
            this.StatusStrip1.SuspendLayout();
            this.SuspendLayout();
            //
            // Label1
            //
            this.Label1.AutoSize = true;
            this.Label1.Location = new System.Drawing.Point(12, 24);
            this.Label1.Name = "Label1";
            this.Label1.Size = new System.Drawing.Size(100, 13);
            this.Label1.TabIndex = 0;
            this.Label1.Text = "Base Search Folder";
            //
            // TextBoxBaseSearch
            //
            this.TextBoxBaseSearch.Location = new System.Drawing.Point(15, 40);
            this.TextBoxBaseSearch.Name = "TextBoxBaseSearch";
            this.TextBoxBaseSearch.Size = new System.Drawing.Size(341, 20);
            this.TextBoxBaseSearch.TabIndex = 1;
            //
            // ButtonChangeBaseSearch
            //
            this.ButtonChangeBaseSearch.Location = new System.Drawing.Point(365, 40);
            this.ButtonChangeBaseSearch.Name = "ButtonChangeBaseSearch";
            this.ButtonChangeBaseSearch.Size = new System.Drawing.Size(150, 23);
            this.ButtonChangeBaseSearch.TabIndex = 2;
            this.ButtonChangeBaseSearch.Text = "Change Folder";
            this.ButtonChangeBaseSearch.UseVisualStyleBackColor = true;
            this.ButtonChangeBaseSearch.Click += new System.EventHandler(this.ButtonChangeBaseSearch_Click);
            //
            // ButtonChangeBaseOutput
            //
            this.ButtonChangeBaseOutput.Location = new System.Drawing.Point(368, 89);
            this.ButtonChangeBaseOutput.Name = "ButtonChangeBaseOutput";
            this.ButtonChangeBaseOutput.Size = new System.Drawing.Size(150, 23);
            this.ButtonChangeBaseOutput.TabIndex = 5;
            this.ButtonChangeBaseOutput.Text = "Change Folder";
            this.ButtonChangeBaseOutput.UseVisualStyleBackColor = true;
            this.ButtonChangeBaseOutput.Click += new System.EventHandler(this.ButtonChangeBaseOutput_Click);
            //
            // TextBoxBaseOutput
            //
            this.TextBoxBaseOutput.Location = new System.Drawing.Point(18, 89);
            this.TextBoxBaseOutput.Name = "TextBoxBaseOutput";
            this.TextBoxBaseOutput.Size = new System.Drawing.Size(341, 20);
            this.TextBoxBaseOutput.TabIndex = 4;
            //
            // Label2
            //
            this.Label2.AutoSize = true;
            this.Label2.Location = new System.Drawing.Point(15, 73);
            this.Label2.Name = "Label2";
            this.Label2.Size = new System.Drawing.Size(98, 13);
            this.Label2.TabIndex = 3;
            this.Label2.Text = "Base Output Folder";
            //
            // StatusStrip1
            //
            this.StatusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.ToolStripProgressBar1,
            this.ToolStripStatusLabel1});
            this.StatusStrip1.Location = new System.Drawing.Point(0, 170);
            this.StatusStrip1.Name = "StatusStrip1";
            this.StatusStrip1.Size = new System.Drawing.Size(554, 22);
            this.StatusStrip1.TabIndex = 6;
            this.StatusStrip1.Text = "StatusStrip1";
            //
            // ToolStripProgressBar1
            //
            this.ToolStripProgressBar1.Name = "ToolStripProgressBar1";
            this.ToolStripProgressBar1.Size = new System.Drawing.Size(100, 16);
            //
            // ToolStripStatusLabel1
            //
            this.ToolStripStatusLabel1.Name = "ToolStripStatusLabel1";
            this.ToolStripStatusLabel1.Size = new System.Drawing.Size(0, 17);
            //
            // buttonStart
            //
            this.buttonStart.Location = new System.Drawing.Point(99, 126);
            this.buttonStart.Name = "buttonStart";
            this.buttonStart.Size = new System.Drawing.Size(75, 23);
            this.buttonStart.TabIndex = 7;
            this.buttonStart.Text = "Start";
            this.buttonStart.UseVisualStyleBackColor = true;
            this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
            //
            // buttonCancel
            //
            this.buttonCancel.Enabled = false;
            this.buttonCancel.Location = new System.Drawing.Point(18, 126);
            this.buttonCancel.Name = "buttonCancel";
            this.buttonCancel.Size = new System.Drawing.Size(75, 23);
            this.buttonCancel.TabIndex = 8;
            this.buttonCancel.Text = "Cancel";
            this.buttonCancel.UseVisualStyleBackColor = true;
            this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
            //
            // MainForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(554, 192);
            this.Controls.Add(this.buttonCancel);
            this.Controls.Add(this.buttonStart);
            this.Controls.Add(this.StatusStrip1);
            this.Controls.Add(this.ButtonChangeBaseOutput);
            this.Controls.Add(this.TextBoxBaseOutput);
            this.Controls.Add(this.Label2);
            this.Controls.Add(this.ButtonChangeBaseSearch);
            this.Controls.Add(this.TextBoxBaseSearch);
            this.Controls.Add(this.Label1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Name = "MainForm";
            this.Text = "Find and Organize Images";
            this.StatusStrip1.ResumeLayout(false);
            this.StatusStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		internal System.Windows.Forms.Label Label1;
		internal System.Windows.Forms.TextBox TextBoxBaseSearch;
		internal System.Windows.Forms.Button ButtonChangeBaseSearch;
		internal System.Windows.Forms.Button ButtonChangeBaseOutput;
		internal System.Windows.Forms.TextBox TextBoxBaseOutput;
		internal System.Windows.Forms.Label Label2;
		internal System.Windows.Forms.StatusStrip StatusStrip1;
		internal System.Windows.Forms.ToolStripProgressBar ToolStripProgressBar1;

		internal System.Windows.Forms.ToolStripStatusLabel ToolStripStatusLabel1;
		public MainForm()
		{
			InitializeComponent();
		}

        private Button buttonStart;
        private FolderBrowserDialog folderBrowserDialog1;
        private Button buttonCancel;
	}
}


text:
<?php

namespace Google\AdsApi\AdWords\v201702\cm;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class ReadOnlyErrorReason
{
    const READ_ONLY = 'READ_ONLY';

}


text:
DECLARE_LOG_CATEGORY_EXTERN(LogFOWController, Log, Log);

UCLASS(BlueprintType, Blueprintable)
class UNCHARTEDWATERS_API AHFogOfWarControler : public AActor
{
	GENERATED_BODY()

public:
	AHFogOfWarControler();
	~AHFogOfWarControler();

	virtual void BeginPlay() override;
	virtual void BeginDestroy() override;
	virtual void PostLoad() override;
	virtual void Tick( float DeltaSeconds ) override;

	UFUNCTION(BlueprintCallable, Category = "FOW")
		void RegisterActor(AActor* Actor);
	UFUNCTION(BlueprintCallable, Category = "FOW")
		void RegisterTracker(AActor* Actor);
	UFUNCTION(BlueprintCallable, Category = "FOW")
		void RemoveActor(AActor* Actor);
	UFUNCTION(BlueprintCallable, Category = "FOW")
		void RemoveTracker(AActor* Actor);

	UFUNCTION(BlueprintCallable, Category = "FOW")
		bool IsPositionVisible(const FVector& pos);

public:
	// !< ͬ²½Í¼ÐÎÏÔ´æ
	void SyncTextureContents();
	// !< ¸üг¡¾°´óС
	void LoadWorldSettings();
	// !< ³õ'»¯×ÊÔ´
	void InitTextureResource();
	// !< ÊÍ·Å×ÊÔ´
	void ResetTextureResource();

protected:
	// All synced actors
	UPROPERTY(VisibleAnywhere, Category = "FOW")
		TArray<AActor*> Actors;
	UPROPERTY(VisibleAnywhere, Category = "FOW")
		TArray<AActor*> Trackers;
	UPROPERTY(VisibleAnywhere, Category = "FOW")
		TArray<uint32> RemovedActors;
	UPROPERTY(VisibleAnywhere, Category = "FOW")
		TArray<uint32> RemovedTrackers;

	// Should sync to global-material-parameter-collections.
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "FOW")
		FBox WorldBounds;
	UPROPERTY(EditAnywhere, Category = "FOW")
		AActor* WorldMinActor;
	UPROPERTY(EditAnywhere, Category = "FOW")
		AActor* WorldMaxActor;
	// Actor view distances
	UPROPERTY(EditAnywhere, Category = "FOW")
		float ActorVisibleUnit;
	// Actor view blur distance
	UPROPERTY(EditAnywhere, Category = "FOW")
		float ActorVisibleBlurDistance;
	UPROPERTY(EditAnywhere, Category = "FOW")
		float FOVBias;
	UPROPERTY(EditAnywhere, Category = "FOW")
		bool EnableBlur;
	UPROPERTY(EditAnywhere, Category = "FOW")
		int16 TextureSize;
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "FOW")
		float BlendDuration;
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "FOW")
		float BlendAlpha;

	// Format : G8 (»Ò¶Èͼ)
	UPROPERTY()
		TArray<uint8> DynamicTexturePixels;
	UPROPERTY()
		TArray<uint8> LastDynamicTexturePixels;

	UPROPERTY(Transient, VisibleAnywhere, BlueprintReadOnly, Category = "FOW")
		UTexture2D* DynamicTexture;
	UPROPERTY(Transient, VisibleAnywhere, BlueprintReadOnly, Category = "FOW")
		UTexture2D* LastDynamicTexture;

protected:
	float BlendStartTime;
	float TexelPerWorldUnit;
	float WorldUnitPerTexel;
	AHFogOfWarThread* Worker;
	FUpdateTextureRegion2D* WholeTextureRegion;
};


text:
import * as React from 'react';

export const Psychopomp = () => (
  Psychopomp
);


text:
<?php

namespace Oro\Bundle\SearchBundle\Tests\Functional\API;

use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase;

/**
 * @outputBuffering enabled
 * @dbIsolation
 * @dbReindex
 */
class SoapAdvancedSearchApiTest extends WebTestCase
{
    /** Default value for offset and max_records */
    const DEFAULT_VALUE = 0;

    protected static $hasLoaded = false;

    protected function setUp()
    {
        $this->initClient(array(), $this->generateWsseAuthHeader());
        $this->initSoapClient();
        $this->loadFixtures(array('Oro\Bundle\SearchBundle\Tests\Functional\API\DataFixtures\LoadSearchItemData'));
    }

    /**
     * @dataProvider advancedSearchDataProvider
     */
    public function testAdvancedSearch(array $request, array $response)
    {
        $result = $this->soapClient->advancedSearch($request['query']);
        $result = $this->valueToArray($result);
        $this->assertEquals($response['count'], $result['count']);
    }

    /**
     * Data provider for SOAP API tests
     *
     * @return array
     */
    public function advancedSearchDataProvider()
    {
        return $this->getApiRequestsData(__DIR__ . DIRECTORY_SEPARATOR . 'advanced_requests');
    }
}


text:
from trie_oop import *

trie = Trie()

file_in = 'dict.txt'
f = open(file_in)
for line in f:
    trie.addWord(line.strip())
f.close()

trie.addWord('doughnut')
trie.addWord('donut')
trie.addWord('donald')
trie.addWord('domino')
trie.addWord('dominion')

searched_word = 'second'
print('foud "', searched_word, '":', trie.hasWord(searched_word))
searched_word = 'time'
print('foud "', searched_word, '":', trie.hasWord(searched_word))
searched_word = 'domino'
print('foud "', searched_word, '":', trie.hasWord(searched_word))
searched_word = 'dominique'
print('foud "', searched_word, '":', trie.hasWord(searched_word))

print()
print('#words:', trie.countWords())
print('size:', trie.getSize())
print('#letters:', trie.countLetters())
print('compression:', trie.compression())

print()
trie.display()
trie.diagram('test', True)


text:
==========================
Designing a new experiment
==========================

Core plugins
------------
Psiexperiment ships with five core plugins that are always loaded when an experiment is started:

* **Context** -
* **Data** - Manages saving, analysis and plotting of data.
* **Controller** - Manages experiment.
* **Token** - Manages generation of both epoch (i.e., finite in duration) and continuous (i.e., infinite in duration) waveforms.
* **Calibration** - Manages calibrations of inputs and outputs. Right now only acoustic inputs and outputs (e.g., microphones and speakers) are supported. Offers chirp, golay and tone-based calibration algorithms.

Getting started
---------------

Psiexperiment is a plugin-based system where the plugins determine the experiment workflow. At a minimum, an experiment must provide the following:

* A list of parameters and/or results
* The inputs and outputs that will be used
* The stimuli (i.e., tokens) that will be generated
* Actions to take when certain events occur.

Your experiment configuration file will define `EXPERIMENT`, which is the name of the experiment and will typically contain the following extensions:

.. code-block:: enaml

    enamldef ControllerManifest(BaseManifest): manifest:

        Extension:
            id = EXPERIMENT + '.sinks'
            point = 'psi.data.sinks'
            ...

        Extension:
            id = EXPERIMENT + '.tokens'
            point = 'psi.token.tokens'
            ...

        Extension:
            id = EXPERIMENT + '.io'
            point = 'psi.controller.io'
            ...

        Extension:
            id = EXPERIMENT + '.selectors'
            point = 'psi.context.selectors'
            ...

        Extension:
            id = EXPERIMENT + '.context'
            point = 'psi.context.items'
            ...

        Extension:
            id = EXPERIMENT + '.actions'
            point = 'psi.controller.actions'
            ...

Let's take a closer look at each of the extensions.

Actions
.......

At a minimum, you will typically define the following two actions (customized for your needs):

.. code-block:: enaml

    Extension:
        id = EXPERIMENT + '.actions'
        point = 'psi.controller.actions'

        ExperimentAction:
            event = 'experiment_initialize'
            command = 'psi.context.initialize'
            kwargs = {'selector': 'default', 'cycles': 1}

        ExperimentAction:
            event = 'engines_configured'
            command = 'dpoae.start'
            kwargs = {'delay': 0.5}

When you press the `start` button on the toolbar, this fires a sequence of three events, `experiment_initialize`, `experiment_prepare` and `experiment_start`.  While `experiment_initialize` and `experiment_prepare` are very similar, certain actions may require that the context has been initialized. To simplify this, we have added `experiment_initialize`. The `psi.context.initialize` command should *always* be bound to this event (if it's bound to `experiment_prepare`, you may get errors if commands bound to `experiment_prepare` need to get the current value of a variable).

Under the hood, the controller will configure the engines during the `experiment_prepare` phase. If you want to configure one of the outputs (in this case, `dpoae`) during this phase, be sure to bind it to the `engine_configured` event to ensure it gets executed after the engine is configured (the engine must be configured before it can properly receive waveform samples from the outputs).

Sequence of events during an experiment
.......................................
* `plugins_started` - All plugins have finished loading. Now, you can perform actions that may require access to another plugin; however, do not assume that the plugins have finished initializing. A number of logging actions are tied to this step.

* `experiment_initialize` - All plugins should have been initialized. This is where you will typically initialize the context (and nothing else).

* `context_initialized` - This only follows `experiment_initialize` if `psi.context.initialize` has properly been bound to `experiment_initialize`. The `psi.context.finalize_io` method is called during this event. During this step, all "orphan" inputs and outputs (i.e., ones where the target or source is specified by name rather than as part of the hierarchy) are connected.

* `experiment_prepare` - The majority of actions required prior to starting an experiment should be tied to this event since the context will now be available for queries.

* `engines_configured` - TODO

* `experiment_start` - Starts the data acquisition engines.

* `experiment_end` - Stops the data acquisition engines.

The power of actions
....................
Actions allow you to insert your own code or invoke commands at any point in the experiment process. A few examples:

* The `abr_base.enaml` file calls a custom function when the `experiment_prepare` event is called. This function reviews the settings specified by the user to determine the sequence of the tone pips (e.g., conventional vs. interleaved, alternating polarity, etc.) and sets up the queue accordingly. While it's theoretically possible to set this using plugins offered by psiexperiment (e.g., alternating polarity could be specified as a "roving" context item), this custom function makes the user interface much simpler and more fool-proof.

* The `pistonphone_calibration.enaml` file calls a custom function, `calculate_sens` once the experiment is complete to calculate the sensitivity of the microphone. Note that the callback for the custom function is defined inside the extension to the `psi.controller.io` point.

Input/Output
............

Example of an input-output plugin:

.. code-block:: enaml

    Extension:
        id = EXPERIMENT + '.io'
        point = 'psi.controller.io'

        Blocked: hw_ai:
            duration = 0.1
            name = 'hw_ai'
            source_name = C.input_channel
            source ::
                # Once the channel is linked
                channel.start_trigger = ''
                channel.samples = round(C.sample_duration * channel.fs)
                channel.input_gain = C.input_gain

`C` is a controller manifest-level variable that allows for lookup of values defined via the context.

Creating your own custom plugins
................................

When defining your own subclasses of `PSIManifest`, we recommend the following naming convetions to minimize name collisions:

.. code-block:: enaml

    Extension:
        id = manifest.id + '.commands'
        point = 'enaml.workbench.core.commands'

        Command:
            id = contribution.name + '.do_action'
            ...

All subclasses of `PSIManifest` have access to the attached `contribution` (an instance of `PSIContribution`) as an attribute.

Common gotchas
--------------
* Outputs and inputs are configured *only if they are deemed active*. If the output of a particular processing chain (e.g., microphone to IIR filter to extract epochs) is not saved to a data store or plotted, then it's assumed it is not used. The controller will then opmit this particular processing chain from the configuration to alleviate system load. This allows us to design intensive processing chains but allow the user to disable them easily by not plotting the result. However, this can be a bit tricky when defining your own custom sinks For example, there's no target for `AnalyzeDPOAE` in `dpoae_base.enaml` (TODO finish).
* When adding new attributes to subclasses of `Declarative`, be sure to use `d_` as appropriate otherwise you will get a `TypeError` when attempting to assign to the attribute in an Enaml file.


text:
<?php
/*
	Question2Answer by Gideon Greenspan and contributors
	http://www.question2answer.org/

	File: qa-include/qa-filter-basic.php
	Description: Basic module for validating form inputs

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	More about this license: http://www.question2answer.org/license.php
*/

require_once QA_INCLUDE_DIR.'db/maxima.php';
require_once QA_INCLUDE_DIR.'util/string.php';

class qa_filter_basic
{
	public function filter_email(&$email, $olduser)
	{
		if (!strlen($email))
			return qa_lang('users/email_required');

		if (!qa_email_validate($email))
			return qa_lang('users/email_invalid');

		if (qa_strlen($email)>QA_DB_MAX_EMAIL_LENGTH)
			return qa_lang_sub('main/max_length_x', QA_DB_MAX_EMAIL_LENGTH);
	}

	public function filter_handle(&$handle, $olduser)
	{
		if (!strlen($handle))
			return qa_lang('users/handle_empty');

		if (preg_match('/[\\@\\+\\/]/', $handle))
			return qa_lang_sub('users/handle_has_bad', '@ + /');

		if (qa_strlen($handle)>QA_DB_MAX_HANDLE_LENGTH)
			return qa_lang_sub('main/max_length_x', QA_DB_MAX_HANDLE_LENGTH);
	}

	public function filter_question(&$question, &$errors, $oldquestion)
	{
		$this->validate_length($errors, 'title', @$question['title'], qa_opt('min_len_q_title'),
			max(qa_opt('min_len_q_title'), min(qa_opt('max_len_q_title'), QA_DB_MAX_TITLE_LENGTH)));

		$this->validate_length($errors, 'content', @$question['content'], 0, QA_DB_MAX_CONTENT_LENGTH); // for storage

		$this->validate_length($errors, 'content', @$question['text'], qa_opt('min_len_q_content'), null); // for display

		if (isset($question['tags'])) {
			$counttags=count($question['tags']);
			$mintags=min(qa_opt('min_num_q_tags'), qa_opt('max_num_q_tags'));

			if ($counttags<$mintags)
				$errors['tags']=qa_lang_sub('question/min_tags_x', $mintags);
			elseif ($counttags>qa_opt('max_num_q_tags'))
				$errors['tags']=qa_lang_sub('question/max_tags_x', qa_opt('max_num_q_tags'));
			else
				$this->validate_length($errors, 'tags', qa_tags_to_tagstring($question['tags']), 0, QA_DB_MAX_TAGS_LENGTH); // for storage
		}

		$this->validate_post_email($errors, $question);
	}

	public function filter_answer(&$answer, &$errors, $question, $oldanswer)
	{
		$this->validate_length($errors, 'content', @$answer['content'], 0, QA_DB_MAX_CONTENT_LENGTH); // for storage
		$this->validate_length($errors, 'content', @$answer['text'], qa_opt('min_len_a_content'), null); // for display
		$this->validate_post_email($errors, $answer);
	}

	public function filter_comment(&$comment, &$errors, $question, $parent, $oldcomment)
	{
		$this->validate_length($errors, 'content', @$comment['content'], 0, QA_DB_MAX_CONTENT_LENGTH); // for storage
		$this->validate_length($errors, 'content', @$comment['text'], qa_opt('min_len_c_content'), null); // for display
		$this->validate_post_email($errors, $comment);
	}

	public function filter_profile(&$profile, &$errors, $user, $oldprofile)
	{
		foreach ($profile as $field => $value)
			$this->validate_length($errors, $field, $value, 0, QA_DB_MAX_PROFILE_CONTENT_LENGTH);
	}

//	The definitions below are not part of a standard filter module, but just used within this one

	/**
	 * Add textual element $field to $errors if length of $input is not between $minlength and $maxlength.
	 *
	 * @deprecated This function will become private in Q2A 1.8. It is specific to this plugin and
	 * should not be used by outside code.
	 */
	public function validate_length(&$errors, $field, $input, $minlength, $maxlength)
	{
		$length = isset($input) ? qa_strlen($input) : 0;

		if ($length < $minlength)
			$errors[$field] = ($minlength == 1) ? qa_lang('main/field_required') : qa_lang_sub('main/min_length_x', $minlength);
		elseif (isset($maxlength) && ($length > $maxlength))
			$errors[$field] = qa_lang_sub('main/max_length_x', $maxlength);
	}

	/**
	 * Wrapper function for validating a post's email address.
	 *
	 * @deprecated This function will become private in Q2A 1.8. It is specific to this plugin and
	 * should not be used by outside code.
	 */
	public function validate_post_email(&$errors, $post)
	{
		if (@$post['notify'] && strlen(@$post['email'])) {
			$error=$this->filter_email($post['email'], null);
			if (isset($error))
				$errors['email']=$error;
		}
	}
}


text:
// Keyglove controller source code - Modular hardware/architecture option definitions
// 2014-12-13 by Jeff Rowberg <jeff@rowberg.net>

/**
 * @file hardware.h
 * @brief Modular hardware/architecture option definitions
 * @author Jeff Rowberg
 * @date 2014-12-13
 *
 * This file defines all of the selectable options which you may want to use in
 * the "config.h" file. If you create new functionality which a modular add-on
 * beyond the already implemented Keyglove code, it should be defined here as a
 * new option and then enabled as a module in the "config.h" file. This file
 * will not normally need to be modified.
 *
 * @see config.h
 */

#ifndef _HARDWARE_H_
#define _HARDWARE_H_

/* Main controller board options. Only one board may be selected at compile time. (defined in KG_BOARD) */

#define KG_BOARD_USER                   0x00        ///< Totally custom board, you better know what you're doing
#define KG_BOARD_TEENSYPP2_T37          0x10        ///< AT90USB128x MCU, 46 I/O pins and prototype/kit design, 37 touch sensors
#define KG_BOARD_TEENSYPP2_T19          0x11        ///< AT90USB128x MCU, 46 I/O pins and prototype/kit design, 19 touch sensors
#define KG_BOARD_ARDUINO_DUE            0x20        ///< **NOT SUPPORTED YET:** SAM3X8E MCU, 50+ I/O pins and prototype/Arduino design
#define KG_BOARD_KEYGLOVE100            0x30        ///< **NOT SUPPORTED YET:** SAM3X8E MCU, 50+ I/O pins and custom design

/* Flex sensor options. Only one choice may be selected at the same time. (defined in KG_FLEX) */

#define KG_FLEX_NONE                    0x00        ///< No flex sensors used
#define KG_FLEX_5FINGERS                0x01        ///< **NOT SUPPORTED YET:** Full 5-finger complement

/* Pressure sensor options. Only one choice may be selected at the same time. (defined in KG_PRESSURE) */

#define KG_PRESSURE_NONE                0x00        ///< No pressure sensors used
#define KG_PRESSURE_5TIPS               0x01        ///< **NOT SUPPORTED YET:** Full 5-fingertip complement

/* Hand selection options. Only one choice may be selected at the same time. (defined in KG_HAND) */

#define KG_HAND_RIGHT                   0x01        ///< Right-hand sensor connection orientation (default)
#define KG_HAND_LEFT                    0x02        ///< Left-hand sensor connection orientation (relevant for kit, others automatic)

/* Dual glove communication options. Only one choice may be selected at the same time. (defined in KG_DUALGLOVE) */

#define KG_DUALGLOVE_NONE               0x00        ///< No dual-glove support
#define KG_DUALGLOVE_RFM22B             0x01        ///< **NOT SUPPORTED YET:** Wireless connection with RFM22B

/* Host interface options. Multiple interfaces may be enabled at the same time. (defined in KG_HOSTIF) */

#define KG_HOSTIF_NONE                  0x00        ///< Don't communicate (weird, maybe you have a reason)
#define KG_HOSTIF_USB_SERIAL            0x01        ///< Hardware USB serial (requires ARM, AT90USB* or ATMega32U* MCU)
#define KG_HOSTIF_USB_RAWHID            0x02        ///< Hardware USB raw HID (requires ARM, AT90USB* or ATMega32U* MCU)
#define KG_HOSTIF_USB_HID               0x04        ///< Hardware USB HID (requires ARM, AT90USB* or ATMega32U* MCU)
#define KG_HOSTIF_BT2_SERIAL            0x08        ///< Bluetooth v2 serial (requires Bluegiga WT12 w/iWRAP)
#define KG_HOSTIF_BT2_RAWHID            0x10        ///< Bluetooth v2 raw HID (requires Bluegiga WT12 w/iWRAP v5+)
#define KG_HOSTIF_BT2_HID               0x20        ///< Bluetooth v2 HID (requires Bluegiga WT12 w/iWRAP)

/* HID support options. Multiple HID types may be enabled at the same time. (defined in KG_HID) */

#define KG_HID_NONE                     0x00        ///< No standard HID support
#define KG_HID_KEYBOARD                 0x01        ///< Include standard HID keyboard support routines
#define KG_HID_MOUSE                    0x02        ///< Include standard HID mouse support routines

/* Motion sensor options. Multiple sensors may be enabled, provided they do not compete. (defined in KG_MOTION) */

#define KG_MOTION_NONE                  0x00        ///< No motion support
#define KG_MOTION_MPU6050_HAND          0x01        ///< 6-axis I2C digital accel/gyro on back of hand
#define KG_MOTION_MPU6050_INDEXTIP      0x02        ///< 6-axis I2C digital accel/gyro on index fingertip

/* Sensory feedback. Multiple options may be enabled. (defined in KG_FEEDBACK) */

#define KG_FEEDBACK_NONE                0x00        ///< No feedback support
#define KG_FEEDBACK_BLINK               0x01        ///< Single LED (e.g. on Arduino/Teensy boards)
#define KG_FEEDBACK_PIEZO               0x02        ///< Piezo buzzer for sound
#define KG_FEEDBACK_VIBRATE             0x04        ///< Vibration motor for haptic feedback
#define KG_FEEDBACK_RGB                 0x08        ///< Combined RGB LED for visual feedback

/* Interface mode definitions. Multiple options may be enabled. */

#define KG_INTERFACE_MODE_NONE          0x00        ///< Don't use this interface for KGAPI data
#define KG_INTERFACE_MODE_OUTGOING_API  0x01        ///< Use this interface to send outgoing KGAPI responses and events
#define KG_INTERFACE_MODE_INCOMING_API  0x02        ///< Use this interface to receive incoming KGAPI commands
#define KG_INTERFACE_MODE_OUTGOING_LOG  0x04        ///< Use this interface to send outgoing log/info data

/* Interface number definitions. Used for differentiating between possible incoming/outgoing channels for KGAPI packets. */

#define KG_INTERFACENUM_USB_SERIAL      1           ///< KGAPI interface identifier for USB serial
#define KG_INTERFACENUM_USB_RAWHID      2           ///< KGAPI interface identifier for USB raw HID
#define KG_INTERFACENUM_BT2_SERIAL      3           ///< KGAPI interface identifier for BT2 serial
#define KG_INTERFACENUM_BT2_RAWHID      4           ///< KGAPI interface identifier for BT2 raw HID
#define KG_INTERFACENUM_BT2_IAP         5           ///< KGAPI interface identifier for BT2 IAP

#endif // _HARDWARE_H_


text:
package de.philipphager.disclosure.util.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatDialogFragment;
import de.philipphager.disclosure.ApplicationComponent;
import de.philipphager.disclosure.DisclosureApp;
import de.philipphager.disclosure.feature.navigation.Navigates;
import de.philipphager.disclosure.feature.navigation.Navigator;
import javax.inject.Inject;

public abstract class BaseDialogFragment extends AppCompatDialogFragment implements Navigates {
  @Inject protected Navigator navigator;

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    inject();
  }

  @Override public Navigator navigate() {
    return navigator;
  }

  protected abstract void injectFragment(ApplicationComponent appComponent);

  private void inject() {
    DisclosureApp application = (DisclosureApp) getActivity().getApplication();
    injectFragment(application.getApplicationComponent());

    navigator.setActivity(getActivity());
  }
}


text:
YUI.add('chart-test-template', function(Y) {
    ChartTestTemplate = function(cfg)
    {
        var i;
        ChartTestTemplate.superclass.constructor.apply(this);
        for(i in cfg)
        {
            if(cfg.hasOwnProperty(i))
            {
                this[i] = cfg[i];
            }
        }
    };

    Y.extend(ChartTestTemplate, Y.Test.Case);
    Y.ChartTestTemplate = ChartTestTemplate;
}, '@VERSION@' ,{requires:['test']});


text:
DSHttpRequestQueue
==================

A simple & high performance Http request queue for iOS applications.

Read me needs to be complemention.


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { EditEntityTemplateService } from './edit-entity-template.service';
import { EditEntityTemplateColumnComponent } from './edit-entity-template-column.component';
import { EditEntityTemplateListItemComponent } from './edit-entity-template-list-item.component';
import { EditEntityTemplateListComponent } from './edit-entity-template-list.component';
import { EditEntityTemplateDetailsComponent } from './edit-entity-template-details.component';
import { EditEntityTemplateComponent } from './edit-entity-template.component';

@NgModule({
  imports: [
        CommonModule
  ],
  declarations: [
		EditEntityTemplateComponent,
		EditEntityTemplateListComponent,
		EditEntityTemplateDetailsComponent,
		EditEntityTemplateColumnComponent,
		EditEntityTemplateListItemComponent
	],
	exports: [
		EditEntityTemplateComponent,
		EditEntityTemplateListComponent,
		EditEntityTemplateDetailsComponent,
		EditEntityTemplateColumnComponent,
		EditEntityTemplateListItemComponent
	],
	providers: [
		{ provide: EditEntityTemplateService, useClass: EditEntityTemplateService }
	]
})
export class EditEntityTemplateModule { }


text:
<?php

namespace Ecg\MagentoFinder\FileInfo;

use Ecg\MagentoFinder\FileInfo,
    Ecg\MagentoFinder\Helper,
    SimpleXMLElement;

class ConfigInfo extends FileInfo implements ConfigInfoInterface
{
    /**
     * @var SimpleXmlElement
     */
    protected $xml;

    /**
     * Constructor
     *
     * @param string $file The file name
     * @param string $relativePath The relative path
     * @param string $relativePathname The relative path name
     * @param array $info
     */
    public function __construct($file, $relativePath, $relativePathname, $info)
    {
        parent::__construct($file, $relativePath, $relativePathname, $info);
        $this->xml = new SimpleXMLElement($this->getContents());
        $this->helper = new Helper;
    }

    public function getRewrites()
    {
        $res = array();

        foreach ($this->xml->xpath('//rewrite') as $item) {
            foreach ($item as $c => $v) {
                $parent = $item->xpath('..');
                if (empty($parent)) {
                    continue;
                }
                $b = $parent[0]->getName();
                $grandParent = $parent[0]->xpath('..');
                if (empty($grandParent)) {
                    continue;
                }

                $a = $grandParent[0]->getName();
                if ($a == 'config') {
                    continue; // skip url rewrites
                }
//                $res[] = array(
//                    'from' => $a . '_' . $b . '_' . $c,
//                    'to'   => (string)$v
//                );
                $className = $this->getGroupedClassName($a, $b, $c);
                $res[$className] [] = (string) $v;

            }
        }

        return $res;
    }

    public function getGroupedClassName($groupType, $classId, $suffix)
    {
        $namespace = (strpos($classId, '_') !== false) ? '' : 'mage_';
        $groupType = substr($groupType, 0, strlen($groupType) - 1);
        $className = $namespace . $classId . '_' . $groupType . '_' . $suffix;
        return $this->helper->ucWords($className);
    }

        /**
     * @todo deal with disabled observers
     * @return array
     */
    public function getEventListeners()
    {
        $res = array();
        $events = $this->xml->xpath('//events/*');

        foreach ($events as $event) {
            $area = $event->xpath('../..');
            $class = $event->xpath('.//class');
            $method = $event->xpath('.//method');
            if ($area && $class && $method) {
                $res[] = array(
                    'area' => (string)$area[0]->getName(),
                    'event' => $event->getName(),
                    'class' => (string)$class[0],
                    'run_method' => (string)$method[0]
                );
            }
        }

        return $res;
    }

    public function getCronJobs()
    {
        $res = array();
        $cronJobs = $this->xml->xpath('//crontab/jobs/*');

        foreach ($cronJobs as $job) {
            $res[] = array(
                'schedule' => (string)$job->schedule->cron_expr,
                'run_method' => (string)$job->run->model,
            );
        }
        return $res;
    }

    /**
     * @return array
     */
    public function getVersion()
    {
        $version = $this->xml->xpath('//modules/' . $this->info['name'] . '/version');
        return count($version) ? (string)$version[0] : '';
    }

    /**
     * @return array
     */
    public function getRouters()
    {
        // TODO: Implement getRouters() method.
    }

    public function getLayoutUpdates()
    {
        $updates = $this->xml->xpath('//layout/updates/*');

        $res = array();
        foreach ($updates as $update) {
            $res[$update->getName()] = array(
                'file' => (string)$update->file,
                'area' => (string)$update->xpath('../../..')[0]->getName()
            );
        }
        return $res;
    }
}


text:
// SPDX-License-Identifier: Apache-2.0

#include "gtest/gtest.h"

// see http://google.github.io/googletest/advanced.html#sanitizer-integration

extern "C"
{
	void __ubsan_on_report() { FAIL() << "Encountered an undefined behavior sanitizer error"; }
	void __asan_on_error() { FAIL() << "Encountered an address sanitizer error"; }
	void __tsan_on_report() { FAIL() << "Encountered a thread sanitizer error"; }
} // extern "C"


text:
class GovspeakContentWorker < WorkerBase
  def perform(id)
    return unless (govspeak_content = GovspeakContent.find_by(id:))

    govspeak_content.render_govspeak!
  end
end


text:
'use strict';

var argscheck = require('cordova/argscheck'),
    exec = require('cordova/exec');

var drminfoExport = {
    getEsn: function (compName, successCallback, errorCallback) {
        argscheck.checkArgs('sfF', 'drminfo.getEsn', arguments);
        errorCallback = errorCallback || function () {};

        var args = [compName];
        exec(successCallback, errorCallback, 'toast.drminfo', 'getEsn', args);
    },
    getSdi: function (successCallback, errorCallback) {
        argscheck.checkArgs('fF', 'drminfo.getSdiId', arguments);
        errorCallback = errorCallback || function () {};

        var args = [];
        exec(successCallback, errorCallback, 'toast.drminfo', 'getSdi', args);
    }
};

module.exports = drminfoExport;