text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information

namespace DotNetNuke.Services.GeneratedImage
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Diagnostics;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;
    using System.Web;

    using DotNetNuke.Common.Utilities;
    using DotNetNuke.Entities.Portals;
    using DotNetNuke.Entities.Users;
    using DotNetNuke.Services.GeneratedImage.ImageQuantization;
    using DotNetNuke.Services.Log.EventLog;
    using DotNetNuke.Services.UserRequest;

    internal class ImageHandlerInternal
    {
        private static TimeSpan defaultClientCacheExpiration = new TimeSpan(0, 10, 0);

        private TimeSpan clientCacheExpiration = defaultClientCacheExpiration;
        private IImageStore imageStore;
        private DateTime? now;

        /// <summary>
        /// Initializes a new instance of the <see cref="ImageHandlerInternal"/> class.
        /// </summary>
        public ImageHandlerInternal()
        {
            this.ContentType = ImageFormat.Jpeg;
            this.ImageCompression = 95;
            this.ImageTransforms = new List<ImageTransform>();
            this.AllowStandalone = false;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ImageHandlerInternal"/> class.
        /// </summary>
        /// <param name="imageStore"></param>
        /// <param name="now"></param>
        internal ImageHandlerInternal(IImageStore imageStore, DateTime now)
            : this()
        {
            this.imageStore = imageStore;
            this.now = now;
        }

        public TimeSpan ClientCacheExpiration
        {
            get
            {
                return this.clientCacheExpiration;
            }

            set
            {
                if (value.Ticks < 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(value), "ClientCacheExpiration must be positive");
                }

                this.clientCacheExpiration = value;
                this.EnableClientCache = true;
            }
        }

        public ImageFormat ContentType { get; set; }

        public long ImageCompression { get; set; }

        public int IPCountMax
        {
            get { return IPCount.MaxCount; }
            set { IPCount.MaxCount = value; }
        }

        public TimeSpan IpCountPurgeInterval
        {
            get { return IPCount.PurgeInterval; }
            set { IPCount.PurgeInterval = value; }
        }

        public bool EnableClientCache { get; set; }

        public bool EnableServerCache { get; set; }

        public bool EnableIPCount { get; set; }

        public bool AllowStandalone { get; set; }

        public string[] AllowedDomains { get; set; }

        public bool LogSecurity { get; set; }

        public List<ImageTransform> ImageTransforms
        {
            get;
            private set;
        }

        private DateTime DateTime_Now
        {
            get
            {
                return this.now ?? DateTime.Now;
            }
        }

        private IImageStore ImageStore
        {
            get
            {
                return this.imageStore ?? DiskImageStore.Instance;
            }
        }

        public void HandleImageRequest(HttpContextBase context, Func<NameValueCollection, ImageInfo> imageGenCallback, string uniqueIdStringSeed)
        {
            context.Response.Clear();

            string ipAddress = UserRequestIPAddressController.Instance.GetUserRequestIPAddress(context.Request);

            // Check if allowed standalone
            if (!this.AllowStandalone && context.Request.UrlReferrer == null && !context.Request.IsLocal)
            {
                string message = "Not allowed to use standalone";
                if (this.LogSecurity)
                {
                    EventLogController logController = new EventLogController();
                    var logInfo = new LogInfo
                    {
                        LogUserID = PortalSettings.Current.UserId,
                        LogPortalID = PortalSettings.Current.PortalId,
                        LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString(),
                    };
                    logInfo.AddProperty("DnnImageHandler", message);
                    logInfo.AddProperty("IP", ipAddress);
                    logController.AddLog(logInfo);
                }

                context.Response.StatusCode = 403;
                context.Response.StatusDescription = message;
                context.Response.End();
                return;
            }

            // Check if domain is allowed to embed image
            if (!string.IsNullOrEmpty(this.AllowedDomains[0]) &&
                context.Request.UrlReferrer != null &&
                context.Request.UrlReferrer.Host.ToLowerInvariant() != context.Request.Url.Host.ToLowerInvariant())
            {
                bool allowed = false;
                string allowedDomains = string.Empty;
                foreach (string allowedDomain in this.AllowedDomains)
                {
                    if (!string.IsNullOrEmpty(allowedDomain))
                    {
                        allowedDomains += allowedDomain + ",";
                        if (context.Request.UrlReferrer.Host.ToLowerInvariant().Contains(allowedDomain.ToLowerInvariant()))
                        {
                            allowed = true;
                        }
                    }
                }

                if (!allowed)
                {
                    string message = $"Not allowed to use from referrer '{context.Request.UrlReferrer.Host}'";
                    if (this.LogSecurity)
                    {
                        EventLogController logController = new EventLogController();
                        var logInfo = new LogInfo
                        {
                            LogUserID = PortalSettings.Current.UserId,
                            LogPortalID = PortalSettings.Current.PortalId,
                            LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString(),
                        };
                        logInfo.AddProperty("DnnImageHandler", message);
                        logInfo.AddProperty("IP", ipAddress);
                        logInfo.AddProperty("AllowedDomains", allowedDomains);
                        logController.AddLog(logInfo);
                    }

                    context.Response.StatusCode = 403;
                    context.Response.StatusDescription = "Forbidden";
                    context.Response.End();
                    return;
                }
            }

            // Generate Image
            var imageMethodData = imageGenCallback(context.Request.QueryString);

            context.Response.ContentType = GetImageMimeType(this.ContentType);
            if (imageMethodData == null)
            {
                throw new InvalidOperationException("The DnnImageHandler cannot return null.");
            }

            if (imageMethodData.IsEmptyImage)
            {
                using (var imageOutputBuffer = new MemoryStream())
                {
                    this.RenderImage(imageMethodData.Image, imageOutputBuffer);
                    var buffer = imageOutputBuffer.GetBuffer();
                    context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                    context.Response.End();
                    return;
                }
            }

            string cacheId = this.GetUniqueIDString(context, uniqueIdStringSeed);

            var userId = -1;
            var cacheCleared = false;
            var isProfilePic = "profilepic".Equals(context.Request.QueryString["mode"], StringComparison.InvariantCultureIgnoreCase);
            if (isProfilePic)
            {
                if (int.TryParse(context.Request.QueryString["userId"], out userId))
                {
                    cacheCleared = this.ClearDiskImageCacheIfNecessary(userId, PortalSettings.Current.PortalId, cacheId);
                }
            }

            // Handle client cache
            var cachePolicy = context.Response.Cache;
            cachePolicy.SetValidUntilExpires(true);
            if (this.EnableClientCache)
            {
                if (!string.IsNullOrEmpty(context.Request.Headers["If-Modified-Since"]) && !string.IsNullOrEmpty(context.Request.Headers["If-None-Match"]) && !cacheCleared)
                {
                    var provider = CultureInfo.InvariantCulture;
                    var lastMod = DateTime.ParseExact(context.Request.Headers["If-Modified-Since"], "r", provider).ToLocalTime();
                    var etag = context.Request.Headers["If-None-Match"];
                    if (lastMod + this.ClientCacheExpiration > this.DateTime_Now && etag == cacheId)
                    {
                        context.Response.StatusCode = 304;
                        context.Response.StatusDescription = "Not Modified";
                        context.Response.End();
                        return;
                    }
                }

                cachePolicy.SetCacheability(HttpCacheability.Public);
                cachePolicy.SetLastModified(this.DateTime_Now);
                cachePolicy.SetExpires(this.DateTime_Now + this.ClientCacheExpiration);
                cachePolicy.SetETag(cacheId);
            }

            // Handle Server cache
            if (this.EnableServerCache)
            {
                var isAnonymousUser = userId <= 0 ? true : false;
                if (isProfilePic && !isAnonymousUser && !this.IsPicVisibleToCurrentUser(userId))
                {
                    string message = "Not allowed to see profile picture";

                    if (this.LogSecurity)
                    {
                        EventLogController logController = new EventLogController();
                        var logInfo = new LogInfo
                        {
                            LogUserID = PortalSettings.Current.UserId,
                            LogPortalID = PortalSettings.Current.PortalId,
                            LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString(),
                        };
                        logInfo.AddProperty("DnnImageHandler", message);
                        logInfo.AddProperty("IP", ipAddress);
                        logController.AddLog(logInfo);
                    }

                    context.Response.StatusCode = 403;
                    context.Response.StatusDescription = "Forbidden";
                    context.Response.End();
                    return;
                }

                if (this.ImageStore.TryTransmitIfContains(cacheId, context.Response))
                {
                    context.Response.Flush();
                    return;
                }
            }

            // Check IP Cout boundaries
            if (this.EnableIPCount)
            {
                if (!IPCount.CheckIp(ipAddress))
                {
                    string message = "Too many requests";

                    if (this.LogSecurity)
                    {
                        EventLogController logController = new EventLogController();
                        var logInfo = new LogInfo
                        {
                            LogUserID = PortalSettings.Current.UserId,
                            LogPortalID = PortalSettings.Current.PortalId,
                            LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString(),
                        };
                        logInfo.AddProperty("DnnImageHandler", message);
                        logInfo.AddProperty("IP", ipAddress);
                        logController.AddLog(logInfo);
                    }

                    context.Response.StatusCode = 429;
                    context.Response.StatusDescription = message;
                    context.Response.End();
                    return;
                }
            }

            if (imageMethodData.HttpStatusCode != null)
            {
                context.Response.StatusCode = (int)imageMethodData.HttpStatusCode;
                context.Response.End();
                return;
            }

            using (var imageOutputBuffer = new MemoryStream())
            {
                Debug.Assert(!(imageMethodData.Image == null && imageMethodData.ImageByteBuffer == null));
                if (imageMethodData.Image != null)
                {
                    this.RenderImage(this.GetImageThroughTransforms(imageMethodData.Image), imageOutputBuffer);
                }
                else if (imageMethodData.ImageByteBuffer != null)
                {
                    this.RenderImage(this.GetImageThroughTransforms(imageMethodData.ImageByteBuffer), imageOutputBuffer);
                }

                byte[] buffer = imageOutputBuffer.GetBuffer();

                context.Response.OutputStream.Write(buffer, 0, buffer.Length);

                if (this.EnableServerCache)
                {
                    this.ImageStore.Add(cacheId, buffer);
                }

                context.Response.End();
            }
        }

        internal static string GetImageMimeType(ImageFormat format)
        {
            string mimeType = "image/x-unknown";

            if (format.Equals(ImageFormat.Gif))
            {
                mimeType = "image/gif";
            }
            else if (format.Equals(ImageFormat.Jpeg))
            {
                mimeType = "image/jpeg";
            }
            else if (format.Equals(ImageFormat.Png))
            {
                mimeType = "image/png";
            }
            else if (format.Equals(ImageFormat.Bmp) || format.Equals(ImageFormat.MemoryBmp))
            {
                mimeType = "image/bmp";
            }
            else if (format.Equals(ImageFormat.Tiff))
            {
                mimeType = "image/tiff";
            }
            else if (format.Equals(ImageFormat.Icon))
            {
                mimeType = "image/x-icon";
            }

            return mimeType;
        }

        private static string GetIDFromBytes(byte[] buffer)
        {
            using (var hasher = SHA1.Create())
            {
                byte[] result = hasher.ComputeHash(buffer);
                var sb = new StringBuilder();
                foreach (var b in result)
                {
                    sb.Append(b.ToString("X2"));
                }

                return sb.ToString();
            }
        }

        /// <summary>
        /// Returns the encoder for the specified mime type.
        /// </summary>
        /// <param name="mimeType">The mime type of the content.</param>
        /// <returns>ImageCodecInfo.</returns>
        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            var encoders = ImageCodecInfo.GetImageEncoders();
            var e = encoders.FirstOrDefault(x => x.MimeType == mimeType);
            return e;
        }

        private string GetUniqueIDString(HttpContextBase context, string uniqueIdStringSeed)
        {
            var builder = new StringBuilder();
            builder.Append(uniqueIdStringSeed);
            foreach (var key in context.Request.QueryString.AllKeys.OrderBy(k => k))
            {
                builder.Append(key);
                builder.Append(context.Request.QueryString.Get(key));
            }

            foreach (var tran in this.ImageTransforms)
            {
                builder.Append(tran.UniqueString);
            }

            return GetIDFromBytes(ASCIIEncoding.ASCII.GetBytes(builder.ToString()));
        }

        private Image GetImageThroughTransforms(Image image)
        {
            try
            {
                Image temp = image;

                foreach (var tran in this.ImageTransforms)
                {
                    temp = tran.ProcessImage(temp);
                }

                return temp;
            }
            finally
            {
                image?.Dispose();
            }
        }

        // Clear the user image disk cache if userid is found in clear list and is within ClientCacheExpiration time.
        private bool ClearDiskImageCacheIfNecessary(int userId, int portalId, string cacheId)
        {
            var cacheKey = string.Format(DataCache.UserIdListToClearDiskImageCacheKey, portalId);
            Dictionary<int, DateTime> userIds;
            if ((userIds = DataCache.GetCache<Dictionary<int, DateTime>>(cacheKey)) == null || !userIds.ContainsKey(userId))
            {
                return false;
            }

            this.ImageStore.ForcePurgeFromServerCache(cacheId);
            DateTime expiry;

            // The clear mechanism is performed for ClientCacheExpiration timespan so that all active clients clears the cache and don't see old data.
            if (!userIds.TryGetValue(userId, out expiry) || DateTime.UtcNow <= expiry.Add(this.ClientCacheExpiration))
            {
                return true;
            }

            // Remove the userId from the clear list when timespan is > ClientCacheExpiration.
            userIds.Remove(userId);
            DataCache.SetCache(cacheKey, userIds);
            return true;
        }

        private Image GetImageThroughTransforms(byte[] buffer)
        {
            using (var memoryStream = new MemoryStream(buffer))
            {
                return this.GetImageThroughTransforms(Image.FromStream(memoryStream));
            }
        }

        private void RenderImage(Image image, Stream outStream)
        {
            try
            {
                if (this.ContentType == ImageFormat.Gif)
                {
                    var quantizer = new OctreeQuantizer(255, 8);
                    using (var quantized = quantizer.Quantize(image))
                    {
                        quantized.Save(outStream, ImageFormat.Gif);
                    }
                }
                else
                {
                    var eps = new EncoderParameters(1)
                    {
                        Param = { [0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, this.ImageCompression) },
                    };
                    var ici = GetEncoderInfo(GetImageMimeType(this.ContentType));
                    image?.Save(outStream, ici, eps);
                }
            }
            finally
            {
                image?.Dispose();
            }
        }

        private bool IsPicVisibleToCurrentUser(int profileUserId)
        {
            var settings = PortalController.Instance.GetCurrentSettings();
            var profileUser = UserController.Instance.GetUser(settings.PortalId, profileUserId);
            if (profileUser == null)
            {
                return false;
            }

            var photoProperty = profileUser.Profile.GetProperty("Photo");
            if (photoProperty == null)
            {
                return false;
            }

            var currentUser = UserController.Instance.GetCurrentUserInfo();
            return ProfilePropertyAccess.CheckAccessLevel(settings, photoProperty, currentUser, profileUser);
        }
    }
}


