text:
using System;

namespace LoggingLibrary.Abstractions
{
  /// <summary>
  /// Abstracts a logger
  /// </summary>
  public abstract class Logger
  {
    /// <summary>
    /// Writes a log entry
    /// </summary>
    /// <param name="level">The logging level</param>
    /// <param name="e">The exception to be logged</param>
    public abstract void Write(LogLevel level, Exception e);
  }
}

redpajama_set_name: RedPajamaGithub


text:
import logging
from django.http import Http404, HttpResponse
import requests
import json
from point import LocationPoint

#Logging
logger = logging.getLogger(__name__)
import os
import datetime, time

class ReittiopasAPI:
    def __init__(self):
        #init
        self.__epsg_in='wgs84'
        self.__epsg_out='wgs84'
        self.__user=os.environ.get('REITTIOPASAPI_USER', '')
        self.__passwd=os.environ.get('REITTIOPASAPI_PASSWD', '')

    def get_reverse_geocode(self, coordinates):
        result = LocationPoint()
        json_response = self.execute_reverse_geocode(coordinates)
        if json_response.status_code == requests.codes.ok:
            try:
                logger.debug(json_response.url)
                r = json.dumps(json_response.json())
                routes = json.loads(r)
                for route in routes:
                    r = json.dumps(route["name"])
                    result.set_address(r.replace('"',""))
                    result.set_coords(coordinates)
            except ValueError:
                logger.debug(json_response.url)
                logger.warn("Unknown location %s" % str(coordinates))
        else:
            logger.warn(json_response.status_code)
            json_response.raise_for_status()

        return result

    def get_reverse_geocode_city(self, coordinates):
        city = ""
        json_response = self.execute_reverse_geocode(coordinates)
        if json_response.status_code == requests.codes.ok:
            try:
                logger.debug(json_response.url)
                r = json.dumps(json_response.json())
                routes = json.loads(r)
                for route in routes:
                    city = str(route["city"])
            except ValueError:
                logger.debug(json_response.url)
                logger.warn("Unknown location %s" % str(coordinates))
        else:
            logger.warn(json_response.status_code)
            json_response.raise_for_status()

        return city

    def execute_reverse_geocode(self, coordinates):
        parameters = {'request': 'reverse_geocode',
                      'coordinate': coordinates,
                      'epsg_in':self.__epsg_in,
                      'epsg_out':self.__epsg_out,
                      'user':self.__user,
                      'pass': self.__passwd}
        json_response = requests.get("http://api.reittiopas.fi/hsl/prod/", params=parameters)
        return json_response

    def is_empty(self, string):
        if string != None:
            if string != 0:
                if len(string) > 0:
                    return False
        return True

    def get_geocode(self, address, city_coordinates):
        result = LocationPoint()
        parameters = {'request': 'geocode',
                      'key': address,
                      'loc_types': 'address',
                      'epsg_in':self.__epsg_in,
                      'epsg_out':self.__epsg_out,
                      'user':self.__user,
                      'pass': self.__passwd}
        json_response = requests.get("http://api.reittiopas.fi/hsl/prod/", params=parameters)
        if json_response.status_code == requests.codes.ok:
            try:
                logger.debug(json_response.url)
                r = json.dumps(json_response.json())
                routes = json.loads(r)
                size = len(routes)
                if size > 1:
                    if self.is_empty(city_coordinates) == False:
                        city = self.get_reverse_geocode_city(city_coordinates)
                for route in routes:
                    r = json.dumps(route["matchedName"])
                    result.set_address(r.replace('"',""))
                    coordinates = str(route["coords"])
                    result.set_coords(coordinates)
                    if self.is_empty(city) == False and city == str(route["city"]):
                        return result

            except ValueError:
                logger.debug(json_response.url)
                logger.warn("Unknown location %s" % str(address))
        else:
            logger.warn(json_response.status_code)
            json_response.raise_for_status()

        return result

    def get_route_information(self, start, end, time1,walk_cost, change_margin):
        #api.reittiopas.fi/hsl/prod/?request=route&from=2546445,6675512&to=2549445,6675513&time=1030&timetype=arrival
        result = ""
        a = time1 #.strptime(time1, "%Y-%m-%d %H:%M:%S")
        d = "%s%02d%02d" % (a.year, a.month, a.day)
        s = "%02d%02d" % (a.hour, a.minute)
        start_time = s
        start_date = int(d)

        logger.warn(d)
        logger.warn(s)

        if change_margin == 0 or change_margin == "":
            change_margin = 1.0

        parameters = {'request': 'route',
                      'from': start,
                      'to': end,
                      'date': start_date,
                      'time': start_time,
                      'walk_cost': walk_cost,
                      'change_margin': change_margin,
                      'epsg_in':self.__epsg_in,
                      'epsg_out':self.__epsg_out,
                      'user':self.__user,
                      'pass': self.__passwd}
        json_response = requests.get("http://api.reittiopas.fi/hsl/prod/", params=parameters)
        if json_response.status_code == requests.codes.ok:
            try:
                logger.debug(json_response.url)
                result = json.loads(json.dumps(json_response.json()))
            except ValueError:
                logger.debug(json_response.url)
                logger.warn("Unknown route %s %s" % (str(start), str(end)))
        else:
            logger.debug(json_response.url)
            logger.warn(json_response.status_code)
            json_response.raise_for_status()

        return result


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

<apidoc>
	<namespace name="SEIDS::Heaps::Binary">
		<class name="MaxHeap" version="1.0">
			<extends>Heap</extends>

			<title>A binary max-heap class</title>
			<description>

					This class provides the main functionalities of a heap,
					keeping the maximum on the top. The underlying
					implementation is a binary heap.

					It provides the same interface as <class>SplMaxHeap</class>
					with the extra methods, <method>Heap::extractInsert</method>
					and <method>Heap::update</method> which allows one to update
					a node in the heap.

			</description>

			<see>
				<link href="http://php.net/manual/en/class.splmaxheap.php">The SplMaxHeap class</link>
			</see>
			<see>
				<class>MinHeap</class>
				<description>A binary min-heap class</description>
			</see>

			<method name="compare" access="protected" version="1.0">
				<title>Compare elements in order to place them correctly in the heap</title>
				<description>

						Compare <parameter>value1</parameter> with
						<parameter>value2</parameter>.

					<note>
						Having multiple elements with the same value in a Heap
						is not recommended. They will end up in an arbitrary
						relative position.
					</note>
				</description>

				<parameter name="value1">The value of the first node being compared.</parameter>
				<parameter name="value2">The value of the second node being compared.</parameter>
				<return type="int">Result of the comparison, positive integer if <parameter>value1</parameter> is greater than <parameter>value2</parameter>, <literal>0</literal> if they are equal, negative integer otherwise.</return>

				<see>
					<link href="http://php.net/manual/en/splmaxheap.compare.php">SplMaxHeap::compare</link>
				</see>
			</method>
		</class>
	</namespace>
</apidoc>


text:
#include <aws/inspector/model/RemoveAttributesFromFindingsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::Inspector::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

RemoveAttributesFromFindingsResult::RemoveAttributesFromFindingsResult()
{
}

