text:
* Add endpoint to get device state [Pablo]
* Check for valid strings or ints in all config values [Pablo]
* Remove quotes in OS version [Pablo]

# v1.5.0

* Add support for delta image download [petrosagg and Pablo]

# v1.4.0

* Report Host OS version to the API [Pablo]
* Use _.defaults instead of _.extend to ensure internal env vars are not overwritten [Pablo]
* Expose resin API key to apps [Pablo]
* On download start, set download_progress to 0. On finish, set state to Idle [Pablo]
* Set GOARM separately for each architecture [Pablo]
* Add armv5 (armel) build [Trong]
* Add OOM protection for the supervisor container, openvpn and connmand [Praneeth]

# v1.3.2

* Do not report the tun addresses to API [Praneeth]

# v1.3.1

* Only save the app if starting the container was successful [Pablo]

# v1.3.0

* Remove volumes when removing a container [Pablo]
* Refactor the still undocumented special env vars into RESIN_SUPERVISOR_ [Pablo]
* Implement several update strategies (kill before download, 0-downtime) [Pablo]
* Fix the error that comes up when no ip addresses are returned by gosuper [Praneeth]
* Switched to docker-progress for pull progress. [Page]
* Fix semver versioning in tcp-ping endpoint. [Praneeth]

# v1.2.1

* Use random name for PubNub channel and report to API [Pablo]

# v1.2.0

* Don't bind mount (the sometimes non-existent) docker.sock [Pablo]
* Expose a RESIN_SUPERVISOR_VERSION env var to app [Pablo]

# v1.1.1

* Prevent non-fatal errors from causing the supervisor to exit [Lorenzo]
* Use buildtime env vars as the default Pubnub and Mixpanel keys [Pablo]

# v1.1.0

* Switch back to using arch-based node images [Pablo]
* Don't allow bootstrap to delete apiSecret from DB [Pablo]
* Add API endpoint to expire and create new API key [Pablo]
* Enable control of API poll interval through Device Variables [Praneeth]
* Allow control of VPN + TCP check + Pub nub logs with Device Environment variables [Praneeth]
* Add GO api for openvpn control [Praneeth]

# v1.0.2

* Fix getting API key from DB by returning its .value [Pablo]

# v1.0.1

* Pass supervisor API key to app, don't regenerate the key, and authenticate ALL requests [Pablo]
* Use raspberrypi2 base image for armv7hf [Pablo]
* Bugfix: wrap all errors from update as Error objects - prevents image cleanup on download failures [Pablo]
* Wait 10 seconds after sending SIGTERM and before sending SIGKILL when stopping a container [petrosagg]

# v1.0.0

* Expose supervisor API to app by allowing all requests from 127.0.0.1 and passing address and port as env vars [Pablo]
* Only apply special actions / boot config on change, and always persist to DB [Pablo]

# v0.0.18

* Fix preloaded apps so that they have the complete environment [Pablo]

# v0.0.17

* Updated bases image to board-specific, and all node versions to 0.10.40-slim [Pablo]
* Allow changing RPi config.txt with environment variables [Pablo]
* Allow special env vars with a callback which don't cause an app restart [Pablo and Praneeth]
* Remove unused config.supervisorContainer in config.coffee [Praneeth]
* Implement and use golang endpoint for getting IPs of the device, also fixes duplicate IP reporting in the JS implementation [Praneeth]
* Refactor bootstrapping to run in background [Pablo]
* Run preloaded app images [Pablo]
* Add API endpoints for device reboot and shutdown [Pablo]
* Add /restart endpoint to restart container [Pablo]
* Add additional mount point for the host dbus on host_run/dbus [Praneeth]
* Switch to golang 1.5.1 for compiling [Praneeth]
* Allow /purge to be called with appId as string or number [Pablo]
* Fetch containerId from DB within lock [Pablo]
* Change update cycle to map by appId [Pablo]
* Allow updates to be forced via an env var or an API call [Pablo]
* Use lockfile to lock updates per app [Pablo]

# v0.0.16

* Disabled the TCP ping whilst the VPN is connected. [Praneeth]
* Added TCP ping enable/disable endpoints. [Praneeth]
* Added initial go supervisor, using it to purge the /data directory of apps. [Pablo]
* Mounted /lib/firmware into the user container. [Pablo]
* Fixed spaces in env vars for web terminal. [Petros]
* Added missing return when no app id specified. [Pablo]
* Try to populate the docker cache before building. [Page]

# v0.0.15