text:
layout: page
title: About
permalink: /about/
published: true
---

I hate writing about me sections.  I don't know who I am.

STOP PRESSURING ME!

![_config.yml]({{ site.baseurl }}/images/tina-stage-fright.jpg)

### Contact me

[jimmy.byrd@outlook.com](mailto:jimmy.byrd@outlook.com)

redpajama_set_name: RedPajamaGithub


text:
namespace Traveller.Models
{
    public class BulkCargo
    {
        public string CargoType { get; set; }
        public int dTons { get; set; }
        public string CargoCode { get; set; }
    }
}


text:
A virtual machine for local php development.
Heavily inspired by the official Laravel local development environment (homestead).

## Requirements

mandatory:

- vagrant >= 1.7
- vagrant-hostmanager (for resolving domains)

## Installation

Before you start it is recommended to install some vagrant plugins with the following command:

``` bash
$ vagrant plugin install vagrant-hostmanager
```

Now you can clone the repository

``` bash
$ git clone https://github.com/KatoPue/KatoGrant.git /path/to/target/directory
```

After that, go to the new directory, set your settings in KatoGrant.yaml and

``` bash
$ vagrant up
```

## Update

Go into your KatoGrant install directory and run

``` bash
$ git stash
$ git pull
$ git stash apply
```

After that, resolve conflicts and provision your box with

``` bash
$ vagrant provision
```

## Services

### SSH

connect via putty to localhost:2222 and login with
- user: `vagrant`
- password: `vagrant`

### MySQL

you can directly connect to localhost:3306 or ssh into the vm and also connect to localhost:3306.
This is with default KatoGrant settings (see KatoGrant.yaml)

- user: `root`
- password: `empty`

Manage the service with:
~~~ bash
$ sudo service mysql start|stop|restart
~~~

### php

Since php interpreters are compiled with fpm, there are also services to be handled.
~~~ bash
$ sudo service php-<version>-fpm start|stop|restart
~~~

To retart the fpm process for php 7.0.11 use the following command:
~~~ bash
$ sudo service php-7.0.11-fpm restart
~~~

### Nginx

~~~ bash
$ sudo service nginx start|stop|restart
~~~

# Troubleshooting

## Windows 10 can not `vagrant add box`, fails without error

Install the "Microsoft Visual C++ 2010 Redistributable Package (x86)".


text:
using System;
using System.Collections.Generic;

namespace Duality.Android.Utility.Zip
{
	public interface IZipArchive : IDisposable
	{
		IEnumerable<IZipEntry> Entries { get; }

		IZipEntry CreateEntry(string name);
		IZipEntry GetEntry(string name);
	}
}


text:
"""

Python Interchangeable Virtual Instrument Library

Copyright (c) 2013-2014 Alex Forencich

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

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

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

"""

from .. import ivi
from .. import dcpwr
from .. import scpi

TrackingType = set(['floating'])
TriggerSourceMapping = {
        'immediate': 'imm',
        'bus': 'bus'}

class rigolBaseDCPwr(scpi.dcpwr.Base, scpi.dcpwr.Trigger, scpi.dcpwr.SoftwareTrigger,
                scpi.dcpwr.Measurement):
    "Rigol generic IVI DC power supply driver"

    def __init__(self, *args, **kwargs):
        self.__dict__.setdefault('_instrument_id', '')

        super(rigolBaseDCPwr, self).__init__(*args, **kwargs)

        self._output_count = 3

        self._output_spec = [
            {
                'range': {
                    'P8V': (8.0, 5.0)
                },
                'ovp_max': 8.8,
                'ocp_max': 5.5,
                'voltage_max': 8.0,
                'current_max': 5.0
            },
            {
                'range': {
                    'P30V': (30.0, 2.0)
                },
                'ovp_max': 33.0,
                'ocp_max': 2.2,
                'voltage_max': 30.0,
                'current_max': 2.0
            },
            {
                'range': {
                    'N30V': (-30.0, 2.0)
                },
                'ovp_max': -33.0,
                'ocp_max': 2.2,
                'voltage_max': -30.0,
                'current_max': 2.0
            }
        ]

        self._memory_size = 10

        self._identity_description = "Rigol generic IVI DC power supply driver"
        self._identity_identifier = ""
        self._identity_revision = ""
        self._identity_vendor = ""
        self._identity_instrument_manufacturer = "Rigol Technologies"
        self._identity_instrument_model = ""
        self._identity_instrument_firmware_revision = ""
        self._identity_specification_major_version = 3
        self._identity_specification_minor_version = 0
        self._identity_supported_instrument_models = ['DP831A', 'DP832', 'DP832A']

        ivi.add_method(self, 'memory.save',
                        self._memory_save)
        ivi.add_method(self, 'memory.recall',
                        self._memory_recall)

        self._init_outputs()

    def _memory_save(self, index):
        index = int(index)
        if index < 1 or index > self._memory_size:
            raise OutOfRangeException()
        if not self._driver_operation_simulate:
            self._write("*sav %d" % index)

    def _memory_recall(self, index):
        index = int(index)
        if index < 1 or index > self._memory_size:
            raise OutOfRangeException()
        if not self._driver_operation_simulate:
            self._write("*rcl %d" % index)


text:
from common import *
from hivenavigator import HiveNavigator
from bcdobject import BCDObject, knownguids
from bcdelement import BCDElement

from devicelocate import scan_devices

