text:
package com.sun.xacml.attr;

import com.sun.xacml.ParsingException;

import java.math.BigInteger;

import java.net.URI;

import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.regex.Matcher;

import org.w3c.dom.Node;

/**
 * Representation of an xf:dayTimeDuration value. This class supports parsing
 * xd:dayTimeDuration values. All objects of this class are immutable and
 * thread-safe. The Date objects returned are not, but
 * these objects are cloned before being returned.
 *
 * @since 1.0
 * @author Steve Hanna
 */
public class DayTimeDurationAttribute extends AttributeValue
{
    /**
     * Official name of this type
     */
    public static final String identifier =
        "http://www.w3.org/TR/2002/WD-xquery-operators-20020816#" +
        "dayTimeDuration";

    /**
     * URI version of name for this type
     *

     * This field is initialized by a static initializer so that
     * we can catch any exceptions thrown by URI(String) and
     * transform them into a RuntimeException, since this should
     * never happen but should be reported properly if it ever does.
     */
    private static URI identifierURI;

    /**
     * RuntimeException that wraps an Exception thrown during the
     * creation of identifierURI, null if none.
     */
    private static RuntimeException earlyException;

    /**
     * Static initializer that initializes the identifierURI
     * class field so that we can catch any exceptions thrown
     * by URI(String) and transform them into a RuntimeException.
     * Such exceptions should never happen but should be reported
     * properly if they ever do.
     */
    static {
        try {
            identifierURI = new URI(identifier);
        } catch (Exception e) {
            earlyException = new IllegalArgumentException();
            earlyException.initCause(e);
        }
    };

    /**
     * Regular expression for dayTimeDuration (a la java.util.regex)
     */
    private static final String patternString =
        "(\\-)?P((\\d+)?D)?(T((\\d+)?H)?((\\d+)?M)?((\\d+)?(.(\\d+)?)?S)?)?";

    /**
     * The index of the capturing group for the negative sign.
     */
    private static final int GROUP_SIGN = 1;

    /**
     * The index of the capturing group for the number of days.
     */
    private static final int GROUP_DAYS = 3;

    /**
     * The index of the capturing group for the number of hours.
     */
    private static final int GROUP_HOURS = 6;

    /**
     * The index of the capturing group for the number of minutes.
     */
    private static final int GROUP_MINUTES = 8;

    /**
     * The index of the capturing group for the number of seconds.
     */
    private static final int GROUP_SECONDS = 10;

    /**
     * The index of the capturing group for the number of nanoseconds.
     */
    private static final int GROUP_NANOSECONDS = 12;

    /**
     * Static BigInteger values. We only use these if one of
     * the components is bigger than Integer.MAX_LONG and we
     * want to detect overflow, so we don't initialize these
     * until they're needed.
     */
    private static BigInteger big24;
    private static BigInteger big60;
    private static BigInteger big1000;
    private static BigInteger bigMaxLong;

    /**
     * A shared Pattern object, only initialized if needed
     */
    private static Pattern pattern;

    /**
     * Negative flag. true if duration is negative, false otherwise
     */
    private boolean negative;

    /**
     * Number of days
     */
    private long days;

    /**
     * Number of hours
     */
    private long hours;

    /**
     * Number of minutes
     */
    private long minutes;

    /**
     * Number of seconds
     */
    private long seconds;

    /**
     * Number of nanoseconds
     */
    private int nanoseconds;

    /**
     * Total number of round seconds (in milliseconds)
     */
    private long totalMillis;

    /**
     * Cached encoded value (null if not cached yet).
     */
    private String encodedValue = null;

    /**
     * Creates a new DayTimeDurationAttribute that represents
     * the duration supplied.
     *
     * @param negative true if the duration is negative, false otherwise
     * @param days the number of days in the duration
     * @param hours the number of hours in the duration
     * @param minutes the number of minutes in the duration
     * @param seconds the number of seconds in the duration
     * @param nanoseconds the number of nanoseconds in the duration
     * @throws IllegalArgumentException if the total number of milliseconds
     *                                  exceeds Long.MAX_LONG
     */
    public DayTimeDurationAttribute(boolean negative, long days, long hours,
                                    long minutes, long seconds,
                                    int nanoseconds)
        throws IllegalArgumentException {
        super(identifierURI);

        // Shouldn't happen, but just in case...
        if (earlyException != null)
            throw earlyException;

        this.negative = negative;
        this.days = days;
        this.hours = hours;
        this.minutes = minutes;
        this.seconds = seconds;
        this.nanoseconds = nanoseconds;

        // Convert all the components except nanoseconds to milliseconds

        // If any of the components is big (too big to be an int),
        // use the BigInteger class to do the math so we can detect
        // overflow.
        if ((days > Integer.MAX_VALUE) || (hours > Integer.MAX_VALUE) ||
            (minutes > Integer.MAX_VALUE) || (seconds > Integer.MAX_VALUE)) {
            if (big24 == null) {
                big24 = BigInteger.valueOf(24);
                big60 = BigInteger.valueOf(60);
                big1000 = BigInteger.valueOf(1000);
                bigMaxLong = BigInteger.valueOf(Long.MAX_VALUE);
            }
            BigInteger bigDays = BigInteger.valueOf(days);
            BigInteger bigHours = BigInteger.valueOf(hours);
            BigInteger bigMinutes = BigInteger.valueOf(minutes);
            BigInteger bigSeconds = BigInteger.valueOf(seconds);

            BigInteger bigTotal = bigDays.multiply(big24).add(bigHours)
                .multiply(big60).add(bigMinutes).multiply(big60)
                .add(bigSeconds).multiply(big1000);

            // If the result is bigger than Long.MAX_VALUE, we have an
            // overflow. Indicate an error (should be a processing error,
            // since it can be argued that we should handle gigantic
            // values for this).
            if (bigTotal.compareTo(bigMaxLong) == 1)
                throw new IllegalArgumentException("total number of " +
                                                   "milliseconds " +
                                                   "exceeds Long.MAX_VALUE");
            // If no overflow, convert to a long.
            totalMillis = bigTotal.longValue();
        } else {
            // The numbers are small, so do it the fast way.
            totalMillis = ((((((days * 24) + hours) * 60) + minutes) * 60) +
                seconds) * 1000;
        }
    }

    /**
     * Returns a new DayTimeDurationAttribute that represents
     * the xf:dayTimeDuration at a particular DOM node.
     *
     * @param root the Node that contains the desired value
     * @return a new DayTimeDurationAttribute representing the
     *         appropriate value (null if there is a parsing error)
     */
    public static DayTimeDurationAttribute getInstance(Node root)
        throws ParsingException, NumberFormatException
    {
        return getInstance(root.getFirstChild().getNodeValue());
    }

    /**
     * Returns the long value for the capturing group groupNumber.
     * This method takes a Matcher that has been used to match a
     * Pattern against a String, fetches the value for the specified
     * capturing group, converts that value to an long, and returns
     * the value. If that group did not match, 0 is returned.
     * If the matched value is not a valid long, NumberFormatException
     * is thrown.
     *
     * @param matcher the Matcher from which to fetch the group
     * @param groupNumber the group number to fetch
     * @return the long value for that groupNumber
     * @throws NumberFormatException if the string value for that
     * groupNumber is not a valid long
     */
    private static long parseGroup(Matcher matcher, int groupNumber)
        throws NumberFormatException {
        long groupLong = 0;

        if (matcher.start(groupNumber) != -1) {
            String groupString = matcher.group(groupNumber);
            groupLong = Long.parseLong(groupString);
        }
        return groupLong;
    }