* Make resolv.conf writable from a user container. [Praneeth]
* Updated pubnub (3.7.13 doesn't seem to have the heartbeat unnecessarily)
* Fixed an issue where an image would not be cleaned up if it was tagged in multiple repos. [Page]
* Use JOBS=MAX for npm install. [Page]
* Updated pinejs-client so that valid ssl certificates are enforced by default. [Page]
* Write the `registered_at` time to config.json as well, in case there is a failure between writing to config.json and writing to knex [Page]

# v0.0.14

* Clean up tmp files left behind by npm [Page]
* Fix an error where mixpanel events would have the wrong uuid set on first provision. [Page]
* Update knexjs to ~0.8.3, which uses lodash 3 and means it will be deduplicated (reducing image size and runtime memory usage) [Page]
* Stop caching config.json, avoids a race that could cause getting stuck repeatedly trying to register [Page]

# v0.0.13

* Bind mount /etc/resolv.conf as ro for application containers and supervisor [Praneeth]

# v0.0.12

* Stopped displaying an error message when trying to start a container that is already started.
* Improved error messages reported to the user in the case of finding an empty string.
* Switched to using the dockerode pull progress mechanism.
* Fixed trying to delete supervisor container when it reports an alternate tag instead of the primary tag.
* Switched to using the i386-node image as a base for the i386-supervisor
* Fixed reporting error objects to mixpanel.


text:
<?php

namespace Nette\Templating;

use Nette;

/**
 * Defines file-based template methods.
 *
 * @author     David Grudl
 */
interface IFileTemplate extends ITemplate
{

	/**
	 * Sets the path to the template file.
	 * @param  string  template file path
	 * @return void
	 */
	function setFile($file);

	/**
	 * Returns the path to the template file.
	 * @return string  template file path
	 */
	function getFile();

}

redpajama_set_name: RedPajamaGithub


text:
import clientCookies from 'cookies-js';
import compose from 'lodash.flowright';
import { Query, Mutation, Subscription, graphql } from 'react-apollo';
import { Helmet } from 'react-helmet';
import { Link, Switch, Redirect, Route } from 'react-router-dom';
import PropTypes from 'prop-types';
import React from 'react';
import { Provider, connect } from 'react-redux';
import { push, replace, go, goBack, goForward } from 'connected-react-router';

import gqltag from './shared/gqltag';
import Document from './client/components/Document';
import Form from './client/components/Form';

module.exports = {
  clientCookies,
  compose,
  connect,
  historyActions: {
    push,
    replace,
    go,
    goBack,
    goForward,
  },
  // NOTE: I don't like this function living here.
  // If it happens again let's find it a new home.
  gql: gqltag,
  Query,
  Mutation,
  Subscription,
  Provider,
  Link,
  Redirect,
  Route,
  Switch,
  graphql,
  PropTypes,
  React,

  Document,
  Meta: Helmet,
  Form,
};


text:
<?php

namespace Deployer\Server\Password;

/**
 * Get password with use another function (Closure)
 *
 * @author Vitaliy Zhuk <zhuk2205@gmail.com>
 */
class CallablePasswordGetter implements PasswordGetterInterface
{
    /**
     * @var callable
     */
    private $callable;

    /**
     * Construct
     *
     * @param callable $callable
     */
    public function __construct($callable)
    {
        if (!is_callable($callable)) {
            throw new \InvalidArgumentException(sprintf(
                'The first argument must be a callable, but "%s" given.',
                is_object($callable) ? get_class($callable) : gettype($callable)
            ));
        }

        $this->callable = $callable;
    }

    /**
     * {@inheritDoc}
     */
    public function getPassword($host, $user)
    {
        return call_user_func($this->callable, $host, $user);
    }
}


text:
import time
import random
import bisect

# given sorted list l
# find the item with value k
# discard half of list each time
# log(n)
def binary_search(l, k):
    start = 0
    end = len(l) - 1
    mid = end/2
    while end > start and start != mid and end != mid:
        if l[mid] == k:
            break
        elif l[mid] > k:
            end = mid
        else:
            start = mid
        # if not met
        # return largest one smaller than k
        mid = (start + end)/2
        # return smallest one larger than k
        # mid = 1 + (start + end)/2
    return mid
k = 2
l = [1,3]

#print l
start = time.time()
print binary_search(l, k)
print time.time() - start
start = time.time()
print bisect.bisect_left(l, k)
print time.time() - start


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Neodroid: droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

Neodroid
    0.2.0

Machine Learning Environment Prototyping Tool

Public Member Functions |
Protected Member Functions |
Properties |
List of all members

droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer Class Reference

 More...

Inheritance diagram for droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer:

<map name="droid_8_runtime_8_prototyping_8_displayers_8_canvas_8_canvas_bar_displayer_inherit__map" id="droid_8_runtime_8_prototyping_8_displayers_8_canvas_8_canvas_bar_displayer_inherit__map">
<area shape="rect" id="node2" href="classdroid_1_1_runtime_1_1_prototyping_1_1_displayers_1_1_displayer.html" title="Displayer" alt="" coords="119,155,197,181"/>
<area shape="rect" id="node3" href="classdroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_prototyping_game_object.html" title="PrototypingGameObject" alt="" coords="5,80,167,107"/>
<area shape="rect" id="node5" href="interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_registerable.html" title="IRegisterable" alt="" coords="174,5,273,32"/>
<area shape="rect" id="node6" href="interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_displayer.html" title="IDisplayer" alt="" coords="191,80,272,107"/>
</map>
[legend]

Collaboration diagram for droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer:

<map name="droid_8_runtime_8_prototyping_8_displayers_8_canvas_8_canvas_bar_displayer_coll__map" id="droid_8_runtime_8_prototyping_8_displayers_8_canvas_8_canvas_bar_displayer_coll__map">
<area shape="rect" id="node2" href="classdroid_1_1_runtime_1_1_prototyping_1_1_displayers_1_1_displayer.html" title="Displayer" alt="" coords="119,155,197,181"/>
<area shape="rect" id="node3" href="classdroid_1_1_runtime_1_1_utilities_1_1_game_objects_1_1_prototyping_game_object.html" title="PrototypingGameObject" alt="" coords="5,80,167,107"/>
<area shape="rect" id="node5" href="interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_registerable.html" title="IRegisterable" alt="" coords="174,5,273,32"/>
<area shape="rect" id="node6" href="interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_displayer.html" title="IDisplayer" alt="" coords="191,80,272,107"/>
</map>
[legend]

Public Member Functions

void 	SetFillAmount (float amount)

override void 	Display (float value)

override void 	Display (Double value)

override void 	Display (float[] values)

override void 	Display (String value)

override void 	Display (Vector3 value)

override void 	Display (Vector3[] value)

override void 	Display (Points.ValuePoint points)

override void 	Display (Points.ValuePoint[] points)

override void 	Display (Points.StringPoint point)

override void 	Display (Points.StringPoint[] points)

override void 	PlotSeries (Points.ValuePoint[] points)

 Public Member Functions inherited from droid.Runtime.Prototyping.Displayers.Displayer

abstract void 	Display (Single value)

abstract void 	Display (Single[] values)

 Public Member Functions inherited from droid.Runtime.Utilities.GameObjects.PrototypingGameObject

void 	RefreshStart ()

void 	RefreshAwake ()

 Public Member Functions inherited from droid.Runtime.Interfaces.IDisplayer

void 	Display (double value)

void 	Display (string value)

Protected Member Functions

override void 	Setup ()

 Protected Member Functions inherited from droid.Runtime.Prototyping.Displayers.Displayer

override void 	RegisterComponent ()

override void 	UnRegisterComponent ()

virtual void 	Clean ()

 Protected Member Functions inherited from droid.Runtime.Utilities.GameObjects.PrototypingGameObject

void 	Start ()

void 	Awake ()

virtual void 	Clear ()

Properties

float 	Value [get, set]

 Properties inherited from droid.Runtime.Prototyping.Displayers.Displayer

AbstractPrototypingEnvironment 	ParentEnvironment [get, set]

override string 	PrototypingTypeName [get]

 Properties inherited from droid.Runtime.Utilities.GameObjects.PrototypingGameObject

virtual string 	PrototypingTypeName [get]

string 	Identifier [get]

 Properties inherited from droid.Runtime.Interfaces.IRegisterable

string 	Identifier [get]

Additional Inherited Members

 Protected Attributes inherited from droid.Runtime.Prototyping.Displayers.Displayer

bool 	_RetainLastPlot = true

dynamic 	_Values = null

 Protected Attributes inherited from droid.Runtime.Utilities.GameObjects.PrototypingGameObject

string 	_Custom_Name = ""

Detailed Description

Definition at line 16 of file CanvasBarDisplayer.cs.

Member Function Documentation

◆ Display() [1/10]

          override void droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer.Display
          (
          float
          value	)

Implements droid.Runtime.Interfaces.IDisplayer.

Definition at line 49 of file CanvasBarDisplayer.cs.

◆ Display() [2/10]

          override void droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer.Display
          (
          Double
          value	)

virtual

Implements droid.Runtime.Prototyping.Displayers.Displayer.

Definition at line 60 of file CanvasBarDisplayer.cs.

◆ Display() [3/10]

          override void droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer.Display
          (
          float []
          values	)

Implements droid.Runtime.Interfaces.IDisplayer.

Definition at line 71 of file CanvasBarDisplayer.cs.

◆ Display() [4/10]

          override void droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer.Display
          (
          String
          value	)

virtual

Implements droid.Runtime.Prototyping.Displayers.Displayer.

Definition at line 82 of file CanvasBarDisplayer.cs.

◆ Display() [5/10]

          override void droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer.Display
          (
          Vector3
          value	)

virtual

Implements droid.Runtime.Prototyping.Displayers.Displayer.

Definition at line 87 of file CanvasBarDisplayer.cs.

◆ Display() [6/10]

          override void droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer.Display
          (
          Vector3 []
          value	)

virtual

Implements droid.Runtime.Prototyping.Displayers.Displayer.

Definition at line 92 of file CanvasBarDisplayer.cs.

◆ Display() [7/10]

          override void droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer.Display
          (
          Points.ValuePoint
          points	)

virtual

Implements droid.Runtime.Prototyping.Displayers.Displayer.

Definition at line 97 of file CanvasBarDisplayer.cs.

◆ Display() [8/10]

          override void droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer.Display
          (
          Points.ValuePoint []
          points	)

virtual

Implements droid.Runtime.Prototyping.Displayers.Displayer.

Definition at line 102 of file CanvasBarDisplayer.cs.

◆ Display() [9/10]

          override void droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer.Display
          (
          Points.StringPoint
          point	)

virtual

Implements droid.Runtime.Prototyping.Displayers.Displayer.

Definition at line 107 of file CanvasBarDisplayer.cs.

◆ Display() [10/10]

          override void droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer.Display
          (
          Points.StringPoint []
          points	)

virtual

Implements droid.Runtime.Prototyping.Displayers.Displayer.

Definition at line 112 of file CanvasBarDisplayer.cs.

◆ PlotSeries()

          override void droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer.PlotSeries
          (
          Points.ValuePoint []
          points	)

virtual

Parameters

points

Implements droid.Runtime.Prototyping.Displayers.Displayer.

Definition at line 114 of file CanvasBarDisplayer.cs.

◆ SetFillAmount()

          void droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer.SetFillAmount
          (
          float
          amount	)

Parameters

amount

Definition at line 38 of file CanvasBarDisplayer.cs.

◆ Setup()

          override void droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer.Setup
          (
          	)

protectedvirtual

Reimplemented from droid.Runtime.Utilities.GameObjects.PrototypingGameObject.

Definition at line 33 of file CanvasBarDisplayer.cs.

Property Documentation

◆ Value

          float droid.Runtime.Prototyping.Displayers.Canvas.CanvasBarDisplayer.Value

getset

Definition at line 22 of file CanvasBarDisplayer.cs.

The documentation for this class was generated from the following file:

/home/heider/Projects/Neodroid/Unity/Examples/Assets/droid/Runtime/Prototyping/Displayers/Canvas/CanvasBarDisplayer.cs

droid

Runtime

Prototyping

Displayers

Canvas

CanvasBarDisplayer

Generated by

     1.8.13


text:
import setuptools

with open("README.md") as f:
    long_description = f.read()

setuptools.setup(
    name="telemeter",
    version="3.0.9",
    author="Killian Meersman",
    author_email="hi@killianm.dev",
    description="Retrieves information about Telenet internet usage",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/KillianMeersman/telemeter",
    packages=setuptools.find_packages(),
    keywords="telenet telemeter",
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    install_requires=["requests"],
)


text:
package beans.config;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * User: guym
 * Date: 1/23/13
 * Time: 2:34 PM
 */
@Retention( RetentionPolicy.RUNTIME )
@Target( {ElementType.FIELD, ElementType.METHOD, ElementType.TYPE} )
public @interface Environment {
    String key();
}


text:
#include "header.h"

#define TITLE_SIZE          64
#define PROCESS_SIZE        MAX_PATH
#define INITIAL_SIZE        51200
#define EXTEND_SIZE         25600
#define REGKEY_PERF         "software\\microsoft\\windows nt\\currentversion\\perflib"
#define REGSUBKEY_COUNTERS  "Counters"
#define PROCESS_COUNTER     "process"
#define PROCESSID_COUNTER   "id process"
#define UNKNOWN_TASK        "Unknown"

struct TLIST {
    DWORD			dwProcessId;
    CHAR			ProcessName[PROCESS_SIZE];
	struct TLIST	*next;
};

int GetTaskList(struct TLIST *tlist)
{
    DWORD                        rc;
    HKEY                         hKeyNames;
    DWORD                        dwType;
    DWORD                        dwSize;
    LPBYTE                       buf = NULL;
    CHAR                         szSubKey[1024];
    LANGID                       lid;
    LPSTR                        p;
    LPSTR						 p2;
    PPERF_DATA_BLOCK             pPerf;
    PPERF_OBJECT_TYPE            pObj;
    PPERF_INSTANCE_DEFINITION    pInst;
    PPERF_COUNTER_BLOCK          pCounter;
    PPERF_COUNTER_DEFINITION     pCounterDef;
    DWORD                        i;
    DWORD                        dwProcessIdTitle;
    DWORD                        dwProcessIdCounter;
    CHAR                         szProcessName[MAX_PATH];
    DWORD                        dwNumTasks;

    // this returns "009" on my system
	lid = MAKELANGID( LANG_ENGLISH, SUBLANG_NEUTRAL );
    wsprintf( szSubKey, "%s\\%03x", REGKEY_PERF, lid );

	// Get handle to "khlm\sw\ms\winnt\cv\perflib\009"
    rc = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
                       szSubKey,
                       0,
                       KEY_READ,
                       &hKeyNames
                     );
    if (rc != ERROR_SUCCESS) {
        goto exit;
    }

    // get the buffer size for the counter value
    rc = RegQueryValueEx( hKeyNames, REGSUBKEY_COUNTERS, NULL, &dwType, NULL, &dwSize);

    if (rc != ERROR_SUCCESS) goto exit;

    // allocate the counter names buffer
    buf = (LPBYTE) malloc(dwSize);

	if (buf == NULL) goto exit;

    memset( (void *) buf, 0, dwSize );

    // read the counter names from the registry
    rc = RegQueryValueEx(hKeyNames, REGSUBKEY_COUNTERS,NULL, &dwType, buf, &dwSize);

    if (rc != ERROR_SUCCESS) {
        goto exit;
    }

    p = (char *) buf;

	dwProcessIdTitle = 0; // added by me as dwProcessIdTitle may be used without init

    while (*p) {
        if (p > (char *) buf) {
            for( p2=p-2; isdigit(*p2); p2--) ;
            }
        if (lstrcmpi(p, PROCESS_COUNTER) == 0) {
            for( p2=p-2; isdigit(*p2); p2--) ;
            lstrcpy( szSubKey, p2+1 );
        }
        else
        if (lstrcmpi(p, PROCESSID_COUNTER) == 0) {
            for( p2=p-2; isdigit(*p2); p2--) ;
            dwProcessIdTitle = atol( p2+1 );
        }
        p += (lstrlen(p) + 1);
    }
    free( buf );

    dwSize = INITIAL_SIZE;
    buf = (LPBYTE) malloc( dwSize );
    if (buf == NULL) {
        goto exit;
    }
    memset( buf, 0, dwSize );

    while (TRUE) {
        rc = RegQueryValueEx( HKEY_PERFORMANCE_DATA,szSubKey,NULL,&dwType,buf,&dwSize);
        pPerf = (PPERF_DATA_BLOCK) buf;
        if ((rc == ERROR_SUCCESS) &&
            (dwSize > 0) &&
            (pPerf)->Signature[0] == (WCHAR)'P' &&
            (pPerf)->Signature[1] == (WCHAR)'E' &&
            (pPerf)->Signature[2] == (WCHAR)'R' &&
            (pPerf)->Signature[3] == (WCHAR)'F' ) {
            break;
        }
        if (rc == ERROR_MORE_DATA) {
            dwSize += EXTEND_SIZE;
            buf = (LPBYTE) realloc( buf, dwSize );
            memset( buf, 0, dwSize );
        }
        else {
            goto exit;
        }
    }

	dwProcessIdCounter = 0; /* added by me as var could be used without init */

    pObj = (PPERF_OBJECT_TYPE) ((DWORD)pPerf + pPerf->HeaderLength);
    pCounterDef = (PPERF_COUNTER_DEFINITION) ((DWORD)pObj + pObj->HeaderLength);
    for (i=0; i<(DWORD)pObj->NumCounters; i++) {
        if (pCounterDef->CounterNameTitleIndex == dwProcessIdTitle) {
            dwProcessIdCounter = pCounterDef->CounterOffset;
            break;
        }
        pCounterDef++;
    }

    dwNumTasks = (DWORD) pObj->NumInstances;

    pInst = (PPERF_INSTANCE_DEFINITION) ((DWORD)pObj + pObj->DefinitionLength);

    for (i=0; i<dwNumTasks; i++) {

        p = (LPSTR) ((DWORD)pInst + pInst->NameOffset);
        rc = WideCharToMultiByte( CP_ACP, 0, (LPCWSTR)p, -1, szProcessName,
			sizeof(szProcessName), NULL, NULL);

        if (!rc) {
            lstrcpy( tlist->ProcessName, UNKNOWN_TASK );
        }

		// load process name into tlist
		lstrcpy( tlist->ProcessName, szProcessName );

		// load Pid into tlist
	    pCounter = (PPERF_COUNTER_BLOCK) ((DWORD)pInst + pInst->ByteLength);
        tlist->dwProcessId = *((LPDWORD) ((DWORD)pCounter + dwProcessIdCounter));
        pInst = (PPERF_INSTANCE_DEFINITION) ((DWORD)pCounter + pCounter->ByteLength);

		// create a new tlist record
		tlist->next = (struct TLIST *) HeapAlloc(GetProcessHeap(), 0, sizeof(struct TLIST));
		if(!(tlist->next)) return(1);

		tlist = tlist->next; // point to the new record
		tlist->next = NULL; // in case this is last record, null serves as a flag
		// note, last record of tlist will be undefined except next which is NULL
    }
	return(0);
exit:
    if(buf) free(buf);
    RegCloseKey( hKeyNames );
    RegCloseKey( HKEY_PERFORMANCE_DATA );
	return(1);
}