RemoveAttributesFromFindingsResult::RemoveAttributesFromFindingsResult(const AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

RemoveAttributesFromFindingsResult& RemoveAttributesFromFindingsResult::operator =(const AmazonWebServiceResult<JsonValue>& result)
{
  const JsonValue& jsonValue = result.GetPayload();
  if(jsonValue.ValueExists("failedItems"))
  {
    Aws::Map<Aws::String, JsonValue> failedItemsJsonMap = jsonValue.GetObject("failedItems").GetAllObjects();
    for(auto& failedItemsItem : failedItemsJsonMap)
    {
      m_failedItems[failedItemsItem.first] = failedItemsItem.second.AsObject();
    }
  }

  return *this;
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.thinkaurelius.titan.diskstorage.log Class Hierarchy (Titan 1.0.0 API)</title>
<meta name="date" content="2015-09-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.thinkaurelius.titan.diskstorage.log

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

com.thinkaurelius.titan.diskstorage.log.ReadMarker

Interface Hierarchy

com.thinkaurelius.titan.diskstorage.log.Log

com.thinkaurelius.titan.diskstorage.log.LogManager

com.thinkaurelius.titan.diskstorage.log.Message

com.thinkaurelius.titan.diskstorage.log.MessageReader

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2012–2015. All rights reserved.


text:
require 'kontena/cli/stacks/yaml/stack_file_loader'

module Kontena
  module Plugin
    module Shell
      class PromptLoader < Kontena::Cli::Stacks::YAML::StackFileLoader
        def self.match?(source, parent = nil)
          source.end_with?('kontena.yml') && !Kontena::Cli::Stacks::YAML::FileLoader.match?(source, parent)
        end

        def read_content
          content = Kontena.prompt.multiline("Enter or paste a stack YAML").join
          raise "Invalid stack YAML" unless YAML.safe_load(content).kind_of?(Hash)
          content
        end

        def origin
          "prompt"
        end

        def registry
          "prompt"
        end
      end
    end
  end
end


text:
// Type definitions for @feathersjs/feathers 3.1
// Project: http://feathersjs.com/
// Definitions by:  Jan Lohage <https://github.com/j2L4e>
//                  Abraao Alves <https://github.com/AbraaoAlves>
//                  Tim Mensch <https://github.com/TimMensch>
//                  Jordan Tucker <https://github.com/jordanbtucker>
//                  Desmond Koh <https://github.com/deskoh>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

// TypeScript Version: 2.8

/// <reference types="node" />

import { EventEmitter } from 'events';

declare const feathers: Feathers;
export = feathers;

interface Feathers {
    // tslint:disable-next-line no-unnecessary-generics
    <T = any>(): feathers.Application<T>;
    version: string;
    SKIP: feathers.SkipSymbol;
    default: Feathers;
}

declare namespace feathers {
    type Id = number | string;
    type NullableId = Id | null;

    interface Query {
        [key: string]: any;
    }

    interface PaginationOptions {
        default: number;
        max: number;
    }

    type ClientSideParams = Pick<Params, 'query' | 'paginate'>;
    type ServerSideParams = Params;

    interface Params {
        query?: Query;
        paginate?: false | Pick<PaginationOptions, 'max'>;

        [key: string]: any; // (JL) not sure if we want this
    }

    interface Paginated<T> {
        total: number;
        limit: number;
        skip: number;
        data: T[];
    }

    // tslint:disable-next-line void-return
    type Hook = (hook: HookContext) => (Promise<HookContext | SkipSymbol | void> | HookContext | SkipSymbol | void);

    type SkipSymbol = symbol | '__feathersSkipHooks';

    interface HookContext<T = any> {
        /**
         * A read only property that contains the Feathers application object. This can be used to
         * retrieve other services (via context.app.service('name')) or configuration values.
         */
        readonly app: Application;
        /**
         * A writeable property containing the data of a create, update and patch service
         * method call.
         */
        data?: T;
        /**
         * A writeable property with the error object that was thrown in a failed method call.
         * It is only available in error hooks.
         */
        error?: any;
        /**
         * A writeable property and the id for a get, remove, update and patch service
         * method call. For remove, update and patch context.id can also be null when
         * modifying multiple entries. In all other cases it will be undefined.
         */
        id?: string | number;
        /**
         * A read only property with the name of the service method (one of find, get,
         * create, update, patch, remove).
         */
        readonly method: string;
        /**
         * A writeable property that contains the service method parameters (including
         * params.query).
         */
        params: Params;
        /**
         * A read only property and contains the service name (or path) without leading or
         * trailing slashes.
         */
        readonly path: string;
        /**
         * A writeable property containing the result of the successful service method call.
         * It is only available in after hooks.
         *
         * `context.result` can also be set in
         *
         *  - A before hook to skip the actual service method (database) call
         *  - An error hook to swallow the error and return a result instead
         */
        result?: T;
        /**
         * A read only property and contains the service this hook currently runs on.
         */
        readonly service: Service<T>;
        /**
         * A writeable, optional property and contains a "safe" version of the data that
         * should be sent to any client. If context.dispatch has not been set context.result
         * will be sent to the client instead.
         */
        dispatch?: T;
        /**
         * A writeable, optional property that allows to override the standard HTTP status
         * code that should be returned.
         */
        statusCode?: number;
        /**
         * A read only property with the hook type (one of before, after or error).
         */
        readonly type: "before" | "after" | "error";
    }

    interface HookMap {
        all: Hook | Hook[];
        find: Hook | Hook[];
        get: Hook | Hook[];
        create: Hook | Hook[];
        update: Hook | Hook[];
        patch: Hook | Hook[];
        remove: Hook | Hook[];
    }

    interface HooksObject {
        before: Partial<HookMap> | Hook | Hook[];
        after: Partial<HookMap> | Hook | Hook[];
        error: Partial<HookMap> | Hook | Hook[];
        finally?: Partial<HookMap> | Hook | Hook[];
    }

    // todo: figure out what to do: These methods don't actually need to be implemented, so they can be undefined at runtime. Yet making them optional gets cumbersome in strict mode.
    interface ServiceMethods<T> {
        find(params?: Params): Promise<T | T[] | Paginated<T>>;

        get(id: Id, params?: Params): Promise<T>;

        create(data: Partial<T> | Array<Partial<T>>, params?: Params): Promise<T | T[]>;

        update(id: NullableId, data: T, params?: Params): Promise<T>;

        patch(id: NullableId, data: Partial<T>, params?: Params): Promise<T>;

        remove(id: NullableId, params?: Params): Promise<T>;
    }

    interface SetupMethod {
        setup(app: Application<any>, path: string): void;
    }

    interface ServiceOverloads<T> {
        create(data: Array<Partial<T>>, params?: Params): Promise<T[]>;

        create(data: Partial<T>, params?: Params): Promise<T>;

        patch(id: NullableId, data: Pick<T, keyof T>, params?: Params): Promise<T>;
    }

    interface ServiceAddons<T> extends EventEmitter {
        hooks(hooks: Partial<HooksObject>): this;
    }

    type Service<T> = ServiceOverloads<T> & ServiceAddons<T> & ServiceMethods<T>;

    interface Application<ServiceTypes = {}> extends EventEmitter {
        get(name: string): any;

        set(name: string, value: any): this;

        disable(name: string): this;

        disabled(name: string): boolean;

        enable(name: string): this;

        enabled(name: string): boolean;

        configure(callback: (this: this, app: this) => void): this;

        hooks(hooks: Partial<HooksObject>): this;

        setup(server?: any): this;

        service<L extends keyof ServiceTypes>(location: L): Service<ServiceTypes[L]>;

        service(location: string): keyof ServiceTypes extends never ? Service<any> : never;

        use(path: string, service: Partial<ServiceMethods<any> & SetupMethod> | Application<any>, options?: any): this;

        version: string;
    }
}


text:
@interface MTBBasicExampleViewController : UIViewController

@end


text:
package org.apache.sqoop.tool;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cloudera.sqoop.Sqoop;
import com.cloudera.sqoop.SqoopOptions;
import com.cloudera.sqoop.hive.HiveImport;
import com.cloudera.sqoop.util.ImportException;

/**
 * Tool that performs database imports of all tables in a database to HDFS.
 */
public class ImportAllTablesTool extends com.cloudera.sqoop.tool.ImportTool {

  public static final Log LOG = LogFactory.getLog(
      ImportAllTablesTool.class.getName());

  public ImportAllTablesTool() {
    super("import-all-tables", true);
  }

  @Override
  /** {@inheritDoc} */
  public int run(SqoopOptions options) {
    HiveImport hiveImport = null;

    if (!init(options)) {
      return 1;
    }

    try {
      if (options.doHiveImport()) {
        hiveImport = new HiveImport(options, manager, options.getConf(), false);
      }

      String [] tables = manager.listTables();
      if (null == tables) {
        System.err.println("Could not retrieve tables list from server");
        LOG.error("manager.listTables() returned null");
        return 1;
      } else {
        for (String tableName : tables) {
          importTable(options, tableName, hiveImport);
        }
      }
    } catch (IOException ioe) {
      LOG.error("Encountered IOException running import job: "
          + ioe.toString());
      if (System.getProperty(Sqoop.SQOOP_RETHROW_PROPERTY) != null) {
        throw new RuntimeException(ioe);
      } else {
        return 1;
      }
    } catch (ImportException ie) {
      LOG.error("Error during import: " + ie.toString());
      if (System.getProperty(Sqoop.SQOOP_RETHROW_PROPERTY) != null) {
        throw new RuntimeException(ie);
      } else {
        return 1;
      }
    } finally {
      destroy(options);
    }

    return 0;
  }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>devtools module — CleverHans  documentation</title>
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/alabaster.css" type="text/css" />

    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />

  <link rel="stylesheet" href="../_static/custom.css" type="text/css" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

devtools module¶

CleverHans

Navigation

attacks module

model module

Related Topics

Documentation overview

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" />
      <input type="submit" value="Go" />
    </form>


text:
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Stardust.Node;
using Stardust.Node.Interfaces;
using Stardust.Node.Timers;

namespace NodeTest.Fakes.Timers
{
	public class NodeStartupNotificationToManagerFake : TrySendNodeStartUpNotificationToManagerTimer
	{
		public ManualResetEventSlim Wait = new ManualResetEventSlim();

		public NodeStartupNotificationToManagerFake(NodeConfiguration nodeConfiguration,
													IHttpSender httpSender,
		                                            double interval = 1000,
		                                            bool autoReset = false) : base(httpSender,
																				   interval,
		                                                                           autoReset)
		{
            SetupAndStart(nodeConfiguration);
		}

		public override Task<HttpResponseMessage> TrySendNodeStartUpToManager(Uri nodeAddress,
																			  Uri callbackToManagerUri,
		                                                                      CancellationToken cancellationToken)
		{
			Wait.Set();

			var response = new HttpResponseMessage(HttpStatusCode.OK);

			var request = new HttpRequestMessage(HttpMethod.Post,
			                                     CallbackToManagerTemplateUri);

			response.RequestMessage = request;

			return Task.FromResult(response);
		}
	}
}


text:
package br.com.architecteam.algorithms.numeric;

public final class ArrayUtils {

    private ArrayUtils() {
    }

    /**
     * Given an array with at least size 2, calculate the maximum product between
     * any 2 numbers
     *
     * @param nums an array with size >= 2
     *
     * @return the maximum possible product between any 2 numbers
     */
    public static int maxProduct(int[] nums) {
	if (nums == null || nums.length < 2) {
	    throw new IllegalArgumentException();
	}

	int small = Integer.MAX_VALUE;
	int smallest = Integer.MAX_VALUE;
	int big = Integer.MIN_VALUE;
	int biggest = Integer.MIN_VALUE;

	for (int i : nums) {
	    if (i < small) {
		small = i;
		if (small < smallest) {
		    int tmp = smallest;
		    smallest = small;
		    small = tmp;
		}
	    }
	    if (i > big) {
		big = i;
		if (big > biggest) {
		    int tmp = biggest;
		    biggest = big;
		    big = tmp;
		}
	    }
	}

	return Math.max(small * smallest, big * biggest);
    }

}


text:
package net.minecraft.client.renderer.tileentity;

import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelEnderCrystal;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityEnderCrystal;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;

public class RenderEnderCrystal extends Render
{
    private static final ResourceLocation enderCrystalTextures = new ResourceLocation("textures/entity/endercrystal/endercrystal.png");
    private ModelBase field_76995_b = new ModelEnderCrystal(0.0F, true);
    private static final String __OBFID = "CL_00000987";

    public RenderEnderCrystal(RenderManager p_i46184_1_)
    {
        super(p_i46184_1_);
        this.shadowSize = 0.5F;
    }

    /**
     * Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then
     * handing it off to a worker function which does the actual work. In all probabilty, the class Render is generic
     * (Render<T extends Entity) and this method has signature public void doRender(T entity, double d, double d1,
     * double d2, float f, float f1). But JAD is pre 1.5 so doesn't do that.
     */
    public void doRender(EntityEnderCrystal p_76986_1_, double p_76986_2_, double p_76986_4_, double p_76986_6_, float p_76986_8_, float p_76986_9_)
    {
        float var10 = (float)p_76986_1_.innerRotation + p_76986_9_;
        GlStateManager.pushMatrix();
        GlStateManager.translate((float)p_76986_2_, (float)p_76986_4_, (float)p_76986_6_);
        this.bindTexture(enderCrystalTextures);
        float var11 = MathHelper.sin(var10 * 0.2F) / 2.0F + 0.5F;
        var11 += var11 * var11;
        this.field_76995_b.render(p_76986_1_, 0.0F, var10 * 3.0F, var11 * 0.2F, 0.0F, 0.0F, 0.0625F);
        GlStateManager.popMatrix();
        super.doRender(p_76986_1_, p_76986_2_, p_76986_4_, p_76986_6_, p_76986_8_, p_76986_9_);
    }

    protected ResourceLocation func_180554_a(EntityEnderCrystal p_180554_1_)
    {
        return enderCrystalTextures;
    }

    /**
     * Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture.
     */
    protected ResourceLocation getEntityTexture(Entity p_110775_1_)
    {
        return this.func_180554_a((EntityEnderCrystal)p_110775_1_);
    }

    /**
     * Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then
     * handing it off to a worker function which does the actual work. In all probabilty, the class Render is generic
     * (Render<T extends Entity) and this method has signature public void doRender(T entity, double d, double d1,
     * double d2, float f, float f1). But JAD is pre 1.5 so doesn't do that.
     */
    public void doRender(Entity p_76986_1_, double p_76986_2_, double p_76986_4_, double p_76986_6_, float p_76986_8_, float p_76986_9_)
    {
        this.doRender((EntityEnderCrystal)p_76986_1_, p_76986_2_, p_76986_4_, p_76986_6_, p_76986_8_, p_76986_9_);
    }
}


text:
package edu.uw.zookeeper.protocol.client;

import io.netty.buffer.ByteBuf;

import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.logging.log4j.LogManager;

import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import com.google.common.base.Optional;

import edu.uw.zookeeper.common.Automaton;
import edu.uw.zookeeper.common.Automatons;
import edu.uw.zookeeper.common.Pair;
import edu.uw.zookeeper.common.Reference;
import edu.uw.zookeeper.common.Stateful;
import edu.uw.zookeeper.common.Automatons.AutomatonListener;
import edu.uw.zookeeper.net.Decoder;
import edu.uw.zookeeper.net.Encoder;
import edu.uw.zookeeper.protocol.ConnectMessage;
import edu.uw.zookeeper.protocol.Frame;
import edu.uw.zookeeper.protocol.Message;
import edu.uw.zookeeper.protocol.Operation;
import edu.uw.zookeeper.protocol.ProtocolCodec;
import edu.uw.zookeeper.protocol.ProtocolMessageAutomaton;
import edu.uw.zookeeper.protocol.ProtocolState;
import edu.uw.zookeeper.protocol.ProtocolResponseMessage;
import edu.uw.zookeeper.protocol.proto.OpCode;
import edu.uw.zookeeper.protocol.proto.OpCodeXid;

/**
 * Implemented for the case where encode is called by a different thread than decode,
 * but it is not safe for multiple threads to call encode or multiple
 * threads to call decode.
 */
public class ClientProtocolCodec
    implements ProtocolCodec<Message.ClientSession, Message.ServerSession, Message.ClientSession, Message.ServerSession> {

    public static ClientProtocolCodec defaults() {
        return newInstance(ProtocolState.ANONYMOUS);
    }

    public static ClientProtocolCodec newInstance(ProtocolState state) {
        Automatons.SynchronizedEventfulAutomaton<ProtocolState, Object,?> automaton =
                Automatons.createSynchronizedEventful(
                        Automatons.createEventful(
                                Automatons.createLogging(
                                        LogManager.getLogger(ClientProtocolCodec.class),
                                        ProtocolMessageAutomaton.asAutomaton(state))));
        Pending pending = Pending.newInstance();
        Encoder<? super Message.ClientSession, ?> encoder =
                Frame.FramedEncoder.create(
                        ClientProtocolEncoder.newInstance(automaton));
        Decoder<Optional<Message.ServerSession>, ?> decoder =
                Frame.FramedDecoder.create(
                        Frame.FrameDecoder.getDefault(),
                        ClientProtocolDecoder.newInstance(automaton, pending));
        return new ClientProtocolCodec(automaton, encoder, decoder, pending.get());
    }

    protected static class Pending implements Function<Integer, OpCode>, Reference<Queue<Pair<Integer, OpCode>>> {
        public static Pending newInstance() {
            return new Pending(new ConcurrentLinkedQueue<Pair<Integer, OpCode>>());
        }

        // must be thread-safe
        private final Queue<Pair<Integer, OpCode>> queue;

        public Pending(Queue<Pair<Integer, OpCode>> queue) {
            this.queue = queue;
        }

        @Override
        public OpCode apply(Integer xid) {
            Pair<Integer, OpCode> next = queue.peek();
            if (next == null) {
                throw new IllegalStateException(String.format("Unexpected xid (%d), no pending requests", xid));
            }
            if (xid.equals(next.first())) {
                return next.second();
            } else {
                throw new IllegalArgumentException(String.format("Unexpected xid (%d), expecting %s", xid, next));
            }
        }

        @Override
        public Queue<Pair<Integer, OpCode>> get() {
            return queue;
        }
    }

    protected final Automatons.EventfulAutomaton<ProtocolState, Object> automaton;
    protected final Encoder<? super Message.ClientSession, ?> encoder;
    protected final Decoder<Optional<Message.ServerSession>, ?> decoder;
    protected final Queue<Pair<Integer, OpCode>> pending;

    protected ClientProtocolCodec(
            Automatons.EventfulAutomaton<ProtocolState, Object> automaton,
            Encoder<? super Message.ClientSession, ?> encoder,
            Decoder<Optional<Message.ServerSession>, ?> decoder,
            Queue<Pair<Integer, OpCode>> pending) {
        this.automaton = automaton;
        this.encoder = encoder;
        this.decoder = decoder;
        this.pending = pending;
    }

    @Override
    public void subscribe(AutomatonListener<ProtocolState> listener) {
        automaton.subscribe(listener);
    }

    @Override
    public boolean unsubscribe(AutomatonListener<ProtocolState> listener) {
        return automaton.unsubscribe(listener);
    }

    @Override
    public Class<Message.ClientSession> encodeType() {
        return Message.ClientSession.class;
    }

    @Override
    public Class<? extends Message.ServerSession> decodeType() {
        return Message.ServerSession.class;
    }

    /**
     * Don't call concurrently!
     */
    @Override
    public void encode(Message.ClientSession input, ByteBuf output) throws IOException {
        encoder.encode(input, output);
        automaton.apply(input);
        // we only need to remember xid -> opcode of pending messages
        if (input instanceof Operation.RequestId) {
            int xid = ((Operation.RequestId) input).xid();
            if (! OpCodeXid.has(xid)) {
                assert (input instanceof Operation.ProtocolRequest);
                OpCode opcode = ((Operation.ProtocolRequest<?>) input).record().opcode();
                Pair<Integer, OpCode> pair = Pair.create(xid, opcode);
                pending.add(pair);
            }
        }
    }

    /**
     * Don't call concurrently!
     */
    @Override
    public Optional<Message.ServerSession> decode(ByteBuf input)
            throws IOException {
        Optional<Message.ServerSession> out =  decoder.decode(input);
        if (out.isPresent()) {
            automaton.apply(out.get());
            Message.ServerSession reply = out.get();
            // the peek and poll need to be atomic
            Pair<Integer, OpCode> next = pending.peek();
            if ((next != null) && (reply instanceof Operation.RequestId)) {
                if (next.first().equals(((Operation.RequestId) reply).xid())) {
                    pending.poll();
                }
            }
        }
        return out;
    }

    @Override
    public ProtocolState state() {
        return automaton.state();
    }

    @Override
    public Optional<Automaton.Transition<ProtocolState>> apply(
            ProtocolState input) {
        return automaton.apply(input);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this).add("state", state()).toString();
    }

    public static class ClientProtocolEncoder implements
            Stateful<ProtocolState>,
            Encoder<Message.ClientSession, Message.ClientSession> {

        public static ClientProtocolEncoder newInstance(
                Stateful<ProtocolState> stateful) {
            return new ClientProtocolEncoder(stateful);
        }

        private final Stateful<ProtocolState> stateful;

        private ClientProtocolEncoder(
                Stateful<ProtocolState> stateful) {
            this.stateful = stateful;
        }

        @Override
        public ProtocolState state() {
            return stateful.state();
        }

        @Override
        public Class<Message.ClientSession> encodeType() {
            return Message.ClientSession.class;
        }

        @Override
        public void encode(Message.ClientSession input, ByteBuf output) throws IOException {
            ProtocolState state = state();
            switch (state) {
            case ANONYMOUS:
            case CONNECTING:
            case CONNECTED:
            case DISCONNECTING:
                input.encode(output);
                break;
            default:
                throw new IllegalStateException(state.toString());
            }
        }
    }

    public static class ClientProtocolDecoder implements
            Stateful<ProtocolState>,
            Decoder<Message.ServerSession, Message.ServerSession> {

        public static ClientProtocolDecoder newInstance(
                Stateful<ProtocolState> stateful,
                Function<Integer, OpCode> xidToOpCode) {
            return new ClientProtocolDecoder(stateful, xidToOpCode);
        }

        private final Stateful<ProtocolState> stateful;
        private final Function<Integer, OpCode> xidToOpCode;

        private ClientProtocolDecoder(
                Stateful<ProtocolState> stateful,
                Function<Integer, OpCode> xidToOpCode) {
            this.stateful = stateful;
            this.xidToOpCode = xidToOpCode;
        }

        @Override
        public ProtocolState state() {
            return stateful.state();
        }

        @Override
        public Class<? extends Message.ServerSession> decodeType() {
            return Message.ServerSession.class;
        }

        @Override
        public Message.ServerSession decode(ByteBuf input) throws IOException {
            ProtocolState state = state();
            Message.ServerSession out;
            switch (state) {
            case CONNECTING:
                out = ConnectMessage.Response.decode(input);
                break;
            case CONNECTED:
            case DISCONNECTING:
                out = ProtocolResponseMessage.decode(xidToOpCode, input);
                break;
            default:
                throw new IllegalStateException(state.toString());
            }
            return out;
        }
    }
}


text:
test("test_rangeValidator", function () {

    var errorMsg = "Test error message";
    var rv = cl.validators.rangeValidator(20, 100, errorMsg);
    var xml = rv.toXml();

    ok(rv.validate(40), "test for value within range");
    ok(!rv.validate(200), "test for value out of range");

    equal(rv.errorMsg, errorMsg, "test error message");

    var xmlDoc = $.parseXML(xml);
    var $xml = $(xmlDoc);
    var $validator = $xml.find("validator[name='rangeValidator']");
    var $minValue = $validator.find('minValue');
    var $maxValue = $validator.find('maxValue');
    var $errorMsg = $validator.find('errorMsg');

    equal(errorMsg, $errorMsg.text(), "test error message");
    equal(parseInt($minValue.text(), 10), 20, "test minValue");
    equal(parseInt($maxValue.text(), 10), 100, "test maxValue");
});


text:
layout: page
title: Sub Limited Conference
date: 2016-05-24
author: Grace Reyes
tags: weekly links, java
status: published
summary: Proin lacus urna, vulputate et lorem ac, condimentum.
banner: images/banner/wedding.jpg
booking:
  startDate: 02/20/2018
  endDate: 02/24/2018
  ctyhocn: WDGOKHX
  groupCode: SLC
published: true
---
Donec ut dolor eget diam ultricies aliquam non ut sapien. Praesent vulputate arcu non blandit tincidunt. Quisque quis aliquet metus, ac euismod justo. Fusce maximus rhoncus nulla viverra aliquet. Integer ultrices, dolor ut hendrerit bibendum, libero augue luctus augue, in commodo enim mi posuere orci. Aenean at velit ut magna imperdiet tempus eget et ipsum. Aenean efficitur nisl nec elit vehicula, nec scelerisque ante imperdiet. Morbi magna velit, pulvinar a porta at, vulputate at velit. Cras egestas porttitor tortor, posuere iaculis nisi malesuada in.
Sed vitae ipsum turpis. Nunc nec sem consectetur, semper purus sed, pretium leo. Fusce eu aliquam orci. Vivamus lacinia ligula elit, quis sagittis tortor tristique eu. Phasellus sem libero, faucibus ut sem ut, auctor molestie ante. Nulla maximus fringilla mattis. Pellentesque porta libero at dolor rhoncus, id dictum enim porttitor. Nulla iaculis efficitur gravida. Nam non eros eu velit ornare pellentesque non id sem.

1 Etiam placerat enim et purus scelerisque auctor.

Sed volutpat turpis sit amet ipsum fermentum dapibus. Ut et pulvinar nulla, sed rhoncus leo. Nullam faucibus tellus non turpis bibendum ullamcorper. Ut eget elementum risus. Pellentesque cursus dapibus posuere. Praesent fermentum condimentum sapien. Maecenas pellentesque risus interdum leo molestie sodales. Nulla rhoncus enim non ante imperdiet placerat. Donec a lacus suscipit, auctor nibh quis, finibus orci. Vestibulum quis congue nulla. Donec ultricies, metus a porta tincidunt, justo diam facilisis sapien, id mattis ante dolor quis libero. Cras et mattis est. Cras eget accumsan mi. Nulla facilisi.


text:
<?php

namespace Tests\BrainExe\Core\Authentication;

use BrainExe\Core\Authentication\RegisterTokens;
use BrainExe\Core\Util\IdGenerator;
use BrainExe\Tests\RedisMockTrait;
use PHPUnit_Framework_MockObject_MockObject as MockObject;
use PHPUnit\Framework\TestCase;
use BrainExe\Core\Redis\Predis;

/**
 * @covers \BrainExe\Core\Authentication\RegisterTokens
 */
class RegisterTokensTest extends TestCase
{

    use RedisMockTrait;

    /**
     * @var RegisterTokens
     */
    private $subject;

    /**
     * @var Predis|MockObject
     */
    private $redis;

    /**
     * @var IdGenerator|MockObject
     */
    private $idGenerator;

    public function setUp()
    {
        $this->redis       = $this->getRedisMock();
        $this->idGenerator = $this->createMock(IdGenerator::class);

        $this->subject = new RegisterTokens();
        $this->subject->setRedis($this->redis);
        $this->subject->setIdGenerator($this->idGenerator);
    }

    public function testAddToken()
    {
        $tokenId = 11880;

        $this->idGenerator
            ->expects($this->once())
            ->method('generateRandomId')
            ->willReturn($tokenId);

        $this->redis
            ->expects($this->once())
            ->method('sadd')
            ->with(RegisterTokens::TOKEN_KEY, [$tokenId]);

        $actualResult = $this->subject->addToken();

        $this->assertEquals($tokenId, $actualResult);
    }

    public function testFetchToken()
    {
        $token = 11880;

        $this->redis
            ->expects($this->once())
            ->method('srem')
            ->with(RegisterTokens::TOKEN_KEY, $token)
            ->willReturn(true);

        $actualResult = $this->subject->fetchToken($token);

        $this->assertTrue($actualResult);
    }
}


text:
package querqy.rewrite.contrib.replace;

import org.junit.Test;
import querqy.parser.WhiteSpaceQuerqyParser;
import querqy.trie.SequenceLookup;
import querqy.trie.model.ExactMatch;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static org.assertj.core.api.Assertions.assertThat;

public class ReplaceRewriterParserTest {

    @Test(expected = IOException.class)
    public void testCombinedInputWIthPrefixAndSuffix() throws IOException {
        String rules = " ab* \t *bc \t abc => cd";
        SequenceLookup<ReplaceInstruction> sequenceLookup = createParser(rules, false).parseConfig();
    }

    @Test
    public void testCombinedInputOnlyExactMatch() throws IOException {
        String rules = " ab \t bc \t abc => cd";
        SequenceLookup<ReplaceInstruction> sequenceLookup = createParser(rules, false).parseConfig();
    }

    @Test
    public void testEmptyOutput() throws IOException {
        String rules = " abc => ";
        SequenceLookup<ReplaceInstruction> sequenceLookup = createParser(rules, false).parseConfig();
        assertThat(sequenceLookup.findExactMatches(Arrays.asList("abc", "cab", "dabc"))).hasSize(1);
    }

    @Test
    public void testEmptyOutputSuffix() throws IOException {
        String rules = " *abc => ";
        SequenceLookup<ReplaceInstruction> sequenceLookup = createParser(rules, false).parseConfig();
        assertThat(sequenceLookup.findSingleTermSuffixMatches(Arrays.asList("dabc", "cab"))).hasSize(1);
    }

    @Test
    public void testDuplicateSuffixCaseSensitive() throws IOException {
        String rules = "*ab => af \n" +
                "*AB => ag";
        SequenceLookup<ReplaceInstruction> sequenceLookup = createParser(rules, false).parseConfig();
        assertThat(sequenceLookup.findSingleTermSuffixMatches(Arrays.asList("cAB", "cab", "dabc"))).hasSize(2);
    }

    @Test
    public void testDuplicatePrefixCaseSensitive() throws IOException {
        String rules = "ab* => af \n" +
                "AB* => ag";
        SequenceLookup<ReplaceInstruction> sequenceLookup = createParser(rules, false).parseConfig();
        assertThat(sequenceLookup.findSingleTermPrefixMatches(Arrays.asList("ABc", "abc", "dabc"))).hasSize(2);
    }

    @Test(expected = IOException.class)
    public void testDuplicatePrefix() throws IOException {
        String rules = "ab* => af \n" +
                "ab* => ag";
        createParser(rules).parseConfig();
    }

    @Test(expected = IOException.class)
    public void testDuplicateSuffix() throws IOException {
        String rules = "*ab => af \n" +
                "*ab => ag";
        createParser(rules).parseConfig();
    }

    @Test(expected = IOException.class)
    public void testTwoWildCardsPerTerm() throws IOException {
        String rules = "*ab* => af";
        createParser(rules).parseConfig();
    }

    @Test(expected = IOException.class)
    public void testWildcardOnly() throws IOException {
        String rules = "* => af";
        createParser(rules).parseConfig();
    }

    @Test(expected = IOException.class)
    public void testEmptyInput() throws IOException {
        String rules = " => af";
        createParser(rules).parseConfig();
    }

    private SequenceLookup<ReplaceInstruction> createRuleExtractor(String rules) throws IOException {
        return createParser(rules).parseConfig();
    }

    private ReplaceRewriterParser createParser(String rules) {
        return createParser(rules, true);
    }

    private ReplaceRewriterParser createParser(String rules, boolean ignoreCase) {
        InputStreamReader input = new InputStreamReader(new ByteArrayInputStream(rules.getBytes()));
        return new ReplaceRewriterParser(
                input, ignoreCase, "\t", new WhiteSpaceQuerqyParser());
    }

    @Test
    public void testSuffixInput() throws IOException {
        String rules = "# comment\n"
                + " *abc => ae \n"
                + " *ab => af \n";

        SequenceLookup<ReplaceInstruction> sequenceLookup = createRuleExtractor(rules);
        assertThat(sequenceLookup.findSingleTermSuffixMatches(Arrays.asList("a", "ab", "dabc"))).hasSize(2);
    }

    @Test(expected = IOException.class)
    public void testImproperSuffixInput() throws IOException {
        String rules = "df *ab => af";
        createParser(rules).parseConfig();
    }

    @Test
    public void testPrefixInput() throws IOException {
        String rules = "# comment\n"
                + " abc* => ae \n"
                + " ab* => af \n";

        InputStreamReader input = new InputStreamReader(new ByteArrayInputStream(rules.getBytes()));
        ReplaceRewriterParser replaceRewriterParser = new ReplaceRewriterParser(
                input, true, "\t", new WhiteSpaceQuerqyParser());

        SequenceLookup<ReplaceInstruction> sequenceLookup = replaceRewriterParser.parseConfig();
        assertThat(sequenceLookup.findSingleTermPrefixMatches(Arrays.asList("a", "ab", "abcd"))).hasSize(2);
    }

    @Test(expected = IOException.class)
    public void testImproperPrefixInput() throws IOException {
        String rules = " ab* df => af \n";

        createParser(rules).parseConfig();
    }

    @Test(expected = IOException.class)
    public void testWrongConfigurationDuplicateInputStringCaseInsensitive() throws IOException {
        String rules = "# comment\n"
                + "c => d \n"
                + " a   B => b \n"
                + "e d \t a b => c";

        createParser(rules).parseConfig();
    }

    @Test
    public void testWrongConfigurationDuplicateInputStringCaseSensitive() throws IOException {
        String rules = "# comment\n"
                + "c => d \n"
                + " a   B => b \n"
                + "e d \t a b => c";

        createParser(rules, false).parseConfig();
    }

    @Test(expected = IOException.class)
    public void testWrongConfiguration() throws IOException {
        String rules = "# comment\n"
                + "something wrong \n"
                + " FG => hi jk  \n ";

        createParser(rules).parseConfig();
    }

    @Test
    public void testMappingCaseInsensitive() throws IOException {
        String rules = "# comment\n"
                + "\n"
                + " ab  \t c d => e \n"
                + " FG => hi jk  \n ";

        SequenceLookup<ReplaceInstruction> sequenceLookup = createParser(rules).parseConfig();

        List<ExactMatch<ReplaceInstruction>> exactMatches;

        exactMatches = sequenceLookup.findExactMatches(list("ab"));
        assertThat(exactMatches).isNotEmpty();

        exactMatches = sequenceLookup.findExactMatches(list("c"));
        assertThat(exactMatches).isEmpty();

        exactMatches = sequenceLookup.findExactMatches(list("c", "d"));
        assertThat(exactMatches).isNotEmpty();

        exactMatches = sequenceLookup.findExactMatches(list("fg"));
        assertThat(exactMatches).isNotEmpty();
    }

    @Test
    public void testMappingCaseSensitive() throws IOException {
        String rules = "AB => cd";

        SequenceLookup<ReplaceInstruction> sequenceLookup = createParser(rules, false).parseConfig();

        List<ExactMatch<ReplaceInstruction>> exactMatches;

        exactMatches = sequenceLookup.findExactMatches(list("AB"));
        assertThat(exactMatches).hasSize(1);

        exactMatches = sequenceLookup.findExactMatches(list("ab"));
        assertThat(exactMatches).isEmpty();
    }

    private ReplaceInstruction instruction(String... str) {
        return new TermsReplaceInstruction(Arrays.asList(str));
    }

    private List<CharSequence> list(String... str) {
        return Arrays.stream(str).collect(Collectors.toCollection(ArrayList::new));
    }
}


text:
using System;
using System.Threading.Tasks;

namespace SphereStudio.Base
{
    /// <summary>
    /// Specifies the reason debug execution was halted.
    /// </summary>
    public enum PauseReason
    {
        /// <summary>
        /// A breakpoint was triggered.
        /// </summary>
        Breakpoint,

        /// <summary>
        /// An exception is about to be thrown.
        /// </summary>
        Exception,
    }

    /// <summary>
    /// Specifies data for a Paused debugger event.
    /// </summary>
    public class PausedEventArgs
    {
        /// <summary>
        /// Constructs data for a Paused debugger event.
        /// </summary>
        /// <param name="reason"></param>
        public PausedEventArgs(PauseReason reason)
        {
            Reason = reason;
        }

        /// <summary>
        /// Gets the reason execution was halted.
        /// </summary>
        public PauseReason Reason { get; private set; }
    }

    /// <summary>
    /// Specifies the interface for a single-step debugger.
    /// </summary>
    public interface IDebugger
    {
        /// <summary>
        /// Gets the fully qualified path of the source file currently being
        /// executed.
        /// </summary>
        string FileName { get; }

        /// <summary>
        /// Gets the line number of the next instruction to be executed.
        /// </summary>
        int LineNumber { get; }

        /// <summary>
        /// Gets whether the debuggee is currently executing.
        /// </summary>
        bool Running { get; }

        /// <summary>
        /// Fires when the debugger is successfully attached.
        /// </summary>
        event EventHandler Attached;

        /// <summary>
        /// Fires when the debugger is detached.
        /// </summary>
        event EventHandler Detached;

        /// <summary>
        /// Fires when execution resumes.
        /// </summary>
        event EventHandler Resumed;

        /// <summary>
        /// Fires when execution pauses (e.g. at a breakpoint).
        /// </summary>
        event EventHandler<PausedEventArgs> Paused;

        /// <summary>
        /// Attaches the debugger.
        /// </summary>
        /// <returns>true if the debugger was successfully attached.</returns>
        Task<bool> Attach();

        /// <summary>
        /// Detaches the debugger.
        /// </summary>
        Task Detach();

        /// <summary>
        /// Sets a breakpoint on a line of code.
        /// </summary>
        /// <param name="fileName">The name of the source file containing the breakpoint.</param>
        /// <param name="lineNumber">The line number of the breakpoint.</param>
        Task SetBreakpoint(string fileName, int lineNumber);

        /// <summary>
        /// Clears an existing breakpoint on a line of code.
        /// </summary>
        /// <param name="fileName">The name of the source file containing the breakpoint.</param>
        /// <param name="lineNumber">The line number of the breakpoint.</param>
        Task ClearBreakpoint(string fileName, int lineNumber);

        /// <summary>
        /// Runs until the next breakpoint is hit or the target terminates,
        /// whichever comes first.
        /// </summary>
        Task Resume();

        /// <summary>
        /// Pauses execution and breaks into the debugger.
        /// </summary>
        Task Pause();

        /// <summary>
        /// Executes the next line of code, stepping into function calls.
        /// </summary>
        Task StepInto();

        /// <summary>
        /// Runs until the current function returns.
        /// </summary>
        Task StepOut();

        /// <summary>
        /// Executes the next line of code.
        /// </summary>
        Task StepOver();
    }
}


text:
using UnityEngine;
using System.Collections;
using System.Text.RegularExpressions;

public static class HName {

	public static string GetPure(string name) {
		// Remove any digits at the end, trim empty stuff, set to lower case.
		return Regex.Replace(name, @"[\d-]", string.Empty).Trim().ToLower();
	}

}


text:
from datetime import date
from django.test import TestCase
from django.test.client import RequestFactory
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from model_mommy import mommy
from animals.models import Animal, PregnancyCheck, Service
from animals import views
from helpers import test_helpers

class AnimalCRUDLTestCase(TestCase):
    def setUp(self):
        self.bull = mommy.make('animals.Animal', ear_tag='123', gender=Animal.GENDER_CHOICES.cow)
        self.cow = mommy.make('animals.Animal', ear_tag='', gender=Animal.GENDER_CHOICES.cow)

    def test_creating_animal(self):
        user = test_helpers.create_logged_in_user(self)
        user.user_permissions.add(Permission.objects.get(codename='animal_create'))
        user.user_permissions.add(Permission.objects.get(codename='animal_list'))
        post_data = {
            'ear_tag': '201',
            'name': 'Saldana',
            'gender': Animal.GENDER_CHOICES.bull,
            'birth_date': date.today()

        }
        url = reverse('animals.animal_create')
        response = self.client.post(url, post_data, follow=True)
        self.assertContains(response, 'Your new animal has been created.')
        self.assertRedirects(response, reverse('animals.animal_list'))

    def test_animal_read(self):
        user = test_helpers.create_logged_in_user(self)
        user.user_permissions.add(Permission.objects.get(codename='animal_read'))
        user.user_permissions.add(Permission.objects.get(codename='service_list'))
        user.user_permissions.add(Permission.objects.get(codename='pregnancycheck_list'))
        user.user_permissions.add(Permission.objects.get(codename='animal_list'))
        user.user_permissions.add(Permission.objects.get(codename='animalnote_list'))
        user.user_permissions.add(Permission.objects.get(codename='transaction_list'))
        user.user_permissions.add(Permission.objects.get(codename='milkproduction_list'))

        dufour = mommy.make('animals.Animal', name='Dufour', birth_date=date.today(), gender=Animal.GENDER_CHOICES.cow)
        # add services
        mommy.make('animals.Service', animal=dufour, sire=self.cow, date=date.today(), notes="Dufour's service")
        # add pregnancycheck
        mommy.make('animals.PregnancyCheck', animal=dufour, result=PregnancyCheck.RESULT_CHOICES.pregnant)
        mommy.make('animals.Animal', ear_tag='56', sire=dufour, name='Dufour calf')
        # add note
        mommy.make('records.AnimalNote', details='Dufour note', animal=dufour)
        # add transaction
        feeds = mommy.make('finances.Category', name='feed')
        transaction = mommy.make('finances.Transaction', category=feeds)
        transaction.animals.add(dufour)
        # add milk production
        mommy.make('animals.MilkProduction', amount=20, animal=dufour)

        url = reverse('animals.animal_read', args=[dufour.id])
        response = self.client.get(url, follow=True)
        self.assertContains(response, "Dufour's service")
        self.assertContains(response, 'Pregnant')
        self.assertContains(response, 'Dufour calf')
        self.assertContains(response, 'feed')
        self.assertContains(response, '20')

    def test_offspring_animal_id_and_service(self):
        user = test_helpers.create_logged_in_user(self)
        user.user_permissions.add(Permission.objects.get(codename='animal_list'))
        user.user_permissions.add(Permission.objects.get(codename='animal_add_offspring'))

        # without the animal id
        url = reverse('animals.animal_add_offspring')
        response = self.client.get(url, follow=True)
        self.assertContains(response, 'Animal Id is required')

        # non existent animal id
        url = reverse('animals.animal_add_offspring') + '?animal=100'
        response = self.client.get(url, follow=True)
        self.assertContains(response, 'Animal Id is required')

        # existing animal but with no service, proceed as normal
        url = reverse('animals.animal_add_offspring') + '?animal=' + str(self.cow.id)
        response = self.client.get(url, follow=True)
        self.assertNotContains(response, 'Animal Id is required')

        # existing animal with service
        service = mommy.make('animals.Service', sire=self.cow, animal=self.cow)
        url = reverse('animals.animal_add_offspring') + '?animal=' + str(self.cow.id)
        response = self.client.get(url, follow=True)
        form_fields = response.context_data['form'].fields
        self.assertEqual(form_fields['birth_date'].initial, date.today())
        self.assertEqual(form_fields['dam'].initial, self.cow)
        self.assertEqual(form_fields['sire'].initial, service.sire)

    def test_adding_offspring(self):
        user = test_helpers.create_logged_in_user(self)
        user.user_permissions.add(Permission.objects.get(codename='animal_list'))
        user.user_permissions.add(Permission.objects.get(codename='animal_add_offspring'))

        post_data = {
            'ear_tag': '104M',
            'gender': Animal.GENDER_CHOICES.bull,
            'name': 'Sasha',
            'birth_date': date.today()
        }

        url = reverse('animals.animal_add_offspring') + '?animal=' + str(self.cow.id)
        self.client.post(url, post_data, follow=True)
        offspring = Animal.objects.latest('created_on')
        self.assertEqual(offspring.ear_tag, '104M')

class ServiceCRUDLTestCase(TestCase):
    def setUp(self):
        self.shauna = mommy.make('animals.Animal', ear_tag='123')
        self.bull = mommy.make('animals.Animal', ear_tag='1243', name='sire', gender=Animal.GENDER_CHOICES.bull)
        self.service = mommy.make('animals.Service', animal=self.shauna, method=Service.METHOD_CHOICES.artificial_insemination,
                                  sire=self.bull)

    def test_offspring_animal_id(self):
        user = test_helpers.create_logged_in_user(self)
        user.user_permissions.add(Permission.objects.get(codename='animal_read'))
        user.user_permissions.add(Permission.objects.get(codename='animal_list'))
        user.user_permissions.add(Permission.objects.get(codename='service_list'))
        user.user_permissions.add(Permission.objects.get(codename='service_create'))

        # without the animal id
        url = reverse('animals.service_create')
        response = self.client.get(url, follow=True)
        self.assertContains(response, 'Animal Id is required')

        # non existent animal id
        url = reverse('animals.service_create') + '?animal=100'
        response = self.client.get(url, follow=True)
        self.assertContains(response, 'Animal Id is required')

        # existing animal but with no service, proceed as normal
        url = reverse('animals.service_create') + '?animal=' + str(self.shauna.id)
        response = self.client.get(url, follow=True)
        self.assertNotContains(response, 'Animal Id is required')

    def adding_service(self):
        user = test_helpers.create_logged_in_user(self)
        user.user_permissions.add(Permission.objects.get(codename='animal_read'))
        user.user_permissions.add(Permission.objects.get(codename='animal_create'))
        user.user_permissions.add(Permission.objects.get(codename='service_create'))
        user.user_permissions.add(Permission.objects.get(codename='service_list'))

        self.phoenix = mommy.make('animals.Animal', ear_tag='PNX')

        post_data = {
            'method': Service.METHOD_CHOICES.artificial_insemination,
            'sire': self.sire.id,
            'date': date.today()
        }

        url = reverse('animals.service_create') + '?animal=' + str(self.phoenix.id)
        response = self.client.post(url, post_data, follow=True)
        service = Service.objects.latest('created_on')
        self.assertEqual(service.animal, self.phoenix)
        self.assertRedirects(response, reverse('animals.animal_read', args=[self.phoenix.id]))
        self.assertContains(response, 'Artificial Insemination')

    def service_read(self):
        user = test_helpers.create_logged_in_user(self)
        user.user_permissions.add(Permission.objects.get(codename='animal_read'))
        user.user_permissions.add(Permission.objects.get(codename='service_read'))
        user.user_permissions.add(Permission.objects.get(codename='pregnancycheck_list'))
        pregnancy_check = mommy.make('animals.PregnancyCheck', animal=self.shauna, result=PregnancyCheck.RESULT_CHOICES.open, service=self.service)
        url = reverse('animals.service_read', args=[self.service.id])
        response = self.client.get(url, follow=True)
        self.assertContains(response, 'Open')
        self.assertContains(response, pregnancy_check.id)
        self.assertContains(response.context_data, 'pregnancychecks')

class PregnancyCheckCRDULTestCase(TestCase):
    def setUp(self):
        self.laryn = mommy.make('animals.Animal', ear_tag='456')
        self.shauna = mommy.make('animals.Animal', ear_tag='123', gender=Animal.GENDER_CHOICES.cow)
        self.shauna_pd = mommy.make('animals.PregnancyCheck', animal=self.shauna, result=PregnancyCheck.RESULT_CHOICES.open)

        self.factory = RequestFactory()

    def test_animal_id_required(self):
        user = test_helpers.create_logged_in_user(self)
        user.user_permissions.add(Permission.objects.get(codename='animal_read'))
        user.user_permissions.add(Permission.objects.get(codename='animal_list'))
        user.user_permissions.add(Permission.objects.get(codename='pregnancycheck_list'))
        user.user_permissions.add(Permission.objects.get(codename='pregnancycheck_create'))

        # without the animal id
        url = reverse('animals.pregnancycheck_create')
        response = self.client.get(url, follow=True)
        self.assertContains(response, 'Animal Id is required')

        # non existent animal id
        url = reverse('animals.pregnancycheck_create') + '?animal=100'
        response = self.client.get(url, follow=True)
        self.assertContains(response, 'Animal Id is required')

        # existing animal but with no service, proceed as normal
        url = reverse('animals.pregnancycheck_create') + '?animal=' + str(self.shauna.id)
        response = self.client.get(url, follow=True)
        self.assertNotContains(response, 'Animal Id is required')

    def test_service_list(self):
        user = test_helpers.create_logged_in_user(self)
        user.user_permissions.add(Permission.objects.get(codename='animal_read'))
        user.user_permissions.add(Permission.objects.get(codename='pregnancycheck_list'))
        request = self.factory.get(reverse('animals.animal_read', args=[self.shauna.id]))
        request.user = user
        request.animal = self.shauna
        pregnancy_response = views.PregnancyCheckCRUDL().view_for_action('list').as_view()(request)
        self.assertIn(self.shauna_pd, pregnancy_response.context_data['pregnancycheck_list'])

        url = reverse('animals.animal_read', args=[self.shauna.id])
        response = self.client.get(url, follow=True)
        self.assertContains(response, 'Open')

        # pregnancy check with a service
        service = mommy.make('animals.Service', animal=self.shauna)
        mommy.make('animals.PregnancyCheck', animal=self.shauna, result=PregnancyCheck.RESULT_CHOICES.pregnant, service=service)
        url = reverse('animals.animal_read', args=[self.shauna.id])
        response = self.client.get(url, follow=True)
        self.assertContains(response, 'Pregnant')

class TreatmentCRUDLTestCase(TestCase):
    def setUp(self):
        self.laryn = mommy.make('animals.Animal', ear_tag='456')
        self.shauna = mommy.make('animals.Animal', ear_tag='123')
        self.treatment = mommy.make('health.Treatment')
        self.treatment.animals.add(self.shauna, self.laryn)

    def test_creating_animal_treatment(self):
        user = test_helpers.create_logged_in_user(self)
        user.user_permissions.add(Permission.objects.get(codename='animal_list'))
        user.user_permissions.add(Permission.objects.get(codename='animal_read'))
        user.user_permissions.add(Permission.objects.get(codename='treatment_create'))
        user.user_permissions.add(Permission.objects.get(codename='treatment_list'))
        # animal id is required
        url = reverse('animals.treatment_create')
        response = self.client.get(url, follow=True)
        self.assertContains(response, 'Animal Id is required')
        # non-existent animal
        url = reverse('animals.treatment_create') + '?animal=1'
        response = self.client.get(url, follow=True)
        self.assertContains(response, 'Animal Id is required')
        # existing animal
        url = reverse('animals.treatment_create') + '?animal=' + str(self.shauna.id)
        response = self.client.get(url, follow=True)
        self.assertNotContains(response, 'Animal Id is required')
        # creating an treatment
        post_data = {
            'date': '2015-04-30',
            'description': 'A test description',
            'notes': 'Nothing much to say'
        }
        response = self.client.post(url, post_data, follow=True)
        self.assertContains(response, 'Your new treatment has been created.')
        self.assertRedirects(response, reverse('animals.animal_read', args=[self.shauna.id]))

    def test_treatment_read(self):
        user = test_helpers.create_logged_in_user(self)
        user.user_permissions.add(Permission.objects.get(codename='treatment_read'))
        url = reverse('animals.treatment_read', args=[self.treatment.id])
        response = self.client.get(url, follow=True)
        self.assertContains(response, reverse('animals.animal_read', args=[self.shauna.id]))
        self.assertContains(response, reverse('animals.animal_read', args=[self.laryn.id]))

class TransactionCRUDLTestCase(TestCase):

    def setUp(self):
        self.shauna = mommy.make('animals.Animal', ear_tag='123')

    def test_animal_id_required(self):
        user = test_helpers.create_logged_in_user(self)
        user.user_permissions.add(Permission.objects.get(codename='animal_read'))
        user.user_permissions.add(Permission.objects.get(codename='animal_list'))
        user.user_permissions.add(Permission.objects.get(codename='transaction_list'))
        user.user_permissions.add(Permission.objects.get(codename='transaction_create'))

        # without the animal id
        url = reverse('animals.transaction_create')
        response = self.client.get(url, follow=True)
        self.assertContains(response, 'Animal Id is required')

        # non existent animal id
        url = reverse('animals.transaction_create') + '?animal=100'
        response = self.client.get(url, follow=True)
        self.assertContains(response, 'Animal Id is required')

        # existing animal, proceed as normal
        url = reverse('animals.transaction_create') + '?animal=' + str(self.shauna.id)
        response = self.client.get(url, follow=True)
        self.assertNotContains(response, 'Animal Id is required')


text:
package org.sagebionetworks.repo.web.service.subscription;

import org.sagebionetworks.repo.manager.UserManager;
import org.sagebionetworks.repo.manager.subscription.SubscriptionManager;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.subscription.Etag;
import org.sagebionetworks.repo.model.subscription.SubscriberCount;
import org.sagebionetworks.repo.model.subscription.SubscriberPagedResults;
import org.sagebionetworks.repo.model.subscription.Subscription;
import org.sagebionetworks.repo.model.subscription.SubscriptionObjectType;
import org.sagebionetworks.repo.model.subscription.SubscriptionPagedResults;
import org.sagebionetworks.repo.model.subscription.SubscriptionRequest;
import org.sagebionetworks.repo.model.subscription.Topic;
import org.springframework.beans.factory.annotation.Autowired;

public class SubscriptionServiceImpl implements SubscriptionService {
	@Autowired
	private UserManager userManager;
	@Autowired
	private SubscriptionManager subscriptionManager;

	@Override
	public Subscription create(Long userId, Topic topic) {
		UserInfo userInfo = userManager.getUserInfo(userId);
		return subscriptionManager.create(userInfo, topic);
	}

	@Override
	public SubscriptionPagedResults getAll(Long userId, Long limit, Long offset, SubscriptionObjectType objectType) {
		UserInfo userInfo = userManager.getUserInfo(userId);
		return subscriptionManager.getAll(userInfo, limit, offset, objectType);
	}

	@Override
	public SubscriptionPagedResults getList(Long userId, SubscriptionRequest request) {
		UserInfo userInfo = userManager.getUserInfo(userId);
		return subscriptionManager.getList(userInfo, request);
	}

	@Override
	public void delete(Long userId, String subscriptionId) {
		UserInfo userInfo = userManager.getUserInfo(userId);
		subscriptionManager.delete(userInfo, subscriptionId);
	}

	@Override
	public void deleteAll(Long userId) {
		UserInfo userInfo = userManager.getUserInfo(userId);
		subscriptionManager.deleteAll(userInfo);
	}

	@Override
	public Subscription get(Long userId, String id) {
		UserInfo userInfo = userManager.getUserInfo(userId);
		return subscriptionManager.get(userInfo, id);
	}

	@Override
	public Etag getEtag(String objectId, ObjectType objectType) {
		return subscriptionManager.getEtag(objectId, objectType);
	}

	@Override
	public SubscriberPagedResults getSubscribers(Long userId, Topic topic, String nextPageToken) {
		UserInfo userInfo = userManager.getUserInfo(userId);
		return subscriptionManager.getSubscribers(userInfo, topic, nextPageToken);
	}

	@Override
	public SubscriberCount getSubscriberCount(Long userId, Topic topic) {
		UserInfo userInfo = userManager.getUserInfo(userId);
		return subscriptionManager.getSubscriberCount(userInfo, topic);
	}

	@Override
	public Subscription subscribeAll(Long userId, SubscriptionObjectType objectType) {
		UserInfo userInfo = userManager.getUserInfo(userId);
		return subscriptionManager.subscribeAll(userInfo, objectType);
	}

}


text:
package com.shejiaomao.weibo.service.listener;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;

import com.cattong.weibo.entity.DirectMessage;
import com.cattong.entity.User;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.HeaderViewListAdapter;
import android.widget.AdapterView.OnItemClickListener;

import com.shejiaomao.maobo.R;
import com.shejiaomao.weibo.activity.ConversationActivity;
import com.shejiaomao.weibo.activity.EditDirectMessageActivity;
import com.shejiaomao.weibo.activity.ProfileActivity;
import com.shejiaomao.weibo.common.Constants;
import com.shejiaomao.weibo.db.LocalAccount;
import com.shejiaomao.weibo.db.LocalDirectMessage;
import com.shejiaomao.weibo.service.adapter.CacheAdapter;
import com.shejiaomao.weibo.service.task.DestroyDirectMessageTask;

public class DirectMessagesItemClickListener implements OnItemClickListener {
    private Context context;
    private DirectMessage message;
	private List<String> listItem;

	public DirectMessagesItemClickListener(Context context) {
		this.context = context;
		listItem = new ArrayList<String>();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Adapter adapter = parent.getAdapter();
		message = (DirectMessage)adapter.getItem(position);
        if (message == null
        	|| (message instanceof LocalDirectMessage
        		&& ((LocalDirectMessage)message).isDivider())) {
        	return;
        }

        if (adapter instanceof HeaderViewListAdapter) {
        	adapter = ((HeaderViewListAdapter)adapter).getWrappedAdapter();
        }
		CacheAdapter<DirectMessage> cacheAdapter = (CacheAdapter<DirectMessage>)adapter;

        Dialog dialog = onCreateDialog(cacheAdapter, position);
        if (dialog != null) {
        	dialog.show();
        }
	}

	public Dialog onCreateDialog(final CacheAdapter<DirectMessage> cacheAdapter, final int position) {
		if (message == null) {
			return null;
		}
		listItem.clear();
		listItem.add(context.getString(R.string.menu_message_reply));
		listItem.add(context.getString(R.string.menu_message_conversation));
		listItem.add(context.getString(R.string.menu_message_user_info));
		listItem.add(context.getString(R.string.menu_message_conversation_destroy));

		Matcher m = Constants.URL_PATTERN.matcher(message.getText());
		while (m.find()) {
			String url = m.group();
			listItem.add(url);
		}

		String[] selectItems = new String[listItem.size()];
        listItem.toArray(selectItems);

		return new AlertDialog.Builder(context)
            .setTitle(R.string.menu_title_message)
            .setItems(selectItems, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                	LocalAccount account = cacheAdapter.getAccount();
                    String myId = account.getUser().getUserId();
                    User conversationUser = message.getSender();
                    if (myId.equals(message.getSenderId())) {
                    	conversationUser = message.getRecipient();
                    }

              		Intent intent = new Intent();
            		Bundle bundle = new Bundle();
                    if (which == 0) {
                        String recipientName = conversationUser.getDisplayName();
                		bundle.putString("DISPLAY_NAME", recipientName);
                		bundle.putInt("TYPE", Constants.EDIT_TYPE_REMESSAGE);
                		intent.putExtras(bundle);

                		intent.setClass(context, EditDirectMessageActivity.class);
                		((Activity)context).startActivity(intent);
                    } else if (which == 1) {
                    	intent.setClass(context, ConversationActivity.class);
                    	bundle.putSerializable("USER", conversationUser);
                    	intent.putExtras(bundle);
                    	context.startActivity(intent);
                    } else if (which == 2) {
                		bundle.putSerializable("USER", conversationUser);
                		intent.putExtras(bundle);

                		intent.setClass(context, ProfileActivity.class);
                		((Activity)context).startActivity(intent);
                    } else if (which == 3) {
                    	destroyConversation(cacheAdapter);
                    } else {
        				intent.setAction(Intent.ACTION_VIEW);
        				intent.setData(Uri.parse(getItem(which)));
        				context.startActivity(intent);
                    }
                }
            })
            .create();
	}

	private String getItem(int i) {
		return listItem.get(i);
	}

	private void destroyConversation(final CacheAdapter<DirectMessage> cacheAdapter) {
		Dialog dialog = new AlertDialog.Builder(context)
		    .setTitle(R.string.title_dialog_alert)
			.setMessage(R.string.msg_message_destroy_conversation_confirm)
			.setPositiveButton(R.string.btn_confirm, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog,	int which) {
					DestroyDirectMessageTask destroyTask = new DestroyDirectMessageTask(cacheAdapter, message);
                	destroyTask.execute();
				}
			})
			.setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			})
			.create();

		dialog.show();
	}
}