class BCD:
    _nav = None
    changed = False
    readonly = False
    _objects = None

    def __init__(self, src, readonly=True):
        '''TODO: docs'''
        self.changed = False
        self.readonly = readonly
        self._nav = HiveNavigator(src,)# write=(not readonly))
        self._nav.seek('/')

    def __getitem__(self, guid):
        guid = guid_bracket(guid)
        for o in self.objects:
            if o.guid == guid or knownguids.get(o.guid,[None])[0] == guid:
                return o
        else:
            raise KeyError('No guid ' + guid)

    def __iter__(self):
        return iter(self.objects)

    def __getattr__(self, guid):
        try:
            return self[guid_bracket(guid)]
        except KeyError:
            raise AttributeError('No guid ' + guid)

    def __contains__(self, guid):
        try:
            self[guid]
            return True
        except KeyError:
            return False

    def __hash__(self):
        return hash(frozenset((hash(o) for o in self.objects)))

    def _generate_objects(self):
        self._objects = tuple((BCDObject(self, guid) for guid in self._nav.subkeys('/Objects')))

    def guid_to_known(self, guid):
        guid = guid_bracket(guid)

        v = knownguids.get(guid)

        if v:
            return v[0]

        default = self.default

        if default and guid == default.guid:
            return '{default}'
        else:
            return guid

    @property
    @cacheresult
    def description(self):
        return self._nav.value('KeyName', '/Description')

    @property
    def objects(self):
        if self._objects is None:
            self._generate_objects()
        return self._objects

    @property
    def osloaders(self):
        return [i for i in self.objects
                if i._type_info == (1,2,3) or
                   i._type_info == (1,3,3)]

    @property
    def default(self):
        try:
            return self[self.bootmgr.default]
        except AttributeError:
            #import traceback
            #printerror('Error in default:\n', traceback.format_exc())
            return None

    def dump(self, tab='', verbose=False):
        scan_devices(verbose)
        for o in self.objects:
            o.dump(tab, verbose)

# END OF LINE.


text:
"""Postfix autoreply models."""

from django.db import models
from django.utils import timezone
from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _

from modoboa.admin.models import Mailbox

class ARmessage(models.Model):

    """Auto reply messages."""

    mbox = models.ForeignKey(Mailbox, on_delete=models.CASCADE)
    subject = models.CharField(
        _("subject"), max_length=255,
        help_text=_("The subject that will appear in sent emails")
    )
    content = models.TextField(
        _("content"),
        help_text=_("The content that will appear in sent emails")
    )
    enabled = models.BooleanField(
        _("enabled"),
        help_text=_("Activate/Deactivate your auto reply"),
        default=False
    )
    fromdate = models.DateTimeField(default=timezone.now)
    untildate = models.DateTimeField(null=True, blank=True)

    class Meta:
        db_table = "postfix_autoreply_armessage"

    def __str__(self):
        return smart_text("AR<{}>: {}".format(self.mbox, self.enabled))

class ARhistoric(models.Model):

    """Auto reply historic."""

    armessage = models.ForeignKey(ARmessage, on_delete=models.CASCADE)
    last_sent = models.DateTimeField(auto_now=True)
    sender = models.CharField(max_length=254)

    class Meta:
        unique_together = ("armessage", "sender")
        db_table = "postfix_autoreply_arhistoric"


text:
@class NSString, ProofImgItem;

@protocol ExposeWithProofCgiDelegate <NSObject>

@optional
- (void)OnUploadImgToCdnSuccess:(NSString *)arg1 withProofImgItem:(ProofImgItem *)arg2;
- (void)OnUploadImgToCdnFail:(NSString *)arg1;
- (void)OnGetExposeLinkError;
- (void)OnGetExposeLinkSuccess:(NSString *)arg1;
- (void)OnExposeWithProofError;
- (void)OnExposeWithProofSuccess;
@end


text:
#include <apr_pools.h>
#include <apr_mmap.h>

#include "serf.h"
#include "serf_bucket_util.h"

typedef struct {
    apr_mmap_t *mmap;
    void *current;
    apr_off_t offset;
    apr_off_t remaining;
} mmap_context_t;

SERF_DECLARE(serf_bucket_t *) serf_bucket_mmap_create(
    apr_mmap_t *file_mmap,
    serf_bucket_alloc_t *allocator)
{
    mmap_context_t *ctx;

    ctx = serf_bucket_mem_alloc(allocator, sizeof(*ctx));
    ctx->mmap = file_mmap;
    ctx->current = NULL;
    ctx->offset = 0;
    ctx->remaining = ctx->mmap->size;

    return serf_bucket_create(&serf_bucket_type_mmap, allocator, ctx);
}

static apr_status_t serf_mmap_read(serf_bucket_t *bucket,
                                     apr_size_t requested,
                                     const char **data, apr_size_t *len)
{
    mmap_context_t *ctx = bucket->data;

    if (requested == SERF_READ_ALL_AVAIL || requested > ctx->remaining) {
        *len = ctx->remaining;
    }
    else {
        *len = requested;
    }

    /* ### Would it be faster to call this once and do the offset ourselves? */
    apr_mmap_offset((void**)data, ctx->mmap, ctx->offset);

    /* For the next read... */
    ctx->offset += *len;
    ctx->remaining -= *len;

    if (ctx->remaining == 0) {
        return APR_EOF;
    }
    return APR_SUCCESS;
}

static apr_status_t serf_mmap_readline(serf_bucket_t *bucket,
                                         int acceptable, int *found,
                                         const char **data, apr_size_t *len)
{
    mmap_context_t *ctx = bucket->data;
    const char *end;

    /* ### Would it be faster to call this once and do the offset ourselves? */
    apr_mmap_offset((void**)data, ctx->mmap, ctx->offset);
    end = *data;

    /* XXX An overflow is generated if we pass &ctx->remaining to readline.
     * Not real clear why.
     */
    *len = ctx->remaining;

    serf_util_readline(&end, len, acceptable, found);

    *len = end - *data;

    ctx->offset += *len;
    ctx->remaining -= *len;

    if (ctx->remaining == 0) {
        return APR_EOF;
    }
    return APR_SUCCESS;
}

static apr_status_t serf_mmap_peek(serf_bucket_t *bucket,
                                     const char **data,
                                     apr_size_t *len)
{
    /* Oh, bah. */
    return APR_ENOTIMPL;
}

SERF_DECLARE_DATA const serf_bucket_type_t serf_bucket_type_mmap = {
    "MMAP",
    serf_mmap_read,
    serf_mmap_readline,
    serf_default_read_iovec,
    serf_default_read_for_sendfile,
    serf_default_read_bucket,
    serf_mmap_peek,
    serf_default_destroy_and_data,
};


text:
package sample.hornetq;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Sender {

	@Autowired
	private JmsTemplate jmsTemplate;

	@Scheduled(fixedDelay = 1000L)
	public void send() {
		this.jmsTemplate.convertAndSend("testQueue", "Hello");
	}

}


text:
/*
 * autocomplete_methods.js
 */
(function($) {

module("autocomplete: methods", {
	teardown: function() {
		$( ":ui-autocomplete" ).autocomplete( "destroy" );
	}
});

test("destroy", function() {
	var beforeHtml = $("#autocomplete").parent().html();
	var afterHtml = $("#autocomplete").autocomplete().autocomplete("destroy").parent().html();
	// Opera 9 outputs role="" instead of removing the attribute like everyone else
	if ($.browser.opera) {
		afterHtml = afterHtml.replace(/ role=""/g, "");
	}
	equal( afterHtml, beforeHtml, "before/after html should be the same" );
})

var data = ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby", "python", "c", "scala", "groovy", "haskell", "perl"];

test("search", function() {
	var ac = $("#autocomplete").autocomplete({
		source: data,
		minLength: 0
	});
	ac.autocomplete("search");
	same( $(".ui-menu .ui-menu-item").length, data.length, "all items for a blank search" );

	ac.val("has");
	ac.autocomplete("search")
	same( $(".ui-menu .ui-menu-item").text(), "haskell", "only one item for set input value" );

	ac.autocomplete("search", "ja");
	same( $(".ui-menu .ui-menu-item").length, 2, "only java and javascript for 'ja'" );

	$("#autocomplete").autocomplete("destroy");
})

})(jQuery);


text:
<?php
/**
 * Good Entity
 * @author PiskunovYV
 */

namespace Direct\WrapperBundle\Entity;

use Direct\WrapperBundle\Entity\Banner;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="good")
 */
class Good {
	/**
	 * @ORM\Id
	 * @ORM\Column(type="integer")
	 * @ORM\GeneratedValue(strategy="AUTO")
	 */
	protected $id;

	/**
	 * @ORM\Column(type="integer")
	 */
	protected $GoodID; // идентификатор товара с сайта

	/**
	 * @ORM\Column(length=255)
	 */
	protected $goodName; // имя товара

	/**
	 * @ORM\Column(type="datetime")
	 */
	protected $loadFromSite; // дата-время загрузки товара с сайта

	/**
	 * @ORM\Column(length=255)
	 */
	protected $goodURL; // URL товара

	/**
	 * @ORM\Column(length=255)
	 */
	protected $goodUrlSearch; // URL поиск товара

	/**
	 * @ORM\Column(type="boolean")
	 */
	protected $goodAvailable;

	/**
	 * @ORM\Column(length=255)
	 */
	protected $model; // модель

	/**
	 * @ORM\ManyToOne(targetEntity="Category")
	 */
	protected $Category;

	/**
	 * @ORM\ManyToOne(targetEntity="Manufacturer")
	 */
	protected $manufacturer; // производитель

	/**
	 * @ORM\OneToMany(targetEntity="KeyWord", mappedBy="good", cascade={"persist", "remove"})
	 */
	protected $keywords; // ключевые слова

	/**
	 * @ORM\OneToMany(targetEntity="BannerParam", mappedBy="bannerParam", cascade={"remove"})
	 */
	protected $bannerParam;

	/**
	 * @ORM\OneToMany(targetEntity="GoodPrice", mappedBy="good", cascade={"persist", "remove"})
	 */
	protected $goodPrice; // цена товара

	private $ExpArticle = array(
       '3'     => '/[0-9a-zA-Zа-яА-Я]+\.[0-9a-zA-Zа-яА-Я]+\.[0-9a-zA-Zа-яА-Я]+\.[0-9a-zA-Zа-яА-Я]+/s',
    );

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->keywords = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Удаляем артикул из названия товара
     * @param string $model Модель товара
     */
    private function delArticul($model) {
    	if(isset($this->ExpArticle[$this->manufacturer->getMakeID()])){
    		$newModel = preg_replace($this->ExpArticle[$this->manufacturer->getMakeID()], '', $model);
    		$newModel = trim($newModel);
    		if($newModel){
    			return $newModel;
    		}
    	}
    	return $model;
    }