char *GetImageName(long pid)
{
	static int init;
	static struct TLIST tlist;
	struct TLIST *t;
	static char Unknown[] = "Unknown";

	if(!init++) {
		tlist.next = NULL;
		if(GetTaskList(&tlist)) return NULL;
		// build list of tasks
	}

	t = &tlist;
	while(t->next) {
		if(t->dwProcessId == (DWORD) pid) return t->ProcessName;
		t = t->next;
	}
	return Unknown;
}


text:
var $                    = require('jquery');
var utils                = require('./utils');
var ZC                   = require('zeroclipboard');
var animations           = require('../data/animations.json');

var $canvas              = $('.canvas');
var $body                = $('body');

ZC.config({
  swfPath: 'node_modules/zeroclipboard/dist/ZeroClipboard.swf'
});

var currIndex            = utils.getRandomIndex(animations);
var copyLinkButtonClient = new ZC($('.copy-link-button'));
var copyCodeButtonClient = new ZC($('.copy-code-button'));

//all animation switches happen based on hash in the url
//this big boy handles it all
$(window).on('hashchange', function() {
  currIndex = utils.getIndexFromCanonicalName(window.location.hash.slice(1), animations);
  currIndex = currIndex < 0 ? utils.getRandomIndex(animations) : currIndex;
  setAnimationVal();
  setAnimationText();
  setInfo();
});

$body.on('click', '.arrow-right', function() {
  currIndex = (++currIndex) % animations.length;
  setHash();
});
$body.on('click', '.arrow-left', function() {
  currIndex = (--currIndex) % animations.length;
  currIndex = currIndex < 0 ? animations.length - 1 : currIndex;
  setHash();
});
$body.on('click', '.cross', function() {
  triggerEsc($body);
});
$body.on('click', '.help-button', function() {
  triggerEsc($body);
  $body.addClass('modal-active');
  $('.help-modal.scale').addClass('show');
});
$body.on('click', '.contrib-button', function() {
  triggerEsc($body);
  $body.addClass('modal-active');
  $('.contrib-modal.scale').addClass('show');
});
$body.on('click', '.share-button', function() {
  triggerEsc($body);
  $body.addClass('modal-active');
  $('.share-modal.scale').addClass('show');
});
$body.on('click', '.export-button', function() {
  utils.getCSS(animations[currIndex], function(err, code){
    if (err) console.error('colorfad.in: %o', err);
    $('.export-modal .code-body').html(code);
  });
  window.Prism.highlightAll();

  triggerEsc($body);

  $body.addClass('modal-active');
  $('.export-modal.scale').addClass('show');
});

copyLinkButtonClient.on('ready', function() {
  copyLinkButtonClient.on('copy', function() {
    var copyBtn = $('.copy-link-button');
    var text    = copyBtn.text();

    copyLinkButtonClient.setText(window.location.href);
    copyBtn.text('Copied!');
    window.setTimeout(function() {
      copyBtn.text(text);
    }, 1000);
  });
  copyLinkButtonClient.on('aftercopy', function(event) {
    console.log('colorfad.in: Copied text to clipboard: ' + event.data['text/plain']);
  });
  copyLinkButtonClient.on('error', function(event) {
    console.log( 'colofad.in: ZeroClipboard error of type "' + event.name + '": ' + event.message );
    ZC.destroy();
  });
});

copyCodeButtonClient.on('ready', function() {
  copyCodeButtonClient.on('copy', function() {
    var copyBtn = $('.copy-code-button');
    var text    = copyBtn.text();

    copyCodeButtonClient.setText($('.export-modal .code-body').text());
    copyBtn.text('Copied!');
    window.setTimeout(function() {
      copyBtn.text(text);
    }, 1000);
  });
  copyCodeButtonClient.on('aftercopy', function(event) {
    console.log('colorfad.in: Copied text to clipboard: ' + event.data['text/plain']);
  });
  copyCodeButtonClient.on('error', function(event) {
    console.log( 'colofad.in: ZeroClipboard error of type "' + event.name + '": ' + event.message );
    ZC.destroy();
  });
});

//proxy left and right arrow presses to prev and next buttons respectively
$body.on('keydown', function(e) {
  //left arrow
  if (e.keyCode === 37) $('.arrow-left').click();
  //right arrow
  if (e.keyCode === 39) $('.arrow-right').click();
  //esc
  if (e.keyCode === 27) {
    $body.removeClass('modal-active');
    $('.show').removeClass('show');
  }
  //question mark and fwd slash (really only fwd slash)
  if (e.keyCode === 191) {
    $('.help-button').click();
  }
  //'c' -> contribute modal toggle
  if (e.keyCode === 67) {
    $('.contrib-button').click();
  }
  //'s' -> share modal toggle
  if (e.keyCode === 83) {
    $('.share-button').click();
  }
  //'x' or 'e' -> share modal toggle
  if (e.keyCode === 88 || e.keyCode === 69) {
    $('.export-button').click();
  }
});

if (window.location.hash && window.location.hash !== '') $(window).trigger('hashchange');
else setHash();

function triggerEsc($el) {
  var e = $.Event('keydown', {
    keyCode: 27,
    which: 27
  });
  e.which = 27;
  $el.trigger(e);
}

function setHash() {
  window.location.hash = utils.getCanonicalName(animations[currIndex].name);
}

function setAnimationVal() {
  return $canvas.css('animation', utils.getAnimationValue(animations, currIndex));
}

function setAnimationText() {
  $('.text').text(animations[currIndex].text);
}

function setInfo() {
  var curr                      = animations[currIndex];
  var animName                  = curr.name;
  var colors                    = curr.colors;
  var author                    = curr.author;
  var authorURL                 = curr.authorURL;

  /**
   * memoize elements for perf
   */
  setInfo.$author               = setInfo.$author || $('.author');
  setInfo.$spansCollectionItems = setInfo.$spansCollectionItems || [];
  setInfo.$authorLink           = setInfo.$authorLink || $('.author > a');
  setInfo.$authorName           = setInfo.$authorName || $('.author-name');
  setInfo.$spansCollection      = setInfo.$spansCollection || $('.hexcode');
  setInfo.$animName             = setInfo.$animName || $('.info .animation-name');

  setInfo.$animName.text(animName);
  setInfo.$spansCollection.attr('hidden', 'hidden');

  colors.forEach(function(v, i) {
    var $span;

    /**
     * colours are limited to hexcode divs which are 20 as of now
     */
    i = i % setInfo.$spansCollection.length;
    $span = setInfo.$spansCollectionItems[i] || (setInfo.$spansCollectionItems[i] = $(setInfo.$spansCollection[i]));
    $span.text(v.toUpperCase());
    $span.removeAttr('hidden');
  });

  if (author) {
    setInfo.$author.show();
    setInfo.$authorName.text(author);
    setInfo.$authorLink.attr('href', authorURL);
  }
  else {
    setInfo.$author.hide();
  }
}

function setModalMargin(){
  var width;
  var $modalContainer;

  $modalContainer = $('.modals-container');
  width = Math.round($modalContainer.outerWidth() / 2) * -1;
  $modalContainer.css('margin-left', width);
}

setModalMargin();

$(window).resize(setModalMargin);

window.$ = $;


text:
纵轴指标信息不能为空

        横轴:
        {{each xAxis as item}}

            {{item.caption}}{{if item.name}}({{item.name}}){{/if}}

            ×

        {{/each}}


text:
package com.sample.apns.server.service;

import com.relayrides.pushy.apns.ApnsClient;
import com.relayrides.pushy.apns.ClientNotConnectedException;
import com.relayrides.pushy.apns.DeliveryPriority;
import com.relayrides.pushy.apns.PushNotificationResponse;
import com.relayrides.pushy.apns.util.SimpleApnsPushNotification;
import com.sample.apns.common.Configuration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Service(value = "apnsNotifier")
public class ApnsNotifier {
    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private Configuration configuration;
    @Value("${pkcs12.cert.file}")
    private Resource pkcs12Cert;
    @Value("${pkcs12.passwd.file}")
    private Resource pkcs12Passwd;
    @Value("${command.timeout_in_secs}")
    private long commandTimeout;
    private TimeUnit commandTimeoutUnit = TimeUnit.SECONDS;

    private ApnsClient<SimpleApnsPushNotification> apnsClient;