text:
import os
import datetime
import unittest
from django.test import TestCase
from data_aggregator import utilities
from django.utils import timezone
from pytz import timezone as tz

class TestUtilities(TestCase):

    def test_set_gcs_base_path(self):
        utilities.set_gcs_base_path("2021-summer", 1)
        self.assertEqual(os.environ["GCS_BASE_PATH"], "2021-summer/1/")
        utilities.set_gcs_base_path("2021-spring", 5)
        self.assertEqual(os.environ["GCS_BASE_PATH"], "2021-spring/5/")

    def test_get_relative_week(self):
        tz_name = "US/Pacific"
        first_day_quarter = datetime.date(2021, 6, 20)
        curr_date = timezone.make_aware(
            datetime.datetime(2020, 6, 20, 0, 0, 0),
            timezone=tz(tz_name))
        week = utilities.get_relative_week(
                            first_day_quarter,
                            cmp_dt=curr_date,
                            tz_name=tz_name)
        self.assertEqual(week, 0)
        curr_date = timezone.make_aware(
            datetime.datetime(2021, 6, 20, 0, 0, 0),
            timezone=tz(tz_name))
        week = utilities.get_relative_week(
                            first_day_quarter,
                            cmp_dt=curr_date,
                            tz_name=tz_name)
        self.assertEqual(week, 1)
        curr_date = timezone.make_aware(
            datetime.datetime(2021, 6, 26, 0, 0, 0),
            timezone=tz(tz_name))
        week = utilities.get_relative_week(
                            first_day_quarter,
                            cmp_dt=curr_date,
                            tz_name=tz_name)
        self.assertEqual(week, 1)
        curr_date = timezone.make_aware(
            datetime.datetime(2021, 6, 27, 0, 0, 0),
            timezone=tz(tz_name))
        week = utilities.get_relative_week(
                            first_day_quarter,
                            cmp_dt=curr_date,
                            tz_name=tz_name)
        self.assertEqual(week, 2)
        curr_date = timezone.make_aware(
            datetime.datetime(2021, 7, 3, 0, 0, 0),
            timezone=tz(tz_name))
        # ensure that UTC dates get converted to PDT
        week = utilities.get_relative_week(
                            first_day_quarter,
                            cmp_dt=curr_date,
                            tz_name=tz_name)
        self.assertEqual(week, 2)
        curr_date = timezone.make_aware(
            datetime.datetime(2021, 7, 4, 0, 0, 0),
            timezone=tz('UTC'))
        week = utilities.get_relative_week(
                            first_day_quarter,
                            cmp_dt=curr_date,
                            tz_name=tz_name)
        self.assertEqual(week, 2)
        curr_date = timezone.make_aware(
            datetime.datetime(2021, 7, 4, 0, 0, 0),
            timezone=tz(tz_name))
        week = utilities.get_relative_week(
                            first_day_quarter,
                            cmp_dt=curr_date,
                            tz_name=tz_name)
        self.assertEqual(week, 3)

    def test_datestring_to_datetime(self):
        # bad input string
        with self.assertRaises(ValueError):
            utilities.datestring_to_datetime("Bad string")

        # bad input not string or unicode
        with self.assertRaises(ValueError):
            utilities.datestring_to_datetime(int(19))

        # %Y-%m-%dT%H:%M:%S.%f good
        ret = utilities.datestring_to_datetime(
            "2019-01-01T23:59:59.999")
        self.assertTrue(ret)
        self.assertTrue(type(ret) is datetime.datetime)

        # %Y-%m-%dT%H:%M:%S.%f < 1900
        with self.assertRaises(ValueError):
            ret = utilities.datestring_to_datetime(
                "1777-01-01T23:59:59.999")

        # %Y-%m-%dT%H:%M:%S.%fZ good
        ret = utilities.datestring_to_datetime(
            "2019-01-01T23:59:59.999Z")
        self.assertTrue(ret)
        self.assertTrue(type(ret) is datetime.datetime)

        # %Y-%m-%dT%H:%M:%S.%fZ < 1900
        with self.assertRaises(ValueError):
            ret = utilities.datestring_to_datetime(
                "1777-01-01T23:59:59.999Z")

        # %Y-%m-%dT%H:%M:%S good
        ret = utilities.datestring_to_datetime(
            "2019-01-01T23:59:59")
        self.assertTrue(ret)
        self.assertTrue(type(ret) is datetime.datetime)

        # %Y-%m-%dT%H:%M:%S < 1900
        with self.assertRaises(ValueError):
            ret = utilities.datestring_to_datetime(
                "1777-01-01T23:59:59")

        # %Y-%m-%dT%H:%M:%SZ good
        ret = utilities.datestring_to_datetime(
            "2019-01-01T23:59:59Z")
        self.assertTrue(ret)
        self.assertTrue(type(ret) is datetime.datetime)

        # %Y-%m-%dT%H:%M:%SZ < 1900
        with self.assertRaises(ValueError):
            ret = utilities.datestring_to_datetime(
                "1777-01-01T23:59:59Z")

        # already a datetime object
        ret1 = utilities.datestring_to_datetime(ret)
        self.assertEqual(ret1, ret)

    def test_get_rad_weekday(self):
        # sunday
        dt = datetime.datetime(2021, 7, 18)
        self.assertEqual(utilities.get_rad_weekday(dt), 0)
        # monday
        dt = datetime.datetime(2021, 7, 19)
        self.assertEqual(utilities.get_rad_weekday(dt), 1)
        # tuesday
        dt = datetime.datetime(2021, 7, 20)
        self.assertEqual(utilities.get_rad_weekday(dt), 2)
        # wednesday
        dt = datetime.datetime(2021, 7, 21)
        self.assertEqual(utilities.get_rad_weekday(dt), 3)
        # thursday
        dt = datetime.datetime(2021, 7, 22)
        self.assertEqual(utilities.get_rad_weekday(dt), 4)
        # friday
        dt = datetime.datetime(2021, 7, 23)
        self.assertEqual(utilities.get_rad_weekday(dt), 5)
        # saturday
        dt = datetime.datetime(2021, 7, 24)
        self.assertEqual(utilities.get_rad_weekday(dt), 6)

    def test_get_term_number(self):
        self.assertEqual(utilities.get_term_number("winter"), 1)
        self.assertEqual(utilities.get_term_number("spring"), 2)
        self.assertEqual(utilities.get_term_number("summer"), 3)
        self.assertEqual(utilities.get_term_number("autumn"), 4)
        with self.assertRaises(ValueError):
            utilities.get_term_number("bad-term")

    def test_get_view_name(self):
        self.assertEqual(
            utilities.get_view_name("2021-summer", 4, "rad"),
            "2021_summer_week_4_rad")
        self.assertEqual(
            utilities.get_view_name("2021-spring", 3, "assignments"),
            "2021_spring_week_3_assignments")
        self.assertEqual(
            utilities.get_view_name("2019-winter", 9, "participations"),
            "2019_winter_week_9_participations")
        with self.assertRaises(ValueError):
            utilities.get_view_name("2021-summer", 4, "bad")

    def test_get_sortable_term_id(self):
        self.assertEqual(utilities.get_sortable_term_id("2021-winter"),
                         "2021-1")
        self.assertEqual(utilities.get_sortable_term_id("2021-spring"),
                         "2021-2")
        self.assertEqual(utilities.get_sortable_term_id("2021-summer"),
                         "2021-3")
        self.assertEqual(utilities.get_sortable_term_id("2021-autumn"),
                         "2021-4")

