text:
/**
 * @file VideoWriter_.cpp
 * @brief mex interface for cv::VideoWriter
 * @ingroup videoio
 * @author Kota Yamaguchi
 * @date 2012
 */
#include "mexopencv.hpp"
using namespace std;
using namespace cv;

namespace {
// Persistent objects
/// Last object id to allocate
int last_id = 0;
/// Object container
map<int,Ptr<VideoWriter> > obj_;

/// Capture Property map for option processing
const ConstMap<string,int> VidWriterProp = ConstMap<string,int>
    ("Quality",    cv::VIDEOWRITER_PROP_QUALITY)
    ("FrameBytes", cv::VIDEOWRITER_PROP_FRAMEBYTES);

/// Option arguments parser used by constructor and open method
struct OptionsParser
{
    /// 4-character code of codec used to compress the frames.
    int fourcc;
    /// Framerate of the created video stream.
    double fps;
    /// Flag to indicate whether to expect color or grayscale frames.
    bool isColor;

    /** Parse input arguments.
     * @param first iterator at the beginning of the arguments vector.
     * @param last iterator at the end of the arguments vector.
     */
    OptionsParser(vector<MxArray>::const_iterator first,
                  vector<MxArray>::const_iterator last)
        : fourcc(CV_FOURCC('U','2','6','3')),  // H263 codec
          fps(25),
          isColor(true)
    {
        nargchk(((last-first) % 2) == 0);
        for (; first != last; first += 2) {
            string key((*first).toString());
            const MxArray& val = *(first + 1);
            if (key == "FourCC") {
                if (val.isChar() && val.numel()==4) {
                    string cc(val.toString());
                    fourcc = VideoWriter::fourcc(cc[0], cc[1], cc[2], cc[3]);
                }
                else
                    fourcc = val.toInt();
            }
            else if (key == "FPS")
                fps = val.toDouble();
            else if (key == "Color")
                isColor = val.toBool();
            else
                mexErrMsgIdAndTxt("mexopencv:error",
                    "Unrecognized option %s", key.c_str());
        }
    };
};
}  // anonymous namespace

/**
 * Main entry called from Matlab
 * @param nlhs number of left-hand-side arguments
 * @param plhs pointers to mxArrays in the left-hand-side
 * @param nrhs number of right-hand-side arguments
 * @param prhs pointers to mxArrays in the right-hand-side
 */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    // Check the number of arguments
    nargchk(nrhs>=2 && nlhs<=1);

    // Argument vector
    vector<MxArray> rhs(prhs, prhs+nrhs);
    int id = rhs[0].toInt();
    string method(rhs[1].toString());

    // Constructor is called. Create a new object from arguments
    if (method == "new") {
        nargchk(nrhs==2 && nlhs==1);
        obj_[++last_id] = makePtr<VideoWriter>();
        plhs[0] = MxArray(last_id);
        return;
    }

    // Big operation switch
    Ptr<VideoWriter> obj = obj_[id];
    if (method == "delete") {
        nargchk(nrhs==2 && nlhs==0);
        obj_.erase(id);
    }
    else if (method == "open") {
        nargchk(nrhs>=4 && nlhs<=1);
        string filename(rhs[2].toString());
        Size frameSize(rhs[3].toSize());
        OptionsParser opts(rhs.begin() + 4, rhs.end());
        bool b = obj->open(filename, opts.fourcc, opts.fps, frameSize,
            opts.isColor);
        plhs[0] = MxArray(b);
    }
    else if (method == "isOpened") {
        nargchk(nrhs==2 && nlhs<=1);
        bool b = obj->isOpened();
        plhs[0] = MxArray(b);
    }
    else if (method == "release") {
        nargchk(nrhs==2 && nlhs==0);
        obj->release();
    }
    else if (method == "write") {
        nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs==0);
        bool flip = true;
        for (int i=3; i<nrhs; i+=2) {
            string key(rhs[i].toString());
            if (key == "FlipChannels")
                flip = rhs[i+1].toBool();
            else
                mexErrMsgIdAndTxt("mexopencv:error",
                    "Unrecognized option %s", key.c_str());
        }
        Mat frame(rhs[2].toMat());
        if (flip && frame.channels() == 3)
            cvtColor(frame, frame, cv::COLOR_RGB2BGR);
        obj->write(frame);
    }
    else if (method == "get") {
        nargchk(nrhs==3 && nlhs<=1);
        string prop(rhs[2].toString());
        double value = obj->get(VidWriterProp[prop]);
        plhs[0] = MxArray(value);
    }
    else if (method == "set") {
        nargchk(nrhs==4 && nlhs==0);
        string prop(rhs[2].toString());
        double value = rhs[3].toDouble();
        bool success = obj->set(VidWriterProp[prop], value);
        if (!success)
            mexWarnMsgIdAndTxt("mexopencv:error",
                "Error setting property %s", prop.c_str());
    }
    else
        mexErrMsgIdAndTxt("mexopencv:error","Unrecognized operation");
}


text:
package com.ibm.watson.app.common.services.bluemix;

import java.util.List;

import com.ibm.watson.app.common.services.BluemixConfiguredService;

public abstract class BaseBluemixService<T extends BaseBluemixServiceConfiguration> implements BluemixConfiguredService {

	protected T config;
	private Class<T> configImpl;

	public BaseBluemixService(Class<T> configImpl) {
		this.configImpl = configImpl;
	}

	@Override
	public void setConfig(Object object) {
		this.config = configImpl.cast(object);
	}

	@Override
	public Class<T> getConfigurationClass() {
		return configImpl;
	}

	@Override
	public String getName() {
		return config.getName();
	}

	@Override
	public String getLabel() {
		return config.getLabel();
	}

	@Override
	public List<String> getTags() {
		return config.getTags();
	}

	@Override
	public String getPlan() {
		return config.getPlan();
	}
}

redpajama_set_name: RedPajamaGithub


text:
export async function getIndexData ({sql, clientRedis}) {
  // 优先在redis如果没有数据库里拿
  // await clientRedis.del('newslist')
  let data = await clientRedis.lrange('newslist', 0, -1)
  if (data.length === 0 || data === null) {
    data = await sql.getSqlData({
      sqlQuery: 'select name from t_user'
    })
    await clientRedis.del('newslist')
    data.map(async (value) => {
      await clientRedis.lpush('newslist', JSON.stringify(value))
    })
  } else {
    let val = 0
    data.map((value) => {
      data[val] = JSON.parse(value)
      val++
    })
    console.log('redis')
  }
  return data
}


text:
<?php
namespace Admin\MedBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="plan_mejoramiento")
 * @ORM\Entity(repositoryClass="Admin\MedBundle\Entity\PlanmejoramientoRepository")
 */
class Planmejoramiento{

/**
 * @ORM\Id
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\GeneratedValue(strategy="AUTO")
     */
 protected $id;

 /**
  * @ORM\Column(type="datetime", nullable=true)
  */
protected $fecha_creacion;

 /**
  * @ORM\Column(type="datetime", nullable=true)
  */
protected $fecha_cierre;

 /**
  * @ORM\Column(type="string", length=512, nullable=true)
  */
protected $observaciones;

/**
 * @ORM\Column(type="float", scale=2, nullable=true)
 */
protected $calificacion;

 /**
  * @ORM\Column(type="integer", nullable=true)
  */
protected $autorid;

/**
     * @var Docente
     * @ORM\ManyToOne(targetEntity="Admin\UnadBundle\Entity\Docente", inversedBy="planmejoramiento")
     * @ORM\JoinColumn(name="docente_id", referencedColumnName="id",
     * nullable=false
     * )
     */
protected $docente;

    /**
     * @ORM\OneToMany(targetEntity="Admin\MedBundle\Entity\Accionespm", mappedBy="plan")
     */
    protected $acciones;

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

    /**
     * Set fecha_creacion
     *
     * @param \DateTime $fechaCreacion
     * @return Planmejoramiento
     */
    public function setFechaCreacion($fechaCreacion)
    {
        $this->fecha_creacion = $fechaCreacion;

        return $this;
    }

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

    /**
     * Set fecha_cierre
     *
     * @param \DateTime $fechaCierre
     * @return Planmejoramiento
     */
    public function setFechaCierre($fechaCierre)
    {
        $this->fecha_cierre = $fechaCierre;

        return $this;
    }

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

    /**
     * Set observaciones
     *
     * @param string $observaciones
     * @return Planmejoramiento
     */
    public function setObservaciones($observaciones)
    {
        $this->observaciones = $observaciones;

        return $this;
    }

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

    /**
     * Set calificacion
     *
     * @param float $calificacion
     * @return Planmejoramiento
     */
    public function setCalificacion($calificacion)
    {
        $this->calificacion = $calificacion;

        return $this;
    }

    /**
     * Get calificacion
     *
     * @return float
     */
    public function getCalificacion()
    {
        return $this->calificacion;
    }

    /**
     * Set docente
     *
     * @param \Admin\UnadBundle\Entity\Docente $docente
     * @return Planmejoramiento
     */
    public function setDocente(\Admin\UnadBundle\Entity\Docente $docente)
    {
        $this->docente = $docente;

        return $this;
    }