    /**
     * Returns a new DayTimeDurationAttribute that represents
     * the xf:dayTimeDuration value indicated by the string provided.
     *
     * @param value a string representing the desired value
     * @return a new DayTimeDurationAttribute representing the
     *         desired value (null if there is a parsing error)
     */
    public static DayTimeDurationAttribute getInstance(String value)
        throws ParsingException, NumberFormatException
    {
        boolean negative = false;
        long days = 0;
        long hours = 0;
        long minutes = 0;
        long seconds = 0;
        int nanoseconds = 0;

        // Compile the pattern, if not already done.
        // No thread-safety problem here. The worst that can
        // happen is that we initialize pattern several times.
        if (pattern == null) {
            try {
                pattern = Pattern.compile(patternString);
            } catch (PatternSyntaxException e) {
                // This should never happen
                throw new ParsingException("unexpected pattern match error");
            }
        }

        // See if the value matches the pattern.
        Matcher matcher = pattern.matcher(value);
        boolean matches = matcher.matches();

        // If not, syntax error!
        if (!matches) {
            throw new ParsingException("Syntax error in dayTimeDuration");
        }

        // If the negative group matched, the value is negative.
        if (matcher.start(GROUP_SIGN) != -1)
            negative = true;

        try {
            // If the days group matched, parse that value.
            days = parseGroup(matcher, GROUP_DAYS);

            // If the hours group matched, parse that value.
            hours = parseGroup(matcher, GROUP_HOURS);

            // If the minutes group matched, parse that value.
            minutes = parseGroup(matcher, GROUP_MINUTES);

            // If the seconds group matched, parse that value.
            seconds = parseGroup(matcher, GROUP_SECONDS);

            // Special handling for fractional seconds, since
            // they can have any resolution.
            if (matcher.start(GROUP_NANOSECONDS) != -1) {
                String nanosecondString = matcher.group(GROUP_NANOSECONDS);

                // If there are less than 9 digits in the fractional seconds,
                // pad with zeros on the right so it's nanoseconds.
                while (nanosecondString.length() < 9)
                    nanosecondString += "0";

                // If there are more than 9 digits in the fractional seconds,
                // drop the least significant digits.
                if (nanosecondString.length() > 9) {
                    nanosecondString = nanosecondString.substring(0, 9);
                }

                nanoseconds = Integer.parseInt(nanosecondString);
            }
        } catch (NumberFormatException e) {
            // If we run into a number that's too big to be a long
            // that's an error. Really, it's a processing error,
            // since one can argue that we should handle that.
            throw e;
        }

        // Here's a requirement that's not checked for in the pattern.
        // The designator 'T' must be absent if all the time
        // items are absent. So the string can't end in 'T'.
        // Note that we don't have to worry about a zero length
        // string, since the pattern won't allow that.
        if (value.charAt(value.length()-1) == 'T')
            throw new ParsingException("'T' must be absent if all" +
                                       "time items are absent");

        // If parsing went OK, create a new DayTimeDurationAttribute object and
        // return it.
        return new DayTimeDurationAttribute(negative, days, hours, minutes,
                                            seconds, nanoseconds);
    }

    /**
     * Returns true if the duration is negative.
     *
     * @return true if the duration is negative, false otherwise
     */
    public boolean isNegative() {
        return negative;
    }

    /**
     * Gets the number of days.
     *
     * @return the number of days
     */
    public long getDays() {
        return days;
    }

    /**
     * Gets the number of hours.
     *
     * @return the number of hours
     */
    public long getHours() {
        return hours;
    }

    /**
     * Gets the number of minutes.
     *
     * @return the number of minutes
     */
    public long getMinutes() {
        return minutes;
    }

    /**
     * Gets the number of seconds.
     *
     * @return the number of seconds
     */
    public long getSeconds() {
        return seconds;
    }

    /**
     * Gets the number of nanoseconds.
     *
     * @return the number of nanoseconds
     */
    public int getNanoseconds() {
        return nanoseconds;
    }

    /**
     * Gets the total number of round seconds (in milliseconds).
     *
     * @return the total number of seconds (in milliseconds)
     */
    public long getTotalSeconds() {
        return totalMillis;
    }

    /**
     * Returns true if the input is an instance of this class and if its
     * value equals the value contained in this class.
     *
     * @param o the object to compare
     *
     * @return true if this object and the input represent the same value
     */
    public boolean equals(Object o) {
        if (! (o instanceof DayTimeDurationAttribute))
            return false;

        DayTimeDurationAttribute other = (DayTimeDurationAttribute)o;

        return ((totalMillis == other.totalMillis) &&
                (nanoseconds == other.nanoseconds) &&
                (negative == other.negative));
    }

    /**
     * Returns the hashcode value used to index and compare this object with
     * others of the same type. Typically this is the hashcode of the backing
     * data object.
     *
     * @return the object's hashcode value
     */
    public int hashCode() {
        // The totalMillis, nanoseconds, and negative fields are all considered
        // by the equals method, so it's best if the hashCode is derived
        // from all of those fields.
        int hashCode = (int) totalMillis ^ (int) (totalMillis >> 32);
        hashCode = 31*hashCode + nanoseconds;
        if (negative)
            hashCode = -hashCode;
        return hashCode;
    }

    /**
     * Converts to a String representation.
     *
     * @return the String representation
     */
    public String toString() {
        StringBuffer sb = new StringBuffer();

        sb.append("DayTimeDurationAttribute: [\n");
        sb.append("  Negative: " + negative);
        sb.append("  Days: " + days);
        sb.append("  Hours: " + hours);
        sb.append("  Minutes: " + minutes);
        sb.append("  Seconds: " + seconds);
        sb.append("  Nanoseconds: " + nanoseconds);
        sb.append("  TotalSeconds: " + totalMillis);
        sb.append("]");

        return sb.toString();
    }

    /**
     * Encodes the value in a form suitable for including in XML data like
     * a request or an obligation. This must return a value that could in
     * turn be used by the factory to create a new instance with the same
     * value.
     *
     * @return a String form of the value
     */
    public String encode() {
        if (encodedValue != null)
            return encodedValue;

        // Length is quite variable
        StringBuffer buf = new StringBuffer(10);

        if (negative)
            buf.append('-');
        buf.append('P');
        if (days != 0) {
            buf.append(Long.toString(days));
            buf.append('D');
        }
        if ((hours != 0) || (minutes != 0)
            || (seconds != 0) || (nanoseconds != 0)) {
            // Only include the T if there are some time fields
            buf.append('T');
        } else {
            // Make sure that there's always at least one field specified
            if (days == 0)
                buf.append("0D");
        }
        if (hours != 0) {
            buf.append(Long.toString(hours));
            buf.append('H');
        }
        if (minutes != 0) {
            buf.append(Long.toString(minutes));
            buf.append('M');
        }
        if ((seconds != 0) || (nanoseconds != 0)) {
            buf.append(Long.toString(seconds));
            if (nanoseconds != 0) {
                buf.append('.');
                buf.append(DateAttribute.zeroPadInt(nanoseconds, 9));
            }
            buf.append('S');
        }

        encodedValue = buf.toString();

        return encodedValue;
    }
}


text:
SYNONYM

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

#### Published in
Curr. Sci. 41(21): 760 (1972)

#### Original name
Aspergillus aureolus Fennell & Raper, 1955

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Sonata\CacheBundle\Invalidation;

use Sonata\CacheBundle\Cache\CacheInterface;
use Sonata\CacheBundle\Invalidation\ModelCollectionIdentifiers;

use Doctrine\Common\EventSubscriber;
use Doctrine\ODM\PHPCR\Event;
use Doctrine\ODM\PHPCR\Event\LifecycleEventArgs;

class DoctrinePHPCRODMListener implements EventSubscriber
{
    protected $caches = array();

    protected $collectionIdentifiers;

    public function __construct(ModelCollectionIdentifiers $collectionIdentifiers, $caches)
    {
        $this->collectionIdentifiers = $collectionIdentifiers;

        foreach ($caches as $cache) {
            $this->addCache($cache);
        }
    }

    public function getSubscribedEvents()
    {
        return array(
            Event::preRemove,
            Event::preUpdate
        );
    }

    public function preRemove(LifecycleEventArgs $args)
    {
        $this->flush($args);
    }

    public function preUpdate(LifecycleEventArgs $args)
    {
        $this->flush($args);
    }

    protected function flush(LifecycleEventArgs $args)
    {
        $identifier = $this->collectionIdentifiers->getIdentifier($args->getDocument());

        if ($identifier === false) {
            return;
        }

        $parameters = array(
            get_class($args->getDocument()) => $identifier
        );

        foreach ($this->caches as $cache) {
            $cache->flush($parameters);
        }
    }

    public function addCache(CacheInterface $cache)
    {
        if (!$cache->isContextual()) {
            return;
        }

        $this->caches[] = $cache;
    }
}


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