if __name__ == "__main__":
    unittest.main()


text:
/* tslint:disable */
//  This file was automatically generated and should not be edited.

export type AverageWinsTicketsQuery = {
  teams:  Array< {
    name: string,
    ticketsSoldCount: number | null,
    winRateAvg: number | null,
  } | null > | null,
};

export type VenueTicketSalesQuery = {
  venues:  Array< {
    name: string,
    ticketSales:  Array< {
      item1: string | null,
      item2: number | null,
    } | null > | null,
  } | null > | null,
};

export type AllTeamsQuery = {
  teams:  Array< {
    name: string,
    contestants:  Array< {
      id: string | null,
      name: string,
    } | null > | null,
  } | null > | null,
};

export type ContestantQueryVariables = {
  contestantId: string,
};

export type ContestantQuery = {
  contestant:  {
    id: string | null,
    name: string,
    dominantHand: number,
    heightCm: number | null,
    weightKg: number | null,
    reachCm: number | null,
    strikesMin: number | null,
  } | null,
};

export type AllMatchesQuery = {
  matches:  Array< {
    id: string | null,
    date: string | null,
    homeTeam:  {
      name: string,
    } | null,
    awayTeam:  {
      name: string,
    } | null,
  } | null > | null,
};

export type MatchQueryVariables = {
  matchId: string,
};