    /**
     * Get docente
     *
     * @return \Admin\UnadBundle\Entity\Docente
     */
    public function getDocente()
    {
        return $this->docente;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->acciones = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add acciones
     *
     * @param \Admin\MedBundle\Entity\Accionespm $acciones
     * @return Planmejoramiento
     */
    public function addAccione(\Admin\MedBundle\Entity\Accionespm $acciones)
    {
        $this->acciones[] = $acciones;

        return $this;
    }

    /**
     * Remove acciones
     *
     * @param \Admin\MedBundle\Entity\Accionespm $acciones
     */
    public function removeAccione(\Admin\MedBundle\Entity\Accionespm $acciones)
    {
        $this->acciones->removeElement($acciones);
    }

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

    /**
     * Set autorid
     *
     * @param integer $autorid
     * @return Planmejoramiento
     */
    public function setAutorid($autorid)
    {
        $this->autorid = $autorid;

        return $this;
    }

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


text:
title:  Lepotica i zveri
date:   28/03/2019
---

### Mišljenje (Efescima 6,12)

Prvi deo 12. poglavlja Otkrivenja prikazuje jednu blistavu ženu (Otkrivenje 12,1.2), aždaju (3. stih), i ženino dete (2. stih) kao glavne ličnosti. Prizor se odvija na nebu. Dete se uzima na nebo, a žena beži u pustinju (Otkrivenje 12,5.6).

Čudo ili znak u vidu trudne žene obučene u sunce, krunisane zvezdama, koja stoji na mesecu simbolizuje Božju čistu crkvu, vernu svojoj Ljubavi, Isusu (Isaija 54,5.6; Jeremija 3,20; 6,2; Jezekilj 16,8-14; Osija 1-3; Galatima 4,26). Sunce kao odeća simbolizuje Hristovu pravednost koja zaodeva crkvu (Malahija 4,2). Slika odeće pojavljuje se takođe u tekstu Isaija 61,10: »Veoma ću se radovati u Gospodu, i duša će se moja veseliti u Bogu mojem, jer me obuče u haljine spasenja i plaštem pravde ogrte me kao kad ženik namjesti nakit i kao kad se nevjesta uresi uresom svojim.« Budući da mesec odražava sunčevu svetlost, on simbolizuje »Mojsijev zakon i svetinju« koji su unapred upućivali na Hrista.1 Dvanaest zvezda označavaju dvanaest izraelskih plemena i održavaju kontinuitet simbola između Starog i Novog zaveta.

Ta žena simbolizuje svakog vernika koji živi životom stalnog sukoba. Slika žene u porođajnim bolovima predstavlja opis stradanja Božjeg naroda (Jovan 16,33). Dobra vest je da Isus Hristos svakom verniku daje potpuni oklop kako bi ga zaštitio od zla (Efescima 6,10.11.13). Borba Božjeg naroda odvija se iznutra i spolja, ali na kraju je Hristova pravednost to što održava naše srce i um čistim uprkos takvim napadima (2. Korinćanima 10,3-5).

Drugi znak je crvena aždaja što simbolizuje staru zmiju, poznatu i pod imenom đavo ili sotona. Crvena boja često simbolizuje nečistotu, ali može da predstavlja i prolivenu krv sotoninih nevinih žrtava (Otkrivenje 16,6; Otkrivenje 17,6; Otkrivenje 18,24). Na kraju, sotona ipak neće biti u stanju da savlada Božji narod koji će izaći kao pobednik (Efescima 6,12).

Otkrivenje 12 ukazuje na prošle, sadašnje i buduće sukobe s kojima će se Božji narod suočavati. Ono otkriva ko je glavni protivnik Božjeg naroda – đavo. Zato je 12. poglavlje Otkrivenja ključno za razumevanje krajnjeg ishoda kosmičkog sukoba između Hrista i sotone.

**Odgovorite**

`1.	Kako možemo biti čisti kao žena opisana u 12. poglavlju Otkrivenja?`

`2.	Ko pobeđuje u tekstu Otkrivenje 12,1-6? Kako je to postignuto? `

`3.	Kako se vaše lične životne borbe uklapaju u taj kosmički sukob? Da li zapažate događaje koji vam ukazuju da su duhovne sile na delu svuda oko vas? `

*Ešli Nataša Odhiambo, Filipini*

_________
1	Uriah Smith, The Prophesies of Daniel and Revelation, (Nashville, TN: Southern Publishing Association, 1946), p. 549.


text:
package models

import (
	"fmt"
	"time"
)

// Update ...
type Update struct {
	LastCheckAt   time.Time
	LastUpdatedAt time.Time
}

// LoadUpdate loads the update entry
func LoadUpdate() (*Update, error) {
	update := &Update{}

	if err := get("registry", "update", &update); err != nil {
		return update, fmt.Errorf("failed to load update: %s", err.Error())
	}

	return update, nil
}

// Save persists the Update to the database
func (u *Update) Save() error {

	// Since there is only ever a single update value, we'll use the registry
	if err := put("registry", "update", u); err != nil {
		return fmt.Errorf("failed to save update: %s", err.Error())
	}

	return nil
}


text:
/* global chartStream */
angular.module('viz3k')
.directive('chartFactionsStream', ['$util', function ($util) {
  'use strict';

  // custom tooltip for chart
  function factionTooltip(key, x, y, e, graph) {
    return '
' + key + '
' +
           '
' + y + ' members in Chapter ' + x + '
';
  }

  function xTickValuesFn(scale) {
    var tickInterval = 10;
    var minValue = scale.domain()[0];
    var maxValue = scale.domain()[1];
    var tickValues = _.times(maxValue/tickInterval, i => (i + 1)*tickInterval);
    tickValues.unshift(minValue);
    if (_.last(tickValues) < maxValue) {
      tickValues.push(maxValue);
    }
    return tickValues;
  }

  function render(svg, factions, chapters) {
    var data = new Array(factions.length);

    for (var f = 0; f < factions.length; f++) {
      var faction = factions[f];
      var values = new Array(chapters.length);

      // find out how many of this faction's members turn up in each chapter
      for (var c = 0; c < chapters.length; c++) {
        var chapter = chapters[c];
        values[c] = {
          x: chapter.chapter,
          y: $util.countFactionMembersInChapter(faction, chapter)
        };
      }

      data[f] = {
        name: faction.name,
        color: faction.color,
        values: values
      };
    }

    return chartStream()
      .data(data)
      .xTickValuesFn(xTickValuesFn)
      .render(svg);
  }

  return {
    restrict: 'A',
    template: '<svg></svg>',
    scope: {
      factions: '=',
      chapters: '='
    },
    link: function (scope, element, attrs) {
      // select the svg tag
      var svg = d3.select(element[0]).select('svg');

      // only render when data is defined
      var renderIfReady = function () {
        if (scope.factions && scope.chapters) {
          render(svg, scope.factions, scope.chapters);
        }
      };

      // watch for changes in data
      scope.$watch('factions', function (newFactions) {
        if (newFactions) {
          renderIfReady();
        }
      });
      scope.$watch('chapters', function (newChapters) {
        if (newChapters) {
          renderIfReady();
        }
      });
    }
  };
}]);


text:
package lib

// Truncate tries to append the "suffix" to the "str". If the length of the appended string exceeds "n",
// the function truncates the "str" to make sure the "suffix" is appended
func Truncate(str, suffix string, n int) string {
	s := str + suffix
	if len(s) <= n {
		return s
	}
	return s[:len(str)-(len(s)-n)] + suffix
}


text:
import sys
import os

from basic.constant import ROOT_PATH
from basic.common import checkToSkip, printStatus

INFO = __file__

def process(options, collection):
    rootpath = options.rootpath
    tpp = options.tpp

    tagfile = os.path.join(rootpath, collection, "TextData", "id.userid.%stags.txt" % tpp)
    resultfile = os.path.join(rootpath, collection, "TextData", "%stag.userfreq.imagefreq.txt" % tpp)
    if checkToSkip(resultfile, options.overwrite):
        return 0

    printStatus(INFO, "parsing " + tagfile)

    tag2imfreq = {}
    tag2users = {}

    for line in open(tagfile):
        elems = str.split(line.strip())
        photoid = elems[0]
        userid = elems[1]
        tagset = set(elems[2:])

        for tag in tagset:
            tag2imfreq[tag] = tag2imfreq.get(tag, 0) + 1
            tag2users.setdefault(tag,[]).append(userid)

    printStatus(INFO, "collecting user-freq and image-freq")
    results = []
    for tag,users in tag2users.iteritems():
        userfreq = len(set(users))
        imfreq = tag2imfreq[tag]
        results.append((tag, userfreq, imfreq))

    printStatus(INFO, "sorting in descending order (user-freq as primary key)")
    results.sort(key=lambda v:(v[1],v[2]), reverse=True)
    printStatus(INFO, "-> %s" % resultfile)

    with open(resultfile, 'w') as fw:
        fw.write(''.join(['%s %d %d\n' % (tag, userfreq, imfreq) for (tag, userfreq, imfreq) in results]))
        fw.close()

def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    from optparse import OptionParser
    parser = OptionParser(usage="""usage: %prog [options] collection""")

    parser.add_option("--overwrite", default=0, type="int", help="overwrite existing file (default: 0)")
    parser.add_option("--tpp", default='lemm', type="string", help="tag preprocess (default: lemm)")
    parser.add_option("--rootpath", default=ROOT_PATH, type="string", help="rootpath where the train and test collections are stored (default: %s)" % ROOT_PATH)

    (options, args) = parser.parse_args(argv)
    if len(args) < 1:
        parser.print_help()
        return 1

    return process(options, args[0])

if __name__ == "__main__":
    sys.exit(main())


text:
import * as React from "react";
import { Box, BoxProps, Card, ResponsiveBox, Text } from "@artsy/palette"
import { createFragmentContainer, graphql } from "react-relay"
import { ShowViewingRoom_show } from "v2/__generated__/ShowViewingRoom_show.graphql"
import { RouterLink } from "v2/System/Router/RouterLink"
import { cropped } from "v2/Utils/resized"
import { useTracking } from "v2/System"
import { useAnalyticsContext } from "v2/System/Analytics/AnalyticsContext"
import {
  ActionType,
  ClickedViewingRoomCard,
  ContextModule,
  OwnerType,
} from "@artsy/cohesion"
import { getStatus } from "v2/Apps/ViewingRoom/Utils/getStatus"
import { extractNodes } from "v2/Utils/extractNodes"

interface ShowViewingRoomProps extends BoxProps {
  show: ShowViewingRoom_show
}

export const ShowViewingRoom: React.FC<ShowViewingRoomProps> = ({
  show,
  ...rest
}) => {
  const [viewingRoom] = extractNodes(show.viewingRoomsConnection)

  const image = cropped(viewingRoom.image?.imageURLs?.normalized!, {
    width: 450,
    height: 600,
  })

  const tracking = useTracking()
  const {
    contextPageOwnerId,
    contextPageOwnerSlug,
    contextPageOwnerType,
  } = useAnalyticsContext()

  const handleClick = () => {
    const payload: ClickedViewingRoomCard = {
      action: ActionType.clickedViewingRoomCard,
      context_module: ContextModule.associatedViewingRoom,
      // @ts-expect-error STRICT_NULL_CHECK
      context_page_owner_type: contextPageOwnerType,
      context_page_owner_id: contextPageOwnerId,
      context_page_owner_slug: contextPageOwnerSlug,
      destination_page_owner_type: OwnerType.viewingRoom,
      destination_page_owner_id: viewingRoom.internalID,
      destination_page_owner_slug: viewingRoom.slug,
      type: "thumbnail",
    }

    tracking.trackEvent(payload)
  }

  return (
    <Box {...rest}>
      <Text variant="xs" textTransform="uppercase" mb={2}>
        Viewing Room
      </Text>

      <ResponsiveBox maxWidth="100%" aspectWidth={3} aspectHeight={4}>
        <RouterLink to={viewingRoom.href} onClick={handleClick}>
          <Card
            maxWidth="100%"
            image={image}
            title={viewingRoom.title}
            subtitle={show.partner?.name}
            status={getStatus({
              status: viewingRoom.status,
              distanceToOpen: viewingRoom.distanceToOpen,
              distanceToClose: viewingRoom.distanceToClose,
            })}
          />
        </RouterLink>
      </ResponsiveBox>
    </Box>
  )
}

export const ShowViewingRoomFragmentContainer = createFragmentContainer(
  ShowViewingRoom,
  {
    show: graphql`
      fragment ShowViewingRoom_show on Show {
        partner {
          ... on Partner {
            name
          }
          ... on ExternalPartner {
            name
          }
        }
        viewingRoomsConnection {
          edges {
            node {
              internalID
              slug
              status
              distanceToOpen(short: true)
              distanceToClose(short: true)
              title
              href
              image {
                imageURLs {
                  normalized
                }
              }
            }
          }
        }
      }
    `,
  }
)


text:
//======================================================================================
// Copyright 5AM Solutions Inc, Yale University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/caarray/LICENSE.txt for details.
//======================================================================================
package gov.nih.nci.caarray.dao.stub;

import gov.nih.nci.caarray.dao.FileDao;
import gov.nih.nci.caarray.domain.file.CaArrayFile;
import gov.nih.nci.caarray.domain.search.FileSearchCriteria;

import java.net.URI;
import java.util.Collections;
import java.util.List;

import com.fiveamsolutions.nci.commons.data.search.PageSortParams;

/**
 *
 */
public class FileDaoStub extends AbstractDaoStub implements FileDao {
    @Override
    public List<CaArrayFile> searchFiles(PageSortParams<CaArrayFile> params, FileSearchCriteria criteria) {
        return Collections.emptyList();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<CaArrayFile> getDeletableFiles(Long projectId) {
        return Collections.emptyList();
    }

    @Override
    public List<URI> getAllFileHandles() {
        return Collections.emptyList();
    }

    @Override
    public void cleanupUnreferencedChildren() {
        // no op
    }

    @Override
    public CaArrayFile getPartialFile(Long projectId, String fileName, long fileSize) {
        return null; // unused. Trying to get rid of stub classes.
    }
}


text:
package com.couchbase.android;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Process;
import android.util.Log;

import com.couchbase.android.Intents.CouchbaseError;
import com.couchbase.android.Intents.CouchbaseStarted;

/**
 * Implementation of the Couchbase service
 *
 */

public class CouchbaseService extends Service {

	/**
	 * Couchbase encountered an error
	 */
	public static final int ERROR = 0;

	/**
	 * Couchbase installation complete
	 */
	public static final int COMPLETE = 1;

	/**
	 * Couchbase startup complete
	 */
	public static final int COUCHBASE_STARTED = 2;

	/**
	 * System shell
	 */
	public static final String shell = "/system/bin/sh";

	/**
	 * The URL Couchbase is running on
	 */
	private static URL url;

	/**
	 * Delegate used to notify the client of events in the service
	 */
	private ICouchbaseDelegate couchbaseDelegate;

	/**
	 * Thread responsible for installing Couchbase
	 */
	private CouchbaseInstaller couchbaseInstallThread;

	/**
	 * Thread responsible for communicating with Couchbase process
	 */
	private static Thread couchbaseRunThread;

	/**
	 *	A handler to pass messages between Couchbase main thread, Couchbase installer thread, and application main thread
	 *
	 *  Couchbase runs in a seperate thread, have the communication run
	 *  through our own handler so the app doesnt need to create a new
	 *  handler to deal with touching the UI from a different thread
	 */
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case ERROR:
				Exception e = (Exception) msg.obj;
				couchbaseError(e);
				break;
			case COMPLETE:
				couchbaseInstallThread = null;
				if(couchbaseRunThread == null)
					startCouchbaseService();
				else
					couchbaseStarted();
				break;
			case COUCHBASE_STARTED:
				url = (URL) msg.obj;
				couchbaseStarted();
				break;
			}
		}
	};