namespace RightpointLabs.ConferenceRoom.Domain
{
    public static class Extensions
    {
        /// <summary>
        /// Similar to <see cref="IDictionary<K,T>.TryGetValue(K, out T)"/>, but returns the value from
        ///   the dictionary instead of using an output parameter.
        /// Returns default(T) if the key does not exist.  This means you cannot tell the difference between a
        ///   default value and a non-existant key.  Do not use this function if you care about the difference.
        ///
        /// This exists partially to allow a nested dictionary structure to be easily traversed via <see cref="Extensions.ChainIfNotNull{T,T}"/>
        /// </summary>
        /// <typeparam name="K">The key type of the dictionary</typeparam>
        /// <typeparam name="T">The value type of the dictionary</typeparam>
        /// <param name="dictionary">The dictionary</param>
        /// <param name="key">The key</param>
        /// <returns>The value in the dictionary for the passed key, or default(T) if the key doesn't exist.</returns>
        public static T TryGetValue<K, T>(this IDictionary<K, T> dictionary, K key)
        {
            T value;
            if (dictionary.TryGetValue(key, out value))
            {
                return value;
            }
            return default(T);
        }

        /// <summary>
        /// If obj is null, returns null immediately.  Otherwises, passes obj to chainCall and returns the result.
        ///
        /// This essentially lets us fake null propagation.  Description: http://kontrawize.blogs.com/kontrawize/2007/03/null_propagatio.html.
        /// </summary>
        /// <typeparam name="T1">The type of the input object</typeparam>
        /// <typeparam name="T2">The return type</typeparam>
        /// <param name="obj">The object to be checked for null and passed to chainCall</param>
        /// <param name="chainCall">The delegate to be called with obj as an argument</param>
        /// <returns>null if obj is null, or the result of calling chainCall with obj as an argument.</returns>
        public static T2 ChainIfNotNull<T1, T2>(this T1 obj, Func<T1, T2> chainCall) where T1 : class
        {
            if (null == obj)
                return default(T2);
            return chainCall(obj);
        }

        public static DateTime TruncateToTheMinute(this DateTime date)
        {
            return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, 0, date.Kind);
        }