export type MatchQuery = {
  match:  {
    date: string | null,
    id: string | null,
    homeTeam:  {
      name: string,
      heightCmAvg: number | null,
      weightKgAvg: number | null,
      reachCmAvg: number | null,
      strikesMinAvg: number | null,
      contestants:  Array< {
        name: string,
        imageUrl: string,
      } | null > | null,
    } | null,
    homeOdds: number | null,
    awayTeam:  {
      name: string,
      heightCmAvg: number | null,
      weightKgAvg: number | null,
      reachCmAvg: number | null,
      strikesMinAvg: number | null,
      contestants:  Array< {
        name: string,
        imageUrl: string,
      } | null > | null,
    } | null,
    awayOdds: number | null,
    umpire:  {
      name: string,
    } | null,
  } | null,
};
/* tslint:enable */


text:
//map initialization
/*
var map = new L.Map('map', { center: new L.LatLng(-1.2641,36.7494),zoom: 13,minZoom: 12,maxZoom: 16});
*/
var map = new L.Map('map',{scrollWheelZoom:false}).setView([-1.2641,36.7494], 13);

//TMS layer
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);

//Add custom icon

var MyIcon = L.icon({
iconUrl: 'https://openmaps.github.io/tutor/svg/flame.svg',
iconSize: [20, 20], // size of the icon
popupAnchor: [0,-15]
});