	/**
	 * This is called when the service is destroyed
	 */
	@Override
	public void onDestroy() {
		couchbaseDelegate = null;
	}

	/**
	 * This is called called on the initial service binding
	 */
	@Override
	public IBinder onBind(Intent intent) {
		return new CouchbaseServiceImpl();
	}

	/**
	 * An implementation of the Couchbase service exposed to clients wrapping around this implementation
	 *
	 */
	public class CouchbaseServiceImpl extends Binder implements ICouchbaseService {

		@Override
		public void startCouchbase(ICouchbaseDelegate cb) {
			couchbaseDelegate = cb;

			if (couchbaseRunThread == null) {
				//if we're not running, trigger install
				//this will be no-op if already installed
				//and will trigger startup through handler
				installCouchbase();
			}
			else {
				couchbaseStarted();
			}
		}
	};

	/**
	 * Nofity the delegate that Couchbase has started
	 */
	void couchbaseStarted() {

		if(url != null) {
			//send broadcast intent
			Intent intent = new Intent(CouchbaseStarted.ACTION);
			intent.putExtra(CouchbaseStarted.HOST, url.getHost());
			intent.putExtra(CouchbaseStarted.PORT, url.getPort());
			intent.putExtra(CouchbaseStarted.PID, Process.myPid());
			getApplicationContext().sendBroadcast(intent);

			//notify delegate
			if (couchbaseDelegate != null) {
				couchbaseDelegate.couchbaseStarted(url.getHost(), url.getPort());
			}
		}
	}

	/**
	 * Notify the delegate that Couchbase has encountered an error
	 */
	void couchbaseError(Exception e) {
		StringWriter sw = new StringWriter();
		e.printStackTrace(new PrintWriter(sw));
		String stacktrace = sw.toString();

		//send broadcast intent
		Intent intent = new Intent(CouchbaseError.ACTION);
		intent.putExtra(CouchbaseError.MESSAGE, stacktrace);
		intent.putExtra(CouchbaseError.PID, Process.myPid());
		getApplicationContext().sendBroadcast(intent);

		//notify delegate
		if (couchbaseDelegate != null) {
			couchbaseDelegate.exit(stacktrace);
		}
	}

	/**
	 * Install Couchbase in a separate thread
	 */
	private void installCouchbase() {
		couchbaseInstallThread = new CouchbaseInstaller(getPackageCodePath(), mHandler);
		couchbaseInstallThread.start();
	}

	/**
	 * Start the Couchbase service in a separate thread
	 */
	void startCouchbaseService() {
		String path = CouchbaseMobile.dataPath();
		String apkPath = getPackageCodePath();

		try {
			new File(path + "/apk.ez").delete();
			Runtime.getRuntime().exec(new String[] { "ln", "-s", apkPath, path + "/apk.ez" });
		} catch (IOException e) {
			Log.v(CouchbaseMobile.TAG, "Error symlinking apk.ez", e);
			Message.obtain(mHandler, CouchbaseService.ERROR, e).sendToTarget();
			return;
		}

		String[] plainArgs = {
				"beam", "-K", "true", "--",
				"-noinput",
				"-boot_var", "APK", path + "/apk.ez",
				"-kernel", "inetrc", "\""+ path + "/erlang/bin/erl_inetrc\"",
				"-native_lib_path", path + "/lib",
				"-sasl", "errlog_type", "all",
				"-boot", path + "/erlang/bin/start",
				"-root", path + "/apk.ez/assets",
				"-eval", "code:load_file(jninif), R = application:start(couch), io:format(\"~w~n\",[R]).",
				"-couch_ini",
				path + "/couchdb/etc/couchdb/default.ini",
				path + "/couchdb/etc/couchdb/local.ini",
				path + "/couchdb/etc/couchdb/android.default.ini"};

		ArrayList<String> args = new ArrayList<String>(Arrays.asList(plainArgs));
		for (String iniPath : CouchbaseMobile.getCustomIniFiles()) {
			args.add(iniPath);
		}

		args.add(path + "/couchdb/etc/couchdb/overrides.ini");
		final String[] argv = args.toArray(new String[args.size()]);
		final String sopath = path + "/lib/libbeam.so";
		final String bindir = path + "/erlang/bin";
		couchbaseRunThread = new Thread() {
			public void run() {
				ErlangThread.setHandler(mHandler);
				ErlangThread.start_erlang(bindir, sopath, argv);
				Log.i(CouchbaseMobile.TAG, "Erlang thread ended.");
			}
		};
		couchbaseRunThread.start();
	}

}


text:
function onUse(cid, item, fromPosition, itemEx, toPosition)
	if(item.actionid == 1004) then
		if(getPlayerStorageValue(cid, Storage.TheInquisition.Questline) == 18) then
			if(item.itemid == 5114) then
				doTeleportThing(cid, toPosition, true)
				doTransformItem(item.uid, 5115)
			end
		end
	end
	return true
end


text:
// issue: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/369
// https://github.com/witoldsz/angular-http-auth/blob/master/src/angular-http-auth.js
/**
 * @license HTTP Auth Interceptor Module for AngularJS
 * (c) 2012 Witold Szczerba
 * License: MIT
 */

/* tslint:disable:no-empty no-shadowed-variable */

class AuthService {
    /**
      * Holds all the requests which failed due to 401 response,
      * so they can be re-requested in future, once login is completed.
      */
    buffer: Array<{ config: ng.IRequestConfig; deferred: ng.IDeferred<any>; }> = [];

    /**
     * Required by HTTP interceptor.
     * Function is attached to provider to be invisible for regular users of this service.
     */
    pushToBuffer = (config: ng.IRequestConfig, deferred: ng.IDeferred<any>) => {
        this.buffer.push({
            config,
            deferred
        });
    }

    $get = [
        '$rootScope', '$injector', ($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) => {
            let $http: ng.IHttpService; // initialized later because of circular dependency problem
            function retry(config: ng.IRequestConfig, deferred: ng.IDeferred<any>) {
                $http = $http || $injector.get<ng.IHttpService>('$http');
                $http(config).then(response => {
                    deferred.resolve(response);
                });
            }
            function retryAll() {
                for (const request of this.buffer) {
                    retry(request.config, request.deferred);
                }

                this.buffer = [];
            }

            return {
                loginConfirmed() {
                    $rootScope.$broadcast('event:auth-loginConfirmed');
                    retryAll();
                }
            };
        }
    ];
}

angular.module('http-auth-interceptor', [])

    .provider('authService', AuthService)

/**
 * $http interceptor.
 * On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'.
 */
    .config(['$httpProvider', 'authServiceProvider', ($httpProvider: ng.IHttpProvider, authServiceProvider: any) => {
        $httpProvider.defaults.headers.common = {Authorization: 'Bearer token'};
        $httpProvider.defaults.headers.get['Authorization'] = 'Bearer token';
        $httpProvider.defaults.headers.post['Authorization'] = (config: ng.IRequestConfig) => 'Bearer token';

        const interceptor = ['$rootScope', '$q', ($rootScope: ng.IScope, $q: ng.IQService) => {
            function success(response: ng.IHttpPromiseCallbackArg<any>) {
                return response;
            }

            function error(response: ng.IHttpPromiseCallbackArg<any>) {
                if (response.status === 401) {
                    const deferred = $q.defer<void>();
                    authServiceProvider.pushToBuffer(response.config, deferred);
                    $rootScope.$broadcast('event:auth-loginRequired');
                    return deferred.promise;
                }
                // otherwise
                return $q.reject(response);
            }

            return (promise: ng.IHttpPromise<any>) => promise.then(success, error);
        }];
        $httpProvider.interceptors.push(interceptor);
    }]);

namespace HttpAndRegularPromiseTests {
    interface Person {
        firstName: string;
        lastName: string;
    }

    type ExpectedResponse = Person;

    interface SomeControllerScope extends ng.IScope {
        person: Person;
        theAnswer: number;
        letters: string[];
        snack: string;
        nothing?: string;
    }

    function someController($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) {
        $http.get<ExpectedResponse>('http://somewhere/some/resource')
            .then((response: ng.IHttpPromiseCallbackArg<ExpectedResponse>) => {
                // typing lost, so something like
                // const i: number = response.data
                // would type check
                $scope.person = response.data;
            });

        $http.get<ExpectedResponse>('http://somewhere/some/resource')
            .then((response: ng.IHttpPromiseCallbackArg<ExpectedResponse>) => {
                // typing lost, so something like
                // const i: number = response.data
                // would NOT type check
                $scope.person = response.data;
            });

        const aPromise: ng.IPromise<Person> = $q.when({ firstName: 'Jack', lastName: 'Sparrow' });
        aPromise.then((person: Person) => {
            $scope.person = person;
        });

        const bPromise: ng.IPromise<number> = $q.when(42);
        bPromise.then((answer: number) => {
            $scope.theAnswer = answer;
        });

        const cPromise: ng.IPromise<string[]> = $q.when(['a', 'b', 'c']);
        cPromise.then((letters: string[]) => {
            $scope.letters = letters;
        });

        // When $q.when is passed an IPromise<T>, it returns an IPromise<T>
        const dPromise: ng.IPromise<string> = $q.when($q.when('ALBATROSS!'));
        dPromise.then((snack: string) => {
            $scope.snack = snack;
        });

        // $q.when may be called without arguments
        const ePromise: ng.IPromise<void> = $q.when();
        ePromise.then(() => {
            $scope.nothing = 'really nothing';
        });
    }
}