        public static T[][] Chunk<T>(this IEnumerable<T> input, int size)
        {
            var data = input.ToList();
            return Enumerable.Range(0, (data.Count - 1) / size + 1).Select(i => data.Skip(i * size).Take(size).ToArray()).ToArray();
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2017-2022 Basis Technology Corp.

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.basistech.rosette</groupId>
        <artifactId>rosette-api-java-binding</artifactId>
        <version>1.23.102-SNAPSHOT</version>
    </parent>
    <artifactId>rosette-api-model</artifactId>
    <name>rosette-api-model</name>
    <description>Rosette API data models</description>
    <properties>
        <delombok.output.directory>${project.build.directory}/delombok</delombok.output.directory>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.basistech.rosette</groupId>
            <artifactId>rosette-api-annotations</artifactId>
            <version>${project.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.basistech</groupId>
            <artifactId>common-api</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>${javax-validation-api.version}</version>
        </dependency>
        <dependency>
            <groupId>com.basistech</groupId>
            <artifactId>adm-model</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.squareup</groupId>
            <artifactId>javapoet</artifactId>
            <version>${java-poet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>biz.aQute.bnd</groupId>
                <artifactId>bnd-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
                    </archive>
                    <excludes>
                        <exclude>**/jackson/**</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok-maven-plugin</artifactId>
                <version>${lombok-maven-plugin.version}</version>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>delombok</goal>
                        </goals>
                        <!-- Point the lombok source to src/main/java instead of src/main/lombok, primarily so that
                             duplicate directories can be avoided -->
                        <configuration>
                            <addOutputDirectory>false</addOutputDirectory>
                            <sourceDirectory>src/main/java</sourceDirectory>
                            <outputDirectory>${delombok.output.directory}</outputDirectory>
                            <formatPreferences>
                                <javaLangAsFQN>skip</javaLangAsFQN>
                            </formatPreferences>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>${maven-javadoc-plugin.version}</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <sourcepath>${delombok.output.directory}</sourcepath>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
@(devMode: Boolean)

@main("Example chat application with Akka/JS") {

Actochat

An actor-base chat application with support for multiple rooms and
  private chats (1 to 1).

  <form role="form">

      Nickname
      <input type="text" class="form-control" id="nickname-edit" placeholder="Enter nickname">

      Email for gravatar
      <input type="email" class="form-control" id="email-edit" placeholder="Gravatar e-mail">

    <button id="connect-button" type="button" class="btn btn-default">Connect</button>
  </form>

            <textarea id="msg-to-send" class="form-control send-message" rows="3" placeholder="Write a reply..."></textarea>

            <button id="send-button" class=" col-lg-4 text-right btn   send-message-btn pull-right" role="button"> Send Message</button>

@if(devMode) {

} else {

}

}


text:
(function($) {
$.SPA = {

IDS:	{
	header: "#header",
	nav: "#nav",
	menu: "#menu",
	aside: "#aside",
	body: "#body",
	tabpages: "#tabpages",
	footer: "#footer"
},

EventType: {
	PageUnload:"PageUnload",
	PageResize:"PageResize"
},

StatusCode: {
	OK:200,
	Error:300,
	Timeout:301
},

_msg:{
	error: "Sorry, the application has encounter an error.",
	serverError: "Sorry, the server error.",
	sessionTimout: "session timeout, please login again.",
	statusCode_503: "HTTP 503 error.",
	exceedMaxOpenPages: "Exceeding maximum open pages:{0}"
},

msg:function(key){
	return this._msg[key];
},

_debug:false,

debug:function(msg){
	if (this._debug) {
		if (typeof(console) != "undefined")
			console.log(msg);
		else
			alert(msg);
	}
},

evalJSON:function(data) {
	try{
		if ($.type(data) == 'string')
			return eval('(' + data + ')');
		else return data;
	} catch (e){
		return {};
	}
},

ajaxError:function(xhr, ajaxOptions, thrownError){
	if (alertMsg) {
		$.SPA.alertMsg("
Http status: " + xhr.status + " " + xhr.statusText + "
"
			+ "
ajaxOptions: "+ajaxOptions + "
"
			+ "
thrownError: "+thrownError + "
"
			+ "
"+xhr.responseText+"
");
	} else {
		$.SPA.alertMsg("Http status: " + xhr.status + " " + xhr.statusText + "\najaxOptions: " + ajaxOptions + "\nthrownError:"+thrownError + "\n" +xhr.responseText);
	}
},

ajaxDone:function(json){
	if (json.statusCode === undefined && json.message === undefined) {
		$.SPA.alertMsg(json);
	}
	if(json.statusCode == $.SPA.StatusCode.Error) {
		$.SPA.alertMsg(json.message || $.SPA.msg("serverError"));
	} else if (json.statusCode == $.SPA.StatusCode.Timeout) {
		$.SPA.alertMsg(json.message || $.SPA.msg("sessionTimout"));
	} else {
		if(json.message) $.SPA.alertMsg(json.message);
	}
},

alertMsg: function(msg, callbacks) {
	alert(msg);
	if (callbacks && callbacks.onOK) callbacks.onOK();
},

wrap: function (elem){
	var $elem = $(elem || document);

	$("a[target=tabpages]", $elem).each(function(){
		$(this).click(function(event){
			var $this = $(this);
			var title = $this.attr("title") || $this.text();
			var icon = $this.data("icon") || "";
			var className = $this.data("class") || "";
			var tabid = $this.data("tabid") || "_blank";
			var refresh = (String($this.data("refresh")) == "true");
			var external = (String($this.data("external")) == "true");
			var closable = (String($this.data("closable")) != "false");
			var url = unescape($this.attr("href")).replaceTmById($(event.target).parents(".unit-box:first"));

			$.SPA.debug(url);
			if (!url.isFinishedTm()) {
				alertMsg.error($this.data("warn") || $.SPA.msg("error"));
				return false;
			}

			$(".tabpages").tabpages("openTab",{
				tabid:tabid,
				url:url,
				title:title,
				icon:icon,
				closable: closable,
				refresh:refresh,
				external:external,
				className:className
			});

			event.preventDefault();
		});
	});

},

layout: function () {
	var h = $(window).height() - $("#header").outerHeight(true) - $("#footer").outerHeight(true) - 5;
	$("#aside").height(h);

	var w = $(window).width();
	if ($("#splitbar").size() == 0) {
	   w = w - 10;
	   $("#body").css({left:5});
	} else {
	   w = w - $("#splitbar").position().left - $("#splitbar").outerWidth(true) - 5;
	}
	$("#body, #tabpages").css({width: w, height: h});

	$(window).trigger($.SPA.EventType.PageResize);
},

init: function(options) {
	var op = $.extend({
			appid:"SPA",
			debug:false,
			showContextMenu: true,
			maxOpenPages:15,
			onInit: $.noop
		}, options);
	this._debug = op.debug;
	this.appid = op.appid;

	$(".msg").each(function(){
	  $.SPA._msg[$(this).attr("title")] = $(this).text();
	});

	var ajaxbg = $("#background,#progressbar").hide();
	$(document).ajaxStart(function(){
		ajaxbg.show();
	}).ajaxStop(function(){
		ajaxbg.hide();
	});

	if ($.fn.menubar) {
		var defaultMenuSelected = function($a) {
			$.get($a.attr("href"), {}, function(html){
				$.SPA.wrap($(".sidebar-container").empty().append(html));
			});
		};

		$(".nav-menu").menubar({
			 onSelected: op.onMenuSelected || defaultMenuSelected
		});
	}

	if($.fn.sidebar) {
		$("#aside.sidebar").sidebar({minW:150, maxW:450,
			onResized: function() {
				$.SPA.layout();
			}
		});
	}

	if($.fn.tabpages) {
		$(".tabpages").tabpages({
			showContextMenu: op.showContextMenu,
			contextMenu: {
				reloadTab: $.SPA.msg("reloadTab"),
				closeCurrentTab: $.SPA.msg("closeCurrentTab"),
				closeOtherTabs: $.SPA.msg("closeOtherTabs"),
				closeAllTabs: $.SPA.msg("closeAllTabs")
			},
			maxOpenPages: op.maxOpenPages,
			onExceedingMaxOpenPages: function() {
				$.SPA.alertMsg($.SPA.msg("exceedMaxOpenPages").format(op.maxOpenPages));
			}
		});
	}

	$.SPA.layout();
	$.SPA.wrap();

	$(window).resize(function(){
		$.SPA.layout();
	});

	if ($.History) $.History.init("#body");

	if ($.isFunction(op.onInit)) op.onInit();

}

};
})(jQuery);


text: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">


text:
Zdb
===

** Elixir access for dynamodb **

[docs](http://stink.net/zdb)

# Usage

## If you want to use Dynamodb local for dev

Add the following to your <project dir>/config/#{Mix.enf}.exs

in this case :dev

    config :zdb,
      ddb_port: 8000,
      ddb_host: 'localhost',
      ddb_scheme: 'http://',
      ddb_key: 'ddb_local_' ++ (Mix.env|>Atom.to_string|> String.to_char_list),
      ddb_skey: 'ddb_local_' ++ (Mix.env|>Atom.to_string|> String.to_char_list)

then install dynamodb and fire it up....

```elixir
## create table
Zdb.create("test_table")

## create item struct

item = %Zitem{key: {:bar,:foo},table: "test_table"}

## put the item
Zdb.put(item)

## get the item
zr = Zdb.get(item)

## Enumerate items
items = zr.items
Enum.each(items,fn(i) -> IO.inspect i end)

## update the item

# setup
map = %{key: "value"}
attributes = [lastPostBy: "bob@bob.com"]
item = %Zitem{key: {:bob,:email},table: "test_table",map: map,attributes: attributes}
Zdb.put(item)

# update

updates = %Zu{attributes: [lastPostBy: "bob@bobo.com"],action: :put,
                 opts: [expected: [lastPostBy: "bob@bob.com"],
                   return_values: :all_new ]
              }
res = Zdb.update(item,updates)

## query multiple items

q = %Zq{table: "test_table",kc: [{"hk",:eq,:bob},{"rk",:begins_with,"e"}]}
res = Zdb.q(q)
```


text:
package net.caseif.flint.common.util.factory;

public interface Factory<T> {
}


text:
"""Diagnostics support for PVOutput."""
from __future__ import annotations

import json
from typing import Any

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant

from .const import DOMAIN
from .coordinator import PVOutputDataUpdateCoordinator

async def async_get_config_entry_diagnostics(
    hass: HomeAssistant, entry: ConfigEntry
) -> dict[str, Any]:
    """Return diagnostics for a config entry."""
    coordinator: PVOutputDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
    # Round-trip via JSON to trigger serialization
    data: dict[str, Any] = json.loads(coordinator.data.json())
    return data


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>TimestampSpeechletRequestVerifier</title>
<meta name="date" content="2016-03-14">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.amazon.speech.speechlet.verifier

Class TimestampSpeechletRequestVerifier

java.lang.Object

com.amazon.speech.speechlet.verifier.TimestampSpeechletRequestVerifier

All Implemented Interfaces:

SpeechletRequestVerifier

public class TimestampSpeechletRequestVerifier
extends java.lang.Object
implements SpeechletRequestVerifier

Verifies whether or not timestamps are valid within a certain tolerance.

 Every request sent by Alexa includes a timestamp. This information is part of the signed portion
 of the request, so it cannot be changed without also invalidating the request signature. Using
 this timestamp to verify the freshness of the request before responding protects the client's
 service from attackers attempting a "replay" attack in which they acquire a properly signed
 request and then repeatedly resend it to disrupt your service.

See Also:

      Checking the Timestamp of the Request

Constructor Summary

Constructors

Constructor and Description

TimestampSpeechletRequestVerifier(long tolerance,
                                 java.util.concurrent.TimeUnit unit)

Constructs a new timestamp verifier with the provided tolerance (in the provided units).

Method Summary

Methods

Modifier and Type
Method and Description

boolean
verify(SpeechletRequest request,
      Session session)

Returns true if the provided date is inclusively within the verifier tolerance, either in the
 past or future, of the current system time.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TimestampSpeechletRequestVerifier

public TimestampSpeechletRequestVerifier(long tolerance,
                                 java.util.concurrent.TimeUnit unit)

Constructs a new timestamp verifier with the provided tolerance (in the provided units).

Parameters:

tolerance - the tolerance of this verifier

unit - the time unit of the tolerance parameter

Method Detail

verify

public boolean verify(SpeechletRequest request,
             Session session)

Returns true if the provided date is inclusively within the verifier tolerance, either in the
 past or future, of the current system time. This method will return false if
 SpeechletRequest or SpeechletRequest.getTimestamp() is null.

Specified by:

verify in interface SpeechletRequestVerifier

Parameters:

request - SpeechletRequest to validate

session - Session context within which to validate the call

Returns:

true if the provided date is within the verifier tolerance, false otherwise

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
Pattern: Unnamed operation

Issue: -

## Description

This rule validates that all operations are named. Naming operations is valuable for including in server-side logs and debugging.

## Examples

**Pass**
```
query FetchUsername {
  viewer {
    name
  }
}
```

**Fail**
```
query {
  viewer {
    name
  }
}
```


text:
package fakes

import (
	"sort"
	"strings"
	"sync"

	"github.com/nttlabs/cli/cf/models"
)

type FakeServicePlanRepo struct {
	SearchReturns map[string][]models.ServicePlanFields
	SearchErr     error

	UpdateStub        func(models.ServicePlanFields, string, bool) error
	updateMutex       sync.RWMutex
	updateArgsForCall []struct {
		arg1 models.ServicePlanFields
		arg2 string
		arg3 bool
	}
	updateReturns struct {
		result1 error
	}
}

func (fake *FakeServicePlanRepo) Search(queryParams map[string]string) ([]models.ServicePlanFields, error) {
	if fake.SearchErr != nil {
		return nil, fake.SearchErr
	}

	if queryParams == nil {
		//return everything
		var returnPlans []models.ServicePlanFields
		for _, value := range fake.SearchReturns {
			returnPlans = append(returnPlans, value...)
		}
		return returnPlans, nil
	}

	searchKey := combineKeys(queryParams)
	if fake.SearchReturns[searchKey] != nil {
		return fake.SearchReturns[searchKey], nil
	}

	return []models.ServicePlanFields{}, nil
}

func combineKeys(mapToCombine map[string]string) string {
	keys := []string{}
	for key, _ := range mapToCombine {
		keys = append(keys, key)
	}
	sort.Strings(keys)

	values := []string{}
	for _, key := range keys {
		values = append(values, mapToCombine[key])
	}

	return strings.Join(values, ":")
}

func (fake *FakeServicePlanRepo) Update(arg1 models.ServicePlanFields, arg2 string, arg3 bool) error {
	fake.updateMutex.Lock()
	defer fake.updateMutex.Unlock()
	fake.updateArgsForCall = append(fake.updateArgsForCall, struct {
		arg1 models.ServicePlanFields
		arg2 string
		arg3 bool
	}{arg1, arg2, arg3})
	if fake.UpdateStub != nil {
		return fake.UpdateStub(arg1, arg2, arg3)
	} else {
		return fake.updateReturns.result1
	}
}

func (fake *FakeServicePlanRepo) UpdateCallCount() int {
	fake.updateMutex.RLock()
	defer fake.updateMutex.RUnlock()
	return len(fake.updateArgsForCall)
}

func (fake *FakeServicePlanRepo) UpdateArgsForCall(i int) (models.ServicePlanFields, string, bool) {
	fake.updateMutex.RLock()
	defer fake.updateMutex.RUnlock()
	return fake.updateArgsForCall[i].arg1, fake.updateArgsForCall[i].arg2, fake.updateArgsForCall[i].arg3
}

func (fake *FakeServicePlanRepo) UpdateReturns(result1 error) {
	fake.UpdateStub = nil
	fake.updateReturns = struct {
		result1 error
	}{result1}
}


text:
<?php

namespace SilverShop\Checkout\Component;

use SilverShop\Checkout\Checkout;
use SilverShop\Model\Order;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\HiddenField;
use SilverStripe\Forms\OptionsetField;
use SilverStripe\Omnipay\GatewayInfo;
use SilverStripe\ORM\ValidationException;
use SilverStripe\ORM\ValidationResult;

class Payment extends CheckoutComponent
{
    public function getFormFields(Order $order)
    {
        $fields = FieldList::create();
        $gateways = GatewayInfo::getSupportedGateways();
        if (count($gateways) > 1) {
            $fields->push(
                OptionsetField::create(
                    'PaymentMethod',
                    _t("SilverShop\Checkout\CheckoutField.PaymentType", "Payment Type"),
                    $gateways,
                    array_keys($gateways)
                )
            );
        }
        if (count($gateways) == 1) {
            $fields->push(
                HiddenField::create('PaymentMethod')->setValue(key($gateways))
            );
        }

        return $fields;
    }

    public function getRequiredFields(Order $order)
    {
        if (count(GatewayInfo::getSupportedGateways()) > 1) {
            return [];
        }

        return array('PaymentMethod');
    }

    public function validateData(Order $order, array $data)
    {
        $result = ValidationResult::create();
        if (!isset($data['PaymentMethod'])) {
            $result->addError(
                _t(__CLASS__ . '.NoPaymentMethod', "Payment method not provided"),
                "PaymentMethod"
            );
            throw new ValidationException($result);
        }
        $methods = GatewayInfo::getSupportedGateways();
        if (!isset($methods[$data['PaymentMethod']])) {
            $result->addError(_t(__CLASS__ . '.UnsupportedGateway', "Gateway not supported"), "PaymentMethod");
            throw new ValidationException($result);
        }
    }

    public function getData(Order $order)
    {
        return array(
            'PaymentMethod' => Checkout::get($order)->getSelectedPaymentMethod(),
        );
    }

    public function setData(Order $order, array $data)
    {
        if (isset($data['PaymentMethod'])) {
            Checkout::get($order)->setPaymentMethod($data['PaymentMethod']);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--

 Copyright 2003 - 2016 The eFaps Team

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

-->

<ui-command xmlns="http://www.efaps.org/xsd"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">

    <uuid>f1d1b7ab-81c1-4318-8fb1-75dcebd45de5</uuid>
    <file-application>eFaps-Kernel</file-application>

    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>Admin_Access_Access4Object_Menu_Action_Create</name>
        <!-- target definitions -->
        <target>
            <form>Admin_Access_Access4ObjectForm</form>
            <execute program="org.efaps.esjp.admin.access.AccessCheck4Object" method="access4ObjectCreate"/>
        </target>
        <!-- properties -->
        <property name="Target">modal</property>
        <property name="TargetCreateType">Admin_Access_Access4Object</property>
        <property name="TargetMode">create</property>
        <property name="WindowHeight">460</property>
        <property name="WindowWidth">515</property>
    </definition>
</ui-command>


text:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');

var bcrypt = require('bcrypt-nodejs');
var config = require('./config/database');
nev = require('email-verification')(mongoose);

var mailgun_keys = require("./config/mailgun")
mongoose.connect(config.database);

var api = require('./routes/api');
var user = require('./routes/users');
var payment = require('./routes/payment');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'uploads')));
app.use(morgan('dev'));
app.use(passport.initialize());
var User = require('./models/user');
var TempUser = require('./models/usertemp');
var myHasher = function(password, tempUserData, insertTempUser, callback) {
  var hash = bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
  return insertTempUser(hash, tempUserData, callback);
};

myHasher = function(password, tempUserData, insertTempUser, callback) {
  bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(password, salt, function(err, hash) {
          return insertTempUser(hash, tempUserData, callback);
      });
  });
};
// NEV configuration =====================
email_html = ''+
'
'+
'

'+
'

Click the following link to confirm your account:

'+
'
Confirm
'+
'
'+
'';

nev.configure({
  persistentUserModel: User,
  expirationTime: 600, // 10 minutes

  verificationURL: 'https://infinite-garden-74421.herokuapp.com/user/email-verification/${URL}', // https://infinite-garden-74421.herokuapp.com/
  transportOptions: {
    service: 'Mailgun',
    auth: {
      user: 'postmaster@sandbox6a3da5aa8d6d40e79c1bca42f7ac1c9d.mailgun.org', // postmaster@sandbox[base64 string].mailgain.org
      pass: 'f98d9c64568a2850a45a071fd0d36c88' // You set this.
    }
  },

  verifyMailOptions: {
    from: mailgun_keys.from,
    subject: 'Please confirm account',
    html: email_html,
    text: 'Please confirm your account by clicking the following link: ${URL}'
  }
}, function(err, options) {
  if (err) {
      console.log(err);
      return;
  }

  console.log('configured: ' + (typeof options === 'object'));
});

nev.generateTempUserModel(User, function(err, tempUserModel) {
  if (err) {
      console.log(err);
      return;
  }

  console.log('generated temp user model: ' + (typeof tempUserModel === 'function'));
});

app.get('/', function(req, res) {
  res.send('Page under construction.');
});

app.use('/api', api);
app.use('/user', user);
app.use('/payment', payment);
app.use('/test',function(req, res) {
  // set locals, only providing error in development
  res.render('emailconfirmresult', {color:'red', msg: 'ERROR: confirming email FAILED' });
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;


text:
(function() {

	var controller = new (function() {

		this.fetchSprint = function(id, onSuccess, onError) {
			onSuccess = onSuccess || function(){};
			onError = onError || function(){};
			var sprints = new Appacitive.ArticleCollection({ schema: 'sprint' });
			var sprint = sprints.createNewArticle();
			sprint.set('__id', id);
			sprint.fetch(function() {
				onSuccess(sprint.getArticle());
			}, onError);
		}

	})();

	var SprintSettingsView = Backbone.View.extend({

		initialize: function() {
			this.render();
		},

		previewStages: function(input) {
			var stages = ['New', 'Completed'];
			if (input && input.length > 0) {
				var tokens = input.split(',').map(function (t) { return t.trim(); });
				if (tokens.length == 1) {
					stages[0] = tokens[0];
				} else if (tokens.length > 1) {
					stages = tokens.concat(['Completed']);
				}
			}
			var html = '', className = '';
			stages = stages.filter(function (s) { return s.trim().length > 0 });
			stages.forEach(function (stage, index) {
				className = '';
				if (index == 0) className = 'label-info';
				if (index == stages.length - 1) className = 'label-success';
				html += '' + stage + ' ';
			});
			$('#divStagesPreview').html(html).data('stages', stages);
		},

		saveChanges: function() {
			var stages = $('#divStagesPreview').data('stages');
			var sprints = new Appacitive.ArticleCollection({ schema: 'sprint' });
			var sprint = sprints.createNewArticle();
			sprint.set('__id', this.model.id);
			sprint.set('stages', stages.join('|'));

			var onError = function() {
				window.loader.hide();
				window.alert.hide();
				window.alert.show('Darn! Could not save your changes. Try again in a minute or you could contact support.');
			};

			window.loader.show('Updating sprint: "' + this.model.title + '"');
			sprint.fetch(function() {
				sprint.save(function() {
					window.loader.hide();
					Backbone.history.navigate('sprints/details/' + sprint.get('__id'), { trigger: true });
				}, onError);
			}, onError);
		},

		render: function() {
			this.$el = $('.content-container').empty();
			var template = $('#tmplSprintSettings').html();
			var rendered = Mustache.render(template, this.model);
			var $element = $(rendered);
			var that = this;
			this.$el.append($element);
			$('#txtSprintStages').unbind('keyup').keyup(function() {
				that.previewStages.apply(that, [$(this).val().trim()]);
			});
			$('#btnSaveChangesSprint').unbind('click').click(function() {
				that.saveChanges.apply(that, []);
			});
		}

	});

	var SprintSettingsRouter = Backbone.Router.extend({

		routes: {
			'sprints/:id/settings': 'settings'
		},

		settings: function(id) {
			if (false && Appacitive.session.get() == null && !Appacitive.Users.currentUser) {
				Backbone.history.navigate('', { trigger: true });
				return;
			}
			var onError = function() {
				window.loader.hide();
				window.alert.hide();
				window.alert.show('Hmmm, could not find the sprint requested. Either it has been deleted or you do not have permission to access it.');
			}
			window.loader.show('Loading sprint details');
			controller.fetchSprint(id, function(sprint) {
				window.loader.hide();
				window.alert.hide();
				var sprintSettingsView = new SprintSettingsView({
					model: {
						name: sprint.title,
						id: sprint.__id
					}
				});
			}, onError)
		}
	});
	var sprintSettingsRouter = new SprintSettingsRouter;

})();


text:
package com.medievallords.carbyne.gates.commands;

import com.medievallords.carbyne.gates.Gate;
import com.medievallords.carbyne.utils.MessageManager;
import com.medievallords.carbyne.utils.StaticClasses;
import com.medievallords.carbyne.utils.command.BaseCommand;
import com.medievallords.carbyne.utils.command.Command;
import com.medievallords.carbyne.utils.command.CommandArgs;
import org.bukkit.command.CommandSender;

/**
 * Created by Calvin on 1/31/2017
 * for the Carbyne-Gear project.
 */
public class GateActiveCommand extends BaseCommand {

    @Command(name = "gate.active", permission = "carbyne.gate.active")
    public void onCommand(CommandArgs commandArgs) {
        CommandSender sender = commandArgs.getSender();
        String[] args = commandArgs.getArgs();

        if (args.length != 2) {
            MessageManager.sendMessage(sender, "&c/gate active [name] [length]");
            return;
        }

        try {
            String gateId = args[0];
            int length = Integer.parseInt(args[1]);

            Gate gate = StaticClasses.gateManager.getGate(gateId);

            if (gate == null) {
                MessageManager.sendMessage(sender, "&cCould not find a gate with the ID \"" + gateId + "\".");
                return;
            }

            gate.setActiveLength(length);
            gate.saveGate();
            MessageManager.sendMessage(sender, "&aYou have set the active length of the gate &b" + gateId + " &ato &b" + length + "&a.");
        } catch (NumberFormatException ignored) {
            MessageManager.sendMessage(sender, "&cYou must input a valid number as the length.");
        }
    }
}


text:
<?php
namespace Itgalaxy\Pillar\Tests;

use Itgalaxy\Pillar\Base\FeatureFactory;
use Itgalaxy\Pillar\Feature\AdminThumbnailColumnFeature;

class AdminThumbnailColumnFeatureTest extends \WP_UnitTestCase
{
    public function setUp()
    {
        parent::setUp();

        FeatureFactory::loadFeature(AdminThumbnailColumnFeature::class);
    }

    public function tearDown()
    {
        FeatureFactory::unloadFeature(AdminThumbnailColumnFeature::class);

        parent::tearDown();
    }

    public function test()
    {
        // Nothing
    }
}


text:
/* eslint-env browser */
const localforage = require('localforage')
localforage.config({ driver: localforage.INDEXEDDB })

function fetchNewToken () {
  return fetch('token')
  .then((result) => result.json())
  .then(({ token }) => token)
}

module.exports = {
  getToken: () => {
    return localforage.getItem('token')
    .then(token => {
      if (token) return token

      return fetchNewToken()
    })
  },

  saveToken: (token) => localforage.setItem('token', token),

  subscribeToken: (token, subscription) => {
    return fetch(`${token}/subscribe`, {
      method: 'POST',
      body: JSON.stringify(subscription)
    })
  },

  unsubscribeToken: (token) => {
    return fetch(`${token}/unsubscribe`)
    .then(() => localforage.removeItem('token'))
  }
}


text:
package com.softwinner.update;

import com.softwinner.update.Utils;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class LoaderReceiver extends BroadcastReceiver {
    private static final String TAG = "LoaderReceiver";

    public static final int CHECK_BEGIN_HOUR = 8;

    public static final int CHECK_ENT_HOUR = 24;

    public static final String UPDATE_GET_NEW_VERSION = "com.softwinner.update.UPDATE_GET_NEW_VERSION";

    public static final String CHECKING_TASK_COMPLETED = "com.softwinner.update.CHECKING_TASK_COMPLETED";

    public long CHECK_REPEATE_TIME = Utils.CHECK_CYCLE_DAY*24 * 60 * 60 * 1000;

    private static boolean rebootShallCheck=false;

    private void DailyCheck(Context context, Preferences prefs) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Calendar mCalendar = Calendar.getInstance();
        mCalendar.setTimeInMillis(System.currentTimeMillis());
        if (!Utils.DEBUG) {
            Log.i(TAG, "data now is :" + mCalendar.getTime());
            mCalendar.set(mCalendar.DAY_OF_YEAR, mCalendar.get(mCalendar.DAY_OF_YEAR) + Utils.CHECK_CYCLE_DAY);

            PendingIntent mPendingIntent = getPendingIntent(context, 0);
            alarmManager.setRepeating(AlarmManager.RTC, mCalendar.getTimeInMillis(),
                    CHECK_REPEATE_TIME, mPendingIntent);
        } else {
            mCalendar.set(mCalendar.MINUTE, mCalendar.get(mCalendar.MINUTE) + 10);
            PendingIntent mPendingIntent = getPendingIntent(context, 0);
            alarmManager.setRepeating(AlarmManager.RTC, mCalendar.getTimeInMillis(), 10 * 60 * 1000,
                    mPendingIntent);
        }
        Log.i(TAG, "check will at time:" + mCalendar.getTime());
    }

    private PendingIntent getPendingIntent(Context paramContext, int paramInt) {
        Intent localIntent = new Intent(paramContext, UpdateService.class);
        localIntent.putExtra(UpdateService.KEY_START_COMMAND,
                UpdateService.START_COMMAND_START_CHECKING);
        return PendingIntent.getService(paramContext, 0, localIntent, 0);
    }

    private void startService(Context context) {
    	if(Utils.DEBUG)Log.d(TAG,"startService");
        Intent mIntent = new Intent(context, UpdateService.class);
        mIntent.putExtra(UpdateService.KEY_START_COMMAND, UpdateService.START_COMMAND_START_CHECKING);
        context.startService(mIntent);
    }

    public boolean checkConnectivity(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        return info != null && info.isConnected();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Preferences prefs = new Preferences(context);
        String action = intent.getAction();
        if (Utils.DEBUG)
            Log.i(TAG, "receive a new action : " + action);
        if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION) && checkConnectivity(context)
                &&rebootShallCheck) {
        	rebootShallCheck=false;
            startService(context);
        } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
        	rebootShallCheck=true;
            DailyCheck(context, prefs);
        }
    }

}