//Add interaction: popup
/*
var marker = L.marker([-1.2641,36.7494], {icon: MyIcon}).addTo(map);
https://github.com/OpenMaps/tutor/blob/master/svg/dribble_gif.gif

L.marker([-1.2641,36.7494], {icon: MyIcon}).bindPopup('Nairobi').addTo(map);
*/
//Custom popup

var customPopup = "Nairobi
";
var customOptions ={
    'maxWidth': '500',
    'className' : 'custom'
}
L.marker([-1.2641,36.7494], {icon: MyIcon}).bindPopup(customPopup,customOptions).addTo(map);

/*
var schools = {
"type": "FeatureCollection",
"features": [{ "type": "Feature",
"properties": { "name": "Chianina" },
"geometry": { "type": "Point", "coordinates": [ -1.2641,36.7494 ] }
},

var schoolpoints = L.geoJson(schools, {
	pointToLayer: function (feature, latlng) {
	return L.marker(latlng, MyIcon);
	}
}).addTo(map);
*/
//Geolocation
map.locate({setView: true, maxZoom: 16});

function onLocationFound(e) {
    var radius = e.accuracy / 2;
    L.marker(e.latlng).addTo(map).bindPopup("You are within " + radius + " meters from this point").openPopup();
    L.circle(e.latlng, radius).addTo(map);
}