// Test for AngularJS Syntax

namespace My.Namespace {
    export const x: any = null; // need to export something for module to kick in
}

class TestProvider implements ng.IServiceProvider {
    constructor(private $scope: ng.IScope) {}

    $get() {}
}

// IModule Registering Test
let mod = angular.module('tests', []);
mod.controller('name', ($scope: ng.IScope) => { });
mod.controller('name', ['$scope', ($scope: ng.IScope) => { }]);
mod.controller('name', class {
    // Uncommenting the next line should lead to a type error because this signature isn't compatible
    // with the signature of the `$onChanges` hook:
    // $onChanges(x: number) { }
});
mod.controller({
    MyCtrl: class{},
    MyCtrl2() {},
    MyCtrl3: ['$fooService', ($fooService: any) => { }]
});
mod.directive('myDirectiveA', ($rootScope: ng.IRootScopeService) => {
    return (scope, el, attrs) => {
        let foo = 'none';
        el.click(e => {
            foo = e.type;
            $rootScope.$apply();
        });
        scope.$watch(() => foo, () => el.text(foo));
    };
});
mod.directive('myDirectiveB', ['$rootScope', ($rootScope: ng.IRootScopeService) => {
    return {
        link(scope, el, attrs) {
            el.click(e => {
                el.hide();
            });
        }
    };
}]);
mod.directive({
    myFooDir: () => ({
        template: 'my-foo-dir.tpl.html'
    }),
    myBarDir: ['$fooService', ($fooService: any) => ({
        template: 'my-bar-dir.tpl.html'
    })]
});
mod.factory('name', ($scope: ng.IScope) => {});
mod.factory('name', ['$scope', ($scope: ng.IScope) => {}]);
mod.factory({
    name1(foo: any) {},
    name2: ['foo', (foo: any) => {}]
});
mod.filter('name', ($scope: ng.IScope) => {});
mod.filter('name', ['$scope', ($scope: ng.IScope) => {}]);
mod.filter({
    name1(foo: any) {},
    name2: ['foo', (foo: any) => {}]
});
mod.provider('name', ($scope: ng.IScope) => ({ $get: () => { } }));
mod.provider('name', TestProvider);
mod.provider('name', ['$scope', ($scope: ng.IScope) => {}]);
mod.provider(My.Namespace);
mod.service('name', ($scope: ng.IScope) => {});
mod.service('name', ['$scope', ($scope: ng.IScope) => {}]);
mod.service({
    MyCtrl: class{},
    MyCtrl2: () => {}, // tslint:disable-line:object-literal-shorthand
    MyCtrl3: ['$fooService', ($fooService: any) => {}]
});
mod.constant('name', 23);
mod.constant('name', '23');
mod.constant(My.Namespace);
mod.value('name', 23);
mod.value('name', '23');
mod.value(My.Namespace);
mod.decorator('name', ($scope: ng.IScope) => {});
mod.decorator('name', ['$scope', ($scope: ng.IScope) => {}]);

// QProvider tests
angular.module('qprovider-test', [])
    .config(['$qProvider', ($qProvider: ng.IQProvider) => {
        const provider: ng.IQProvider = $qProvider.errorOnUnhandledRejections(false);
        const currentValue: boolean = $qProvider.errorOnUnhandledRejections();
    }]);

// Promise signature tests
let foo: ng.IPromise<number>;
foo.then((x) => {
    // x is inferred to be a number
    x.toFixed();
    return 'asdf';
}).then((x) => {
    // x is inferred to be string
    const len = x.length;
    return 123;
}, (e) => {
    return anyOf2([123], toPromise([123])); // IPromise<T> | T, both are good for the 2nd arg of .then()
}).then((x) => {
    // x is infered to be a number or number[]
    if (Array.isArray(x)) {
        x[0].toFixed();
    } else {
        x.toFixed();
    }
    return;
}).catch(e => {
    return foo || 123; // IPromise<T> | T, both are good for .catch()
}).then(x => {
    // x is infered to be void | number
    x && x.toFixed();
    // Typescript will prevent you to actually use x as a local variable before you check it is not void
    // Try object:
    return { a: 123 };
}).then((x) => {
    // Object is inferred here
    x.a = 123;
    // Try a promise
    const y: ng.IPromise<number> = null;
    const condition: boolean = null;
    return condition ? y : x.a; // IPromise<T> | T, both are good for the 1st arg of .then()
}).then((x) => {
    // x is infered to be a number, which is the resolved value of a promise
    x.toFixed();
});

// $q signature tests
namespace TestQ {
    interface TResult {
        a: number;
        b: string;
        c: boolean;
    }
    interface TValue {
        e: number;
        f: boolean;
    }
    interface TOther {
        g: string;
        h: number;
    }
    const tResult: TResult = null;
    const promiseTResult: angular.IPromise<TResult> = null;
    const tValue: TValue = null;
    const promiseTValue: angular.IPromise<TValue> = null;
    const tOther: TOther = null;
    const promiseTOther: angular.IPromise<TOther> = null;

    const $q: angular.IQService = null;
    const promiseAny: angular.IPromise<any> = null;

    const assertPromiseType = <T>(arg: angular.IPromise<T>) => arg;

    // $q constructor
    {
        let result: angular.IPromise<TResult>;
        result = new $q<TResult>((resolve: (value: TResult) => any) => {});
        result = new $q<TResult>((resolve: (value: TResult) => any, reject: (value: any) => any) => {});
        result = $q<TResult>((resolve: (value: TResult) => any) => {});
        result = $q<TResult>((resolve: (value: TResult) => any, reject: (value: any) => any) => {});
    }

    // $q.all
    {
        let result: angular.IPromise<any[]>;
        result = $q.all([promiseAny, promiseAny]);
        // TS should infer that n1 and n2 are numbers and have toFixed.
        $q.all([1, $q.when(2)]).then(([ n1, n2 ]) => n1.toFixed() + n2.toFixed());
        $q.all([1, $q.when(2), '3']).then(([ n1, n2, n3 ]) => n1.toFixed() + n2.toFixed() + n3.slice(1));
    }
    {
        let result: angular.IPromise<TResult[]>;
        result = $q.all<TResult>([promiseAny, promiseAny]);
    }
    {
        let result: angular.IPromise<{[id: string]: any; }>;
        result = $q.all({a: promiseAny, b: promiseAny});
    }
    {
        let result: angular.IPromise<{a: number; b: string; }>;
        result = $q.all<{a: number; b: string; }>({a: promiseAny, b: promiseAny});
    }

    // $q.defer
    {
        let result: angular.IDeferred<TResult>;
        result = $q.defer<TResult>();
        result.resolve(tResult);
        const anyValue: any = null;
        result.reject(anyValue);
        result.promise.then(result => {
            return $q.resolve<TResult>(result);
        });
    }

    // $q.reject
    {
        let result: angular.IPromise<never>;
        result = $q.reject();
        result = $q.reject('');
        result.catch(() => 5).then(x => x.toFixed());
    }

    // $q.resolve
    {
        let result: angular.IPromise<void>;
        result = $q.resolve();
    }
    {
        let result: angular.IPromise<TResult>;
        result = $q.resolve<TResult>(tResult);
        result = $q.resolve<TResult>(promiseTResult);
        result = $q.resolve<TResult | TOther>(Math.random() > 0.5 ? tResult : promiseTOther);
        result = $q.resolve(Math.random() > 0.5 ? tResult : promiseTOther);
    }

    // $q.when
    {
        let result: angular.IPromise<void>;
        result = $q.when();
    }
    {
        let result: angular.IPromise<TResult>;
        let resultOther: angular.IPromise<TOther>;

        result = $q.when<TResult>(tResult);
        result = $q.when<TResult>(promiseTResult);

        result = $q.when<TResult, TValue>(tValue, (result: TValue) => tResult);
        result = $q.when<TResult, TValue>(tValue, (result: TValue) => tResult, (any) => any);
        result = $q.when<TResult, TValue>(tValue, (result: TValue) => tResult, (any) => any, (any) => any);

        result = $q.when<TResult, TValue>(promiseTValue, (result: TValue) => tResult);
        result = resultOther = $q.when<TResult, TOther, TValue>(promiseTValue, (result: TValue) => tResult, (any) => tOther);
        result = resultOther = $q.when<TResult, TOther, TValue>(promiseTValue, (result: TValue) => tResult, (any) => tOther, (any) => any);
        result = resultOther = $q.when<TResult, TOther, TValue>(promiseTValue, (result: TValue) => tResult, (any) => promiseTOther);
        result = resultOther = $q.when<TResult, TOther, TValue>(promiseTValue, (result: TValue) => tResult, (any) => promiseTOther, (any) => any);

        result = $q.when<TResult, TValue>(tValue, (result: TValue) => promiseTResult);
        result = $q.when<TResult, TValue>(tValue, (result: TValue) => promiseTResult, (any) => any);
        result = $q.when<TResult, TValue>(tValue, (result: TValue) => promiseTResult, (any) => any, (any) => any);

        result = $q.when<TResult, TValue>(promiseTValue, (result: TValue) => promiseTResult);
        result = resultOther = $q.when<TResult, TOther, TValue>(promiseTValue, (result: TValue) => promiseTResult, (any) => tOther);
        result = resultOther = $q.when<TResult, TOther, TValue>(promiseTValue, (result: TValue) => promiseTResult, (any) => tOther, (any) => any);
        result = resultOther = $q.when<TResult, TOther, TValue>(promiseTValue, (result: TValue) => promiseTResult, (any) => promiseTOther);
        result = resultOther = $q.when<TResult, TOther, TValue>(promiseTValue, (result: TValue) => promiseTResult, (any) => promiseTOther, (any) => any);
    }
}

let httpFoo: ng.IHttpPromise<number>;
httpFoo.then((x) => {
    // When returning a promise the generic type must be inferred.
    const innerPromise: ng.IPromise<number> = null;
    return innerPromise;
}).then((x) => {
    // must still be number.
    x.toFixed();
});

httpFoo.then((response: ng.IHttpPromiseCallbackArg<any>) => {
    const h = response.headers('test');
    h.charAt(0);
    const hs = response.headers();
    hs['content-type'].charAt(1);
});

// Deferred signature tests
namespace TestDeferred {
    const any: any = null;

    interface TResult {
        a: number;
        b: string;
        c: boolean;
    }
    const tResult: TResult = null;

    const deferred: angular.IDeferred<TResult> = null;

    // deferred.resolve
    {
        let result: void;
        result = deferred.resolve() as void;
        result = deferred.resolve(tResult) as void;
    }

    // deferred.reject
    {
        let result: void;
        result = deferred.reject();
        result = deferred.reject(any);
    }