text:
(function () {
    'use strict';

var tmpl = '';

// Class to add vessel as POI on Leaflet
function DeviceOnMap (map, data) {
    this.trace=[];  // keep trace of device trace on xx positions
    this.count=0;   // number of points created for this device
    this.devid = data.devid;
    this.src   = data.src;
    this.name  = data.name;
    this.cargo = data.cargo;
    this.vessel= ' cargo-' + data.cargo;
    this.map=map;
    this.lastshow = new Date().getTime();
}

DeviceOnMap.prototype.CreateCircle= function (radius) {
    var marker= L.marker([this.lat, this.lon],  {
        icon : L.divIcon({className:'vessel trace ' + this.src, iconSize:[3,3]}),
        clickable: true,
        title: this.name + ' [mmsi='+ this.devid+ ']'
      }).addTo(this.map);
    var info= "Name=" +this.name+" mmsi="+this.devid +"
lat:"+this.lat.toFixed(4) +" lon:" +this.lon.toFixed(4) +
              " sog:" + this.sog.toFixed(2)+ " cog:"+ this.cog.toFixed(2)+"
time: " +  this.LastShow();
    marker.bindPopup(""+info+"");
    return (marker);
};

DeviceOnMap.prototype.LastShow =function () {
    var date=new Date(this.lastshow);
    var hours   = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    var time    = hours+':'+minutes+':'+seconds;
    return time;
};

   // build a vector base on device heading & speed
DeviceOnMap.prototype.CreateVector =function () {
    if (this.vector) this.map.removeLayer (this.vector);

    // Create a vector lenght from this speed
    var len=2*this.sog;
    var sinDir, cosDir;

    // compute x/y direction depending on device heading
    if (this.cog < 180)  sinDir=1; else sinDir=-1;
    if (this.cog > 270 && this.cog < 90 )   cosDir=1; else cosDir=-1;
    // pts (0.0) is left uppercorner
    var pts= this.map.latLngToContainerPoint ([this.lat, this.lon]);
    var newx= parseInt (pts.x + (Math.sin(this.cog / 180)*len*sinDir));
    var newy= parseInt (pts.y + (Math.cos(this.cog* Math.PI / 180)*len*cosDir));

    this.vector=L.polyline ([[this.lat, this.lon], this.map.containerPointToLatLng(L.point(newx,newy))],
                {clickable:false, className: "vessel vector " +this.src, opacity:0.7, dashArray:[3, 10]}).addTo(this.map);

};

// Create a marker from device object and plate in on the map
DeviceOnMap.prototype.CreateMarker= function (status) {
    var activeclass;

    if (!this.lat || !this.lon) return;
    if (status) activeclass='active '; else activeclass='inactive ';

    this.active=status;
    this.marker= L.marker([this.lat, this.lon],
        {
           icon : L.divIcon({className:'vessel lonlat ' + activeclass + this.src + this.vessel, iconSize:[10,10]}),
           clickable: true,
           title: this.name + ' mmsi='+ this.devid+ '['+ activeclass + ']'
        }).addTo(this.map);

    var info= "Nom=" + this.name + " mmsi=" + this.devid + '/' + this.cargo + " " +
              "
Pos:" + this.lat.toFixed(4) + "," + this.lon.toFixed(4)  +
              "
LastShow=" + this.LastShow() + " ";
    this.marker.bindPopup(""+info+"");
};

// if no marker create on, else move it and update trace
DeviceOnMap.prototype.UpdatePos = function (data) {

    // no valid position just ignore
    if (!data.lat || !data.lon) return;
    this.lat = data.lat;
    this.lon = data.lon;
    this.sog = data.sog || 0;
    this.cog = data.cog || 0;
    this.lastshow = new Date().getTime();

    // if not active rebuilt marker
    if (!this.active) {
        if (this.marker) this.map.removeLayer (this.marker);
        this.CreateMarker(true);
    } else {
        if (this.sog > 0) {
            // move data marker to new location
            this.marker.setLatLng ([this.lat, this.lon]);
            // add a new point to trace
            var current= this.count;
            var next   = ++this.count % 10; // trace lenght
            this.trace[current]= this.CreateCircle (2);
            // clear old trace point if needed
            if (this.trace[next]) this.map.removeLayer (this.trace[next]);
        }
    }

    var info= "Nom=" + this.name + " mmsi=" + this.devid + '/[' + this.cargo + "] " +
              "
Pos:" + this.lat.toFixed(4) + "," + this.lon.toFixed(4)  +
              " Sog:" + this.sog.toFixed(2)+ " Cog:"+ this.cog.toFixed(2) + "" +
              "
LastShow=" + this.LastShow() + " ";

    this.marker.bindPopup(""+info+"");

    this.CreateVector();
};

DeviceOnMap.prototype.UpdateInfo= function(data) {
    var updated = false;

    // if AIS authent arrive after 1st position let's refresh VesselMaker
    if (!this.name && data.name) {
        update =true;
        this.name= data.name;
    }

    if (!this.cargo && data.cargo) {
        update =true;
        this.cargo= data.cargo;
    }

    if (updated) {
        if (this.marker) this.map.removeLayer (this.marker);
        this.CreateMarker(true);
    }
};

DeviceOnMap.prototype.DevicePing= function(data) {

    // if device was inactive change it status
    if (!this.active) {
        if (this.marker) this.map.removeLayer (this.marker);
        this.CreateMarker(true);
    }
    this.lastshow = new Date().getTime();
};

DeviceOnMap.prototype.SetInactive=function () {
    if (this.vector) this.map.removeLayer (this.vector);
    for (var slot in this.trace) {
        if (!this.trace [slot]) this.map.removeLayer(this.trace [slot]);
    }
    if (this.marker) this.map.removeLayer (this.marker);
    this.CreateMarker(false);
};

DeviceOnMap.prototype.RemoveTarget=function (scope) {
    if (this.marker) this.map.removeLayer (this.marker);
    for (var slot in this.trace) {
        if (!this.trace[slot]) this.map.removeLayer(this.trace [slot]);
    }
    delete scope.activeVessels [this.devid];
};

function AisWebsock (uri, callback) {

    var restart = function () {
       console.log ("AisWebsock will retry %s in 10s", uri);
       setTimeout (openws, 10000);
    };

    var openws = function () {

        var ws = new WebSocket(uri);
        if (!ws)  {
            console.log ("AisWebsock Open %s fail", uri);
            restart();
            return;
        } else console.log ("AisWebsock done ", uri);

        ws.onmessage = function (event) {
            callback (event.data);
        };

        ws.onerror = function (event) {
            console.log ("AisWebsock Closing %s", uri);
            restart();
        };
    };

    openws();     // init webscocket

}

    angular.module('AisToMap', [])
            .directive('aisToMap', function ($location, $timeout, urlquery) {

                function mymethods(scope, elem, attrs) {
                    scope.activeVessels=[];

                    // process AIS position returned by websocket
                    scope.DisplayCallback = function (message) {
                        console.log ('data=%s', message);
                        var data= JSON.parse (message);

                        switch (data.type) {
                            case 0: // initial messages get both auth & position info
                               scope.activeVessels [data.devid]= new DeviceOnMap (scope.map, data);
                               scope.activeVessels [data.devid].UpdateInfo(data);
                               scope.activeVessels [data.devid].UpdatePos (data);
                               break;

                            case 1: // authentication
                                if (!scope.activeVessels[data.devid]) scope.activeVessels [data.devid]= new DeviceOnMap (scope.map, data);
                                scope.activeVessels [data.devid].UpdateInfo (data);
                                break;

                            case 2: // position update
                                if (!scope.activeVessels[data.devid]) scope.activeVessels [data.devid]= new DeviceOnMap (scope.map, data);
                                scope.activeVessels [data.devid].UpdatePos (data);
                                break;

                            case 3: // device ping
                                if (scope.activeVessels[data.devid]) scope.activeVessels[data.devid].DevicePing(data);
                                break;

                            case 4: // data quit let's clean the place
                                if (!scope.activeVessels [data.devid]) {
                                    scope.activeVessels [data.devid].RemoveTarget(scope);
                                }
                                break;
                            default:
                               console.log ("HOOP: unknown message type: %s [%s]", data.type, JSON.stringify(data));
                        }
                    };

                    scope.CleanOldPos = function () {
                        var timeout1 = new Date().getTime() - (scope.inactivity*1000);
                        var timeout2 = new Date().getTime() - (scope.inactivity*2000);
                        for (var devid in scope.activeVessels) {
                            var vessel = scope.activeVessels[devid];
                            if (vessel.lastshow < timeout2) vessel.RemoveTarget(scope);
                            else if (vessel.lastshow < timeout1) vessel.SetInactive();
                        }
                        // Check for inactive vessels every 30s
                        $timeout (scope.CleanOldPos, scope.inactivity*250);
                    };

                    scope.StartTracking= function() {
                        // open websocket on sinagot.net localtraffic + Mobile + Tracker
                        new AisWebsock ("ws://" + $location.host() + "/ais-droid?API_KEY=123456789", scope.DisplayCallback);

                        // start process to clean old position
                        scope.CleanOldPos();
                    };

                    scope.Init = function() {

                        scope.map = L.map(attrs.id,  {"keyboardZoomOffset": 0.05, maxZoom: 20, "scrollWheelZoom": true });

                        // Default Morbihan (South Britanny)
                        scope.lat=urlquery.lat   || 48.123;
                        scope.lng=urlquery.lng   || -3.05;
                        scope.zoom=urlquery.zoom || 9;

                        scope.minzoom=attrs.minzoom || 0;
                        scope.maxzoom=attrs.maxzoom || 12;

                        scope.inactivity=attrs.inactivity || 1000; // time before moving target to inactive

                        // Warning: to use Tangram vector layer
                        //  - need to force load of tangram.min.js not concatenated with any other JS files
                        //  - load tangram.min.js with Index.htlm template and not through gulp
                        //var tangramLayer = Tangram.leafletLayer({
                        //    workerUrl: 'http://sinagot.prod/aisweb',
                        //    scene: 'config/LeafletMap.yaml',
                        //    attribution: 'Mapzen'
                        //}).addTo (scope.map);

                        var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
                        var osmAttrib='Map data © OpenStreetMap';
                        var osm = new L.TileLayer(osmUrl, {attribution: osmAttrib}).addTo (scope.map);

                        // References http://wiki.openseamap.org/wiki/OpenSeaMap_in_Website
                        var OpenSeaMap = L.tileLayer (
                            'http://tiles.openseamap.org/seamark/{z}/{x}/{y}.png',
                            {attribution: 'Map data: © OpenSeaMap aisweb by sinagot.net'}
                        ).addTo (scope.map);

                        // center the map
                        scope.map.setView ([scope.lat, scope.lng], scope.zoom);

                        $timeout (scope.StartTracking, 125);

                        // add listener on mouse move
                        scope.map.getContainer().addEventListener('mouseup', function (event) {
                            var latlng = scope.map.getCenter();
                            scope.lat = latlng.lat;
                            scope.lng = latlng.lng;

                            $location.search({lat:scope.lat, lng:scope.lng, zoom: scope.zoom});
                            scope.$apply();
                        });
                        scope.map.getContainer().addEventListener('mousewheel', function (event) {
                            scope.zoom = scope.map.getZoom();
                            $location.search({lat:scope.lat, lng:scope.lng, zoom: scope.zoom});
                            scope.$apply();
                        });
                    };

                    scope.Init ();

                }

                return {
                    restrict: 'E',
                    template: tmpl,
                    link: mymethods,
                    scope: {}
                };
            });
})();