    /**
     *
     * Проверяет слово на букв-цифр-букв  и цифр-букв-цифр
     * @param str $partName - часть слова
     */
    private function _searchWordNum(&$partName,$adSearch = 1){
    	$combination = array();
    	if(preg_match('/^([a-z]+)([0-9]+)([a-z]+)/i',$partName,$matches)){
    		//Если первое слово начинается из букв-цифр-букв-цифр
    		// Hitachi DS18DVF3 - Hitachi DS18DVF3 -Hitachi DS18, Hitachi DS18DVF3
    		$combination = array(
    		//Hitachi DS18
    				$matches[1].$matches[2],
    				//Hitachi DS18DVF3
    				$partName,
    		);
    		//тем у кого галка есть - оставить как сейчас, а у кого нет - как сейчас, но вернуть обычный исходник для объявления и добавить фразу с "производитель число"
    		if(!$adSearch){
    			$partName = $matches[1].' '.$matches[2];
    			$combination[] = $matches[1].' '.$matches[2].' '.$matches[3];
    			$combination[] = $matches[1].' '.$matches[2];
    		}

    	}else if(preg_match('/^([0-9]+)([a-z]+)([0-9]+)/i',$partName,$matches)){
    		//Если первое слово начинается из цифр-букв-цифр
    		// Hitachi DS18DVF3 - Hitachi 18DVF3DS -Hitachi DS18, Hitachi 18DVF3DS
    		$combination = array(
    		//Hitachi DS18
    				$matches[2].$matches[1],
    				//Hitachi 18DVF3DS
    				$partName,
    		);
    		//тем у кого галка есть - оставить как сейчас, а у кого нет - как сейчас, но вернуть обычный исходник для объявления и добавить фразу с "производитель число"

    		if(!$adSearch){
    			$partName = $matches[1].' '.$matches[2];
    			$combination[] = $matches[1].' '.$matches[2].' '.$matches[3];
    			$combination[] = $matches[1].' '.$matches[2];
    		}
    	}

    	return $combination;
    }

    /**
     * Функция возвращает модель для конкретного товара
     * @return string Модель товара
     */
    public function SearchModel() {
    	$model = "";
    	$name = strtolower($this->goodName);
    	$name = preg_replace("/\s+/", " ", $name);
    	$brand = strtolower(trim($this->manufacturer->getCaption()));
    	$model = substr($name, strpos($name, $brand) + strlen($brand));
    	$model = preg_replace('/([^0-9a-zа-я., ]+)/i', ' ', $model);
    	return trim($model);
    }