    // deferred.notify
    {
        let result: void;
        result = deferred.notify();
        result = deferred.notify(any);
    }

    // deferred.promise
    {
        let result: angular.IPromise<TResult>;
        result = deferred.promise;
    }
}

namespace TestInjector {
    const $injector: angular.auto.IInjectorService = null;

    $injector.strictDi = true;

    $injector.annotate(() => {});
    $injector.annotate(() => {}, true);

    // $injector.instantiate
    {
        class Foobar {
            constructor($q) {}
        }
        let result: Foobar = $injector.instantiate(Foobar);
    }

    // $injector.invoke
    {
        function foobar(v: boolean): number {
            return 7;
        }
        let result = $injector.invoke(foobar);
        if (!(typeof result === 'number')) {
            // This fails to compile if 'result' is not exactly a number.
            let expectNever: never = result;
        }

        let anyFunction: Function = foobar;
        let anyResult: string = $injector.invoke(anyFunction);
    }
}

// Promise signature tests
namespace TestPromise {
    const any: any = null;

    interface TResult {
        kind: 'result';
        a: number;
        b: string;
        c: boolean;
    }

    interface TOther {
        kind: 'other';
        d: number;
        e: string;
        f: boolean;
    }

    function isTResult(x: TResult | TOther): x is TResult {
        return x.kind === 'result';
    }

    const tresult: TResult = null;
    const tresultPromise: ng.IPromise<TResult> = null;
    const tresultHttpPromise: ng.IHttpPromise<TResult> = null;

    const tother: TOther = null;
    const totherPromise: ng.IPromise<TOther> = null;
    const totherHttpPromise: ng.IHttpPromise<TOther> = null;

    const promise: angular.IPromise<TResult> = null;
    const $q: angular.IQService = null;

    const assertPromiseType = <T>(arg: angular.IPromise<T>) => arg;
    const reject = $q.reject();

    // promise.then
    assertPromiseType<any>(promise.then((result) => any));
    assertPromiseType<any>(promise.then((result) => any, (any) => any));
    assertPromiseType<any>(promise.then((result) => any, (any) => any, (any) => any));

    assertPromiseType<never>(promise.then((result) => reject));
    assertPromiseType<never>(promise.then((result) => reject, (any) => reject));
    assertPromiseType<never>(promise.then((result) => reject, (any) => reject, (any) => any));

    assertPromiseType<TResult>(promise.then((result) => result));
    assertPromiseType<TResult>(promise.then((result) => tresult));
    assertPromiseType<TResult>(promise.then((result) => tresultPromise));
    assertPromiseType<TResult>(promise.then((result) => result, (any) => any));
    assertPromiseType<TResult>(promise.then((result) => result, (any) => any, (any) => any));
    assertPromiseType<TResult>(promise.then((result) => result, (any) => reject, (any) => any));

    assertPromiseType<TResult>(promise.then((result) => anyOf2(reject, result)));
    assertPromiseType<TResult>(promise.then((result) => anyOf3(result, tresultPromise, reject)));
    assertPromiseType<TResult>(promise.then(
        (result) => anyOf3(reject, result, tresultPromise),
        (reason) => anyOf3(reject, tresult, tresultPromise)
    ));

    assertPromiseType<ng.IHttpPromiseCallbackArg<TResult>>(promise.then((result) => tresultHttpPromise));

    assertPromiseType<TResult | TOther>(promise.then((result) => result, (any) => tother));
    assertPromiseType<TResult | TOther>(promise.then(
        (result) => anyOf3(reject, result, totherPromise),
        (reason) => anyOf3(reject, tother, tresultPromise)
    ));

    assertPromiseType<TResult | TOther>(promise.then<TResult | TOther, TResult>(
        (result) => anyOf3(tresultPromise, result, totherPromise)
    ));

    assertPromiseType<TResult | TOther>(promise.then((result) => result, (any) => tother, (any) => any));
    assertPromiseType<TResult | TOther>(promise.then((result) => tresultPromise, (any) => totherPromise));
    assertPromiseType<TResult | TOther>(promise.then((result) => tresultPromise, (any) => totherPromise, (any) => any));
    assertPromiseType<ng.IHttpPromiseCallbackArg<TResult | TOther>>(promise.then((result) => tresultHttpPromise, (any) => totherHttpPromise));
    assertPromiseType<ng.IHttpPromiseCallbackArg<TResult | TOther>>(promise.then((result) => tresultHttpPromise, (any) => totherHttpPromise, (any) => any));

    assertPromiseType<TOther>(promise.then((result) => tother));
    assertPromiseType<TOther>(promise.then((result) => tother, (any) => any));
    assertPromiseType<TOther>(promise.then((result) => tother, (any) => any, (any) => any));
    assertPromiseType<TOther>(promise.then((result) => totherPromise));
    assertPromiseType<TOther>(promise.then((result) => totherPromise, (any) => any));
    assertPromiseType<TOther>(promise.then((result) => totherPromise, (any) => any, (any) => any));
    assertPromiseType<ng.IHttpPromiseCallbackArg<TOther>>(promise.then((result) => totherHttpPromise));
    assertPromiseType<ng.IHttpPromiseCallbackArg<TOther>>(promise.then((result) => totherHttpPromise, (any) => any));
    assertPromiseType<ng.IHttpPromiseCallbackArg<TOther>>(promise.then((result) => totherHttpPromise, (any) => any, (any) => any));

    assertPromiseType<boolean>(promise.then((result) => tresult, (any) => tother).then(ambiguous => isTResult(ambiguous) ? ambiguous.c : ambiguous.f));

    // promise.catch
    assertPromiseType<any>(promise.catch((err) => err));
    assertPromiseType<any>(promise.catch((err) => any));
    assertPromiseType<TResult>(promise.catch((err) => tresult));
    assertPromiseType<TResult>(promise.catch((err) => anyOf2(tresult, reject)));
    assertPromiseType<TResult>(promise.catch((err) => anyOf3(tresult, tresultPromise, reject)));
    assertPromiseType<TResult>(promise.catch((err) => tresultPromise));
    assertPromiseType<TResult | ng.IHttpPromiseCallbackArg<TResult>>(promise.catch((err) => tresultHttpPromise));
    assertPromiseType<TResult | TOther>(promise.catch((err) => tother));
    assertPromiseType<TResult | TOther>(promise.catch((err) => totherPromise));
    assertPromiseType<TResult | ng.IHttpPromiseCallbackArg<TOther>>(promise.catch((err) => totherHttpPromise));

    assertPromiseType<boolean>(promise.catch((err) => tother).then(ambiguous => isTResult(ambiguous) ? ambiguous.c : ambiguous.f));

    // promise.finally
    assertPromiseType<TResult>(promise.finally(() => any));
    assertPromiseType<TResult>(promise.finally(() => tresult));
    assertPromiseType<TResult>(promise.finally(() => tother));
}

function test_angular_forEach() {
    const values: { [key: string]: string } = { name: 'misko', gender: 'male' };
    const log: string[] = [];
    angular.forEach(values, (value, key, obj) => {
        obj[key] = value;
        this.push(key + ': ' + value);
    }, log);
    // expect(log).toEqual(['name: misko', 'gender: male']);
}

// angular.element() tests
let element = angular.element('div.myApp');
let scope: ng.IScope = element.scope();
let isolateScope: ng.IScope = element.isolateScope();
isolateScope = element.find('div.foo').isolateScope();
isolateScope = element.children().isolateScope();

// $timeout signature tests
namespace TestTimeout {
    interface TResult {
        a: number;
        b: string;
        c: boolean;
    }
    const fnTResult: (...args: any[]) => TResult = null;
    const promiseAny: angular.IPromise<any> = null;
    const $timeout: angular.ITimeoutService = null;

    // $timeout
    {
        let result: angular.IPromise<any>;
        result = $timeout();
    }
    {
        let result: angular.IPromise<void>;
        result = $timeout(1);
        result = $timeout(1, true);
    }
    {
        let result: angular.IPromise<TResult>;
        result = $timeout(fnTResult);
        result = $timeout(fnTResult, 1);
        result = $timeout(fnTResult, 1, true);
        result = $timeout(fnTResult, 1, true, 1);
        result = $timeout(fnTResult, 1, true, 1, '');
        result = $timeout(fnTResult, 1, true, 1, '', true);
    }

    // $timeout.cancel
    {
        let result: boolean;
        result = $timeout.cancel();
        result = $timeout.cancel(promiseAny);
    }
}

function test_IAttributes(attributes: ng.IAttributes) {
    return attributes;
}

test_IAttributes({
    $normalize(classVal) { return 'foo'; },
    $addClass(classVal) {},
    $removeClass(classVal) {},
    $updateClass(newClass, oldClass) {},
    $set(key, value) {},
    $observe(name: any, fn: any) {
        return fn;
    },
    $attr: {}
});

class SampleDirective implements ng.IDirective {
    restrict = 'A';
    name = 'doh';

    compile(templateElement: ng.IAugmentedJQuery) {
        return {
            post: this.link
        };
    }

    static instance(): ng.IDirective {
        return new SampleDirective();
    }

    link(scope: ng.IScope) {}
}

class SampleDirective2 implements ng.IDirective {
    restrict = 'EAC';

    compile(templateElement: ng.IAugmentedJQuery) {
        return {
            pre: this.link
        };
    }

    static instance(): ng.IDirective {
        return new SampleDirective2();
    }

    link(scope: ng.IScope) {}
}

angular.module('SameplDirective', []).directive('sampleDirective', SampleDirective.instance).directive('sameplDirective2', SampleDirective2.instance);

angular.module('AnotherSampleDirective', []).directive('myDirective', ['$interpolate', '$q', ($interpolate: ng.IInterpolateService, $q: ng.IQService) => {
    return {
        restrict: 'A',
        link: (scope: ng.IScope, el: ng.IAugmentedJQuery, attr: ng.IAttributes) => {
            $interpolate(attr['test'])(scope);
            $interpolate('', true)(scope);
            $interpolate('', true, 'html')(scope);
            $interpolate('', true, 'html', true)(scope);
            const defer = $q.defer();
            defer.reject();
            defer.resolve();
            defer.promise.then(d => d)
            .then(
                (): any => null,
                (): any => null)
            .catch((): any => null)
            .finally((): any => null);
            let promise = new $q((resolve) => {
                resolve();
            });

            promise = new $q((resolve, reject) => {
                reject();
                resolve(true);
            });

            promise = new $q<boolean>((resolver, reject) => {
                resolver(true);
                reject(false);
            });
        }
    };
}]);

// test from https://docs.angularjs.org/guide/directive
angular.module('docsSimpleDirective', [])
    .controller('Controller', ['$scope', ($scope: any) => {
        $scope.customer = {
            name: 'Naomi',
            address: '1600 Amphitheatre'
        };
    }])
    .directive('myCustomer', () => {
        return {
            template: 'Name: {{customer.name}} Address: {{customer.address}}'
        };
    });

angular.module('docsTemplateUrlDirective', [])
    .controller('Controller', ['$scope', ($scope: any) => {
        $scope.customer = {
            name: 'Naomi',
            address: '1600 Amphitheatre'
        };
    }])
    .directive('myCustomer', () => {
        return {
            templateUrl: 'my-customer.html'
        };
    });