text:
package org.apache.camel.component.huaweicloud.smn.models;

public class ClientConfigurations {

    private String operation;
    private String secretKey;
    private String authenticationkey;
    private String projectId;
    private String topicUrn;
    private String subject;
    private String proxyHost;
    private int proxyPort;
    private String proxyUser;
    private String proxyPassword;
    private String serviceEndpoint;
    private int messageTtl;
    private boolean ignoreSslVerification;

    public String getOperation() {
        return operation;
    }

    public void setOperation(String operation) {
        this.operation = operation;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getAuthenticationkey() {
        return authenticationkey;
    }

    public void setAuthenticationkey(String authenticationkey) {
        this.authenticationkey = authenticationkey;
    }

    public String getProjectId() {
        return projectId;
    }

    public void setProjectId(String projectId) {
        this.projectId = projectId;
    }

    public String getTopicUrn() {
        return topicUrn;
    }

    public void setTopicUrn(String topicUrn) {
        this.topicUrn = topicUrn;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getProxyHost() {
        return proxyHost;
    }

    public void setProxyHost(String proxyHost) {
        this.proxyHost = proxyHost;
    }

    public int getProxyPort() {
        return proxyPort;
    }

    public void setProxyPort(int proxyPort) {
        this.proxyPort = proxyPort;
    }

    public String getProxyUser() {
        return proxyUser;
    }

    public void setProxyUser(String proxyUser) {
        this.proxyUser = proxyUser;
    }

    public String getProxyPassword() {
        return proxyPassword;
    }

    public void setProxyPassword(String proxyPassword) {
        this.proxyPassword = proxyPassword;
    }

    public String getServiceEndpoint() {
        return serviceEndpoint;
    }

    public void setServiceEndpoint(String serviceEndpoint) {
        this.serviceEndpoint = serviceEndpoint;
    }

    public int getMessageTtl() {
        return messageTtl;
    }

    public void setMessageTtl(int messageTtl) {
        this.messageTtl = messageTtl;
    }

    public boolean isIgnoreSslVerification() {
        return ignoreSslVerification;
    }

    public void setIgnoreSslVerification(boolean ignoreSslVerification) {
        this.ignoreSslVerification = ignoreSslVerification;
    }
}


text:
<!doctype html>

		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

		<title>AAP'15 | Candidatura</title>

		<meta name="description" content="Lisbon Psych Fest, produced by Killer Mathilda, aims to showcase new and exciting alternative music from several different countries, while also focusing on exposing emerging local bands.">
		<meta name="keywords" content="Artes, Arts, Performativas, Performing, Ourique, Almodôvar, Music, alternative, independent, fest, Festival">
		<meta name="author" content="BEM BOM STUDIO">

		<meta property="og:title" content="ATALAIA ARTES PERFORMATIVAS 2015">
		<meta property="og:image" content="../img/img-fb.jpg">
		<meta property="og:site_name" content="ATALAIA ARTES PERFORMATIVAS">
		<meta property="og:description" content="Lisbon Psych Fest, produced by Killer Mathilda, aims to showcase new and exciting alternative music from several different countries, while also focusing on exposing emerging local bands.">

		<link rel="shortcut icon" href="favicon.ico">

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

		<link rel="stylesheet" href="css/reset.css">
		<link rel="stylesheet" href="css/style.css">

		<link href="css/full-slider.css" rel="stylesheet">
		<link href="css/modal.css" rel="stylesheet">
		<link href="css/pages.css" rel="stylesheet">

Imprensa

Edições Anteriores

Blog

Candidaturas para 2016

 OLÁ,
 FORMULÁRIO BREVEMENTE DISPONÍVEL.

Organização

Contatos

E.  aap@atalaiaartes.com

T.  +351 28 651 22 63 / +351 96 786 56 54

M.  Rua Gago Coutinho, 31, 7670-289 Ourique, Portugal

Segue-nos

							Facebook
							Twitter
							Vimeo

© Atalaia Artes Performativas . Todos os direitos reservados

Criação de
								LUDICUS LUCIDUS


text:
package com.tinkerpop.blueprints.util.wrappers.partition;

import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Index;
import com.tinkerpop.blueprints.IndexableGraph;
import com.tinkerpop.blueprints.Parameter;
import com.tinkerpop.blueprints.util.wrappers.WrapperGraph;

import java.util.Set;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class PartitionIndexableGraph<T extends IndexableGraph> extends PartitionGraph<T> implements IndexableGraph, WrapperGraph<T> {

    public PartitionIndexableGraph(final T baseIndexableGraph, final String writeGraphKey, final String writeGraph, final Set<String> readGraphs) {
        super(baseIndexableGraph, writeGraphKey, writeGraph, readGraphs);
    }

    public PartitionIndexableGraph(final T baseIndexableGraph, final String writeGraphKey, final String readWriteGraph) {
        super(baseIndexableGraph, writeGraphKey, readWriteGraph);
    }

    public void dropIndex(final String indexName) {
        baseGraph.dropIndex(indexName);
    }

    public Iterable<Index<? extends Element>> getIndices() {
        return new PartitionIndexIterable(baseGraph.getIndices(), this);
    }

    @SuppressWarnings("hiding")
	public <T extends Element> Index<T> getIndex(final String indexName, final Class<T> indexClass) {
        final Index<T> index = baseGraph.getIndex(indexName, indexClass);
        if (null == index)
            return null;
        else {
            return new PartitionIndex<T>(index, this);
        }
    }

    @SuppressWarnings("hiding")
	public <T extends Element> Index<T> createIndex(final String indexName, final Class<T> indexClass, final Parameter... indexParameters) {
        return new PartitionIndex<T>(baseGraph.createIndex(indexName, indexClass, indexParameters), this);
    }

}


text:
using System;
using Jasily.Data.SQLBuilder.Enums;

namespace Jasily.Data.SQLBuilder.Attributes
{
    public class DbConflictableAttribute : Attribute
    {
        public SQLiteConflictMode Conflict { get; set; }
    }
}