    public String push(Map<String, Object> params) throws Exception {
        String token = (String) params.get("token");
        String topic = (String) params.get("topic");
        String payload = (String) params.get("payload");
        Date invalidationTime = configuration.convertStringToDate((String) params.get("invalidationTime"));
        DeliveryPriority priority = DeliveryPriority.IMMEDIATE;
        String priorityStr = (String) params.get("priority");
        if (!StringUtils.isBlank(priorityStr)) {
            priority = DeliveryPriority.valueOf(priorityStr);
        }

        StringBuilder replyMessage = new StringBuilder();
        replyMessage.append(String.format("Pushing:\n%s", params));

        SimpleApnsPushNotification pushNotification =
                new SimpleApnsPushNotification(token, topic, payload, invalidationTime, priority);

        try {
            PushNotificationResponse<SimpleApnsPushNotification> pushNotificationResponse =
                    apnsClient.sendNotification(pushNotification).get(commandTimeout, commandTimeoutUnit);

            if (pushNotificationResponse.isAccepted()) {
                replyMessage.append("\nEverything worked! The notification was successfully sent to and accepted by the gateway.");
            } else {
                if (pushNotificationResponse.getTokenInvalidationTimestamp() != null) {
                    replyMessage.append("\nNotification was rejected by the APNs gateway " +
                            "because the destination token is no longer valid: " +
                            pushNotificationResponse.getRejectionReason());
                } else {
                    replyMessage.append("\nNotification rejected by the APNs gateway: " +
                            pushNotificationResponse.getRejectionReason());
                }
            }
        } catch (ExecutionException e) {
            // Something went wrong when trying to send the notification to the
            // APNs gateway. The notification never actually reached the gateway,
            // so we shouldn't consider this a permanent failure.
            log.error("Failed to send push notification.", e);
            replyMessage.append("\nFailed to send push notification: " + e.getCause());

            if (e.getCause() instanceof ClientNotConnectedException) {
                // If we failed to send the notification because the client isn't
                // connected, we can wait for an automatic reconnection attempt
                // to succeed before sending more notifications.
                apnsClient.getReconnectionFuture().await(commandTimeout, commandTimeoutUnit);
            }
        }

        return replyMessage.toString();
    }

    @PostConstruct
    public void initialize() throws Exception {
        Validate.notNull(configuration, "Configuration must not be null");
        Validate.notNull(pkcs12Cert, "Certificate file must not be null");
        Validate.isTrue(pkcs12Cert.exists(), "Certificate file must exists");
        Validate.isTrue(commandTimeout > 0, "Timeout must be any positive number");

        File certFile = getCertFile();
        String certPassword = getCertPassword();

        log.debug("Connecting to APNs gateway using certificate '{}' with password '{}'", certFile.getAbsolutePath(),
                certPassword);

        apnsClient = new ApnsClient<>(certFile, certPassword);
        // connect to the APNs gateway
        apnsClient.connect(ApnsClient.DEVELOPMENT_APNS_HOST).await(commandTimeout, commandTimeoutUnit);

        Validate.isTrue(apnsClient.isConnected(), "Can't connect to the APNs gateway. Check log file.");
    }

    @PreDestroy
    public void shutdown() throws Exception {
        if (apnsClient != null) {
            apnsClient.disconnect().await(commandTimeout, commandTimeoutUnit);
        }
    }

    private File getCertFile() throws IOException {
        return pkcs12Cert.getFile();
    }

    private String getCertPassword() throws IOException {
        String password;
        if (pkcs12Passwd != null && pkcs12Passwd.exists()) {
            // read password from file
            password = IOUtils.toString(pkcs12Passwd.getURI()).trim();
        } else {
            password = "";
        }

        return password;
    }
}


text:
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('tournament', '0108_league_time_control'),
    ]

    operations = [
        migrations.CreateModel(
            name='LeagueNotification',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('date_created', models.DateTimeField(auto_now_add=True)),
                ('date_modified', models.DateTimeField(auto_now=True)),
                ('type', models.CharField(choices=[('mod', 'Moderation stream')], max_length=255)),
                ('slack_channel', models.CharField(max_length=255)),
                ('league', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tournament.League')),
            ],
        ),
        migrations.AlterUniqueTogether(
            name='leaguenotification',
            unique_together=set([('league', 'slack_channel', 'type')]),
        ),
    ]


text:
import {trimPackage} from 'app/components/events/interfaces/frame/utils';
import {Event, Frame} from 'app/types';
import {Thread} from 'app/types/events';

import getRelevantFrame from './getRelevantFrame';
import getThreadStacktrace from './getThreadStacktrace';
import trimFilename from './trimFilename';

type ThreadInfo = {
  label?: string;
  filename?: string;
};

function filterThreadInfo(thread: Thread, event: Event): ThreadInfo {
  const stacktrace = getThreadStacktrace(thread, event, false);
  const threadInfo: ThreadInfo = {};

  if (!stacktrace) {
    return threadInfo;
  }

  const relevantFrame: Frame = getRelevantFrame(stacktrace);

  if (relevantFrame.filename) {
    threadInfo.filename = trimFilename(relevantFrame.filename);
  }

  if (relevantFrame.function) {
    threadInfo.label = relevantFrame.function;
    return threadInfo;
  }

  if (relevantFrame.package) {
    threadInfo.label = trimPackage(relevantFrame.package);
    return threadInfo;
  }

  if (relevantFrame.module) {
    threadInfo.label = relevantFrame.module;
    return threadInfo;
  }

  return threadInfo;
}

export default filterThreadInfo;


text:
package org.jboss.as.quickstarts.rshelloworld;

import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

/**
 * A simple JAX-RS 2.0 REST service which is able to say hello to the world using an injected HelloService CDI bean.
 * The {@link javax.ws.rs.Path} class annotation value is related to the {@link org.jboss.as.quickstarts.rshelloworld.HelloWorldApplication}'s path.
 *
 * @author gbrey@redhat.com
 * @author Eduardo Martins
 *
 */

@Path("/")
public class HelloWorld {
    @Inject
    HelloService helloService;

    /**
     * Retrieves a JSON hello world message.
     * The {@link javax.ws.rs.Path} method annotation value is related to the one defined at the class level.
     * @return
     */
    @GET
    @Path("json")
    @Produces({ "application/json" })
    public JsonObject getHelloWorldJSON() {
        return Json.createObjectBuilder()
            .add("result", helloService.createHelloMessage("World"))
            .build();
    }

    /**
     * Retrieves a XML hello world message.
     * The {@link javax.ws.rs.Path} method annotation value is related to the one defined at the class level.
     * @return
     */
    @GET
    @Path("xml")
    @Produces({ "application/xml" })
    public String getHelloWorldXML() {
        return "<xml><result>" + helloService.createHelloMessage("World") + "</result></xml>";
    }

}