angular.module('docsRestrictDirective', [])
    .controller('Controller', ['$scope', ($scope: any) => {
        $scope.customer = {
            name: 'Naomi',
            address: '1600 Amphitheatre'
        };
    }])
    .directive('myCustomer', () => {
        return {
            restrict: 'E',
            templateUrl: 'my-customer.html'
        };
    });

angular.module('docsScopeProblemExample', [])
    .controller('NaomiController', ['$scope', ($scope: any) => {
        $scope.customer = {
            name: 'Naomi',
            address: '1600 Amphitheatre'
        };
    }])
    .controller('IgorController', ['$scope', ($scope: any) => {
        $scope.customer = {
            name: 'Igor',
            address: '123 Somewhere'
        };
    }])
    .directive('myCustomer', () => {
        return {
            restrict: 'E',
            templateUrl: 'my-customer.html'
        };
    });

angular.module('docsIsolateScopeDirective', [])
    .controller('Controller', ['$scope', ($scope: any) => {
        $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
        $scope.igor = { name: 'Igor', address: '123 Somewhere' };
    }])
    .directive('myCustomer', () => {
        return {
            restrict: 'E',
            scope: {
                customerInfo: '=info'
            },
            templateUrl: 'my-customer-iso.html'
        };
    });

angular.module('docsIsolationExample', [])
    .controller('Controller', ['$scope', ($scope: any) => {
        $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
        $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' };
    }])
    .directive('myCustomer', () => {
        return {
            restrict: 'E',
            scope: {
                customerInfo: '=info'
            },
            templateUrl: 'my-customer-plus-vojta.html'
        };
    });

angular.module('docsTimeDirective', [])
    .controller('Controller', ['$scope', ($scope: any) => {
        $scope.format = 'M/d/yy h:mm:ss a';
    }])
    .directive('myCurrentTime', ['$interval', 'dateFilter', ($interval: any, dateFilter: any) => {
        return {
            link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) {
                let format: any;
                let timeoutId: any;

                function updateTime() {
                    element.text(dateFilter(new Date(), format));
                }

                scope.$watch(attrs['myCurrentTime'], (value: any) => {
                    format = value;
                    updateTime();
                });

                element.on('$destroy', () => {
                    $interval.cancel(timeoutId);
                });

                // start the UI update process; save the timeoutId for canceling
                timeoutId = $interval(() => {
                    updateTime(); // update DOM
                }, 1000);
            }
        };
    }]);

angular.module('docsTransclusionDirective', [])
    .controller('Controller', ['$scope', ($scope: any) => {
        $scope.name = 'Tobias';
    }])
    .directive('myDialog', () => {
        return {
            restrict: 'E',
            transclude: true,
            templateUrl: 'my-dialog.html'
        };
    });

angular.module('docsTransclusionExample', [])
    .controller('Controller', ['$scope', ($scope: any) => {
        $scope.name = 'Tobias';
    }])
    .directive('myDialog', () => {
        return {
            restrict: 'E',
            transclude: true,
            scope: {},
            templateUrl: 'my-dialog.html',
            link(scope: ng.IScope, element: ng.IAugmentedJQuery) {
                scope['name'] = 'Jeff';
            }
        };
    });

angular.module('docsIsoFnBindExample', [])
    .controller('Controller', ['$scope', '$timeout', ($scope: any, $timeout: any) => {
        $scope.name = 'Tobias';
        $scope.hideDialog = () => {
            $scope.dialogIsHidden = true;
            $timeout(() => {
                $scope.dialogIsHidden = false;
            }, 2000);
        };
    }])
    .directive('myDialog', () => {
        return {
            restrict: 'E',
            transclude: true,
            scope: {
                close: '&onClose'
            },
            templateUrl: 'my-dialog-close.html'
        };
    });

angular.module('dragModule', [])
    .directive('myDraggable', ['$document', ($document: any) => {
        return (scope: any, element: any, attr: any) => {
            let startX = 0;
            let startY = 0;
            let x = 0;
            let y = 0;

            element.css({
                position: 'relative',
                border: '1px solid red',
                backgroundColor: 'lightgrey',
                cursor: 'pointer'
            });

            element.on('mousedown', (event: any) => {
                // Prevent default dragging of selected content
                event.preventDefault();
                startX = event.pageX - x;
                startY = event.pageY - y;
                $document.on('mousemove', mousemove);
                $document.on('mouseup', mouseup);
            });

            function mousemove(event: any) {
                y = event.pageY - startY;
                x = event.pageX - startX;
                element.css({
                    top: y + 'px',
                    left:  x + 'px'
                });
            }

            function mouseup() {
                $document.off('mousemove', mousemove);
                $document.off('mouseup', mouseup);
            }
        };
    }]);

angular.module('docsTabsExample', [])
    .directive('myTabs', () => {
        return {
            restrict: 'E',
            transclude: true,
            scope: {},
            controller($scope: ng.IScope) {
                const panes: any = $scope['panes'] = [];

                $scope['select'] = (pane: any) => {
                    angular.forEach(panes, (pane: any) => {
                        pane.selected = false;
                    });
                    pane.selected = true;
                };

                this.addPane = (pane: any) => {
                    if (panes.length === 0) {
                        $scope['select'](pane);
                    }
                    panes.push(pane);
                };
            },
            templateUrl: 'my-tabs.html'
        };
    })
    .directive('myPane', () => {
        return {
            require: '^myTabs',
            restrict: 'E',
            transclude: true,
            scope: {
                title: '@'
            },
            link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, tabsCtrl: any) {
                tabsCtrl.addPane(scope);
            },
            templateUrl: 'my-pane.html'
        };
    });

angular.module('multiSlotTranscludeExample', [])
    .directive('dropDownMenu', () => {
        return {
            transclude: {
                button: 'button',
                list: 'ul',
            },
            link(scope, element, attrs, ctrl, transclude) {
                // without scope
                transclude().appendTo(element);
                transclude(clone => clone.appendTo(element));

                // with scope
                transclude(scope, clone => clone.appendTo(element));
                transclude(scope, clone => clone.appendTo(element), element, 'button');
                transclude(scope, null, element, 'list').addClass('drop-down-list').appendTo(element);
            }
        };
    });

angular.module('componentExample', [])
    .component('counter', {
        require: {ctrl: '^ctrl'},
        bindings: {
            count: '='
        },
        controller: 'CounterCtrl',
        controllerAs: 'counterCtrl',
        template() {
            return '';
        },
        transclude: {
            el: 'target'
        }
    })
    .component('anotherCounter', {
        controller() {},
        require: {
            parent: '^parentCtrl'
        },
        template: '',
        transclude: true
    });

interface ICopyExampleUser {
    name?: string;
    email?: string;
    gender?: string;
}

interface ICopyExampleScope {
    user: ICopyExampleUser;
    master: ICopyExampleUser;
    update(copyExampleUser: ICopyExampleUser): any;
    reset(): any;
}

angular.module('copyExample', [])
    .controller('ExampleController', ['$scope', ($scope: ICopyExampleScope) => {
        $scope.master = { };

        $scope.update = user => {
            // Example with 1 argument
            $scope.master = angular.copy(user);
        };

        $scope.reset = () => {
            // Example with 2 arguments
            angular.copy($scope.master, $scope.user);
        };

        $scope.reset();
    }]);

namespace locationTests {
    const $location: ng.ILocationService = null;

    /*
     * From https://docs.angularjs.org/api/ng/service/$location
     */

    // given url http://example.com/#/some/path?foo=bar&baz=xoxo
    const searchObject = $location.search();
    // => {foo: 'bar', baz: 'xoxo'}

    function assert(condition: boolean) {
        if (!condition) {
            throw new Error();
        }
    }

    // set foo to 'yipee'
    $location.search('foo', 'yipee');
    // => $location

    // set foo to 5
    $location.search('foo', 5);
    // => $location

    /*
     * From: https://docs.angularjs.org/guide/$location
     */

    // in browser with HTML5 history support:
    // open http://example.com/#!/a -> rewrite to http://example.com/a
    // (replacing the http://example.com/#!/a history record)
    assert($location.path() === '/a');

    $location.path('/foo');
    assert($location.absUrl() === 'http://example.com/foo');

    assert($location.search() === {});
    $location.search({ a: 'b', c: true });
    assert($location.absUrl() === 'http://example.com/foo?a=b&c');

    $location.path('/new').search('x=y');
    assert($location.url() === 'new?x=y');
    assert($location.absUrl() === 'http://example.com/new?x=y');

    // in browser without html5 history support:
    // open http://example.com/new?x=y -> redirect to http://example.com/#!/new?x=y
    // (again replacing the http://example.com/new?x=y history item)
    assert($location.path() === '/new');
    assert($location.search() === { x: 'y' });

    $location.path('/foo/bar');
    assert($location.path() === '/foo/bar');
    assert($location.url() === '/foo/bar?x=y');
    assert($location.absUrl() === 'http://example.com/#!/foo/bar?x=y');
}

// NgModelController
function NgModelControllerTyping() {
    const ngModel: angular.INgModelController = null;
    const $http: angular.IHttpService = null;
    const $q: angular.IQService = null;

    // See https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$validators
    ngModel.$validators['validCharacters'] = (modelValue, viewValue) => {
        const value = modelValue || viewValue;
        return /[0-9]+/.test(value) &&
            /[a-z]+/.test(value) &&
            /[A-Z]+/.test(value) &&
            /\W+/.test(value);
    };

    ngModel.$asyncValidators['uniqueUsername'] = (modelValue, viewValue) => {
        const value = modelValue || viewValue;
        return $http.get('/api/users/' + value).
            then(function resolved() {
                return $q.reject('exists');
            }, function rejected() {
                return true;
            });
    };
}

let $filter: angular.IFilterService;

function testFilter() {
    const items: string[] = null;
    $filter('filter')(items, 'test');
    $filter('filter')(items, {name: 'test'});
    $filter('filter')(items, (val, index, array) => {
        return true;
    });
    $filter('filter')(items, (val, index, array) => {
      return true;
    }, (actual, expected) => {
        return actual === expected;
    });
}

function testCurrency() {
    $filter('currency')(126);
    $filter('currency')(126, '$', 2);
}

function testNumber() {
    $filter('number')(167);
    $filter('number')(167, 2);
}

function testDate() {
    $filter('date')(new Date());
    $filter('date')(new Date(), 'yyyyMMdd');
    $filter('date')(new Date(), 'yyyyMMdd', '+0430');
}

function testJson() {
    const json: string = $filter('json')({test: true}, 2);
}

function testLowercase() {
    const lower: string = $filter('lowercase')('test');
}

function testUppercase() {
    const lower: string = $filter('uppercase')('test');
}

function testLimitTo() {
    const limitTo = $filter('limitTo');
    let filtered: number[] = $filter('limitTo')([1, 2, 3], 5);
    filtered = $filter('limitTo')([1, 2, 3], 5, 2);

    let filteredString: string = $filter('limitTo')('124', 4);
    filteredString = $filter('limitTo')(124, 4);
}

function testOrderBy() {
    let filtered: number[] = $filter('orderBy')([1, 2, 3], 'test');
    filtered = $filter('orderBy')([1, 2, 3], 'test', true);
    filtered = $filter('orderBy')([1, 2, 3], ['prop1', 'prop2']);
    filtered = $filter('orderBy')([1, 2, 3], (val: number) => 1);
    let filtered2: string[] = $filter('orderBy')(['1', '2', '3'], (val: string) => 1);
    filtered2 = $filter('orderBy')(['1', '2', '3'], [
        (val: string) => 1,
        (val: string) => 2
    ]);
}