    /**
     * Метод формирует ключевые слова и
     * возвращает результат в виде массива
     * @return array
     */
    public function formKeywords() {
    	return split(' ', $this->model);
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set goodName
     *
     * @param string $goodName
     * @return Good
     */
    public function setGoodName($goodName)
    {
        $this->goodName = $goodName;

        return $this;
    }

    /**
     * Get goodName
     *
     * @return string
     */
    public function getGoodName()
    {
        return $this->goodName;
    }

    /**
     * Set model
     *
     * @param string $model
     * @return Good
     */
    public function setModel($model)
    {
        $this->model = $model;

        return $this;
    }

    /**
     * Get model
     *
     * @return string
     */
    public function getModel()
    {
        return $this->model;
    }

    /**
     * Set manufacturer
     *
     * @param \Direct\WrapperBundle\Entity\Manufacturer $manufacturer
     * @return Good
     */
    public function setManufacturer(\Direct\WrapperBundle\Entity\Manufacturer $manufacturer = null)
    {
        $this->manufacturer = $manufacturer;

        return $this;
    }

    /**
     * Get manufacturer
     *
     * @return \Direct\WrapperBundle\Entity\Manufacturer
     */
    public function getManufacturer()
    {
        return $this->manufacturer;
    }

    /**
     * Add keywords
     *
     * @param \Direct\WrapperBundle\Entity\Keyword $keywords
     * @return Good
     */
    public function addKeyword(\Direct\WrapperBundle\Entity\Keyword $keywords)
    {
        $this->keywords[] = $keywords;

        return $this;
    }

    /**
     * Remove keywords
     *
     * @param \Direct\WrapperBundle\Entity\Keyword $keywords
     */
    public function removeKeyword(\Direct\WrapperBundle\Entity\Keyword $keywords)
    {
        $this->keywords->removeElement($keywords);
    }

    /**
     * Get keywords
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getKeywords()
    {
        return $this->keywords;
    }

    /**
     * Set GoodID
     *
     * @param integer $goodID
     * @return Good
     */
    public function setGoodID($goodID)
    {
        $this->GoodID = $goodID;

        return $this;
    }

    /**
     * Get GoodID
     *
     * @return integer
     */
    public function getGoodID()
    {
        return $this->GoodID;
    }

    /**
     * Set loadFromSite
     *
     * @param \DateTime $loadFromSite
     * @return Good
     */
    public function setLoadFromSite($loadFromSite)
    {
        $this->loadFromSite = $loadFromSite;

        return $this;
    }

    /**
     * Get loadFromSite
     *
     * @return \DateTime
     */
    public function getLoadFromSite()
    {
        return $this->loadFromSite;
    }

    /**
     * Set goodURL
     *
     * @param string $goodURL
     * @return Good
     */
    public function setGoodURL($goodURL)
    {
        $this->goodURL = $goodURL;

        return $this;
    }

    /**
     * Get goodURL
     *
     * @return string
     */
    public function getGoodURL()
    {
        return $this->goodURL;
    }

    /**
     * Set goodAvailable
     *
     * @param boolean $goodAvailable
     * @return Good
     */
    public function setGoodAvailable($goodAvailable)
    {
        $this->goodAvailable = $goodAvailable;

        return $this;
    }

    /**
     * Get goodAvailable
     *
     * @return boolean
     */
    public function getGoodAvailable()
    {
        return $this->goodAvailable;
    }

    /**
     * Add goodPrice
     *
     * @param \Direct\WrapperBundle\Entity\GoodPrice $goodPrice
     * @return Good
     */
    public function addGoodPrice(\Direct\WrapperBundle\Entity\GoodPrice $goodPrice)
    {
        $this->goodPrice[] = $goodPrice;

        return $this;
    }

    /**
     * Remove goodPrice
     *
     * @param \Direct\WrapperBundle\Entity\GoodPrice $goodPrice
     */
    public function removeGoodPrice(\Direct\WrapperBundle\Entity\GoodPrice $goodPrice)
    {
        $this->goodPrice->removeElement($goodPrice);
    }

    /**
     * Get goodPrice
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getGoodPrice()
    {
        return $this->goodPrice;
    }

    /**
     * Add manufacturer
     *
     * @param \Direct\WrapperBundle\Entity\Manufacturer $manufacturer
     * @return Good
     */
    public function addManufacturer(\Direct\WrapperBundle\Entity\Manufacturer $manufacturer)
    {
        $this->manufacturer[] = $manufacturer;

        return $this;
    }

    /**
     * Remove manufacturer
     *
     * @param \Direct\WrapperBundle\Entity\Manufacturer $manufacturer
     */
    public function removeManufacturer(\Direct\WrapperBundle\Entity\Manufacturer $manufacturer)
    {
        $this->manufacturer->removeElement($manufacturer);
    }

    /**
     * Set goodUrlSearch
     *
     * @param string $goodUrlSearch
     * @return Good
     */
    public function setGoodUrlSearch($goodUrlSearch)
    {
        $this->goodUrlSearch = $goodUrlSearch;

        return $this;
    }

    /**
     * Get goodUrlSearch
     *
     * @return string
     */
    public function getGoodUrlSearch()
    {
        return $this->goodUrlSearch;
    }

    /**
     * Set Category
     *
     * @param \Direct\WrapperBundle\Entity\Category $category
     * @return Good
     */
    public function setCategory(\Direct\WrapperBundle\Entity\Category $category = null)
    {
        $this->Category = $category;

        return $this;
    }

    /**
     * Get Category
     *
     * @return \Direct\WrapperBundle\Entity\Category
     */
    public function getCategory()
    {
        return $this->Category;
    }

    /**
     * Add bannerParam
     *
     * @param \Direct\WrapperBundle\Entity\BannerParam $bannerParam
     * @return Good
     */
    public function addBannerParam(\Direct\WrapperBundle\Entity\BannerParam $bannerParam)
    {
        $this->bannerParam[] = $bannerParam;

        return $this;
    }

    /**
     * Remove bannerParam
     *
     * @param \Direct\WrapperBundle\Entity\BannerParam $bannerParam
     */
    public function removeBannerParam(\Direct\WrapperBundle\Entity\BannerParam $bannerParam)
    {
        $this->bannerParam->removeElement($bannerParam);
    }

    /**
     * Get bannerParam
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getBannerParam()
    {
        return $this->bannerParam;
    }
}


text:
import bowerstatic
from webtest import TestApp as Client
import os
import sys
import json
from datetime import datetime, timedelta
import pytest

from bowerstatic import compat
from bowerstatic import filesystem_microsecond_autoversion

def test_local_falls_back_to_components():
    bower = bowerstatic.Bower()

    components = bower.components('components', os.path.join(
        os.path.dirname(__file__), 'bower_components'))

    local = bower.local_components('local', components)

    def wsgi(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html;charset=UTF-8')])
        include = local.includer(environ)
        include('jquery/dist/jquery.js')
        return [b'Hello!']

    wrapped = bower.wrap(wsgi)

    c = Client(wrapped)

    response = c.get('/')
    assert response.body == (
        b''
        b'Hello!')

    response = c.get('/bowerstatic/components/jquery/2.1.1/dist/jquery.js')
    assert response.body == b'/* jquery.js 2.1.1 */\n'

def test_local_with_local_component_main():
    bower = bowerstatic.Bower()

    components = bower.components('components', os.path.join(
        os.path.dirname(__file__), 'bower_components'))

    local = bower.local_components('local', components)

    path = os.path.join(
        os.path.dirname(__file__), 'local_component')

    local.component(path, version='2.0')

    def wsgi(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html;charset=UTF-8')])
        include = local.includer(environ)
        include('local_component')
        return [b'Hello!']

    wrapped = bower.wrap(wsgi)

    c = Client(wrapped)

    response = c.get('/')
    assert response.body == (
        b''
        b'Hello!')

    response = c.get('/bowerstatic/local/local_component/2.0/local.js')
    assert response.body == b'/* this is local.js */\n'

def test_local_with_local_component_specific_file():
    bower = bowerstatic.Bower()

    components = bower.components('components', os.path.join(
        os.path.dirname(__file__), 'bower_components'))

    local = bower.local_components('local', components)

    path = os.path.join(
        os.path.dirname(__file__), 'local_component')

    local.component(path, version='2.0')

    def wsgi(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html;charset=UTF-8')])
        include = local.includer(environ)
        include('local_component/local.js')
        return [b'Hello!']

    wrapped = bower.wrap(wsgi)

    c = Client(wrapped)

    response = c.get('/')
    assert response.body == (
        b''
        b'Hello!')

    response = c.get('/bowerstatic/local/local_component/2.0/local.js')
    assert response.body == b'/* this is local.js */\n'

def test_local_internal_dependencies():
    bower = bowerstatic.Bower()

    components = bower.components('components', os.path.join(
        os.path.dirname(__file__), 'bower_components'))

    local = bower.local_components('local', components)

    path = os.path.join(
        os.path.dirname(__file__), 'local_component')

    local.component(path, version='2.0')

    local.resource('local_component/second.js', dependencies=[
        'local_component/local.js'])

    def wsgi(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html;charset=UTF-8')])
        include = local.includer(environ)
        include('local_component/second.js')
        return [b'Hello!']

    wrapped = bower.wrap(wsgi)

    c = Client(wrapped)

    response = c.get('/')

    assert response.body == (
        b''
        b'\n'
        b''
        b'Hello!')

def test_local_external_dependencies():
    bower = bowerstatic.Bower()

    components = bower.components('components', os.path.join(
        os.path.dirname(__file__), 'bower_components'))

    local = bower.local_components('local', components)

    path = os.path.join(
        os.path.dirname(__file__), 'local_component')

    local.component(path, version='2.0')

    local.resource('local_component/local.js', dependencies=[
        'jquery'])

    def wsgi(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html;charset=UTF-8')])
        include = local.includer(environ)
        include('local_component/local.js')
        return [b'Hello!']

    wrapped = bower.wrap(wsgi)

    c = Client(wrapped)

    response = c.get('/')

    assert response.body == (
        b''
        b'\n'
        b''
        b'Hello!')

def test_local_bower_json_dependencies():
    bower = bowerstatic.Bower()

    components = bower.components('components', os.path.join(
        os.path.dirname(__file__), 'bower_components'))

    local = bower.local_components('local', components)

    path = os.path.join(
        os.path.dirname(__file__), 'local_component_deps')

    local.component(path, version='2.0')

    def wsgi(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html;charset=UTF-8')])
        include = local.includer(environ)
        include('local_component')
        return [b'Hello!']

    wrapped = bower.wrap(wsgi)

    c = Client(wrapped)

    response = c.get('/')

    assert response.body == (
        b''
        b'\n'
        b''
        b'Hello!')

def test_local_with_missing_version():
    bower = bowerstatic.Bower()

    components = bower.components('components', os.path.join(
        os.path.dirname(__file__), 'bower_components'))

    local = bower.local_components('local', components)

    path = os.path.join(
        os.path.dirname(__file__), 'local_component_missing_version')

    with pytest.raises(ValueError) as err:
        local.component(path, version=None)
    assert str(err.value).startswith('Missing _release and version in')
    assert str(err.value).endswith('/tests/local_component_missing_version')

# FIXME: strictly speaking Linux ext3 also has a failing bug here,
# but I don't know how to reliably detect whether the filesystem has
# only second granularity so this will have to do
@pytest.mark.skipif(
    sys.platform == 'darwin',
    reason="Microsecond granularity does not work on Mac OS X")
def test_local_with_microsecond_auto_version(tmpdir):
    # need to cut things a bit of slack, as filesystem time can apparently
    # be ahead slightly
    after_dt = datetime.now() - timedelta(seconds=1)

    # create a bower component directory
    component_dir = tmpdir.mkdir('component')
    bower_json_file = component_dir.join('bower.json')
    bower_json_file.write(json.dumps({
        'name': 'component',
        'version': '2.1',  # should be ignored
        'main': 'main.js'
    }))
    main_js_file = component_dir.join('main.js')
    main_js_file.write('/* this is main.js */')

    # now expose it through local
    bower = bowerstatic.Bower(autoversion=filesystem_microsecond_autoversion)

    components = bower.components('components', os.path.join(
        os.path.dirname(__file__), 'bower_components'))

    local = bower.local_components('local', components)

    local.component(component_dir.strpath, version=None)

    def wsgi(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html;charset=UTF-8')])
        include = local.includer(environ)
        include('component/main.js')
        return [b'Hello!']

    wrapped = bower.wrap(wsgi)

    c = Client(wrapped)

    response = c.get('/')
    before_dt = datetime.now()

    def get_url_dt(response):
        s = compat.text_type(response.body, 'UTF-8')
        start = s.find('src="') + len('src="')
        end = s.find('"', start)
        url = s[start:end]
        parts = url.split('/')
        url_dt_str = parts[4]
        url_dt = datetime.strptime(url_dt_str, '%Y-%m-%dT%H:%M:%S.%f')
        return url_dt_str, url_dt

    url_dt_str, url_dt = get_url_dt(response)

    assert url_dt >= after_dt
    assert url_dt <= before_dt

    response = c.get('/bowerstatic/local/component/%s/main.js' % url_dt_str)
    assert response.body == b'/* this is main.js */'

    after_dt = datetime.now() - timedelta(seconds=1)

    # now we modify a file
    main_js_file.write('/* this is main.js, modified */')

    response = c.get('/')

    before_dt = datetime.now()

    original_url_dt_str, original_url_dt = url_dt_str, url_dt
    url_dt_str, url_dt = get_url_dt(response)
    assert original_url_dt_str != url_dt_str
    assert url_dt >= after_dt
    assert url_dt <= before_dt
    assert url_dt > original_url_dt

    c.get('/bowerstatic/local/component/%s/main.js' % original_url_dt_str,
          status=404)
    response = c.get('/bowerstatic/local/component/%s/main.js' %
                     url_dt_str)
    assert response.body == b'/* this is main.js, modified */'

def test_local_with_second_auto_version(tmpdir):
    # need to cut things a bit of slack, as filesystem time can apparently
    # be ahead slightly
    after_dt = datetime.now() - timedelta(seconds=1)

    # create a bower component directory
    component_dir = tmpdir.mkdir('component')
    bower_json_file = component_dir.join('bower.json')
    bower_json_file.write(json.dumps({
        'name': 'component',
        'version': '2.1',  # should be ignored
        'main': 'main.js'
    }))
    main_js_file = component_dir.join('main.js')
    main_js_file.write('/* this is main.js */')

    # now expose it through local
    # the default autoversioning scheme uses second granularity
    bower = bowerstatic.Bower()

    components = bower.components('components', os.path.join(
        os.path.dirname(__file__), 'bower_components'))

    local = bower.local_components('local', components)

    local.component(component_dir.strpath, version=None)

    def wsgi(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html;charset=UTF-8')])
        include = local.includer(environ)
        include('component/main.js')
        return [b'Hello!']

    wrapped = bower.wrap(wsgi)

    c = Client(wrapped)

    response = c.get('/')
    before_dt = datetime.now()

    def get_url_dt(response):
        s = compat.text_type(response.body, 'UTF-8')
        start = s.find('src="') + len('src="')
        end = s.find('"', start)
        url = s[start:end]
        parts = url.split('/')
        url_dt_str = parts[4]
        url_dt = datetime.strptime(url_dt_str, '%Y-%m-%dT%H:%M:%S')
        return url_dt_str, url_dt

    url_dt_str, url_dt = get_url_dt(response)

    assert url_dt >= after_dt
    assert url_dt <= before_dt

    response = c.get('/bowerstatic/local/component/%s/main.js' % url_dt_str)
    assert response.body == b'/* this is main.js */'

    after_dt = datetime.now() - timedelta(seconds=1)

    # now we modify a file
    main_js_file.write('/* this is main.js, modified */')

    response = c.get('/')

    before_dt = datetime.now()

    original_url_dt = url_dt
    url_dt_str, url_dt = get_url_dt(response)
    assert url_dt >= after_dt
    assert url_dt <= before_dt
    assert url_dt >= original_url_dt

    response = c.get('/bowerstatic/local/component/%s/main.js' %
                     url_dt_str)
    assert response.body == b'/* this is main.js, modified */'


text:
<?php namespace Model;

class Models extends \Eloquent
{
    public function unit()
    {
        return $this->belongsTo('\Model\Units', 'unit_id');
    }

    public function temperaturesForProbes()
    {
        return $this->belongsTo('\Model\TemperaturesForProbes', 'target_id');
    }

    public function temperaturesForPods()
    {
        return $this->belongsTo('\Model\TemperaturesForPods', 'target_id');
    }

    public function temperaturesForGoodsIn()
    {
        return $this->belongsTo('\Model\TemperaturesForGoodsIn', 'target_id');
    }

    public function trainingRecords()
    {
        return $this->belongsTo('\Model\TrainingRecords', 'target_id');
    }

    public function foodIncidents()
    {
        return $this->belongsTo('\Model\FoodIncidents', 'target_id');
    }

    public function navinotes()
    {
        return $this->belongsTo('\Model\Navinotes', 'target_id');
    }

    public function notifications()
    {
        return $this->belongsTo('\Model\Notifications', 'target_id');
    }

    public function supportTickets()
    {
        return $this->belongsTo('\Model\SupportTickets', 'target_id');
    }

    public function supportReplies()
    {
        return $this->belongsTo('\Model\SupportReplies', 'target_id');
    }

    public function healthQuestionnaires()
    {
        return $this->belongsTo('\Model\HealthQuestionnaires', 'target_id');
    }

    public function cleaningSchedulesItems()
    {
        return $this->belongsTo('\Model\CleaningSchedulesItems', 'target_id');
    }

    public function checkListItems()
    {
        return $this->belongsTo('\Model\CheckListItems', 'target_id');
    }

    public function formsAnswers()
    {
        return $this->belongsTo('\Model\FormsAnswers','target_id');
    }

    public function target()
    {
        return $this->{$this->target_type};
    }

    public function options ($type = null)
    {
        $parent = \Model\OptionsMenu::with([ 'childrens' => function($query) use($type) {
            if($type == 'inputs')
                $query->whereNotIn('type',['feature']);
        }])->whereIdentifier($this->getTable())->whereType('root')->first();
        $optIds = ($parent && $parent -> childrens) ? $parent -> childrens -> lists('id') : [];
        return $this->hasMany('\Model\Options', 'target_id')->whereTargetType($this->getTable())->whereIn('option_id',$optIds);
    }

    public function getDisabledModules()
    {
        $option = $this->getOption('manage_unit_modules');
        if($option){
            $values = unserialize($option->values);
            return isset($values['disabled_modules'])?$values['disabled_modules']:[];
        }
        return false;
    }

    public function hasOption( $identifier )
    {
        $options = $this -> options() -> get();
        if($options->count())
            foreach ($options as $option) {
                if( $option->option->identifier == $identifier )
                {
                    return true;
                }
            }
        return false;
    }

    public function getOption( $identifier )
    {
        $options = $this -> options() -> get();
        if($options->count())
            foreach ($options as $option) {
                if( $option->option->identifier == $identifier )
                {
                    return $option;
                }
            }
        return null;
    }

    public function getOptionById( $id )
    {
        $options = $this -> options() -> get();
        if($options->count())
            foreach ($options as $option) {
                if( $option->option->id == $id )
                {
                    return $option;
                }
            }
        return null;
    }

    public function checkAccess()
    {
        $user = \Auth::user();
        if ( $user -> hasRole('local-manager') || $user -> hasRole('visitor') )
            return $this -> unit_id == $user -> unit() -> id;
        elseif ( $user -> hasRole('hq-manager') ) {
            return in_array($this -> unit_id, $user -> headquarter() -> getUnitsId());
        }
        elseif ( $user -> hasRole('admin') ) {
            return true;
        }
        return false;
    }

    public function date($date=null)
    {
        $tz = \Config::get('app.timezone');
        if(\Auth::check()){
            $tz = \Auth::user()->timezone;
        }
        if(is_null($date)) {
            $date = $this->created_at;
        }
        $date = \Carbon::createFromFormat('Y-m-d H:i:s',$date,'UTC')->timezone($tz);
        $date = ($date->timestamp <= 0) ? '2010-10-10 10:10:10' : $date;
        return \String::date($date);
    }

    public function created_at($date=null)
    {
        $tz = \Config::get('app.timezone');
        if(\Auth::check()){
            $tz = \Auth::user()->timezone;
        }
        if(is_null($date)) {
            $date = $this->created_at;
        }
        $date = ($date->timestamp <= 0) ? '2010-10-10 10:10:10' : $date;
        return \Carbon::createFromFormat('Y-m-d H:i:s',$date,'UTC')->timezone($tz)->format('d-m-Y H:i');
    }

    public function updated_at()
    {
        return $this->date($this->updated_at);
    }

    public function expiry_date()
    {
        $tz = \Config::get('app.timezone');
        if(\Auth::check()){
            $tz = \Auth::user()->timezone;
        }
        return \Carbon::createFromFormat('Y-m-d H:i:s',$this->expiry_date,'UTC')->timezone($tz)->format('d-m-Y H:i');
    }

    public function date_start()
    {
        return $this->date($this->start);
    }

    public function date_end()
    {
        return $this->date($this->end);
    }

    public function getSectionName()
    {
        $table  = $this -> getTable();
        return \Lang::get('/common/sections.'.$table.'.title');
    }

    public function filterValidAscii($text)
    {
        return preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $text);
    }

    public function getOutstandingTaskItemTitle($details = NULL)
    {
        return 'getUrl('item').'">'.\Lang::get('/common/sections.'.$this -> getTable().'.messages.outstanding_tasks').'';
    }

    public static function moreLessButton($bid){
        return '<button class="text-xs label btn-green btn pull-right" data-toggle="class:show animated fadeInRight" data-target="#'.$bid.'">

                More

                Less
                </button>';
    }

    public function getNotificationTemplate($dest,$content, $bid){
        $outerClass = $dest == 'header' ? 'm-b b-b' : '';
        $ico        = $dest == 'header' ? '' : '';
        $createdAt  = $dest == 'header' ? 'Created at: '.$this->created_at().'' : '';

        return
            '
'.
                $ico.
                ''.$this->moreLessButton($bid).
                        $createdAt.
                        $content.
                    ''.
                ''.
            '
';
    }

    public function getSchedulesDate()
    {
        $start =  \Carbon::parse($this->start)->timezone($this->tz);
        $end   =  \Carbon::parse($this->end)->timezone($this->tz);
        if($this -> all_day){
            $start = $start -> format('d-m-Y');
            $end   = $end   -> format('d-m-Y');
            $dispDate = ($start==$end) ? $start : $start . ' : ' . $end;
        }else{
            $start = $start -> format('d-m-Y H:i');
            $end   = $end   -> format('d-m-Y H:i');
            $dispDate = ($start==$end) ? $start : $start . ' : ' . $end;
        }
        return $dispDate;
    }
}


text:
/* ***********************************************************
 * This file was automatically generated on 2014-08-11.      *
 *                                                           *
 * Bindings Version 2.0.2                                    *
 *                                                           *
 * If you have a bugfix for this file and want to commit it, *
 * please fix the bug in the generator. You can find a link  *
 * to the generator git on tinkerforge.com                   *
 *************************************************************/

var Device = require('./Device');

BrickletGPS.DEVICE_IDENTIFIER = 222;
BrickletGPS.CALLBACK_COORDINATES = 17;
BrickletGPS.CALLBACK_STATUS = 18;
BrickletGPS.CALLBACK_ALTITUDE = 19;
BrickletGPS.CALLBACK_MOTION = 20;
BrickletGPS.CALLBACK_DATE_TIME = 21;
BrickletGPS.FUNCTION_GET_COORDINATES = 1;
BrickletGPS.FUNCTION_GET_STATUS = 2;
BrickletGPS.FUNCTION_GET_ALTITUDE = 3;
BrickletGPS.FUNCTION_GET_MOTION = 4;
BrickletGPS.FUNCTION_GET_DATE_TIME = 5;
BrickletGPS.FUNCTION_RESTART = 6;
BrickletGPS.FUNCTION_SET_COORDINATES_CALLBACK_PERIOD = 7;
BrickletGPS.FUNCTION_GET_COORDINATES_CALLBACK_PERIOD = 8;
BrickletGPS.FUNCTION_SET_STATUS_CALLBACK_PERIOD = 9;
BrickletGPS.FUNCTION_GET_STATUS_CALLBACK_PERIOD = 10;
BrickletGPS.FUNCTION_SET_ALTITUDE_CALLBACK_PERIOD = 11;
BrickletGPS.FUNCTION_GET_ALTITUDE_CALLBACK_PERIOD = 12;
BrickletGPS.FUNCTION_SET_MOTION_CALLBACK_PERIOD = 13;
BrickletGPS.FUNCTION_GET_MOTION_CALLBACK_PERIOD = 14;
BrickletGPS.FUNCTION_SET_DATE_TIME_CALLBACK_PERIOD = 15;
BrickletGPS.FUNCTION_GET_DATE_TIME_CALLBACK_PERIOD = 16;
BrickletGPS.FUNCTION_GET_IDENTITY = 255;
BrickletGPS.FIX_NO_FIX = 1;
BrickletGPS.FIX_2D_FIX = 2;
BrickletGPS.FIX_3D_FIX = 3;
BrickletGPS.RESTART_TYPE_HOT_START = 0;
BrickletGPS.RESTART_TYPE_WARM_START = 1;
BrickletGPS.RESTART_TYPE_COLD_START = 2;
BrickletGPS.RESTART_TYPE_FACTORY_RESET = 3;

function BrickletGPS(uid, ipcon) {
	//Device for receiving GPS position

	/*
	Creates an object with the unique device ID *uid* and adds it to
	the IP Connection *ipcon*.
	*/
	Device.call(this, this, uid, ipcon);
	BrickletGPS.prototype = Object.create(Device);
	this.responseExpected = {};
	this.callbackFormats = {};
	this.APIVersion = [2, 0, 0];
	this.responseExpected[BrickletGPS.FUNCTION_GET_COORDINATES] = Device.RESPONSE_EXPECTED_ALWAYS_TRUE;
	this.responseExpected[BrickletGPS.FUNCTION_GET_STATUS] = Device.RESPONSE_EXPECTED_ALWAYS_TRUE;
	this.responseExpected[BrickletGPS.FUNCTION_GET_ALTITUDE] = Device.RESPONSE_EXPECTED_ALWAYS_TRUE;
	this.responseExpected[BrickletGPS.FUNCTION_GET_MOTION] = Device.RESPONSE_EXPECTED_ALWAYS_TRUE;
	this.responseExpected[BrickletGPS.FUNCTION_GET_DATE_TIME] = Device.RESPONSE_EXPECTED_ALWAYS_TRUE;
	this.responseExpected[BrickletGPS.FUNCTION_RESTART] = Device.RESPONSE_EXPECTED_FALSE;
	this.responseExpected[BrickletGPS.FUNCTION_SET_COORDINATES_CALLBACK_PERIOD] = Device.RESPONSE_EXPECTED_TRUE;
	this.responseExpected[BrickletGPS.FUNCTION_GET_COORDINATES_CALLBACK_PERIOD] = Device.RESPONSE_EXPECTED_ALWAYS_TRUE;
	this.responseExpected[BrickletGPS.FUNCTION_SET_STATUS_CALLBACK_PERIOD] = Device.RESPONSE_EXPECTED_TRUE;
	this.responseExpected[BrickletGPS.FUNCTION_GET_STATUS_CALLBACK_PERIOD] = Device.RESPONSE_EXPECTED_ALWAYS_TRUE;
	this.responseExpected[BrickletGPS.FUNCTION_SET_ALTITUDE_CALLBACK_PERIOD] = Device.RESPONSE_EXPECTED_TRUE;
	this.responseExpected[BrickletGPS.FUNCTION_GET_ALTITUDE_CALLBACK_PERIOD] = Device.RESPONSE_EXPECTED_ALWAYS_TRUE;
	this.responseExpected[BrickletGPS.FUNCTION_SET_MOTION_CALLBACK_PERIOD] = Device.RESPONSE_EXPECTED_TRUE;
	this.responseExpected[BrickletGPS.FUNCTION_GET_MOTION_CALLBACK_PERIOD] = Device.RESPONSE_EXPECTED_ALWAYS_TRUE;
	this.responseExpected[BrickletGPS.FUNCTION_SET_DATE_TIME_CALLBACK_PERIOD] = Device.RESPONSE_EXPECTED_TRUE;
	this.responseExpected[BrickletGPS.FUNCTION_GET_DATE_TIME_CALLBACK_PERIOD] = Device.RESPONSE_EXPECTED_ALWAYS_TRUE;
	this.responseExpected[BrickletGPS.CALLBACK_COORDINATES] = Device.RESPONSE_EXPECTED_ALWAYS_FALSE;
	this.responseExpected[BrickletGPS.CALLBACK_STATUS] = Device.RESPONSE_EXPECTED_ALWAYS_FALSE;
	this.responseExpected[BrickletGPS.CALLBACK_ALTITUDE] = Device.RESPONSE_EXPECTED_ALWAYS_FALSE;
	this.responseExpected[BrickletGPS.CALLBACK_MOTION] = Device.RESPONSE_EXPECTED_ALWAYS_FALSE;
	this.responseExpected[BrickletGPS.CALLBACK_DATE_TIME] = Device.RESPONSE_EXPECTED_ALWAYS_FALSE;
	this.responseExpected[BrickletGPS.FUNCTION_GET_IDENTITY] = Device.RESPONSE_EXPECTED_ALWAYS_TRUE;
	this.callbackFormats[BrickletGPS.CALLBACK_COORDINATES] = 'I c I c H H H H';
	this.callbackFormats[BrickletGPS.CALLBACK_STATUS] = 'B B B';
	this.callbackFormats[BrickletGPS.CALLBACK_ALTITUDE] = 'I I';
	this.callbackFormats[BrickletGPS.CALLBACK_MOTION] = 'I I';
	this.callbackFormats[BrickletGPS.CALLBACK_DATE_TIME] = 'I I';

	this.getCoordinates = function(returnCallback, errorCallback) {
		/*
		Returns the GPS coordinates. Latitude and longitude are given in the
		``DD.dddddd°`` format, the value 57123468 means 57.123468°.
		The parameter ``ns`` and ``ew`` are the cardinal directions for
		latitude and longitude. Possible values for ``ns`` and ``ew`` are 'N', 'S', 'E'
		and 'W' (north, south, east and west).

		PDOP, HDOP and VDOP are the dilution of precision (DOP) values. They specify
		the additional multiplicative effect of GPS satellite geometry on GPS
		precision. See
		`here <http://en.wikipedia.org/wiki/Dilution_of_precision_(GPS)>`__
		for more information. The values are give in hundredths.

		EPE is the "Estimated Position Error". The EPE is given in cm. This is not the
		absolute maximum error, it is the error with a specific confidence. See
		`here <http://www.nps.gov/gis/gps/WhatisEPE.html>`__ for more information.

		This data is only valid if there is currently a fix as indicated by
		:func:`GetStatus`.
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_GET_COORDINATES, [], '', 'I c I c H H H H', returnCallback, errorCallback);
	};
	this.getStatus = function(returnCallback, errorCallback) {
		/*
		Returns the current fix status, the number of satellites that are in view and
		the number of satellites that are currently used.

		Possible fix status values can be:

		.. csv-table::
		 :header: "Value", "Description"
		 :widths: 10, 100

		 "1", "No Fix, :func:`GetCoordinates` and :func:`GetAltitude` return invalid data"
		 "2", "2D Fix, only :func:`GetCoordinates` returns valid data"
		 "3", "3D Fix, :func:`GetCoordinates` and :func:`GetAltitude` return valid data"

		There is also a :ref:`blue LED <gps_bricklet_fix_led>` on the Bricklet that
		indicates the fix status.
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_GET_STATUS, [], '', 'B B B', returnCallback, errorCallback);
	};
	this.getAltitude = function(returnCallback, errorCallback) {
		/*
		Returns the current altitude and corresponding geoidal separation.

		Both values are given in cm.

		This data is only valid if there is currently a fix as indicated by
		:func:`GetStatus`.
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_GET_ALTITUDE, [], '', 'I I', returnCallback, errorCallback);
	};
	this.getMotion = function(returnCallback, errorCallback) {
		/*
		Returns the current course and speed. Course is given in hundredths degree
		and speed is given in hundredths km/h. A course of 0° means the Bricklet is
		traveling north bound and 90° means it is traveling east bound.

		Please note that this only returns useful values if an actual movement
		is present.

		This data is only valid if there is currently a fix as indicated by
		:func:`GetStatus`.
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_GET_MOTION, [], '', 'I I', returnCallback, errorCallback);
	};
	this.getDateTime = function(returnCallback, errorCallback) {
		/*
		Returns the current date and time. The date is
		given in the format ``ddmmyy`` and the time is given
		in the format ``hhmmss.sss``. For example, 140713 means
		14.05.13 as date and 195923568 means 19:59:23.568 as time.
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_GET_DATE_TIME, [], '', 'I I', returnCallback, errorCallback);
	};
	this.restart = function(restartType, returnCallback, errorCallback) {
		/*
		Restarts the GPS Bricklet, the following restart types are available:

		.. csv-table::
		 :header: "Value", "Description"
		 :widths: 10, 100

		 "0", "Hot start (use all available data in the NV store)"
		 "1", "Warm start (don't use ephemeris at restart)"
		 "2", "Cold start (don't use time, position, almanacs and ephemeris at restart)"
		 "3", "Factory reset (clear all system/user configurations at restart)"
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_RESTART, [restartType], 'B', '', returnCallback, errorCallback);
	};
	this.setCoordinatesCallbackPeriod = function(period, returnCallback, errorCallback) {
		/*
		Sets the period in ms with which the :func:`Coordinates` callback is triggered
		periodically. A value of 0 turns the callback off.

		:func:`Coordinates` is only triggered if the coordinates changed since the
		last triggering.

		The default value is 0.
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_SET_COORDINATES_CALLBACK_PERIOD, [period], 'I', '', returnCallback, errorCallback);
	};
	this.getCoordinatesCallbackPeriod = function(returnCallback, errorCallback) {
		/*
		Returns the period as set by :func:`SetCoordinatesCallbackPeriod`.
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_GET_COORDINATES_CALLBACK_PERIOD, [], '', 'I', returnCallback, errorCallback);
	};
	this.setStatusCallbackPeriod = function(period, returnCallback, errorCallback) {
		/*
		Sets the period in ms with which the :func:`Status` callback is triggered
		periodically. A value of 0 turns the callback off.

		:func:`Status` is only triggered if the status changed since the
		last triggering.

		The default value is 0.
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_SET_STATUS_CALLBACK_PERIOD, [period], 'I', '', returnCallback, errorCallback);
	};
	this.getStatusCallbackPeriod = function(returnCallback, errorCallback) {
		/*
		Returns the period as set by :func:`SetStatusCallbackPeriod`.
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_GET_STATUS_CALLBACK_PERIOD, [], '', 'I', returnCallback, errorCallback);
	};
	this.setAltitudeCallbackPeriod = function(period, returnCallback, errorCallback) {
		/*
		Sets the period in ms with which the :func:`Altitude` callback is triggered
		periodically. A value of 0 turns the callback off.

		:func:`Altitude` is only triggered if the altitude changed since the
		last triggering.

		The default value is 0.
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_SET_ALTITUDE_CALLBACK_PERIOD, [period], 'I', '', returnCallback, errorCallback);
	};
	this.getAltitudeCallbackPeriod = function(returnCallback, errorCallback) {
		/*
		Returns the period as set by :func:`SetAltitudeCallbackPeriod`.
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_GET_ALTITUDE_CALLBACK_PERIOD, [], '', 'I', returnCallback, errorCallback);
	};
	this.setMotionCallbackPeriod = function(period, returnCallback, errorCallback) {
		/*
		Sets the period in ms with which the :func:`Motion` callback is triggered
		periodically. A value of 0 turns the callback off.

		:func:`Motion` is only triggered if the motion changed since the
		last triggering.

		The default value is 0.
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_SET_MOTION_CALLBACK_PERIOD, [period], 'I', '', returnCallback, errorCallback);
	};
	this.getMotionCallbackPeriod = function(returnCallback, errorCallback) {
		/*
		Returns the period as set by :func:`SetMotionCallbackPeriod`.
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_GET_MOTION_CALLBACK_PERIOD, [], '', 'I', returnCallback, errorCallback);
	};
	this.setDateTimeCallbackPeriod = function(period, returnCallback, errorCallback) {
		/*
		Sets the period in ms with which the :func:`DateTime` callback is triggered
		periodically. A value of 0 turns the callback off.

		:func:`DateTime` is only triggered if the date or time changed since the
		last triggering.

		The default value is 0.
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_SET_DATE_TIME_CALLBACK_PERIOD, [period], 'I', '', returnCallback, errorCallback);
	};
	this.getDateTimeCallbackPeriod = function(returnCallback, errorCallback) {
		/*
		Returns the period as set by :func:`SetDateTimeCallbackPeriod`.
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_GET_DATE_TIME_CALLBACK_PERIOD, [], '', 'I', returnCallback, errorCallback);
	};
	this.getIdentity = function(returnCallback, errorCallback) {
		/*
		Returns the UID, the UID where the Bricklet is connected to,
		the position, the hardware and firmware version as well as the
		device identifier.

		The position can be 'a', 'b', 'c' or 'd'.

		The device identifier numbers can be found :ref:`here <device_identifier>`.
		|device_identifier_constant|
		*/
		this.ipcon.sendRequest(this, BrickletGPS.FUNCTION_GET_IDENTITY, [], '', 's8 s8 c B3 B3 H', returnCallback, errorCallback);
	};
}

module.exports = BrickletGPS;


text:
package de.ustutt.iaas.lcm.labs.standalone;

import java.util.Date;

import org.apache.camel.Exchange;
import org.apache.camel.LoggingLevel;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jackson.JacksonDataFormat;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.apache.camel.spi.DataFormat;

import com.fasterxml.jackson.databind.JsonNode;

class MyRouteBuilder extends RouteBuilder {

	@Override
	public void configure() throws Exception {

		from("timer:foo?delay={{delaymillisecs}}&period={{periodmillisecs}}")
		.process(new Processor() {
					public void process(Exchange exchange) throws Exception {
							System.out.println("Invoked timer at " + new Date());
					}
				})
		.bean("foo")
		.noAutoStartup();

		// test route 1
		from("bla:queue:A")
		.log(LoggingLevel.INFO, "...msg...")
		.to("bla:topic:B")
		.bean("foo") // only sysout
		.to("log:bla")
		.bean("bean1") // JMS onMessage, unmarshal text into JsonNode
		.routeId("route1");

		// JSON text <-> JsonNode object
		DataFormat jsonFormat = new JacksonDataFormat(JsonNode.class);

		// test route 2
		from("bla:topic:B")
		.to("log:route2")
		//.unmarshal().json(JsonLibrary.Jackson, JsonNode.class, true)
		.unmarshal(jsonFormat)
			.description("JSON_text2node", "JSON text -> JsonNode object", null)
		.to("log:route2")
		.bean("debugBean")
			.description("debugBean", "prints information about the camel message body to sysout", null)
		//.marshal().json(JsonLibrary.Jackson, JsonNode.class, true)
		.marshal(jsonFormat)
			.description("JSON_node2text", "JsonNode object -> JSON text", null)
		.to("log:route2")
		.bean("debugBean")
		.to("bla:queue:C")
		// set route ID
		.routeId("route2");

		from("bla:queue:C")
		.to("log:route3")
		.choice()
		    .when().jsonpath("$[?(@.category == 'cat-A')]")
		    	.log("choice 1, cat-A")
			.when().jsonpath("$[?(@.category == 'cat-B')]")
				.log("choice 2, cat-B")
			.otherwise()
				.log("otherwise")
			.end()
		.to("log:route3")
		.routeId("route3");

	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Digital Art Crew</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Catamaran:100,200,300,400,500,600,700,800,900" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Muli" rel="stylesheet">

    <link rel="stylesheet" href="vendor/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="vendor/simple-line-icons/css/simple-line-icons.css">

    <link href="css/new-age.css" rel="stylesheet">

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

            </button>
            Digital Art Crew

About

Our Program

              Workshops

Intro to Project Management

Intro to Photography

Intro to Graphic Design

Intro to HTML & CSS

Intro to JavaScript

Personal Website Project

Professional Development

Intro to Visual Programming

Final Project review

Pricing

Team

Testimonials

Contact

          Login

                    Login via

                         Facebook
                         Twitter

                    or
                    <form class="form" role="form" method="post" action="login" accept-charset="UTF-8" id="login-nav">

                           Email address
                           <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Email address" required>

                           Password
                           <input type="password" class="form-control" id="exampleInputPassword2" placeholder="Password" required>

Forget the password ?

                           <button type="submit" class="btn btn-primary btn-block">Sign in</button>

                               <input type="checkbox"> keep me logged-in

                   </form>

                New here ? Join Us

    <video autoplay loop  id="bgvid">
    <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunxxxny.webm" type="video/webm">
   <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4">
  </video>

Site Currently Construction - Coming January 2017!

Digital Art Crew is a multimedia and tech education training company designed to teach individuals the fundamentals of design and computer programming through an online e-learning video platform.

                        Ready to get started?

Our Program

Our program is an affordable, 12-week course designed to get you prepared to land an entry-level position in the field of digital art and technology. Courses can be taken as individual modules or complete the entire program. By the end of the 8 week course you will have completed a personal website, professional resume and completed an interactive project.

DAC Workshops

                            Intro to Project Management

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                               tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                               quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                               consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                               cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                               proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

                            Intro to Photography

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                              tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                              quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                              consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                              cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                              proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

                            Intro to Graphich Design

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                                tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                                quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                                cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                                proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

                                Intro to HTML & CSS

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                                 tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                                 quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                 consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                                 cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                                 proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

                                Intro to JavaScript

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                                    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                                    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                                    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                                    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

                                    Personal Web Project

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                                       tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                                       quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                       consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                                       cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                                       proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

                                    Intro to Professional Development

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                                      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                                      quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                      consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                                      cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                                      proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

                                    Intro to Visual Programming

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                                       tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                                       quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                       consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                                       cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                                       proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

                                    Final Project

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                                       tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                                       quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                       consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                                       cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                                       proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Pricing Sign up as individual or an organization

Student By Course

$49 / year

 Course Certificate

 Unlimited Access to Curriculum

 Online Support

                            SIGN UP NOW!

Student by Program

$249 / year

 Course Certificate

 Unlimited Access to Curriculum

 Online Support

                            SIGN UP NOW!

Business - 1

$1499 / year

 Course Certificate for up to 10

 Unlimited Access to Curriculum

 Online Support

                            SIGN UP NOW!

Business - 2

$2999 / year

 Course Certificate for up to 25

 Unlimited Access to Curriculum

 Online Support

                            SIGN UP NOW!

Business - 3

$7499 / year

 Course Certificate for up to 100

 Unlimited Access to Curriculum

 Online Support

                            SIGN UP NOW!

Web Consultation

$75 / hour

 Discuss project with professional

 Unlimited projects

 24/7 support

                            SIGN UP NOW!

Design Consultation

$75 / hour

 Personal use

 Unlimited projects

 24/7 support

                            SIGN UP NOW!

Online Mentoring

$75 / hour

Online Professional Mentoring

 Unlimited projects

 24/7 support

                            SIGN UP NOW!

Our Team

Donte Burney

                            Job Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iste saepe et quisquam nesciunt maxime.

Garrett Bradley

                            Job Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iste saepe et quisquam nesciunt maxime.

Karim Mayfield

                            Job Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iste saepe et quisquam nesciunt maxime.

Daniel Robertson

                            Job Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iste saepe et quisquam nesciunt maxime.

John Smith

                            Job Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iste saepe et quisquam nesciunt maxime.

John Smith

                            Job Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iste saepe et quisquam nesciunt maxime.

Our Customers

Experience

                  "We are all constructed
                  out of our self dialogue."

— BRYANT MCGILL

Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum.
                Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum

              "We are all constructed
              out of our self dialogue."

— BRYANT MCGILL

Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum.
            Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum

Email Donte Burney at digitalartcrew@gmail.com

© 2016 Digital Art Crew. All Rights Reserved.


text:
package org.terasology.world.chunks.blockdata;

import com.google.common.base.Preconditions;

import java.nio.ByteBuffer;

/**
 * TeraSparseArrayByte is the base class used to implement sparse arrays with elements of size 4 bit or 8 bit.
 *
 */
public abstract class TeraSparseArrayByte extends TeraSparseArray {

    protected byte[][] inflated;
    protected byte[] deflated;
    protected byte fill;

    protected TeraSparseArrayByte() {
        super();
    }

    protected TeraSparseArrayByte(int sizeX, int sizeY, int sizeZ) {
        super(sizeX, sizeY, sizeZ, false);
    }

    protected TeraSparseArrayByte(int sizeX, int sizeY, int sizeZ, byte[][] inflated, byte[] deflated) {
        super(sizeX, sizeY, sizeZ, false);
        this.inflated = Preconditions.checkNotNull(inflated);
        this.deflated = Preconditions.checkNotNull(deflated);
        Preconditions.checkArgument(inflated.length == sizeY, "The length of parameter 'inflated' has to be " + sizeY + " but is " + inflated.length);
        Preconditions.checkArgument(deflated.length == sizeY, "The length of parameter 'deflated' has to be " + sizeY + " but is " + deflated.length);
    }

    protected TeraSparseArrayByte(int sizeX, int sizeY, int sizeZ, byte fill) {
        super(sizeX, sizeY, sizeZ, false);
        this.fill = fill;
    }

    protected abstract TeraArray createSparse(byte defaultFill);

    protected abstract TeraArray createSparse(byte[][] inflatedData, byte[] deflatedData);

    protected abstract int rowSize();

    @Override
    protected void initialize() {
    }

    @Override
    public final int getEstimatedMemoryConsumptionInBytes() {
        if (inflated == null) {
            return 9;
        }
        int result = 9 + getSizeY() + (getSizeY() * 4);
        for (int i = 0; i < getSizeY(); i++) {
            if (inflated[i] != null) {
                result += 12 + rowSize();
            }
        }
        return result;
    }

    @Override
    public final TeraArray copy() {
        if (inflated == null) {
            return createSparse(fill);
        }
        byte[][] inf = new byte[getSizeY()][];
        byte[] def = new byte[getSizeY()];
        for (int y = 0; y < getSizeY(); y++) {
            if (inflated[y] != null) {
                inf[y] = new byte[rowSize()];
                System.arraycopy(inflated[y], 0, inf[y], 0, rowSize());
            }
        }
        System.arraycopy(deflated, 0, def, 0, getSizeY());
        return createSparse(inf, def);
    }

    protected abstract static class SerializationHandler<T extends TeraSparseArrayByte> extends TeraArray.BasicSerializationHandler<T> {

        protected abstract T createArray(int sizeX, int sizeY, int sizeZ);

        @Override
        protected int internalComputeMinimumBufferSize(T array) {
            final byte[][] inf = array.inflated;
            if (inf == null) {
                return 2;
            } else {
                int sizeY = array.getSizeY();
                int rowSize = array.rowSize();
                int result = 1;
                for (int y = 0; y < sizeY; y++) {
                    if (inf[y] == null) {
                        result += 2;
                    } else {
                        result += 1 + rowSize;
                    }
                }
                return result;
            }
        }

        @Override
        protected void internalSerialize(T array, ByteBuffer buffer) {
            final byte[][] inf = array.inflated;
            if (inf == null) {
                buffer.put((byte) 0);
                buffer.put(array.fill);
            } else {
                buffer.put((byte) 1);
                int sizeY = array.getSizeY();
                int rowSize = array.rowSize();
                final byte[] def = array.deflated;
                for (int y = 0; y < sizeY; y++) {
                    final byte[] row = inf[y];
                    if (row == null) {
                        buffer.put((byte) 0);
                        buffer.put(def[y]);
                    } else {
                        buffer.put((byte) 1);
                        buffer.put(row, 0, rowSize);
                    }
                }
            }
        }

        @Override
        protected T internalDeserialize(int sizeX, int sizeY, int sizeZ, ByteBuffer buffer) {
            final byte hasData = buffer.get();
            final T array = createArray(sizeX, sizeY, sizeZ);
            if (hasData == 0) {
                array.fill = buffer.get();
                return array;
            }
            int rowSize = array.rowSize();
            array.inflated = new byte[sizeY][];
            array.deflated = new byte[sizeY];
            for (int y = 0; y < sizeY; y++) {
                final byte hasRow = buffer.get();
                if (hasRow == 0) {
                    array.deflated[y] = buffer.get();
                } else {
                    array.inflated[y] = new byte[rowSize];
                    buffer.get(array.inflated[y], 0, rowSize);
                }
            }
            return array;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.wildfly.swarm</groupId>
    <artifactId>microprofile-config-examples</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>microprofile-config-complex-example</artifactId>
  <name>WildFly Swarm: Example for MicroProfile Config (Complex)</name>
  <packaging>jar</packaging>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.wildfly.swarm</groupId>
        <artifactId>bom-all</artifactId>
        <version>${version.org.wildfly.swarm}</version>
        <scope>import</scope>
        <type>pom</type>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <build>
    <plugins>
      <plugin>
        <groupId>org.wildfly.swarm</groupId>
        <artifactId>wildfly-swarm-plugin</artifactId>
        <version>${version.org.wildfly.swarm}</version>
        <configuration>
          <mainClass>org.wildfly.swarm.microprofile.config.example.complex.Main</mainClass>
        </configuration>
        <executions>
          <execution>
            <id>package</id>
          </execution>
          <execution>
            <id>start</id>
            <configuration>
              <useUberJar>true</useUberJar>
            </configuration>
          </execution>
          <execution>
            <id>stop</id>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <!-- Java EE 7 dependency -->
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
      <scope>provided</scope>
    </dependency>
    <!-- WildFly Swarm Fractions -->
    <dependency>
      <groupId>org.wildfly.swarm</groupId>
      <artifactId>jaxrs</artifactId>
    </dependency>
    <dependency>
      <groupId>org.wildfly.swarm</groupId>
      <artifactId>microprofile-config</artifactId>
      <version>${project.version}</version>
    </dependency>
  </dependencies>
</project>