map.on('locationfound', onLocationFound);

function onLocationError(e) {
    alert(e.message);
}

map.on('locationerror', onLocationError);

/*
function showCoords(e) {
	popup
		.setLatLng(e.latlng)
		.setContent(e.latlng.toString())
		.openOn(map);
}
map.on('click', showCoords);
*/


text:
![Evolution-A3](https://cloud.githubusercontent.com/assets/8865327/7921364/f944fe48-0872-11e5-8b42-c73af9b3b615.jpg "Evolution-A3")
Evolution-A3 is a remake of the popular Armed Assualt (ArmA) mission, Evolution Blue by KilJoy.
Evolution-A3 features all of the original gameplay mechanics, either in their original form, redesigned by myself, or with similair community content replacing the functionality of the original outdated code.

# Features

  - All features can be *disabled/enabled* via **mission parameters**.
  - AI units can be recruited via **bon_recruit_units** at the staging base via *action menu*, and airdropped in the field via *BI's communication menu*.
  - Dynamic view distance settings with **CHVD** can be set via action menu in the staging base.
  - HALO insertions using **ATM_airdrop** via action menu in the staging base.
  - Player loadout saved to user profile and modified via BI's **Virtual Arsenal**.
  - The **original Evolution** sounds!
  - **BI's dynamic groups** interface can be used via action menu at the staging base or at anytime by pressing 'U'.
  - **Meatball's randomWeather2** generates random, MP-sync'd weather throughout the game.
  - **Quiksilver's cleanup** and BI's **wreck and corpse management** keeps the mission running smooth throughout the entire game.
  - Overall OPFOR unit management moved to **VCOM AI** for complex AI counterparts.
  - **Headless Client implementation** automatically detects and offloads AI to your HC.
  - **Pilot loadout requirements** enforced to fly aircraft, includes auto-switching of loadout if you're in the base.
  - **Modular sidemissions** that provide bonus points to all players, and extra bonus points to the players responsible for completing the task, including: CSAR, Defend, Attack, Defend the Base, Ambush, and AAA hunt.
  - **Officer and POW Capturing** in every area of operation for bonus points!
  - **OPFOR support assets** may be available at the AO including mortar, anti-air, CAS, and sniper support.
  - All powered by the **Community Upgrade Project**.

> The overall goal of this project is to bring Evolution Blue up to ArmA 3 standards while preserving as much original gameplay as possible. Minor additions such as Revive and Support Assets that delineate from the origional concept should be added with optional paramters.

### Current Version

Latest version available on [Steam Workshop](http://steamcommunity.com/sharedfiles/filedetails/?id=677540897).

Discussion available at [Bohemia Interactive Forums](http://forums.bistudio.com/showthread.php?191210-(Co30)-Evolution-A3).

### Requirements

Evolution-A3 Classic requires the [Community Upgrade Project](https://steamcommunity.com/workshop/filedetails/?id=583575232).
![CUP](http://images.akamai.steamusercontent.com/ugc/355021463469540173/635B16F9F148CF9B8D615E2BE536B1A19F0E0E92/ "CUP")