function testDynamicFilter() {
    // Test with separate variables
    const dateFilter = $filter('date');
    const myDate = new Date();
    dateFilter(myDate , 'EEE, MMM d');

    // Test with dynamic name
    const filterName = 'date';
    const dynDateFilter = $filter<ng.IFilterDate>(filterName);
    dynDateFilter(new Date());
}

type MyCustomFilter = (value: string) => string;

function testCustomFilter() {
    const filterCustom = $filter<MyCustomFilter>('custom');
    const filtered: string = filterCustom('test');
}

function parseTyping() {
    const $parse: angular.IParseService = null;
    const compiledExp = $parse('a.b.c');
    if (compiledExp.constant) {
        return compiledExp({});
    } else if (compiledExp.literal) {
        return compiledExp({}, {a: {b: {c: 42}}});
    }
}

function parseWithParams() {
    const $parse: angular.IParseService = null;
    const compiledExp1 = $parse('a.b.c', () => null);
    const compiledExp2 = $parse('a.b.c', null, false);
}

function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjectorService {
    if (mode === 'debug') {
        return angular.bootstrap(element, ['main', ($provide: ng.auto.IProvideService) => {
            $provide.decorator('$rootScope', ($delegate: ng.IRootScopeService) => {
                $delegate['debug'] = true;
            });
        }, 'debug-helpers'], {
            strictDi: true
        });
    }
    return angular.bootstrap(element, ['main'], {
        strictDi: false
    });
}

function testIHttpParamSerializerJQLikeProvider() {
    const serializer: angular.IHttpParamSerializer = null;
    serializer({
        a: 'b'
    });
}

function anyOf2<T1, T2>(v1: T1, v2: T2) {
    return Math.random() < 0.5 ? v1 : v2;
}

function anyOf3<T1, T2, T3>(v1: T1, v2: T2, v3: T3) {
    const rnd = Math.random();
    return rnd < 0.33 ? v1 : rnd < 0.66 ? v2 : v3;
}

function toPromise<T>(val: T): ng.IPromise<T> {
    const p: ng.IPromise<T> = null;
    return p;
}


text:
include_recipe "apt"

apt_repository "virtualbox" do
  uri "http://download.virtualbox.org/virtualbox/debian"
  distribution node["lsb"]["codename"]
  components ["contrib"]
  key "http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc"
  action :add
end

package "smbios-utils"
package "libsmbios2"
package "virtualbox-guest-additions"
package "virtualbox-ose-guest-utils"
package "virtualbox-ose-guest-x11"
package "virtualbox-ose-guest-dkms"


text:
package com.github.aelstad.keccakj.spi;

import com.github.aelstad.keccakj.provider.Constants;

public class Shake128Key extends RawKey {

	@Override
	public String getAlgorithm() {
		return Constants.SHAKE128_STREAM_CIPHER;
	}

}


text:
package com.assylias.jbloomberg;

import java.util.HashMap;
import java.util.Map;

/**
 * A list of the fields available when requesting IntradayTick data.
 */
public enum IntradayTickField {

    TIME("time"),
    TYPE("type"),
    VALUE("value"),
    SIZE("size"),
    CONDITION_CODE("conditionCode"),
    EXCHANGE_CODE("exchangeCode"),
    MIC_CODE("micCode"),
    BROKER_BUY_CODE("brokerBuyCode"),
    BROKER_SELL_CODE("brokerSellCode"),
    RPS_CODE("rpsCode");

    private final static Map<String, IntradayTickField> map = new HashMap<>(IntradayTickField.values().length, 1);

    static {
        for (IntradayTickField f : IntradayTickField.values()) {
            map.put(f.code, f);
        }
    }

    static IntradayTickField of(String field) {
        IntradayTickField f = map.get(field);
        if (f == null) throw new IllegalArgumentException("Not a valid field: " + field);
        else return f;
    }
    private String code;

    private IntradayTickField(String code) {
        this.code = code;
    }
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import { useQuery } from '@apollo/react-hooks';
import gql from 'graphql-tag';
import styles from './styles.module.scss';

export const Event = ({ name, url, start, logo }) => {
  const date = new Date(start);

  return (

          Date: {date.getMonth() + 1}-{date.getDate()}-{date.getFullYear()}

{name}

  );
};

Event.propTypes = {
  name: PropTypes.string,
  url: PropTypes.string,
  start: PropTypes.string,
  logo: PropTypes.string,
};

Event.defaultProps = {
  name: null,
  url: null,
  start: null,
  logo: null,
};

const EVENTS = gql`
  {
    events {
      name
      url
      start
      end
      free
      logo
    }
  }
`;

export function Events() {
  const { loading, error, data } = useQuery(EVENTS);

  if (loading || error || !data.events.length) {
    let str = 'No events are scheduled at this time.';

    if (loading) str = 'loading...';
    if (error)
      str =
        'An error has occured while fetching our events. Feel free to report this issue to a group admin.';

    return
{str}
;
  }

  return data.events.map((k) => Event(k));
}

const Calendar = () => (

Upcoming Events

      <Events />

);

export default Calendar;


text:
import { reduce } from './reduce';
import { has } from './has';
import { assoc } from './assoc';

const reduceBy = (valFn, valAcc, keyFn, list) =>
  reduce(
    (acc, item) => {
      const key = keyFn(item);
      const val = valFn(has(key, acc) ? acc[key] : valAcc, item);
      return assoc(key, val, acc);
    },
    {},
    list,
  );

export { reduceBy };


text:
import collections
import functools
import random
import time

from .lfu import LFUCache
from .lru import LRUCache
from .rr import RRCache
from .ttl import TTLCache

try:
    from threading import RLock
except ImportError:
    from dummy_threading import RLock

_CacheInfo = collections.namedtuple('CacheInfo', [
    'hits', 'misses', 'maxsize', 'currsize'
])

class _NullContext:
    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

_nullcontext = _NullContext()

def _makekey_untyped(args, kwargs):
    return (args, tuple(sorted(kwargs.items())))

def _makekey_typed(args, kwargs):
    key = _makekey_untyped(args, kwargs)
    key += tuple(type(v) for v in args)
    key += tuple(type(v) for _, v in sorted(kwargs.items()))
    return key

def _cachedfunc(cache, typed=False, lock=None):
    makekey = _makekey_typed if typed else _makekey_untyped
    context = lock() if lock else _nullcontext

    def decorator(func):
        stats = [0, 0]

        def wrapper(*args, **kwargs):
            key = makekey(args, kwargs)
            with context:
                try:
                    result = cache[key]
                    stats[0] += 1
                    return result
                except KeyError:
                    stats[1] += 1
            result = func(*args, **kwargs)
            with context:
                try:
                    cache[key] = result
                except ValueError:
                    pass  # value too large
            return result

        def cache_info():
            with context:
                hits, misses = stats
                maxsize = cache.maxsize
                currsize = cache.currsize
            return _CacheInfo(hits, misses, maxsize, currsize)

        def cache_clear():
            with context:
                stats[:] = [0, 0]
                cache.clear()

        wrapper.cache_info = cache_info
        wrapper.cache_clear = cache_clear
        return functools.update_wrapper(wrapper, func)

    return decorator

def lfu_cache(maxsize=128, typed=False, getsizeof=None, lock=RLock):
    """Decorator to wrap a function with a memoizing callable that saves
    up to `maxsize` results based on a Least Frequently Used (LFU)
    algorithm.

    """
    return _cachedfunc(LFUCache(maxsize, getsizeof), typed, lock)

def lru_cache(maxsize=128, typed=False, getsizeof=None, lock=RLock):
    """Decorator to wrap a function with a memoizing callable that saves
    up to `maxsize` results based on a Least Recently Used (LRU)
    algorithm.

    """
    return _cachedfunc(LRUCache(maxsize, getsizeof), typed, lock)

def rr_cache(maxsize=128, choice=random.choice, typed=False, getsizeof=None,
             lock=RLock):
    """Decorator to wrap a function with a memoizing callable that saves
    up to `maxsize` results based on a Random Replacement (RR)
    algorithm.

    """
    return _cachedfunc(RRCache(maxsize, choice, getsizeof), typed, lock)

def ttl_cache(maxsize=128, ttl=600, timer=time.time, typed=False,
              getsizeof=None, lock=RLock):
    """Decorator to wrap a function with a memoizing callable that saves
    up to `maxsize` results based on a Least Recently Used (LRU)
    algorithm with a per-item time-to-live (TTL) value.
    """
    return _cachedfunc(TTLCache(maxsize, ttl, timer, getsizeof), typed, lock)


text:
package org.zstack.network.service.virtualrouter;

import org.zstack.header.vm.VmInstanceVO;
import org.zstack.header.vo.EntityGraph;
import org.zstack.header.vo.ForeignKey;
import org.zstack.header.vo.SoftDeletionCascade;
import org.zstack.header.vo.SoftDeletionCascades;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
@SoftDeletionCascades({
        @SoftDeletionCascade(parent = VirtualRouterVmVO.class, joinColumn = "uuid")
})
@EntityGraph(
        friends = {
                @EntityGraph.Neighbour(type = VmInstanceVO.class, myField = "uuid", targetField = "uuid")
        }
)
public class VirtualRouterSoftwareVersionVO {
    @Id
    @Column
    @ForeignKey(parentEntityClass = VirtualRouterVmVO.class, onDeleteAction = ForeignKey.ReferenceOption.RESTRICT)
    private String uuid;

    @Column
    private String softwareName;

    @Column
    private String currentVersion;

    @Column
    private String latestVersion;

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public String getSoftwareName() {
        return softwareName;
    }

    public void setSoftwareName(String softwareName) {
        this.softwareName = softwareName;
    }

    public String getCurrentVersion() {
        return currentVersion;
    }

    public void setCurrentVersion(String ipsecCurrentVersion) {
        this.currentVersion = ipsecCurrentVersion;
    }

    public String getLatestVersion() {
        return latestVersion;
    }