text:
package com.amazonaws.services.resiliencehub.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteAppAssessmentResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The Amazon Resource Name (ARN) of the assessment. The format for this ARN is: arn:partition
     * :resiliencehub:region:account:app-assessment/app-id. For more information
     * about ARNs, see  Amazon
     * Resource Names (ARNs) in the AWS General Reference.
     *

     */
    private String assessmentArn;
    /**
     *

     * The current status of the assessment for the resiliency policy.
     *

     */
    private String assessmentStatus;

    /**
     *

     * The Amazon Resource Name (ARN) of the assessment. The format for this ARN is: arn:partition
     * :resiliencehub:region:account:app-assessment/app-id. For more information
     * about ARNs, see  Amazon
     * Resource Names (ARNs) in the AWS General Reference.
     *

     *
     * @param assessmentArn
     *        The Amazon Resource Name (ARN) of the assessment. The format for this ARN is: arn:partition
     *        :resiliencehub:region:account:app-assessment/app-id. For more
     *        information about ARNs, see  Amazon Resource Names
     *        (ARNs) in the AWS General Reference.
     */

    public void setAssessmentArn(String assessmentArn) {
        this.assessmentArn = assessmentArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the assessment. The format for this ARN is: arn:partition
     * :resiliencehub:region:account:app-assessment/app-id. For more information
     * about ARNs, see  Amazon
     * Resource Names (ARNs) in the AWS General Reference.
     *

     *
     * @return The Amazon Resource Name (ARN) of the assessment. The format for this ARN is: arn:partition
     *         :resiliencehub:region:account:app-assessment/app-id. For more
     *         information about ARNs, see  Amazon Resource Names
     *         (ARNs) in the AWS General Reference.
     */

    public String getAssessmentArn() {
        return this.assessmentArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the assessment. The format for this ARN is: arn:partition
     * :resiliencehub:region:account:app-assessment/app-id. For more information
     * about ARNs, see  Amazon
     * Resource Names (ARNs) in the AWS General Reference.
     *

     *
     * @param assessmentArn
     *        The Amazon Resource Name (ARN) of the assessment. The format for this ARN is: arn:partition
     *        :resiliencehub:region:account:app-assessment/app-id. For more
     *        information about ARNs, see  Amazon Resource Names
     *        (ARNs) in the AWS General Reference.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DeleteAppAssessmentResult withAssessmentArn(String assessmentArn) {
        setAssessmentArn(assessmentArn);
        return this;
    }

    /**
     *

     * The current status of the assessment for the resiliency policy.
     *

     *
     * @param assessmentStatus
     *        The current status of the assessment for the resiliency policy.
     * @see AssessmentStatus
     */

    public void setAssessmentStatus(String assessmentStatus) {
        this.assessmentStatus = assessmentStatus;
    }

    /**
     *

     * The current status of the assessment for the resiliency policy.
     *

     *
     * @return The current status of the assessment for the resiliency policy.
     * @see AssessmentStatus
     */

    public String getAssessmentStatus() {
        return this.assessmentStatus;
    }

    /**
     *

     * The current status of the assessment for the resiliency policy.
     *

     *
     * @param assessmentStatus
     *        The current status of the assessment for the resiliency policy.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see AssessmentStatus
     */

    public DeleteAppAssessmentResult withAssessmentStatus(String assessmentStatus) {
        setAssessmentStatus(assessmentStatus);
        return this;
    }

    /**
     *

     * The current status of the assessment for the resiliency policy.
     *

     *
     * @param assessmentStatus
     *        The current status of the assessment for the resiliency policy.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see AssessmentStatus
     */

    public DeleteAppAssessmentResult withAssessmentStatus(AssessmentStatus assessmentStatus) {
        this.assessmentStatus = assessmentStatus.toString();
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getAssessmentArn() != null)
            sb.append("AssessmentArn: ").append(getAssessmentArn()).append(",");
        if (getAssessmentStatus() != null)
            sb.append("AssessmentStatus: ").append(getAssessmentStatus());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DeleteAppAssessmentResult == false)
            return false;
        DeleteAppAssessmentResult other = (DeleteAppAssessmentResult) obj;
        if (other.getAssessmentArn() == null ^ this.getAssessmentArn() == null)
            return false;
        if (other.getAssessmentArn() != null && other.getAssessmentArn().equals(this.getAssessmentArn()) == false)
            return false;
        if (other.getAssessmentStatus() == null ^ this.getAssessmentStatus() == null)
            return false;
        if (other.getAssessmentStatus() != null && other.getAssessmentStatus().equals(this.getAssessmentStatus()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getAssessmentArn() == null) ? 0 : getAssessmentArn().hashCode());
        hashCode = prime * hashCode + ((getAssessmentStatus() == null) ? 0 : getAssessmentStatus().hashCode());
        return hashCode;
    }

    @Override
    public DeleteAppAssessmentResult clone() {
        try {
            return (DeleteAppAssessmentResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
const ldap = require('ldapjs')

exports.store = {
  mixinCallback: function() {
    var self = this

    self.ldap_errors = []
    self.connection.on('error', function(err) {
      throw err
    })
  },

  addLdapValidationError: function(errorType, msgMatch, attribute, error) {
    if (ldap[errorType]) {
      this.ldap_errors.push({
        cls: ldap[errorType],
        match: msgMatch,
        attribute: attribute,
        error: error
      })
    }
  },

  convertLdapErrorToValidationError: function(record, error) {
    for (var i = 0; i < this.ldap_errors.length; i++) {
      // check error class
      if (error instanceof this.ldap_errors[i].cls) {
        // check message match
        if (error.message.match(this.ldap_errors[i].match)) {
          // add validation error + return null to avoid promise rejection
          record.errors.add(
            this.ldap_errors[i].attribute,
            this.ldap_errors[i].error
          )
          return record.errors
        }
      }
    }

    return error
  }
}


text:
#include <graphene/chain/protocol/buyback.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/exceptions.hpp>
#include <graphene/chain/hardfork.hpp>

namespace graphene { namespace chain {

void evaluate_buyback_account_options( const database& db, const buyback_account_options& bbo )
{
   const asset_object& a = bbo.asset_to_buy(db);
   GRAPHENE_ASSERT( a.issuer == bbo.asset_to_buy_issuer,
      account_create_buyback_incorrect_issuer, "Incorrect asset issuer specified in buyback_account_options", ("asset", a)("bbo", bbo) );
   GRAPHENE_ASSERT( !a.buyback_account.valid(),
      account_create_buyback_already_exists, "Cannot create buyback for asset which already has buyback", ("asset", a)("bbo", bbo) );
   // TODO:  Replace with chain parameter #554
   GRAPHENE_ASSERT( bbo.markets.size() < GRAPHENE_DEFAULT_MAX_BUYBACK_MARKETS,
      account_create_buyback_too_many_markets, "Too many buyback markets", ("asset", a)("bbo", bbo) );
}

} }


text:
package org.hisp.dhis.program;

import static org.junit.Assert.assertEquals;

import java.util.Set;
import org.junit.Test;
import com.google.common.collect.Sets;

/**
* @author Lars Helge Overland
*/
public class ProgramIndicatorTest
{
    @Test
    public void testGetIdentifiersEvent()
    {
        String expression = "#{chG8sINMf11.yD5mUKAm3aK} + #{chG8sINMf11.UaGD9u0kaur} - A{y1Bhi6xHtVk}";

        Set<String> expected = Sets.newHashSet( "yD5mUKAm3aK", "UaGD9u0kaur", "y1Bhi6xHtVk" );

        assertEquals( expected, ProgramIndicator.getDataElementAndAttributeIdentifiers( expression, AnalyticsType.EVENT ) );
    }

    @Test
    public void testGetIdentifiersEnrollment()
    {
        String expression = "#{chG8sINMf11.yD5mUKAm3aK} + #{chG8sINMf11.UaGD9u0kaur} - A{y1Bhi6xHtVk}";

        Set<String> expected = Sets.newHashSet( "chG8sINMf11_yD5mUKAm3aK", "chG8sINMf11_UaGD9u0kaur", "y1Bhi6xHtVk" );

        assertEquals( expected, ProgramIndicator.getDataElementAndAttributeIdentifiers( expression, AnalyticsType.ENROLLMENT ) );
    }
}


text:
'use strict';

const resolveNestedSelector = require('postcss-resolve-nested-selector');

function isNestedRule(node) {
  return /(?:at)?rule/.test(node.parent.type);
}

function hasChildNodes(node) {
  return node.nodes && node.nodes.length;
}

function hasNoDeclarations(node) {
  return hasChildNodes(node) && node.every(child => child.type !== 'decl');
}

function hasOnlyAllowedAtRules(node) {
  let containsAllowed = false;
  let containsNotAllowed = false;

  if (hasChildNodes(node)) {
    node.each(child => {
      if (
        child.type === 'atrule' &&
        (child.name === 'extend' || child.name === 'media')
      ) {
        containsAllowed = true;
      } else if (child.type !== 'comment') {
        containsNotAllowed = true;
      }
    });
  }
  return containsAllowed && !containsNotAllowed;
}

function unWrapSelectors(rule) {
  let selectors = [];
  rule.selectors.forEach(selector => {
    selectors = selectors.concat(resolveNestedSelector(selector, rule));
  });
  return selectors;
}

function getSelectors(rule) {
  // Skip validation on rules with no declarations
  // as these don't exist after rules have been unwrapped (unless the selector contains only a @extend or @media)
  if (hasNoDeclarations(rule) && !hasOnlyAllowedAtRules(rule)) {
    return [];
  }

  if (isNestedRule(rule)) {
    return unWrapSelectors(rule);
  }

  return rule.selectors;
}

module.exports = getSelectors;


text:
const init = () => {
  const button = document.querySelector('.js-print-btn')

  if (button) {
    button.addEventListener('click', function (e) {
      e.preventDefault()
      window.print()
    })
  }
}

module.exports = {
  init: init
}


text:
'use strict';

/**
 * Created by maluramichael on 13/09/16.
 */

class Provider {
	constructor() {

	}

	logEvent(name, data) {

	}

	logScreen(name) {

	}
}

export default Provider;


text:
<?php
include 'measurement-events/eventListIncludes.php';

/**
 * Main Measurement Event Factory class that produces Measurement Event objects.
 *
 * @class MeasurementEventFactory
 */
class MeasurementEventFactory {

    /**
     * Instance of the class
     *
     * @var MeasurementEventFactory
     */
    private static $instance = null;

    /**
     * Gets the instance for this class
     *
     * @return MeasurementEventFactory
     */
    public static function getInstance() {
        if(is_null(self::$instance)){
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Instantiates a subclass of MeasurementEventList based on the given plugin name
     *
     * @param $pluginName - string that represents the plugin name to create a list of events for
     * @return MeasurementEventList
     */
    public function createMeasurementEventList($pluginName) {
        $eventList = null;
        switch($pluginName) {
            case 'WooCommerce':
                $eventList = new WoocommerceEventList();
                break;
            case 'WPForms Lite':
            case 'WPForms':
                $eventList = new WPFormsEventList();
                break;
            case 'Contact Form 7':
                $eventList = new CF7EventList();
                break;
            case 'Formidable Forms':
                $eventList = new FormidableFormsEventList();
                break;
            case 'Ninja Forms':
                $eventList = new NinjaFormsEventList();
                break;
        }
        return $eventList;
    }

}


text:
from m5.params import *
from m5.proxy import *

from BaseTLB import BaseTLB
from MemObject import MemObject

class X86PagetableWalker(MemObject):
    type = 'X86PagetableWalker'
    cxx_class = 'X86ISA::Walker'
    cxx_header = 'arch/x86/pagetable_walker.hh'
    port = MasterPort("Port for the hardware table walker")
    system = Param.System(Parent.any, "system object")

class X86TLB(BaseTLB):
    type = 'X86TLB'
    cxx_class = 'X86ISA::TLB'
    cxx_header = 'arch/x86/tlb.hh'
    size = Param.Int(64, "TLB size")
    walker = Param.X86PagetableWalker(\
            X86PagetableWalker(), "page table walker")


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="HandheldFriendly" content="true" />
  <link rel="shortcut icon" href="https://www.epa.gov/sites/all/themes/epa/favicon.ico" type="image/vnd.microsoft.icon" />
  <meta name="MobileOptimized" content="width" />
  <meta http-equiv="cleartype" content="on" />
  <meta http-equiv="ImageToolbar" content="false" />
  <meta name="viewport" content="width=device-width" />
  <meta name="version" content="20161218" />

  <meta name="DC.description" content="" />
  <meta name="DC.title" content="" />
  <title>
  Connectivity in a Heterogeneous Landscape: The Genetics and Population Dynamics of the Olympic Marmot|

  Research Project Database | Grantee Research Project | ORD | US EPA</title>

  <meta name="keywords" content="" />
  <link rel="shortlink" href="" />
  <link rel="canonical" href="" />
  <meta name="DC.creator" content="" />
  <meta name="DC.language" content="en" />
  <meta name="DC.Subject.epachannel" content="" />
  <meta name="DC.type" content="" />
  <meta name="DC.date.created" content="" />
  <meta name="DC.date.modified" content="2004-03-02" />

  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/misc/ui/jquery.ui.autocomplete.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/lib/jquery.ui.theme.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/libraries/template2/s.css" media="all" />

	<link rel="alternate" type="application/atom+xml" title="EPA.gov All Press Releases" href="https://www.epa.gov/newsreleases/search/rss" />
	<link rel="alternate" type="application/atom+xml" title="EPA.gov Headquarters Press Releases" href="https://www.epa.gov/newsreleases/search/rss/field_press_office/headquarters" />
	<link rel="alternate" type="application/atom+xml" title="Greenversations, EPA's Blog" href="https://blog.epa.gov/blog/feed/" />

Jump to main content

  <hgroup class="site-name-and-slogan">

US EPA

United States Environmental Protection Agency

  </hgroup>
  <form class="epa-search" method="get" action="https://search.epa.gov/epasearch/epasearch">
    Search
    <input class="form-text" placeholder="Search EPA.gov" name="querytext" id="search-box" value=""/>
    <button class="epa-search-button" id="search-button" type="submit" title="Search">Search</button>
    <input type="hidden" name="fld" value="" />
    <input type="hidden" name="areaname" value="" />
    <input type="hidden" name="areacontacts" value="" />
    <input type="hidden" name="areasearchurl" value="" />
    <input type="hidden" name="typeofsearch" value="epa" />
    <input type="hidden" name="result_template" value="2col.ftl" />
    <input type="hidden" name="filter" value="sample4filt.hts" />
  </form>

Contact Us

Related Information

Research Grants

P3: Student Design Competition

Research Fellowships

Small Business Innovation Research (SBIR)

Grantee Research Project Results Search

      Connectivity in a Heterogeneous Landscape: The Genetics and Population Dynamics of the Olympic Marmot

    EPA Grant Number: U915967

    Title: Connectivity in a Heterogeneous Landscape: The Genetics and Population Dynamics of the Olympic Marmot

    Investigators:
     Cox Griffin, Suzanne A.

    Institution:

      University of Montana

    	EPA Project Officer:

           Just, Theodore J.

      Project Period:
      January 1, 2001 through
        January 1, 2004

        Project Amount:

          $101,632

      RFA:
      STAR Graduate Fellowships (2001)

        		RFA Text |
          Recipients Lists

      Research Category:

          Fellowship - Terrestrial Ecology and Ecosystems
          ,
          Academic Fellowships
          ,
          Ecological Indicators/Assessment/Restoration

Objective:

As protected areas become increasingly isolated,
  understanding and maintaining connectivity among populations of key species
  both within and
  between remaining areas will become increasingly important. Dispersal is a
  fundamental determinant of population dynamics and persistence, but a long-standing
  ecological challenge has been determining the role that the intervening landscape
  plays in controlling dispersal among local populations. The objective of this
  research project is to combine demographic estimates of within- and among-population
  vital rates, genetic analyses, and modeling approaches to explore the influence
of landscape composition and structure on movement.

Approach:

This synthetic approach of combining demographic
  estimates of within- and among-population vital rates, genetic analyses, and
  modeling approaches
  to explore the influence of landscape composition and structure on movement
  will be used to understand and predict the dynamics of Olympic marmots (Marmota
  olympus), a naturally fragmented species of conservation concern, endemic to
  the Olympic Peninsula. To identify the landscape features that impede or enhance
  connectivity, populations will first be identified in surveys guided by a geographic
  information system model for suitable habitat. DNA will be collected noninvasively
  up to 100 local populations to provide pairwise estimates of gene flow among
  populations. Demographic rates will be estimated from a subset of these populations.
  Multiple hypotheses representing movement through the landscape will be modeled
  in a spatially explicit, individually based simulation model of marmot population
  dynamics. Outputs from different realizations of the simulation model, varying
  because of the underlying model for dispersal, will be evaluated against observed
  genetic patterns to identify the most parsimonious model for movement across
  the landscape. Marmot dynamics will be predicted under possible future climate
  scenarios, incorporating expected changes in landscape and demographic parameters.
  Finally, in collaboration with Olympic National Park personnel, a marmot monitoring
  and management program will be developed based on current and future distribution
  and demographics, habitat needs and landscape use, and population genetic structure.

Supplemental Keywords:

      fellowship, Marmota olympus, population dynamics, population genetic structure, landscape use, landscape composition, habitat needs.

Top of Page

 The perspectives, information and conclusions conveyed in research project abstracts, progress reports, final reports, journal abstracts and journal publications convey the viewpoints of the principal investigator and may not represent the views and policies of ORD and EPA.  Conclusions drawn by the principal investigators have not been reviewed by the Agency.

Main menu

Environmental Topics

Laws & Regulations

About EPA

Discover.

Accessibility

EPA Administrator

Budget & Performance

Contracting

Grants

No FEAR Act Data

Privacy and Security

Connect.

Data.gov

Inspector General

Jobs

Newsroom

Open Government

Regulations.gov

Subscribe

USA.gov

White House

Ask.

Contact Us

Hotlines

FOIA Requests

Frequent Questions

Follow.

Facebook

Twitter

YouTube

Flickr

Instagram

Last updated on Tuesday, March 2, 2004


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S15.9.4.1_A1_T3;
 * @section: 15.9.4.1;
 * @assertion: The Date property "prototype" has { DontEnum, DontDelete, ReadOnly } attributes;
 * @description: Checking DontEnum attribute;
 */

if (Date.propertyIsEnumerable('prototype')) {
  $ERROR('#1: The Date.prototype property has the attribute DontEnum');
}

for(x in Date) {
  if(x === "prototype") {
    $ERROR('#2: The Date.prototype has the attribute DontEnum');
  }
}


text:
<meta_metadata_repository name="postalAddress"
  package="ecologylab.bigsemantics.generated.library">

  <meta_metadata name="postal_address" extends="contact_point" schema_org_itemtype="http://schema.org/PostalAddress"
    comment="Resembles a schema.org PostalAddress, but adds the county field.">
    <scalar name="street_address" scalar_type="String" schema_org_itemprop="streetAddress"
      comment="number + street + apartment" navigates_to="location" />
    <scalar name="locality" scalar_type="String" schema_org_itemprop="addressLocality" label="city"
      comment="This is really the city." />
    <scalar name="region" scalar_type="String" schema_org_itemprop="addressRegion"
      comment="This is state in the U.S., province in Canada, and varies internationaaly." />
    <scalar name="postal_code" scalar_type="String" schema_org_itemprop="postalCode" label="zip code"
      comment="The internationalized version of zip code." />
    <scalar name="county" scalar_type="String" />
    <scalar name="country" scalar_type="String" schema_org_itemprop="addressCountry" />
  </meta_metadata>

</meta_metadata_repository>


text:
package cli;

import java.io.*;

import util.PConfError;

public final class CliDefParser {

    public static final int CLI_TOKENS_MIN_COUNT  = 4;
    public static final int CLI_TOKENS_MAX_COUNT  = 32;

    private CliCommand.CliMode cliCmdMode = CliCommand.CliMode.main;
    private boolean isScmCommand=false;

    private PConfError errProc = PConfError.getInstance();

    public void setSCMCommand(boolean isScm)        { isScmCommand = isScm; }

    public void setCliCmdMode(CliCommand.CliMode newCliCmdMode) {
        //assert CliCommand.isValidCmdMode(newCliCmdMode);
        cliCmdMode = newCliCmdMode;
    }

    public boolean parseDefFile(CliCommandTree cliCommandTree, String fileName)
    {
        boolean result = true;

        System.out.println("process file: " + fileName + "...");

        try {

            BufferedReader input = new BufferedReader(new FileReader(new File(fileName).getAbsoluteFile()));
            try {

                String cmdLine;
                while ((cmdLine = readOneCmdLine(input)) != null)
                {
                    cmdLine = cmdLine.trim();
                    if (cmdLine.length() == 0)
                        continue;

                    if (cmdLine.endsWith(";")) {
                        cmdLine = cmdLine.substring(0, cmdLine.length()-1);
                    }

                    if (isCommentLine(cmdLine))
                        continue;

                    CliCommand cliCommand = new CliCommand();
                    cliCommand.setCliCmdMode(cliCmdMode);
                    cliCommand.setSource(CliCommand.Source.def);

                    if (!parseCmdLine(cmdLine, cliCommand)) {
                        result = false;
                    }

                    if (cliCommand.isSCMCommand() && (!isScmCommand))
                        continue;

                    if (!cliCommand.validate()) {
                        result = false;
                        continue;
                    }

                    if (!cliCommandTree.addCommand(cliCommand)) {
                        result = false;
                        continue;
                    }

                    //System.out.println("CliDefParser::parseDefFile, output:" + cliCommand);
                }
            } finally {
                input.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (result)
            System.out.println("process file: " + fileName + " done!\n");
        else
            System.out.println("Error in process file: " + fileName + "!\n");

        return result;
    }

    private String readOneCmdLine(BufferedReader input)
    {
        try {
            int newLineNeed=0;
            String cmdLine = input.readLine();
            if (cmdLine == null)  return null;

            do {
                newLineNeed = 0;
                for (int i=0; i<cmdLine.length(); i++)
                {
                    if (cmdLine.charAt(i) == '\\')
                    {
                        newLineNeed = 1;
                        String newLine = input.readLine();

                        if ( newLine == null)
                        {
                            printError("CliDefParser file terminated on continuation", cmdLine);
                            return null;
                        }

                        cmdLine = cmdLine.substring(0, i) + newLine;
                        break;
                    }
                }

            } while (newLineNeed == 1);

            return cmdLine;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private boolean isCommentLine(String line)
    {
        // one line at least have 2 chars "{}", or it is invalid
        if (line.length() <= 2)
            return true;

        //  the following is considered as comments start: "#" "//" and space
        //  the following is considered as version control "%"
        if (Character.isSpaceChar(line.charAt(0)) || line.charAt(0)=='#')
            return true;

        if (line.charAt(0) == '%')
            return true;

        if (line.startsWith("//"))
            return true;

        return false;
    }

    /* parse one command line
     * example of UI line in *.def file
     * {UIsysDumpMem:netman:diag:"dm":(Addr,<address>,0,0xffffffff):(Int,<count>,0,0xffffffff):[Ustr,<option>,0,2]}
     * return:
     *      true : no error happens, continue next command line
     *      false: error happen, stop the parse and exist
     */
    private boolean parseCmdLine(String cmdLine, CliCommand cliCommand)
    {
        if ((cmdLine.charAt(0) == 'S') || (cmdLine.charAt(0)=='s'))
        {
            cliCommand.setSCMCommand(true);
            cmdLine = cmdLine.substring(1);
        }

        String[] tokens = splitTokens(cmdLine);
        if (tokens == null)
            return false;

        cliCommand.setFunctionName(tokens[0]);

        if (!cliCommand.setPrivilege(tokens[1])) {
            return false;
        }

        if (!cliCommand.setDisplayMode(tokens[2])) {
            return false;
        }

        //System.out.println("CliDefParser::parseCmdLine, function name:" + cliCommand.getFunctionName());

        int idx;
        String curKey = "";

        // start parse the keyword
        for (idx=3; (idx<tokens.length); idx++) {

            curKey = tokens[idx].trim();

            if (curKey.startsWith("\"") && curKey.endsWith("\""))
            {
                // remove start and end '"'
                curKey = curKey.substring(1, curKey.length()-1);

                CliNodeKeyword cliKeyword = new CliNodeKeyword();
                /*
                if (!cliKeyword.setSyntaxKeyword(curKey.trim()))
                {
                    printError("Error: keyword is too longer: " + curKey, cmdLine);
                    return false;
                }
                */

                cliKeyword.setNodeShow(cliCommand.getDisplayMode());

                cliCommand.addNode(cliKeyword);
            }
            else if (curKey.startsWith("(") || curKey.startsWith("["))
            {
                CliNodeParameter cliParam =
                        parseParam(cmdLine, curKey, cliCommand.getDisplayMode());

                if (cliParam==null) {
                    printError("invalid parameter in key: " + curKey, cmdLine);
                    return false;
                }

                cliCommand.addNode(cliParam);
            }
            else
            {
                printError("invalid token defined: " + curKey, cmdLine);
                return false;
            }
        }

        // start parse the parameters
        for (; idx<tokens.length; idx++)
        {
            //System.out.println("parse parameter: "+tokens[idx]);
            CliNodeParameter cliParam = parseParam(cmdLine, tokens[idx], cliCommand.getDisplayMode());
            if (cliParam==null)
                return false;

            //System.out.println("add parameter to command");
            cliCommand.addNode(cliParam);
        }

        // set the function node
        CliNodeFunction cliFun = new CliNodeFunction();
        cliFun.setSyntaxKeyword(cliCommand.getFunctionName());
        cliFun.setNodeShow(cliCommand.getDisplayMode());
        cliFun.setCliCommand(cliCommand);
        cliCommand.addNode(cliFun);

        //System.out.println(cliCommand);
        return true;
    }

    /* translate the following string from *.def to CliParameter
     *      [Int,<time-to-wait>,1,10]
     *      (Int,<count>,0,0xffffffff)
     *      (Case,{current|previous},0,0)
     */
    private CliNodeParameter parseParam(String cmdLine, String param, boolean cliShow)
    {
        CliNodeParameter cliParam = new CliNodeParameter();

        if (param.startsWith("(") && param.endsWith(")"))
            cliParam.setRequired("mandatory");
        else if (param.startsWith("[") && param.endsWith("]"))
            cliParam.setRequired("optional");
        else
        {
            printError("CliDefParser Invalid parameter definition: " + param, cmdLine);
            return null;
        }

        // remove begin and end flag for "[]" or "()"
        param = param.substring(1,  param.length()-1);
        //System.out.println("parseParam, param: " + param);

        String[] tokens = param.split(",");

        // each parameter have 4 tokens
        if (tokens.length != 4) {
            printError("CliDefParser Invalid parameter definition: " + param, cmdLine);
            return null;
        }

        if (!cliParam.setSyntaxKeyword(tokens[1]))
        {
            printError("CliDefParser Invalid parameter definition (keyword too long): " + param, cmdLine);
            return null;
        }
        cliParam.setNodeShow(cliShow);

        if (!cliParam.setDataType(tokens[0]))
            return null;

        if (!cliParam.setRange(tokens[2]+","+tokens[3]))
            return null;

        /*
        if (!cliParam.setMinValue(tokens[2]))
            return null;

        if (!cliParam.setMaxValue(tokens[3]))
            return null;
        */

        return cliParam;
    }

    private String[] splitTokens(String cmdLine)
    {
        String [] tokens = cmdLine.split(":");

        for (int i=0; i<tokens.length; i++)
            tokens[i] = tokens[i].trim();

        if ((tokens.length < CLI_TOKENS_MIN_COUNT) ||
            (tokens.length > CLI_TOKENS_MAX_COUNT))
        {
            printError("Invalid UI definition", cmdLine);
            return null;
        }

        if (tokens[0].charAt(0) != '{')
        {
            printError("Illegal opening delimiter on line", cmdLine);
            return null;
        }
        else
        {
            tokens[0] = tokens[0].substring(1);
        }

        String lastToken = tokens[tokens.length-1];
        if (!lastToken.endsWith("}"))
        {
            printError("Illegal ending delimiter on line", cmdLine);
            return null;
        }
        else
        {
            tokens[tokens.length-1] = lastToken.substring(0, lastToken.length()-1);
        }

        /*
        System.out.println("CliDefParser::splitTokens: ");
        for (int i=0; i<tokens.length; i++)
            System.out.print(tokens[i] + " ");
        System.out.println();
        */

        return tokens;
    }

    private void printError(String description, String cmdLine) {
        errProc.addMessage("Error: " + description);
        errProc.addMessage("Error command line: " + cmdLine + "\n");
    }
}


text:
package com.bernard.beaconportal.activities.helper;

import junit.framework.TestCase;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class HtmlConverterTest extends TestCase {
    // Useful if you want to write stuff to a file for debugging in a browser.
    private static final boolean WRITE_TO_FILE = Boolean.parseBoolean(System.getProperty("mail.htmlConverterTest.writeToFile", "false"));
    private static final String OUTPUT_FILE = "C:/temp/parse.html";

    public void testTextQuoteToHtmlBlockquote() {
        String message = "Panama!\r\n" +
            "\r\n" +
            "Bob Barker <bob@aol.com> wrote:\r\n" +
            "> a canal\r\n" +
            ">\r\n" +
            "> Dorothy Jo Gideon <dorothy@aol.com> espoused:\r\n" +
            "> >A man, a plan...\r\n" +
            "> Too easy!\r\n" +
            "\r\n" +
            "Nice job :)\r\n" +
            ">> Guess!";
        String result = HtmlConverter.textToHtml(message);
        writeToFile(result);
        assertEquals("
"
            + "Panama!
"
            + "
"
            + "Bob Barker <bob@aol.com> wrote:
"
            + "
"
            +   " a canal
"
            +   "
"
            +   " Dorothy Jo Gideon <dorothy@aol.com> espoused:
"
            +   "
"
            +     "A man, a plan...
"
            +   "
"
            +     " Too easy!
"
            +   "
"
            +   "
"
            +   "Nice job :)
"
            +   "
"
            +     "
"
            +     " Guess!"
            +   "
"
            + "
"
            + "
", result);
    }

    public void testTextQuoteToHtmlBlockquoteIndented() {
        String message = "*facepalm*\r\n" +
            "\r\n" +
            "Bob Barker <bob@aol.com> wrote:\r\n" +
            "> A wise man once said...\r\n" +
            ">\r\n" +
            ">     LOL F1RST!!!!!\r\n" +
            ">\r\n" +
            "> :)";
        String result = HtmlConverter.textToHtml(message);
        writeToFile(result);
        assertEquals("
"
                + "*facepalm*
"
                + "
"
                + "Bob Barker <bob@aol.com> wrote:
"
                + "
"
                +   " A wise man once said...
"
                +   "
"
                +   "     LOL F1RST!!!!!
"
                +   "
"
                +   " :)"
                + "

", result);

    }

    public void testQuoteDepthColor() {
        assertEquals(HtmlConverter.getQuoteColor(1), HtmlConverter.QUOTE_COLOR_LEVEL_1);
        assertEquals(HtmlConverter.getQuoteColor(2), HtmlConverter.QUOTE_COLOR_LEVEL_2);
        assertEquals(HtmlConverter.getQuoteColor(3), HtmlConverter.QUOTE_COLOR_LEVEL_3);
        assertEquals(HtmlConverter.getQuoteColor(4), HtmlConverter.QUOTE_COLOR_LEVEL_4);
        assertEquals(HtmlConverter.getQuoteColor(5), HtmlConverter.QUOTE_COLOR_LEVEL_5);

        assertEquals(HtmlConverter.getQuoteColor(-1), HtmlConverter.QUOTE_COLOR_DEFAULT);
        assertEquals(HtmlConverter.getQuoteColor(0), HtmlConverter.QUOTE_COLOR_DEFAULT);
        assertEquals(HtmlConverter.getQuoteColor(6), HtmlConverter.QUOTE_COLOR_DEFAULT);

        String message = "zero\r\n" +
            "> one\r\n" +
            ">> two\r\n" +
            ">>> three\r\n" +
            ">>>> four\r\n" +
            ">>>>> five\r\n" +
            ">>>>>> six";
        String result = HtmlConverter.textToHtml(message);
        writeToFile(result);
        assertEquals("
"
                + "zero
"
                + "
"
                +   " one
"
                +   "
"
                +     " two
"
                +     "
"
                +       " three
"
                +       "
"
                +         " four
"
                +         "
"
                +           " five
"
                +           "
"
                +             " six"
                +           "
"
                +         "
"
                +       "
"
                +     "
"
                +   "
"
                + "
"
                + "
", result);
    }

    private void writeToFile(final String content) {
        if (!WRITE_TO_FILE) {
            return;
        }
        try {
            System.err.println(content);

            File f = new File(OUTPUT_FILE);
            f.delete();

            FileWriter fstream = new FileWriter(OUTPUT_FILE);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(content);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void testPreserveSpacesAtFirst() {
        String message = "foo\r\n"
                + " bar\r\n"
                + "  baz\r\n";
        String result = HtmlConverter.textToHtml(message);
        writeToFile(result);
        assertEquals("
"
                + "foo
"
                + " bar
"
                + "  baz
"
                + "
", result);
    }

    public void testPreserveSpacesAtFirstForSpecialCharacters() {
        String message =
                  " \r\n"
                + "  &\r\n"
                + "    \n"
                + "   <\r\n"
                + "  > \r\n";
        String result = HtmlConverter.textToHtml(message);
        writeToFile(result);
        assertEquals("
"
                + "
"
                + "  &
"
                + "
"
                + "   <
"
                + "
"
                + "
"
                + "
"
                + "
", result);
    }

    public void testLinkifyBitcoinAndHttpUri() {
        String text = "bitcoin:19W6QZkx8SYPG7BBCS7odmWGRxqRph5jFU http://example.com/";

        StringBuffer outputBuffer = new StringBuffer();
        HtmlConverter.linkifyText(text, outputBuffer);

        assertEquals("" +
                "bitcoin:19W6QZkx8SYPG7BBCS7odmWGRxqRph5jFU" +
                " " +
                "" +
                "http://example.com/" +
                "", outputBuffer.toString());
    }
}


text:
Simple command line utility for developing and deploying AWS Lambda functions.

Why? Because webpack wasn't cutting it:

![Size matters](docs/code-size.png)

Webpack regularly put out 10MB bundles.  Rollup does magic, and reduces that down to just what's needed.  Like god intended.

## Installing

`yarn add bty --dev`

## Getting started

### Prerequisites

- You must have aws cli named profiles set up so you can use `AWS_PROFILE`.  See https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html
- Create a `resource.json` file in the root of your project directory.  For an example of how to structure a new project, see [this repo](https://github.com/cmawhorter/betty-ddb-crud-microservice).

### Creating a new project
```sh
export AWS_PROFILE=[your profile name]
mkdir my-project && cd my-project
echo '{ "name": "test-betty-function" }' > resource.json
npm install bty --save-dev
mkdir src
echo 'export function handler(event, context, callback) { callback(null, { statusCode: 200, body: JSON.stringify(`hello ${Date.now()}`) }); }' > src/main.js
```

A barebones betty project will now be set up.  You're now ready for development and deployment.

### Developing with betty

All commands should be from project root.

### Building your function

Under the hood, betty uses rollup to convert your project.  After you make changes to your `src` files, you'll need to do a build.

```sh
bty build --development
```

The result of the build will be placed into `dist/index.js` along with a sourcemap.

#### Serving locally for testing

To invoke your work locally, you can serve your lambda function using a built-in [lambda emulator](https://github.com/cmawhorter/lambda-emulator).

```sh
bty serve --development --type apigateway
```

You should see something like this:

```
Server running at:  http://localhost:3000
```

Open http://localhost:3000 up in a browser if all went well, you'll see something like `hello 1515707821329`.

If you don't include `--type apigateway`, your lambda emulator will be running in direct invoke mode.  This means that you must use the aws-sdk to invoke your function by doing something like this:

```sh
# For some reason newer versions of aws-sdk are getting an
# error and I haven't had a chance to figure out why
# https://github.com/cmawhorter/lambda-emulator/issues/4
npm i aws-sdk@2.7.27
```

And then:

```js
const AWS = require('aws-sdk');
const lambda = new AWS.Lambda({
  endpoint:           'http://localhost:3000', // required
  region:             'local-dev',             // required?
  accessKeyId:        'a',                     // something required
  secretAccessKey:    'b',                     // something required
  maxRetries:         0,                       // optional
});
lambda.invoke({
  // only one handler can be tested per server so this
  // is largely for logging and making context have something
  // more production-ish
  FunctionName: 'some-function',
  Payload: JSON.stringify({
    some: 'data',
    goes: true,
    here: {
      now: Date.now(),
    },
  }),
  InvocationType:   'RequestResponse', // ignored by emulator
}, (err, data) => {
  if (err) throw err;
  console.log('Response', data.Payload);
});
```

#### Watching

If you're in the early stages of development, you don't want to have to continuously build/test.  Instead, use watch.

```sh
# You will need to open two tabs.  Don't forget to export AWS_PROFILE=... in
# your second tab or else you'll get an error
bty build --development --watch
bty serve --development --type apigateway --watch
````

Now, whenever you make changes to `src/main.js` and supporting files, a new build will be created and the lambda emulator will automatically reload it.

### Deploying your function

#### Update AWS

Bundles the contents of `dist/` into a zip file suitable for lambda and creates/updates the remote function.

```sh
AWS_REGION=us-west-2 bty update --development
```

##### Error: Role cannot be assumed by function

This is an aws problem and just means the function (and role) was just created but, the role is not yet available.

Just run the command again and it should complete successfully.  Once a function is created, this error will never happen again.

### Build and updating

Building and deploying can be combined into a single command:

```sh
AWS_REGION=us-west-2 bty deploy --development
```

## resource.json

See the JSON Schema for resource.json for format: https://github.com/cmawhorter/betty/blob/master/schema/resource.json

### Options

It's based on package.json and most of it is self explanatory.

### resource.js

Instead of resource.json, you can use javascript and use `resource.js`.

This allows you to do powerful things like keep your secrets out of git and staged env vars:

```js
module.exports = {
  "name":               "some-function",
  "configuration": {
    "memory":           256,
    "timeout":          20,
    "source":           "src/main.js",
    "main":             "dist/index.js",
    "entry":            "index.handler",
    // betty sets globals when loading your resource.js file.
    // you can use these for staged deploys.
    // i usually do this and have an empty env.json-template file
    // and other files like env-development.json env-production.json
    "environment":      require(`./env-${global.betty.env}.json`),
  },
  "resources": {
    // if your function depends on another lambda function include it here
    // and it'll automatically get IAM invoke privileges
    "some-other-lambda-function": "*"
  },
  "assets": [
    // if your function owns other aws services, you would place them here.
    // the permissions you specify will be managed by betty.
    // provisioning assets is NOT managed by betty however.  as a matter of
    // convention, i recommend including a ./provision/*.js script that
    // handles that.  e.g. provision/dynamodb.js would set up these tables
    {
      "service":        "dynamodb",
      "name":           "table/some-table",
      "permissions":    [ "dynamodb:BatchGetItem", "dynamodb:BatchWriteItem", "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Query", "dynamodb:UpdateItem" ]
    },
    {
      "service":        "dynamodb",
      "name":           "table/some-table/*",
      "permissions":    [ "dynamodb:BatchGetItem", "dynamodb:BatchWriteItem", "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Query", "dynamodb:UpdateItem" ]
    }
  ],
  // if this function will be consumed by other functions downstream, create a policy.
  // these permissions will automatically be granted to those functions.
  // this is the policy that gets granted via resources above.
  // most of the time this will look identical to what's here.
  "policy": [
    {
      "service":        "lambda",
      "region":         "*",
      "name":           "function:marketplace-checkout",
      "permissions":    [ "lambda:InvokeFunction" ]
    }
  ]
};```


text:
define(['sandbox', 'd3', 'psgraph', 'expressions', 'interact'], function(sandbox, d3, psgraph, expressions, interact) {

    var Views = {};

    var PSTricksView = sandbox.mvc.View({

        className: 'pspicture-view',
        initialize: function() {

            var env = this.env = this.options.content.settings;
            var svg = this.svg = psgraph.init.call(env, this.el);

            var self = this;
            var plots = this.options.content.plot;

            svg.on('touchmove', function() {

                d3.event.preventDefault();
                var touchcoords = d3.touches(this)[0];

                userEvent(touchcoords);

            }, false);

            svg.on('mousemove', function() {

                var coords = d3.mouse(this);
                userEvent(coords);

            }, false);

            function userEvent (coords) {

                svg.selectAll('.userline').remove();
                svg.selectAll('.psplot').remove();

                var currentEnvironment = {};

                // find special vars
                _.each(plots, function(plot, k) {
                    if (k.match(/uservariable/)) {

                        _.each(plot, function (data) {
                            data.env.userx = coords[0];
                            data.env.usery = coords[1];
                            var dd = data.fn.call(data.env, data.match);
                            currentEnvironment[data.data.name] = dd.value;
                        });

                    }
                });

                _.each(plots, function(plot, k) {

                    if (k.match(/psplot/)) {

                        _.each(plot, function(data) {

                            _.each(currentEnvironment, function(variable, name) {
                                data.env.variables[name] = variable;
                            });

                            var d = data.fn.call(data.env, data.match);

                            d.global = {};
                            _.extend(d.global, env); // give pspicture!

                            psgraph[k].call(d, svg);
                        });

                    }

                    if (k.match(/userline/)) {

                        _.each(plot, function(data) {

                            var d = data.fn.call(data.env, data.match);

                            data.env.x2 = coords[0]; // / env.xunit;
                            data.env.y2 = coords[1]; // / env.yunit;

                            data.data.x2 = data.env.x2;
                            data.data.y2 = data.env.y2;

                            if (data.data.xExp2) {
                                data.data.x2 =  d.userx2(coords);
                                data.data.x1 =  d.userx(coords);
                            } else if (data.data.xExp) {
                                data.data.x2 =  d.userx(coords);
                            }

                            if (data.data.yExp2) {

                                data.data.y2 =  d.usery2(coords);
                                data.data.y1 =  d.usery(coords);

                            } else if (data.data.yExp) {
                                data.data.y2 = d.usery(coords);
                            }

                            d.global = {};
                            _.extend(d.global, env); // give pspicture!
                            _.extend(d, data.data);
                            psgraph[k].call(d, svg);
                        });

                    }

                });

            }

        },

        afterRender: function() {

            var env = this.env;
            var svg = this.svg;

            var el = this.el;

            var plots = this.options.content.plot;

            _.each(plots, function(plot, k) {

                if (k.match(/rput/)) return;

                if (psgraph.hasOwnProperty(k)) {
                    _.each(plot, function(data) {

                        data.data.global = env; // give access to pspicture!
                        psgraph[k].call(data.data, svg);
                    });
                }

            });

            _.each(plots.rput, function(rput) {
                var elem = psgraph.rput.call(rput.data, this.el);
            }, this);

        }

    });

    var MathView = sandbox.mvc.View({

        className: 'mathjax-view',
        beforeRender: function() {
            $(this.el).html(this.options.content.lines.join('\n'));
        },
        afterRender: function() {
            var process = MathJax.Hub.Queue(["Typeset",MathJax.Hub,this.el]);
            if (typeof process === 'function') process();

        }

    });

    var WellView = sandbox.mvc.View({

        className: 'well',
        beforeRender: function() {
            $(this.el).html(this.options.content.lines.join('\n'));
        },
        afterRender: function() {
            var process = MathJax.Hub.Queue(["Typeset",MathJax.Hub,this.el]);
            if (typeof process === 'function') process();

        }

    });

    var EnumerateView = sandbox.mvc.View({

        className: 'mathjax-view',
        tagName: 'ul',
        beforeRender: function() {
            var ls = [];
            _.each(this.options.content.lines, function(line) {
                var m = line.match(/\\item (.*)/);
                if (m) {
                    ls.push( '<li>' + m[1] + '</li>' );
                } else {
                    ls.push(line);
                }
            });

            $(this.el).html(ls.join('\n'));
        },
        afterRender: function() {
            var process = MathJax.Hub.Queue(["Typeset",MathJax.Hub,this.el]);
            if (typeof process === 'function') process();

        }

    });

    var BasicView = sandbox.mvc.View({
        tagName: 'pre',
        beforeRender: function() {
            $(this.el).html(this.options.content.lines.join('\n'));
        }
    });

    Views.TEX = sandbox.mvc.View({

        initialize: function() {

            window.lastScrollTo = $(document).scrollTop();

        },

        beforeRender: function() {

            // iterate through the parsed object!
            // insert subviews

            // create MATH view
            // create PSTRICKS view

            _.each(this.options.latex, function(element) {

                if (! element.hasOwnProperty('type')) {
                    throw new Error('no type!');
                }

                if (element.type.match(/math/)) {
                    var math = new MathView({
                        content: element
                    });
                    this.insertView(math);

                } else if (element.type.match(/pspicture/)) {

                    var pstricks = new PSTricksView({
                        content: element
                    });
                    this.insertView(pstricks);

                    if (element.env.sliders && element.env.sliders.length) {

                        //give related interactive elements the SVG reference!!
                        var slidersView = new interact.SlidersView({
                            env: element.env,
                            sliders: element.env.sliders,
                            plot: element.plot,
                            svg: pstricks.svg
                        });
                        this.insertView(slidersView);

                    }

                } else if (element.type.match(/verbatim/)) {

                    var raw = new BasicView({
                        content: element
                    });
                    this.insertView(raw);

                } else if (element.type.match(/enumerate/)) {

                    var enumerate = new EnumerateView({
                        content: element
                    });
                    this.insertView(enumerate);

                } else if (element.type.match(/nicebox/)) {

                    var well = new WellView({
                        content: element
                    });
                    this.insertView(well);

                } else {
                    //console.log('dont know what this is: ' + element.type);
                }

            }, this);

        },

        afterRender: function() {
            window.scrollTo(0, window.lastScrollTo);
        }

    });

    return Views;

});