    public void setLatestVersion(String ipsecLatestVersion) {
        this.latestVersion = ipsecLatestVersion;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

using CodeWick.Areas.Account.Models;
using CodeWick.Helpers;

namespace CodeWick.Areas.Account.Controllers {
    [HandleError]
    [SessionAttribute]
    public class PasswordController : Controller {
        // GET: /Account/Password/Change
        [Authorize]
        public ActionResult Change() {
            return View();
        }

        // POST: /Account/Password/Change
        [Authorize]
        [HttpPost]
        public ActionResult Change(PasswordModel model) {
            if (ModelState.IsValid) {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                ////bool changePasswordSucceeded;
                try {
                    //MembershipChangeLater
                    ////MembershipUser currentUser = ASPNET_Membership.WebSecurity.GetUser(User.Identity.Name);
                    ////changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                } catch (Exception) {
                    ////changePasswordSucceeded = false;
                }

                //MembershipChangeLater
                ////if (changePasswordSucceeded) {
                ////    return RedirectToAction("ChangePasswordSuccess");
                ////} else {
                ////    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                ////}
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // GET: /Account/Password/ChangeSuccess
        public ActionResult ChangeSuccess() {
            return View();
        }
    }
}


text:
from zope.interface import Interface, implements

from twisted.application import internet, service, strports
from twisted.internet import protocol, reactor, defer
from twisted.words.protocols import irc
from twisted.protocols import basic
from twisted.python import components
from twisted.web import resource, server, static, xmlrpc, microdom
from twisted.web.woven import page, model, interfaces
from twisted.spread import pb
from OpenSSL import SSL
import cgi

class IFingerService(Interface):

    def getUser(user):
        """Return a deferred returning a string"""

    def getUsers():
        """Return a deferred returning a list of strings"""

class IFingerSetterService(Interface):

    def setUser(user, status):
        """Set the user's status to something"""

def catchError(err):
    return "Internal error in server"

class FingerProtocol(basic.LineReceiver):

    def lineReceived(self, user):
        d = self.factory.getUser(user)
        d.addErrback(catchError)
        def writeValue(value):
            self.transport.write(value+'\n')
            self.transport.loseConnection()
        d.addCallback(writeValue)

class IFingerFactory(Interface):

    def getUser(user):
        """Return a deferred returning a string"""

    def buildProtocol(addr):
        """Return a protocol returning a string"""

class FingerFactoryFromService(protocol.ServerFactory):
    implements(IFingerFactory)

    protocol = FingerProtocol

    def __init__(self, service):
        self.service = service

    def getUser(self, user):
        return self.service.getUser(user)

components.registerAdapter(FingerFactoryFromService,
                           IFingerService,
                           IFingerFactory)

class FingerSetterProtocol(basic.LineReceiver):

    def connectionMade(self):
        self.lines = []

    def lineReceived(self, line):
        self.lines.append(line)

    def connectionLost(self, reason):
        if len(self.lines) == 2:
            self.factory.setUser(*self.lines)

class IFingerSetterFactory(Interface):

    def setUser(user, status):
        """Return a deferred returning a string"""

    def buildProtocol(addr):
        """Return a protocol returning a string"""

class FingerSetterFactoryFromService(protocol.ServerFactory):

    implements(IFingerSetterFactory)

    protocol = FingerSetterProtocol

    def __init__(self, service):
        self.service = service

    def setUser(self, user, status):
        self.service.setUser(user, status)

components.registerAdapter(FingerSetterFactoryFromService,
                           IFingerSetterService,
                           IFingerSetterFactory)

class IRCReplyBot(irc.IRCClient):

    def connectionMade(self):
        self.nickname = self.factory.nickname
        irc.IRCClient.connectionMade(self)

    def privmsg(self, user, channel, msg):
        user = user.split('!')[0]
        if self.nickname.lower() == channel.lower():
            d = self.factory.getUser(msg)
            d.addErrback(catchError)
            d.addCallback(lambda m: "Status of %s: %s" % (msg, m))
            d.addCallback(lambda m: self.msg(user, m))

class IIRCClientFactory(Interface):

    """
    @ivar nickname
    """

    def getUser(user):
        """Return a deferred returning a string"""

    def buildProtocol(addr):
        """Return a protocol"""

class IRCClientFactoryFromService(protocol.ClientFactory):

    implements(IIRCClientFactory)

    protocol = IRCReplyBot
    nickname = None

    def __init__(self, service):
        self.service = service

    def getUser(self, user):
        return self.service.getUser(user)

components.registerAdapter(IRCClientFactoryFromService,
                           IFingerService,
                           IIRCClientFactory)

class UsersModel(model.MethodModel):

    def initialize(self, *args, **kwargs):
        self.service=args[0]

    def wmfactory_users(self, request):
        return self.service.getUsers()

components.registerAdapter(UsersModel, IFingerService, interfaces.IModel)

class UserStatusTree(page.Page):

    template = """<title>Users</title>

Users

"""

    def initialize(self, *args, **kwargs):
        self.service=args[0]

    def getDynamicChild(self, path, request):
        return UserStatus(user=path, service=self.service)

    def wchild_RPC2 (self, request):
        return UserStatusXR(self.service)

components.registerAdapter(UserStatusTree, IFingerService, resource.IResource)

class UserStatus(page.Page):

    template='''<title view="Text" model="user"/>

    '''

    def initialize(self, **kwargs):
        self.user = kwargs['user']
        self.service = kwargs['service']

    def wmfactory_user(self, request):
        return self.user

    def wmfactory_status(self, request):
        return self.service.getUser(self.user)

class UserStatusXR(xmlrpc.XMLRPC):

    def __init__(self, service):
        xmlrpc.XMLRPC.__init__(self)
        self.service = service

    def xmlrpc_getUser(self, user):
        return self.service.getUser(user)

    def xmlrpc_getUsers(self):
        return self.service.getUsers()

class IPerspectiveFinger(Interface):

    def remote_getUser(username):
        """return a user's status"""

    def remote_getUsers():
        """return a user's status"""

class PerspectiveFingerFromService(pb.Root):

    implements(IPerspectiveFinger)

    def __init__(self, service):
        self.service = service

    def remote_getUser(self, username):
        return self.service.getUser(username)

    def remote_getUsers(self):
        return self.service.getUsers()

components.registerAdapter(PerspectiveFingerFromService,
                           IFingerService,
                           IPerspectiveFinger)

class FingerService(service.Service):

    implements(IFingerService)

    def __init__(self, filename):
        self.filename = filename
        self._read()

    def _read(self):
        self.users = {}
        for line in file(self.filename):
            user, status = line.split(':', 1)
            user = user.strip()
            status = status.strip()
            self.users[user] = status
        self.call = reactor.callLater(30, self._read)

    def getUser(self, user):
        return defer.succeed(self.users.get(user, "No such user"))

    def getUsers(self):
        return defer.succeed(self.users.keys())

class ServerContextFactory:

    def getContext(self):
        """Create an SSL context.

        This is a sample implementation that loads a certificate from a file
        called 'server.pem'."""
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_certificate_file('server.pem')
        ctx.use_privatekey_file('server.pem')
        return ctx

# Easy configuration

def makeService(config):
    # finger on port 79
    s = service.MultiService()
    f = FingerService(config['file'])
    h = internet.TCPServer(79, IFingerFactory(f))
    h.setServiceParent(s)

    # website on port 8000
    r = resource.IResource(f)
    r.templateDirectory = config['templates']
    site = server.Site(r)
    j = internet.TCPServer(8000, site)
    j.setServiceParent(s)

    # ssl on port 443
#    if config.get('ssl'):
#        k = internet.SSLServer(443, site, ServerContextFactory())
#        k.setServiceParent(s)

    # irc fingerbot
    if config.has_key('ircnick'):
        i = IIRCClientFactory(f)
        i.nickname = config['ircnick']
        ircserver = config['ircserver']
        b = internet.TCPClient(ircserver, 6667, i)
        b.setServiceParent(s)

    # Pespective Broker on port 8889
    if config.has_key('pbport'):
        m = internet.TCPServer(
            int(config['pbport']),
            pb.PBServerFactory(IPerspectiveFinger(f)))
        m.setServiceParent(s)

    return s


text:
ANSIBLE_METADATA = {'status': ['preview'],
                    'supported_by': 'community',
                    'version': '1.0'}

DOCUMENTATION = '''
---
module: rabbitmq_plugin
short_description: Adds or removes plugins to RabbitMQ
description:
  - Enables or disables RabbitMQ plugins
version_added: "1.1"
author: '"Chris Hoffman (@chrishoffman)"'
options:
  names:
    description:
      - Comma-separated list of plugin names
    required: true
    default: null
    aliases: [name]
  new_only:
    description:
      - Only enable missing plugins
      - Does not disable plugins that are not in the names list
    required: false
    default: "no"
    choices: [ "yes", "no" ]
  state:
    description:
      - Specify if plugins are to be enabled or disabled
    required: false
    default: enabled
    choices: [enabled, disabled]
  prefix:
    description:
      - Specify a custom install prefix to a Rabbit
    required: false
    version_added: "1.3"
    default: null
'''

EXAMPLES = '''
# Enables the rabbitmq_management plugin
- rabbitmq_plugin:
    names: rabbitmq_management
    state: enabled
'''

import os

class RabbitMqPlugins(object):
    def __init__(self, module):
        self.module = module

        if module.params['prefix']:
            if os.path.isdir(os.path.join(module.params['prefix'], 'bin')):
                bin_path = os.path.join(module.params['prefix'], 'bin')
            elif os.path.isdir(os.path.join(module.params['prefix'], 'sbin')):
                bin_path = os.path.join(module.params['prefix'], 'sbin')
            else:
                # No such path exists.
                raise Exception("No binary folder in prefix %s" %
                        module.params['prefix'])

            self._rabbitmq_plugins = bin_path + "/rabbitmq-plugins"

        else:
            self._rabbitmq_plugins = module.get_bin_path('rabbitmq-plugins', True)

    def _exec(self, args, run_in_check_mode=False):
        if not self.module.check_mode or (self.module.check_mode and run_in_check_mode):
            cmd = [self._rabbitmq_plugins]
            rc, out, err = self.module.run_command(cmd + args, check_rc=True)
            return out.splitlines()
        return list()

    def get_all(self):
        list_output = self._exec(['list', '-E', '-m'], True)
        plugins = []
        for plugin in list_output:
            if not plugin:
                break
            plugins.append(plugin)

        return plugins

    def enable(self, name):
        self._exec(['enable', name])

    def disable(self, name):
        self._exec(['disable', name])

def main():
    arg_spec = dict(
        names=dict(required=True, aliases=['name']),
        new_only=dict(default='no', type='bool'),
        state=dict(default='enabled', choices=['enabled', 'disabled']),
        prefix=dict(required=False, default=None)
    )
    module = AnsibleModule(
        argument_spec=arg_spec,
        supports_check_mode=True
    )

    names = module.params['names'].split(',')
    new_only = module.params['new_only']
    state = module.params['state']

    rabbitmq_plugins = RabbitMqPlugins(module)
    enabled_plugins = rabbitmq_plugins.get_all()

    enabled = []
    disabled = []
    if state == 'enabled':
        if not new_only:
            for plugin in enabled_plugins:
                if plugin not in names:
                    rabbitmq_plugins.disable(plugin)
                    disabled.append(plugin)

        for name in names:
            if name not in enabled_plugins:
                rabbitmq_plugins.enable(name)
                enabled.append(name)
    else:
        for plugin in enabled_plugins:
            if plugin in names:
                rabbitmq_plugins.disable(plugin)
                disabled.append(plugin)

    changed = len(enabled) > 0 or len(disabled) > 0
    module.exit_json(changed=changed, enabled=enabled, disabled=disabled)

# import module snippets
from ansible.module_utils.basic import *

if __name__ == '__main__':
    main()


text:
import React from "react";

import BreadCrumbs from "./BreadCrumbs";
import GlobalActions from "./GlobalActions";

export default function Header({
  sidebarIsActive,
  toggleSidebar,
}: {
  sidebarIsActive: boolean;
  toggleSidebar: () => void;
}): JSX.Element {
  return (

        <button
          type="button"
          className={
            sidebarIsActive
              ? "fa fa-bars navbar-toggle active"
              : "fa fa-bars navbar-toggle"
          }
          onClick={toggleSidebar}
          aria-label="Toggle navigation"
        />

          <BreadCrumbs />

            <GlobalActions />

  );
}