text:
{% raw %}
$$
\newcommand{\bsth}{{\boldsymbol\theta}}
\newcommand{\nptime}{\textsf{NP}}
\newcommand{\ptime}{\textsf{P}}
\newcommand{\disteq}{\overset{d}{=}}
%linalg
\newcommand{\mat}[1]{\begin{pmatrix} #1 \end{pmatrix}}
\newcommand{\detmat}[1]{\begin{vmatrix} #1 \end{vmatrix}}
\newcommand{\spanb}[1]{\text{span}\{ #1 \}}
\DeclareMathOperator{\conv}{conv} % convex hull
\DeclareMathOperator{\cone}{cone}
\DeclareMathOperator{\vectorize}{vec}
\DeclareMathOperator{\matricize}{mat}
\DeclareMathOperator{\adj}{adj}
\DeclareMathOperator{\diag}{diag}
\DeclareMathOperator{\tr}{tr}
\DeclareMathOperator{\rank}{rank}
\DeclareMathOperator*{\argmin}{argmin}
\DeclareMathOperator*{\proj}{proj}
% brackets, norms, cardinalities
\newcommand{\pa}[1]{ \left({#1}\right) }
\newcommand{\ha}[1]{ \left[{#1}\right] }
\newcommand{\ca}[1]{ \left\{{#1}\right\} }
\newcommand{\inner}[1]{\left\langle #1 \right\rangle}
\newcommand{\innercpy}[1]{\inner{ #1, #1 }}
\newcommand{\norm}[1]{\left\| #1 \right\|}
\newcommand{\abs}[1]{\left|{#1}\right|}
\newcommand{\card}[1]{\left\vert{#1}\right\vert}
% math vectors
\newcommand{\va}{\textbf{a}}
\newcommand{\vb}{\textbf{b}}
\newcommand{\vc}{\textbf{c}}
\newcommand{\vd}{\textbf{d}}
\newcommand{\ve}{\textbf{e}}
\newcommand{\vf}{\textbf{f}}
\newcommand{\vg}{\textbf{g}}
\newcommand{\vh}{\textbf{h}}
\newcommand{\vi}{\textbf{i}}
\newcommand{\vj}{\textbf{j}}
\newcommand{\vk}{\textbf{k}}
\newcommand{\vl}{\textbf{l}}
\newcommand{\vm}{\textbf{m}}
\newcommand{\vn}{\textbf{n}}
\newcommand{\vo}{\textbf{o}}
\newcommand{\vp}{\textbf{p}}
\newcommand{\vq}{\textbf{q}}
\newcommand{\vr}{\textbf{r}}
\newcommand{\vs}{\textbf{s}}
\newcommand{\vt}{\textbf{t}}
\newcommand{\vu}{\textbf{u}}
\newcommand{\vv}{\textbf{v}}
\newcommand{\vw}{\textbf{w}}
\newcommand{\vx}{\textbf{x}}
\newcommand{\vy}{\textbf{y}}
\newcommand{\vz}{\textbf{z}}
\newcommand{\vzero}{\textbf{0}}
\newcommand{\vone}{\textbf{1}}
\newcommand{\valpha}{{\boldsymbol\alpha}}
\newcommand{\vepsilon}{{\boldsymbol\epsilon}}
\newcommand{\vnu}{{\boldsymbol\nu}}
\newcommand{\vpi}{{\boldsymbol\pi}}
\newcommand{\veta}{{\boldsymbol\eta}}
\newcommand{\vsigma}{ {\boldsymbol\sigma}}
\newcommand{\vbeta}{ {\boldsymbol\beta}}
\newcommand{\vtheta}{ {\boldsymbol\theta}}
\newcommand{\vdelta}{ {\boldsymbol\delta}}
\newcommand{\vlambda}{ {\boldsymbol\lambda}}
\newcommand{\vmu}{ {\boldsymbol\mu}}
% common math sets
\newcommand{\Z}{\mathbb{Z}}
\newcommand{\R}{\mathbb{R}}
\newcommand{\C}{\mathbb{C}}
\newcommand{\N}{\mathbb{N}}
\newcommand{\Q}{\mathbb{Q}}
\newcommand{\F}{\mathbb{F}}
\newcommand{\T}{\mathbb{T}}
% limits
\def\sumn{\sum_{n=0}^\infty}
\def\limn{\lim_{n\rightarrow\infty}}
\def\prodn{\prod_{n=0}^\infty}
% mathcal
\newcommand{\mcA}{\mathcal{A}}
\newcommand{\mcB}{\mathcal{B}}
\newcommand{\mcC}{\mathcal{C}}
\newcommand{\mcD}{\mathcal{D}}
\newcommand{\mcE}{\mathcal{E}}
\newcommand{\mcF}{\mathcal{F}}
\newcommand{\mcG}{\mathcal{G}}
\newcommand{\mcH}{\mathcal{H}}
\newcommand{\mcI}{\mathcal{I}}
\newcommand{\mcJ}{\mathcal{J}}
\newcommand{\mcK}{\mathcal{K}}
\newcommand{\mcL}{\mathcal{L}}
\newcommand{\mcM}{\mathcal{M}}
\newcommand{\mcN}{\mathcal{N}}
\newcommand{\mcO}{\mathcal{O}}
\newcommand{\mcP}{\mathcal{P}}
\newcommand{\mcQ}{\mathcal{Q}}
\newcommand{\mcR}{\mathcal{R}}
\newcommand{\mcS}{\mathcal{S}}
\newcommand{\mcT}{\mathcal{T}}
\newcommand{\mcU}{\mathcal{U}}
\newcommand{\mcV}{\mathcal{V}}
\newcommand{\mcW}{\mathcal{W}}
\newcommand{\mcX}{\mathcal{X}}
\newcommand{\mcY}{\mathcal{Y}}
\newcommand{\mcZ}{\mathcal{Z}}
% distribs, probability
\newcommand{\disteq}{\overset{d}{=}}
\newcommand\independent{\perp \!\!\! \perp}
\DeclareMathOperator{\Laplace}{Laplace}
\DeclareMathOperator{\Poisson}{Poisson}
\DeclareMathOperator{\Exponential}{Exponential}
\DeclareMathOperator{\Multinomial}{Multinomial}
\DeclareMathOperator{\Bernoulli}{Bernoulli}
\DeclareMathOperator{\Categorical}{Categorical}
\DeclareMathOperator{\Uniform}{Uniform}
\DeclareMathOperator{\Binomial}{Binomial}
\DeclareMathOperator{\Hypergeometric}{Hypergeometric}
\DeclareMathOperator{\GammaDist}{Gamma}
\DeclareMathOperator{\NegativeBinomial}{NegativeBinomial}
\DeclareMathOperator\sub{sub}
\renewcommand{\d}[1]{\mathop{\mathrm{d} #1 }}
\newcommand{\dkl}[2]{\mathop{D_\mathrm{KL}}\left({#1}\;\middle\|\;{#2}\right)}
\newcommand{\sg}{\mathop{\mathrm{SG}}}
\newcommand{\se}{\mathop{\mathrm{SE}}}
%operators
\DeclareMathOperator{\power}{{\mathcal{P}}}
\DeclareMathOperator{\var}{var}
\DeclareMathOperator{\cov}{cov}
\DeclareMathOperator\mathProb{\mathbb{P}}
\DeclareMathOperator\mathExp{\mathbb{E}}
\DeclareMathOperator*\mathExpUnder{\mathbb{E}}
\DeclareMathOperator*\fat{fat}
\renewcommand{\P}{\mathProb} % need to overwrite stupid paragraph symbol
\newcommand{\E}{\mathExp} % need to overwrite stupid paragraph symbol
\newcommand{\set}[2]{ \left\{ #1 \,\middle|\, #2 \right\} }
\newcommand{\CE}[2]{ \mathExp\left[ #1 \,\middle|\, #2 \right] }
\renewcommand{\CP}[2]{ \mathProb\left\{ #1 \,\middle|\, #2 \right\} }
$$
{% endraw %}

redpajama_set_name: RedPajamaGithub


text:
.class Lcom/android/server/wifi/WifiController$1;
.super Landroid/content/BroadcastReceiver;
.source "WifiController.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/server/wifi/WifiController;-><init>(Landroid/content/Context;Lcom/android/server/wifi/WifiServiceImpl;Landroid/os/Looper;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/wifi/WifiController;

# direct methods
.method constructor <init>(Lcom/android/server/wifi/WifiController;)V
    .locals 0

    .prologue
    .line 239
    iput-object p1, p0, Lcom/android/server/wifi/WifiController$1;->this$0:Lcom/android/server/wifi/WifiController;

    invoke-direct {p0}, Landroid/content/BroadcastReceiver;-><init>()V

    return-void
.end method

# virtual methods
.method public onReceive(Landroid/content/Context;Landroid/content/Intent;)V
    .locals 3
    .param p1, "context"    # Landroid/content/Context;
    .param p2, "intent"    # Landroid/content/Intent;

    .prologue
    .line 242
    invoke-virtual {p2}, Landroid/content/Intent;->getAction()Ljava/lang/String;

    move-result-object v0

    .line 243
    .local v0, "action":Ljava/lang/String;
    const-string v1, "com.android.server.WifiManager.action.DEVICE_IDLE"

    invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_1

    .line 244
    iget-object v1, p0, Lcom/android/server/wifi/WifiController$1;->this$0:Lcom/android/server/wifi/WifiController;

    const v2, 0x26005

    invoke-virtual {v1, v2}, Lcom/android/server/wifi/WifiController;->sendMessage(I)V

    .line 249
    :cond_0
    :goto_0
    return-void

    .line 245
    :cond_1
    const-string v1, "android.net.wifi.STATE_CHANGE"

    invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_0

    .line 246
    iget-object v2, p0, Lcom/android/server/wifi/WifiController$1;->this$0:Lcom/android/server/wifi/WifiController;

    const-string v1, "networkInfo"

    invoke-virtual {p2, v1}, Landroid/content/Intent;->getParcelableExtra(Ljava/lang/String;)Landroid/os/Parcelable;

    move-result-object v1

    check-cast v1, Landroid/net/NetworkInfo;

    iput-object v1, v2, Lcom/android/server/wifi/WifiController;->mNetworkInfo:Landroid/net/NetworkInfo;

    goto :goto_0
.end method


text:
FROM node:7.7.4-alpine
ADD . /code
WORKDIR /code
RUN npm install
ENTRYPOINT ["node","virtual-sensor.js"]
EXPOSE 1883


text:
html .clearfix, *:first-child+html .clearfix {
  zoom: 1; }


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

public class Test41
{

    //GetByCardTypeAndMaximumDamage
    [TestCase]
    public void GetByCardTypeAndMaximumDamage_ShouldWorkCorrectly()
    {
        //Arrange
        IArena RA = new RoyaleArena();
        Battlecard cd1 = new Battlecard(2, CardType.SPELL, "valq", 14, 5);
        Battlecard cd2 = new Battlecard(1, CardType.SPELL, "valq", 14, 5);
        Battlecard cd3 = new Battlecard(4, CardType.SPELL, "valq", 15, 6);
        Battlecard cd4 = new Battlecard(3, CardType.SPELL, "valq", 15, 7);
        Battlecard cd5 = new Battlecard(8, CardType.SPELL, "valq", 18, 8);
        List<Battlecard> expected = new List<Battlecard>()
        {
            cd4, cd3, cd2, cd1
        };
        //Act
        RA.Add(cd1);
        RA.Add(cd3);
        RA.Add(cd2);
        RA.Add(cd4);
        RA.Add(cd5);
        //Assert
        List<Battlecard> actual = RA
            .GetByCardTypeAndMaximumDamage(CardType.SPELL, 17)
            .ToList();
        CollectionAssert.AreEqual(expected, actual);
    }

}


text:
"""
Copyright 2017-2018 Fizyr (https://fizyr.com)

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

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

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

import argparse
import os
import sys

# Allow relative imports when being executed as script.
if __name__ == "__main__" and __package__ is None:
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
    import keras_retinanet.bin  # noqa: F401
    __package__ = "keras_retinanet.bin"

# Change these to absolute imports if you copy this script outside the keras_retinanet package.
from .. import models
from ..utils.config import read_config_file, parse_anchor_parameters, parse_pyramid_levels
from ..utils.gpu import setup_gpu
from ..utils.tf_version import check_tf_version

def parse_args(args):
    parser = argparse.ArgumentParser(description='Script for converting a training model to an inference model.')

    parser.add_argument('model_in', help='The model to convert.')
    parser.add_argument('model_out', help='Path to save the converted model to.')
    parser.add_argument('--backbone', help='The backbone of the model to convert.', default='resnet50')
    parser.add_argument('--no-nms', help='Disables non maximum suppression.', dest='nms', action='store_false')
    parser.add_argument('--no-class-specific-filter', help='Disables class specific filtering.', dest='class_specific_filter', action='store_false')
    parser.add_argument('--config', help='Path to a configuration parameters .ini file.')
    parser.add_argument('--nms-threshold', help='Value for non maximum suppression threshold.', type=float, default=0.5)
    parser.add_argument('--score-threshold', help='Threshold for prefiltering boxes.', type=float, default=0.05)
    parser.add_argument('--max-detections', help='Maximum number of detections to keep.', type=int, default=300)
    parser.add_argument('--parallel-iterations', help='Number of batch items to process in parallel.', type=int, default=32)

    return parser.parse_args(args)

def main(args=None):
    # parse arguments
    if args is None:
        args = sys.argv[1:]
    args = parse_args(args)

    # make sure tensorflow is the minimum required version
    check_tf_version()

    # set modified tf session to avoid using the GPUs
    setup_gpu('cpu')

    # optionally load config parameters
    anchor_parameters = None
    pyramid_levels = None
    if args.config:
        args.config = read_config_file(args.config)
        if 'anchor_parameters' in args.config:
            anchor_parameters = parse_anchor_parameters(args.config)

        if 'pyramid_levels' in args.config:
            pyramid_levels = parse_pyramid_levels(args.config)

    # load the model
    model = models.load_model(args.model_in, backbone_name=args.backbone)

    # check if this is indeed a training model
    models.check_training_model(model)

    # convert the model
    model = models.convert_model(
        model,
        nms=args.nms,
        class_specific_filter=args.class_specific_filter,
        anchor_params=anchor_parameters,
        pyramid_levels=pyramid_levels,
        nms_threshold=args.nms_threshold,
        score_threshold=args.score_threshold,
        max_detections=args.max_detections,
        parallel_iterations=args.parallel_iterations
    )

    # save model
    model.save(args.model_out)

if __name__ == '__main__':
    main()


text:
namespace Mairegger.Printing.Tests.Content
{
    using System.Diagnostics.CodeAnalysis;
    using System.Threading;
    using System.Windows;
    using System.Windows.Controls;
    using Mairegger.Printing.Content;
    using NUnit.Framework;

    [TestFixture]
    public class PrintDocumentBackgroundTest
    {
        [Test]
        [Apartment(ApartmentState.STA)]
        public void Ctor_Element()
        {
            Panel p = new StackPanel();
            var printDocumentBackground = new PrintDocumentBackground(p, Rect.Empty);
            Assert.That(printDocumentBackground.Element, Is.EqualTo(p));
        }

        [Test]
        [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute", Justification = "OK for UnitTests")]
        public void Ctor_Null_ThrowsArgumentNullException()
        {
            Assert.That(() => new PrintDocumentBackground(null, Rect.Empty), Throws.ArgumentNullException);
        }

        [Test]
        [Apartment(ApartmentState.STA)]
        public void Ctor_Size()
        {
            var size = new Rect(new Point(4, 4), new Size(10, 10));
            var printDocumentBackground = new PrintDocumentBackground(new StackPanel(), size);
            Assert.That(printDocumentBackground.Size, Is.EqualTo(size));
        }
    }
}


text:
package com.ubirch.auth.model.db

import java.net.URI

/**
  * author: cvandrei
  * since: 2017-03-13
  */
case class ContextProviderConfig(context: String,
                                 appId: String = "legacy", // TODO remove default once /provider/info/list/$CONTEXT has been removed
                                 provider: String,
                                 clientId: String,
                                 clientSecret: String,
                                 callbackUrl: URI
                                )


text:
@implementation ListViewProgressView

@end


text:
#ifndef _KERN_REBOOT_H_
#define _KERN_REBOOT_H_

/*
 * Constants for libc's <sys/reboot.h> and the reboot() system call.
 * (Not all that important.)
 */

/* Codes for reboot */
#define RB_REBOOT     0      /* Reboot system */
#define RB_HALT       1      /* Halt system and do not reboot */
#define RB_POWEROFF   2      /* Halt system and power off */

#endif /* _KERN_REBOOT_H_ */


text:
layout:     post
title:      "Wrangling of Openstreetmaps data"
date:       2014-12-15 12:00:00
source_url: https://github.com/alexbra/ud-nd-project2
---
In this project I've choose Tacoma,WA in https://www.openstreetmap.org and use data munging techniques, such as assessing the quality of the data for validity, accuracy, completeness, consistency and uniformity, to clean the OpenStreetMap data for this place.
<!--more-->
###Code source on Github
[https://github.com/alexbra/ud-nd-project2][1]

[1]:[https://github.com/alexbra/ud-nd-project2]


text:
/*	$OpenBSD: cpu.h,v 1.2 2001/09/02 19:40:24 miod Exp $	*/
/*	$NetBSD: cpu.h,v 1.1 1996/09/30 16:34:21 ws Exp $	*/

/*
 * Copyright (C) 1995, 1996 Wolfgang Solfrank.
 * Copyright (C) 1995, 1996 TooLs GmbH.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by TooLs GmbH.
 * 4. The name of TooLs GmbH may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#ifndef	_MACHINE_CPU_H_
#define	_MACHINE_CPU_H_

#include <powerpc/cpu.h>

#define	CACHELINESIZE	32			/* For now		XXX */

extern __inline void
syncicache(from, len)
	void *from;
	int len;
{
	int l = len;
	char *p = from;

	do {
		__asm__ __volatile__ ("dcbst 0,%0" :: "r"(p));
		p += CACHELINESIZE;
	} while ((l -= CACHELINESIZE) > 0);
	__asm__ __volatile__ ("sync");
	p = from;
	l = len;
	do {
		__asm__ __volatile__ ("icbi 0,%0" :: "r"(p));
		p += CACHELINESIZE;
	} while ((l -= CACHELINESIZE) > 0);
	__asm__ __volatile__ ("isync");
}

extern __inline void
invdcache(from, len)
	void *from;
	int len;
{
	int l = len;
	char *p = from;

	do {
		__asm__ __volatile__ ("dcbi 0,%0" :: "r"(p));
		p += CACHELINESIZE;
	} while ((l -= CACHELINESIZE) > 0);
	__asm__ __volatile__ ("sync");
}

#endif	/* _MACHINE_CPU_H_ */


text:
Resolving Identifiers
=====================

### `SimpleFSResolver`

This supplied implementation just unescapes the identifier and tacks a constant path onto the front. e.g. if `ident = 01%2F02%2F0001.jp2` and in the config file:

```ini
[resolver]
impl = 'loris.resolver.SimpleFSResolver'
src_img_root=/usr/local/share/images
```

then `app.resolver.resolve(ident)` will return

```
/usr/local/share/images/01/02/0001.jp2
```

### `SimpleHTTPResolver`

#### Main Configuration

This supplied implementation allows one to resolve identifiers against a HTTP source. This resolver requires a variable of "cache_root" be specified (the location to locally cache retrieved images) and that either "source_prefix" and/or "uri_resolvable" is configured.

A sample config of this resolver might be:

```ini
[resolver]
impl = 'loris.resolver.SimpleHTTPResolver'
source_prefix='https://<server>/fedora/objects/'
source_suffix='/datastreams/accessMaster/content'
cache_root='/usr/local/share/images/loris'
user='<if needed else remove this line>'
pw='<if needed else remove this line>'
```

Another sample configuration assuming one wishes to use uri's:

```ini
[resolver]
impl = 'loris.resolver.SimpleHTTPResolver'
uri_resolvable=True
cache_root='/usr/local/share/images/loris'
```

A full configuration sample that shows all the options and their defaults are:

```ini
[resolver]
impl = 'loris.resolver.SimpleHTTPResolver'
source_prefix=''
source_suffix=''
uri_resolvable=False
head_resolvable=False #DO set this to true if using Fedora Commons 3.8 or later. Earlier versions have a bug for a head response.
default_format=None #Set this if your HTTP server doesn't populate content-response. An example value might be "jp2".
user=None
pw=None
cache_root='<must be configured>'
```

#### Required Other Configurations

Additionally, please note the following must also exist if the "enable_caching" is True and be configured to be owned by the loris user. While the cache_root above with the larger derivatives can be on a NAS, these following must likely be stored on the local server file system to avoid problems (they are somewhat small however):

```ini
[img.ImageCache]
cache_dp = '/var/cache/loris/img' # rwx
cache_links = '/var/cache/loris/links' # rwx

[img_info.InfoCache]
cache_dp = '/var/cache/loris/info' # rwx
```

#### Examples in the Wild

[https://www.digitalcommonwealth.org](https://www.digitalcommonwealth.org) - Used for all object images except thumbnails.

### `Creating Your Own`

See `resolver._AbstractResolver` for details. Note that any properties you add in the `[resolver.Resolver]` section will be in the `self.config` dictionary as long as you subclass `_AbstractResolver`.

* * *

Proceed to the [Run `setup.py`](setup.md) or go [Back to README](../README.md)


text:
define([
    './../KmlElements',
    './KmlFeature',
    './KmlOverlay',
    '../util/NodeTransformers',
    '../../../util/Offset',
    '../../../shapes/ScreenImage',
    '../../../util/WWUtil'
], function (KmlElements,
             KmlFeature,
             KmlOverlay,
             NodeTransformers,
             Offset,
             ScreenImage,
             WWUtil) {
    "use strict";

    /**
     * Constructs an KmlScreenOverlay. Applications usually don't call this constructor. It is called by {@link
        * KmlFile} as objects from Kml file are read. This object is already concrete implementation.
     * @alias KmlScreenOverlay
     * @classdesc Contains the data associated with ScreenOverlay node.
     * @param options {Object}
     * @param options.objectNode {Node} Node representing ScreenOverlay
     * @constructor
     * @throws {ArgumentError} If the node is null or undefined.
     * @see https://developers.google.com/kml/documentation/kmlreference#screenoverlay
     * @augments KmlOverlay
     */
    var KmlScreenOverlay = function (options) {
        KmlOverlay.call(this, options);

        console.log("Create Screen Overlay", this);
    };

    KmlScreenOverlay.prototype = Object.create(KmlOverlay.prototype);

    Object.defineProperties(KmlScreenOverlay.prototype, {
        /**
         * Indicates the angle of rotation of the parent object. A value of 0 means no rotation. The value is an
         * angle in degrees counterclockwise starting from north. Use +-180 to indicate the rotation of the parent
         * object from
         * 0. The center of the <rotation>, if not (.5,.5), is specified in <rotationXY>.
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {Number}
         */
        kmlRotation: {
            get: function () {
                return this._factory.specific(this, {name: 'rotation', transformer: NodeTransformers.number});
            }
        },

        /**
         * Either the number of pixels, a fractional component of the image, or a pixel inset indicating the x
         * component of a point on the overlay image.
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlOverlayXYx: {
            get: function () {
                return this._factory.specific(this, {name: 'overlayXY', transformer: NodeTransformers.attribute('x'), attribute: 'kmlOverlayXYx'});
            }
        },

        /**
         * Either the number of pixels, a fractional component of the image, or a pixel inset indicating the y
         * component of a point on the overlay image.
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlOverlayXYy: {
            get: function () {
                return this._factory.specific(this, {name: 'overlayXY', transformer: NodeTransformers.attribute('y'), attribute: 'kmlOverlayXYy'});
            }
        },

        /**
         * Units in which the x value is specified. A value of "fraction" indicates the x value is a fraction of the
         * image. A value of "pixels" indicates the x value in pixels. A value of "insetPixels" indicates the indent
         * from the right edge of the image.
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlOverlayXYxunits: {
            get: function () {
                return this._factory.specific(this, {name: 'overlayXY', transformer: NodeTransformers.attribute('xunits'), attribute: 'kmlOverlayXYxunits'});
            }
        },

        /**
         * Units in which the y value is specified. A value of "fraction" indicates the y value is a fraction of the
         * image. A value of "pixels" indicates the y value in pixels. A value of "insetPixels" indicates the indent
         * from the top edge of the image.
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlOverlayXYyunits: {
            get: function () {
                return this._factory.specific(this, {name: 'overlayXY', transformer: NodeTransformers.attribute('yunits'), attribute: 'kmlOverlayXYyunits'});
            }
        },

        /**
         * Either the number of pixels, a fractional component of the screen, or a pixel inset indicating the x
         * component of a point on the screen.
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlScreenXYx: {
            get: function () {
                return this._factory.specific(this, {name: 'screenXY', transformer: NodeTransformers.attribute('x'), attribute: 'kmlScreenXYx'});
            }
        },

        /**
         * Either the number of pixels, a fractional component of the screen, or a pixel inset indicating the y
         * component of a point on the screen.
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlScreenXYy: {
            get: function () {
                return this._factory.specific(this, {name: 'screenXY', transformer: NodeTransformers.attribute('y'), attribute: 'kmlScreenXYy'});
            }
        },

        /**
         * Units in which the x value is specified. A value of "fraction" indicates the x value is a fraction of
         * the
         * screen. A value of "pixels" indicates the x value in pixels. A value of "insetPixels" indicates the
         * indent from the right edge of the screen.
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlScreenXYxunits: {
            get: function () {
                return this._factory.specific(this, {name: 'screenXY', transformer: NodeTransformers.attribute('xunits'), attribute: 'kmlScreenXYxunits'});
            }
        },

        /**
         * Units in which the y value is specified. A value of fraction indicates the y value is a fraction of the
         * screen. A value of "pixels" indicates the y value in pixels. A value of "insetPixels" indicates the
         * indent from the top edge of the screen.
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlScreenXYyunits: {
            get: function () {
                return this._factory.specific(this, {name: 'screenXY', transformer: NodeTransformers.attribute('yunits'), attribute: 'kmlScreenXYyunits'});
            }
        },

        /**
         * It decides by how much will be the screen overlay rotated in x direction
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlRotationXYx: {
            get: function () {
                return this._factory.specific(this, {name: 'rotationXY', transformer: NodeTransformers.attribute('x'), attribute: 'kmlRotationXYx'});
            }
        },

        /**
         * It decides by how much will be the screen overlay rotated in y direction
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlRotationXYy: {
            get: function () {
                return this._factory.specific(this, {name: 'rotationXY', transformer: NodeTransformers.attribute('y'), attribute: 'kmlRotationXYy'});
            }
        },

        /**
         * Units in which the x value is specified. A value of "fraction" indicates the x value is a fraction of
         * the
         * screen. A value of "pixels" indicates the x value in pixels. A value of "insetPixels" indicates the
         * indent from the right edge of the screen.
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlRotationXYxunits: {
            get: function () {
                return this._factory.specific(this, {name: 'rotationXY', transformer: NodeTransformers.attribute('xunits'), attribute: 'kmlRotationXYxunits'});
            }
        },

        /**
         * Units in which the y value is specified. A value of fraction indicates the y value is a fraction of the
         * screen. A value of "pixels" indicates the y value in pixels. A value of "insetPixels" indicates the
         * indent from the top edge of the screen.
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlRotationXYyunits: {
            get: function () {
                return this._factory.specific(this, {name: 'rotationXY', transformer: NodeTransformers.attribute('yunits'), attribute: 'kmlRotationXYyunits'});
            }
        },

        /**
         * A value of +-1 indicates to use the native dimension
         * A value of 0 indicates to maintain the aspect ratio
         * A value of n sets the value of the dimension
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlSizex: {
            get: function () {
                return this._factory.specific(this, {name: 'size', transformer: NodeTransformers.attribute('x'), attribute: 'kmlSizex'});
            }
        },

        /**
         * A value of +-1 indicates to use the native dimension
         * A value of 0 indicates to maintain the aspect ratio
         * A value of n sets the value of the dimension
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlSizey: {
            get: function () {
                return this._factory.specific(this, {name: 'size', transformer: NodeTransformers.attribute('y'), attribute: 'kmlSizey'});
            }
        },

        /**
         * Units in which the x value is specified. A value of "fraction" indicates the x value is a fraction of
         * the
         * screen. A value of "pixels" indicates the x value in pixels. A value of "insetPixels" indicates the
         * indent from the right edge of the screen.
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlSizexunits: {
            get: function () {
                return this._factory.specific(this, {name: 'size', transformer: NodeTransformers.attribute('xunits'), attribute: 'kmlSizexunits'});
            }
        },

        /**
         * Units in which the y value is specified. A value of fraction indicates the y value is a fraction of the
         * screen. A value of "pixels" indicates the y value in pixels. A value of "insetPixels" indicates the
         * indent from the top edge of the screen.
         * @memberof KmlScreenOverlay.prototype
         * @readonly
         * @type {String}
         */
        kmlSizeyunits: {
            get: function () {
                return this._factory.specific(this, {name: 'size', transformer: NodeTransformers.attribute('yunits'), attribute: 'kmlSizeyunits'});
            }
        }
    });

	/**
     * @inheritDoc
     */
    KmlScreenOverlay.prototype.render = function(dc, kmlOptions) {
        KmlFeature.prototype.render.call(this, dc, kmlOptions);

        if(!this._renderable) {
            if(this.kmlIcon) {
                this._renderable = new ScreenImage(
                    new Offset(
                        this.kmlScreenXYxunits,
                        this.kmlScreenXYx,
                        this.kmlScreenXYyunits,
                        this.kmlScreenXYy
                    ),
                    this.kmlIcon.kmlHref
                );
                this._renderable.imageOffset = new Offset(
                    this.kmlOverlayXYxunits,
                    this.kmlOverlayXYx,
                    this.kmlOverlayXYyunits,
                    this.kmlOverlayXYy
                );
                dc.redrawRequested = true;
            }
        }

        if(this._renderable) {
            this._renderable.render(dc);
        }
    };

    /**
     * @inheritDoc
     */
    KmlScreenOverlay.prototype.getTagNames = function () {
        return ['ScreenOverlay'];
    };

    KmlElements.addKey(KmlScreenOverlay.prototype.getTagNames()[0], KmlScreenOverlay);

    return KmlScreenOverlay;
});


text:
    Run History
    State History

  <button type="button" class="btn btn-primary btn-sm add-button pull-right"
          ng-show="isAuthorized([userRoles.admin, userRoles.creator]) && !isPipelineRunning && pipelineStateHistory.length"
          ng-click="clearHistory()">
     {{'home.detailPane.historyTab.clearHistory' | translate}}
  </button>

      Last Status Change
      User
      Status
      Message
      Parameters
      Summary

      {{history.timeStamp | date:'medium'}}
      {{history.user}}

        {{history.message}}

        {{history.attributes['RUNTIME_PARAMETERS'] | json}}

        View Summary ...

      No Status.

      Run Count
      Started
      Completed
      Duration
      User
      Status
      Input
      Output
      Error
      Summary

      {{history.appName}}
      {{history.started | date:'medium'}}

        {{history.completed | date:'medium'}}
        --

        {{history.completed | amDifference : history.started | amDurationFormat }}
        {{history.completed | amDifference | amDurationFormat }}

      {{history.user}}

        {{history.status}}

           ( View Stack Trace... )

      {{history.metrics ? (history.inputRecords | number) : '--'}}
      {{history.metrics ? (history.outputRecords | number) : '--'}}
      {{history.metrics ? (history.errorRecordsAndMessages | number) : '--'}}

        View Summary ...

      No Status.


text:
"""
example of building a simple ssh-tunnel

To run: python simple_tunnel.py
"""

from pathos.secure import Tunnel

if __name__ == '__main__':
    import sys
    rhost = 'localhost'
   #rhost = 'foobar.danse.us'
   #rhost = 'computer.cacr.caltech.edu'
    rport = 23

    t = Tunnel('Tunnel')
    lport = t.connect(rhost, rport)
    print 'SSH Tunnel to:', rhost
    print 'Remote port:', rport
    print 'Local port:', lport
    print 'Press <Enter> to disconnect'
    sys.stdin.readline()
    t.disconnect()


text:
/*global describe, it, beforeEach, expect, xit, jasmine */
/*jshint laxbreak:true */

describe("Legend XML parsing", function () {
    "use strict";

    var Legend = require('../../../src/core/legend.js'),
        Icon = require('../../../src/core/icon.js'),
        Point = require('../../../src/math/point.js'),
        RGBColor = require('../../../src/math/rgb_color.js'),
        xmlString,
        colorString = "0x56839c",
        bordercolorString = "0x941394",
        baseString = "-1,-1",
        anchorString = "0,0",
        positionString = "0.5,1",
        visibleBool = true,
        frameString = "padding",
        opacityString = "1",
        borderString = "10",
        rowsString = "4",
        columnsString = "3",
        cornerradiusString = "5",
        paddingString = "4",
        $xml,
        legend;

    var $, jqw = require('../../node_jquery_helper.js').createJQuery();
    beforeEach(function() { $ = jqw.$; });

    var JQueryXMLParser;
    beforeEach(function () {
        JQueryXMLParser = require('../../../src/parser/xml/jquery_xml_parser.js')($);
    });

    beforeEach(function () {
        xmlString = ''
            + '<legend'
            +     ' color="' + colorString + '"'
            +     ' bordercolor="' + bordercolorString + '"'
            +     ' base="' + baseString + '"'
            +     ' anchor="' + anchorString + '"'
            +     ' position="' + positionString + '"'
            +     ' visible="' + visibleBool + '"'
            +     ' frame="' + frameString + '"'
            +     ' opacity="' + opacityString + '"'
            +     ' border="' + borderString + '"'
            +     ' rows="' + rowsString + '"'
            +     ' columns="' + columnsString + '"'
            +     ' cornerradius="' + cornerradiusString + '"'
            +     ' padding="' + paddingString + '"'
            +     '/>';
        $xml = JQueryXMLParser.stringToJQueryXMLObj(xmlString);
        legend = Legend.parseXML($xml);
    });

    it("should be able to parse a legend from XML", function () {
        expect(legend).not.toBeUndefined();
        expect(legend instanceof Legend).toBe(true);
    });

    it("should be able to parse a legend from XML and read its 'base' attribute", function () {
        expect(legend.base().x()).toEqual((Point.parse(baseString)).x());
        expect(legend.base().y()).toEqual((Point.parse(baseString)).y());
    });

    it("should be able to parse a legend from XML and read its 'anchor' attribute", function () {
        expect(legend.anchor().x()).toEqual((Point.parse(anchorString)).x());
        expect(legend.anchor().y()).toEqual((Point.parse(anchorString)).y());
    });

    it("should be able to parse a legend from XML and read its 'position' attribute", function () {
        expect(legend.position().x()).toEqual((Point.parse(positionString)).x());
        expect(legend.position().y()).toEqual((Point.parse(positionString)).y());
    });

    it("should be able to parse a legend from XML and read its 'frame' attribute", function () {
        expect(legend.frame()).toEqual(frameString.toLowerCase());
    });

    it("should be able to parse a legend from XML and read its 'color' attribute", function () {
        expect(legend.color().getHexString("0x")).toEqual((RGBColor.parse(colorString)).getHexString("0x"));
    });

    it("should be able to parse a legend from XML and read its 'bordercolor' attribute", function () {
        expect(legend.bordercolor().getHexString("0x")).toEqual((RGBColor.parse(bordercolorString)).getHexString("0x"));
    });

    it("should be able to parse a legend from XML and read its 'opacity' attribute", function () {
        expect(legend.opacity()).toEqual(parseFloat(opacityString));
    });

    it("should be able to parse a legend from XML and read its 'border' attribute", function () {
        expect(legend.border()).toEqual(parseInt(borderString, 10));
    });

    it("should be able to parse a legend from XML and read its 'rows' attribute", function () {
        expect(legend.rows()).toEqual(parseInt(rowsString, 10));
    });

    it("should be able to parse a legend from XML and read its 'columns' attribute", function () {
        expect(legend.columns()).toEqual(parseInt(columnsString, 10));
    });

    it("should be able to parse a legend from XML and read its 'cornerradius' attribute", function () {
        expect(legend.cornerradius()).toEqual(parseInt(cornerradiusString, 10));
    });

    it("should be able to parse a legend from XML and read its 'padding' attribute", function () {
        expect(legend.padding()).toEqual(parseInt(paddingString, 10));
    });

    describe("Icon parsing", function () {
        var heightString = "35",
            widthString = "50",
            borderString = "2";

        beforeEach(function () {
            xmlString = ''
                + '<legend'
                +     ' color="0x56839c"'
                +     ' bordercolor="0x941394"'
                +     ' base="-1,-1"'
                +     ' anchor="0,0"'
                +     ' position="0.3,0.2"'
                +     ' visible="true"'
                +     ' frame="padding"'
                +     ' opacity="1"'
                +     ' border="10"'
                +     ' rows="4"'
                +     ' columns="3"'
                +     ' cornerradius="5"'
                +     ' padding="2"'
                +     '>'
                +     '<icon'
                +         ' height="' + heightString + '"'
                +         ' width="' + widthString + '"'
                +         ' border="' + borderString + '"'
                +     '/>'
                + '</legend>';
            $xml = JQueryXMLParser.stringToJQueryXMLObj(xmlString);
            legend = Legend.parseXML($xml);
        });

        it("should be able to parse a legend with children from XML", function () {
            expect(legend).not.toBeUndefined();
            expect(legend instanceof Legend).toBe(true);
            expect(legend.icon()).not.toBeUndefined();
            expect(legend.icon() instanceof Icon).toBe(true);
        });

        it("should properly parse a legend tag with an icon child tag from XML", function () {
            expect(legend.icon().height()).toEqual(parseInt(heightString, 10));
            expect(legend.icon().width()).toEqual(parseInt(widthString, 10));
            expect(legend.icon().border()).toEqual(parseInt(borderString, 10));
        });

    });

});


text:
<!-- AUTO-GENERATED-CONTENT:START (PKGJSON:template=Hello ${foo}) -->
Hello undefined
<!-- AUTO-GENERATED-CONTENT:END -->


text:
int executeLookAround(void)
{
   if (isLit(player->location))
   {
      printPrivate("You are in %s.\n", player->location->description);
   }
   else
   {
      printPrivate("It is very dark in here.\n");
   }
   listObjectsAtLocation(player->location);
   return 1;
}

int executeLook(void)
{
   OBJECT *obj = getVisible("what you want to look at", params[0]);
   switch (getDistance(player, obj))
   {
   case distHereContained:
      printPrivate("Hard to see, try to get it first.\n");
      return 0;
   case distOverthere:
      printPrivate("Too far away, move closer please.\n");
      return 0;
   case distNotHere:
      printPrivate("You don't see any %s here.\n", params[0]);
      return 0;
   case distUnknownObject:
      // already handled by getVisible
      return 0;
   default:
      printPrivate("%s\n", obj->details);
      listObjectsAtLocation(obj);
      return 1;
   }
}

static void movePlayer(OBJECT *passage)
{
   if (passage->destination != NULL)
   {
      printSee("%s\n", passage->textGo);
      player->location = passage->destination;
      printAny(player, player, " see ", "You enter.\n");
      executeLookAround();
   }
   else
   {
      printPrivate("%s\n", passage->textGo);
   }
}

int executeGo(void)
{
   OBJECT *obj = getVisible("where you want to go", params[0]);
   switch (getDistance(player, obj))
   {
   case distOverthere:
      movePlayer(getPassage(player->location, obj));
      return 1;
   case distNotHere:
      printPrivate("You don't see any %s here.\n", params[0]);
      return 0;
   case distUnknownObject:
      // already handled by getVisible
      return 0;
   default:
      movePlayer(obj);
      return 1;
   }
}


text:
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext, Template, Context, loader
from django.utils.safestring import mark_safe
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth.models import User, Group

import django.contrib.auth
import ldap

from django.contrib.auth.decorators import login_required
from django.template import RequestContext, Context, loader
from django.db import models

def setup(request):
    t = loader.get_template('django_ldap_wizard/setup.html')
    successful_connect = False

    if request.GET:
        try:
            uri = request.GET.get("ldap_url", "")
            bind_dn = request.GET.get('bind_dn', "")
            bind_pw = request.GET.get('bind_pw', "")
            base_dn = request.GET.get('base_dn', "")

            con = ldap.initialize(uri)
            con.simple_bind_s( bind_dn, bind_pw )
            message = "Successfully tested your connection settings."
            successful_connect = True
        except ldap.SERVER_DOWN:
            message = "Unable to contact LDAP server -- perhaps you specified the wrong URI or the server is not accepting connections"
        except ldap.INVALID_CREDENTIALS:
            message = "Unable to authenticate using those credentials. Please double check them!"
        except ldap.LDAPError, e:
            if type(e.message) == dict and e.message.has_key('desc'):
                message = e.message['desc']
            else:
                message = "Invalid input data, check your settings"
    else:
        uri = ""
        bind_dn = ""
        bind_pw = ""
        base_dn = ""
        message = ""

    ctx = {
        "uri": uri,
        "bind_dn": bind_dn,
        "bind_pw": bind_pw,
        "base_dn": base_dn,
        "message": message,
        "success": successful_connect
    }

    c = RequestContext(request, ctx)
    return HttpResponse(t.render(c))


text:
  int main()                                                           \
  {                                                                    \
    const TestFramework::TestItem groupName ## _Items[] =              \
    {                                                                  \
      TEST_ITEMS                                                       \
    };                                                                 \
                                                                       \
    const TestFramework::TestGroup groupName ## _Group =               \
    {                                                                  \
      #groupName,                                                      \
      groupName ## _Items,                                             \
      sizeof(groupName ## _Items) / sizeof(*groupName ## _Items)       \
    };                                                                 \
                                                                       \
    const bool success = TestFramework::RunTests(groupName ## _Group); \
    return success ? 0 : 1;                                            \
  }                                                                    \

#define ASSERT_MESSAGE(condition, message)                                  \
  __ASSERT_FORMAT__(condition, logger, __FILE__, __LINE__, ("%s", message)) \

#define ASSERT_FORMAT(condition, format)                                    \
  __ASSERT_FORMAT__(condition, logger, __FILE__, __LINE__, format)          \

#define __ASSERT_FORMAT__(condition, logger, file, line, format)            \
  if (!(condition))                                                         \
  {                                                                         \
    logger.Print("line %u in %s: ", line, file);                            \
    logger.Print format;                                                    \
    return false;                                                           \
  }                                                                         \

#define ERROR_MESSAGE(message)                                              \
  __ERROR_FORMAT__(logger, __FILE__, __LINE__, ("%s", message))             \

#define ERROR_FORMAT(format)                                                \
  __ERROR_FORMAT__(logger, __FILE__, __LINE__, format)                      \

#define __ERROR_FORMAT__(logger, file, line, format)                        \
  {                                                                         \
    logger.Print("line %u in %s: ", line, file);                            \
    logger.Print format;                                                    \
  }                                                                         \

namespace TestFramework
{

typedef bool TestFunction(Bond::OutputStream &logger);

struct TestItem
{
	const char *testName;
	TestFunction *testFunction;
};

struct TestGroup
{
	const char *groupName;
	const TestItem *items;
	unsigned numItems;
};

bool RunTests(const TestGroup &testGroup);

}

#endif


text:
set -eux

# $1 —— absolute path to destination file, should end with .zip, ideally
# $2 —— absolute path to directory from which to add entries to the archive
# $3 —— if files should be zip64 or not

if [[$3]]; then
	pushd "$2" && find . -print | zip -fz "$1" -@ && popd
else
	pushd "$2" && find . -print | zip "$1" -@ && popd
fi


text:
using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameRes.Utility;

namespace GameRes.Formats.Vitamin
{
    internal class SbiMetaData : ImageMetaData
    {
        public bool HasPalette;
        public bool IsPacked;
        public int  InputSize;
    }

    [Export(typeof(ImageFormat))]
    public class SbiFormat : ImageFormat
    {
        public override string         Tag { get { return "SBI"; } }
        public override string Description { get { return "Vitamin image format"; } }
        public override uint     Signature { get { return 0x0A494253; } } // 'SBI'

        public SbiFormat ()
        {
            Extensions = new string[] { "cmp" };
        }

        public override ImageMetaData ReadMetaData (IBinaryStream stream)
        {
            var header = stream.ReadHeader (0x20);
            if (header[4] != 1 || header[5] != 0)
                return null;
            int bpp = header[6];
            if (bpp < 8)
                return null;
            return new SbiMetaData
            {
                Width   = header.ToUInt16 (7),
                Height  = header.ToUInt16 (9),
                BPP     = bpp,
                InputSize = header.ToInt32 (0xB),
                IsPacked = 0 != header[0x10],
                HasPalette = 8 == bpp && 0 == header[0xF],
            };
        }

        public override ImageData Read (IBinaryStream stream, ImageMetaData info)
        {
            using (var reader = new SbiReader (stream, (SbiMetaData)info))
            {
                reader.Unpack();
                return ImageData.Create (info, reader.Format, reader.Palette, reader.Data, reader.Stride);
            }
        }

        public override void Write (Stream file, ImageData image)
        {
            throw new System.NotImplementedException ("SbiFormat.Write not implemented");
        }
    }

    internal sealed class SbiReader : IDisposable
    {
        IBinaryStream   m_input;
        SbiMetaData     m_info;
        byte[]          m_output;
        int             m_stride;

        public byte[]           Data { get { return m_output; } }
        public PixelFormat    Format { get; private set; }
        public BitmapPalette Palette { get; private set; }
        public int            Stride { get { return m_stride; } }

        public SbiReader (IBinaryStream input, SbiMetaData info)
        {
            m_input = input;
            m_info = info;
            m_stride = ((int)m_info.Width * m_info.BPP / 8 + 3) & ~3;
            m_output = new byte[m_stride * (int)m_info.Height];
            if (32 == m_info.BPP)
                Format = PixelFormats.Bgr32;
            else if (24 == m_info.BPP)
                Format = PixelFormats.Bgr24;
            else if (16 == m_info.BPP)
                Format = PixelFormats.Bgr565;
            else if (8 == m_info.BPP)
            {
                if (m_info.HasPalette)
                    Format = PixelFormats.Indexed8;
                else
                    Format = PixelFormats.Gray8;
            }
            else
                throw new InvalidFormatException();
        }

        public void Unpack ()
        {
            m_input.Position = 0x20;
            int input_size = m_info.InputSize - 0x20;
            if (m_info.HasPalette)
            {
                Palette = ImageFormat.ReadPalette (m_input.AsStream, 0x100, PaletteFormat.Rgb);
                input_size -= 0x300;
            }
            int x = 0;
            int y = (int)m_info.Height - 1;
            int dst = m_stride * y;
            if (!m_info.IsPacked)
            {
                while (dst >= 0)
                {
                    if (m_stride != m_input.Read (m_output, dst, m_stride))
                        throw new EndOfStreamException();
                    dst -= m_stride;
                }
                return;
            }
            int pixel_size = m_info.BPP / 8;
            var buffer = new byte[0x180];
            while (input_size > 0)
            {
                int count = m_input.ReadUInt8();
                --input_size;
                if (count < 0x80)
                {
                    int c = count * pixel_size;
                    if (c != m_input.Read (buffer, 0, c))
                        throw new EndOfStreamException();
                    input_size -= c;
                }
                else if (count >= 0x80)
                {
                    count &= 0x7F;
                    if (pixel_size != m_input.Read (buffer, 0, pixel_size))
                        throw new EndOfStreamException();
                    input_size -= pixel_size;
                    Binary.CopyOverlapped (buffer, 0, pixel_size, pixel_size * (count-1));
                }
                int src = 0;
                while (count > 0)
                {
                    int line_left = (int)m_info.Width - x;
                    if (count < line_left)
                    {
                        line_left = count;
                        x += count;
                    }
                    else
                    {
                        x = 0;
                    }
                    int chunk = pixel_size * line_left;
                    Buffer.BlockCopy (buffer, src, m_output, dst, chunk);
                    src += chunk;
                    if (0 == x)
                        dst = m_stride * --y;
                    else
                        dst += chunk;
                    count -= line_left;
                }
            }
        }

        #region IDisposable Members
        public void Dispose ()
        {
        }
        #endregion
    }
}


text:
import * as React from 'react';
import { shallow } from 'enzyme';

import { Notification } from './../../src/elements/Notification';

describe('Notification', () => {
    it('should render a div with .notification', () => {
        const component = shallow(<Notification>My Notification</Notification>);
        expect(component.contains(
My Notification
)).toBe(true);
    });

    it('should render a p with .notification', () => {
        const component = shallow(<Notification tag='p'>My Notification</Notification>);
        expect(component.contains(
My Notification
)).toBe(true);
    });

    it('should render a div with .notification and modifiers', () => {
        const component = shallow(<Notification isColor='black'>My Notification</Notification>);
        expect(component.hasClass('notification')).toBe(true);
        expect(component.hasClass('is-black')).toBe(true);
    });

    it('should render a div with .notification, modifiers and custom classNames', () => {
        const component = shallow(<Notification isColor='primary' className='custom'>Any Content</Notification>);
        expect(component.hasClass('notification')).toBe(true);
        expect(component.hasClass('is-primary')).toBe(true);
        expect(component.hasClass('custom')).toBe(true);
    });

    it('should render a div with .notification and custom classNames', () => {
        const component = shallow(<Notification className='custom'>Any Content</Notification>);
        expect(component.hasClass('notification')).toBe(true);
        expect(component.hasClass('custom')).toBe(true);
    });
});


text:
require 'spec_helper'

describe Rack::EncodingGuard::RejectStrategy do
  include_examples 'Strategy'

  let! :env do
    Rack::MockRequest.env_for('http://example.com/some/path?and=query&string=set')
  end

  let :app_response do
    [200, {}, ['Default']]
  end

  context 'with valid environment' do
    it 'cascades to the app response' do
      strategy = described_class.new
      expect(strategy.process(env) { app_response }).to eq app_response
    end
  end

  INVALID_ENV_VARS = {
    'HTTP_REFERER' => "http://example.com/so\255me/ref\255erer/path",
    'PATH_INFO'    => "/some/pa\255th",
    'REQUEST_URI'  => "/so\255me/request/path?a\255nd=query",
    'REQUEST_PATH' => "/some/pa\255th",
    'QUERY_STRING' => "and=que\255ry&str\255ing=set"
  }

  INVALID_ENV_VARS.each do |name, value|
    context "with invalid #{name}" do
      before do
        env[name] = value
      end

      it 'responds with bad request status' do
        expected_response = [400, {}, ['Bad Request']]
        strategy = described_class.new
        expect(strategy.process(env) { app_response }).to eq expected_response
      end

      context 'with response text configured' do
        it 'responds with bad request status and custom message' do
          custom_text = 'Something went wrong'
          expected_response = [400, {}, [custom_text]]
          strategy = described_class.new(with: custom_text)
          expect(strategy.process(env) { app_response }).to eq expected_response
        end
      end
    end
  end
end


text:
"""
A config rev object that persists itself
"""
from bz2 import compress, decompress

import structlog
from simplejson import dumps, loads

from voltha.core.config.config_rev import ConfigRevision, children_fields

log = structlog.get_logger()

class PersistedConfigRevision(ConfigRevision):

    compress = False

    __slots__ = ('_kv_store',)

    def __init__(self, branch, data, children=None):
        self._kv_store = branch._node._root._kv_store
        super(PersistedConfigRevision, self).__init__(branch, data, children)

    def _finalize(self):
        super(PersistedConfigRevision, self)._finalize()
        self.store()

    def __del__(self):
        try:
            if self._hash:
                if self._config.__weakref__ is None:
                    if self._config._hash in self._kv_store:
                        del self._kv_store[self._config._hash]
                assert self.__weakref__ is None
                if self._hash in self._kv_store:
                    del self._kv_store[self._hash]
        except Exception, e:
            # this should never happen
            log.exception('del-error', hash=self.hash, e=e)

    def store(self):

        try:
            # crude serialization of children hash and config data hash
            if self._hash in self._kv_store:
                return

            self.store_config()

            children_lists = {}
            for field_name, children in self._children.iteritems():
                hashes = [rev.hash for rev in children]
                children_lists[field_name] = hashes

            data = dict(
                children=children_lists,
                config=self._config._hash
            )
            blob = dumps(data)
            if self.compress:
                blob = compress(blob)

            self._kv_store[self._hash] = blob

        except Exception, e:
            log.exception('store-error', e=e)

    @classmethod
    def load(cls, branch, kv_store, msg_cls, hash):
        #  Update the branch's config store
        blob = kv_store[hash]
        if cls.compress:
            blob = decompress(blob)
        data = loads(blob)

        config_hash = data['config']
        config_data = cls.load_config(kv_store, msg_cls, config_hash)

        children_list = data['children']
        assembled_children = {}
        node = branch._node
        for field_name, meta in children_fields(msg_cls).iteritems():
            child_msg_cls = tmp_cls_loader(meta.module, meta.type)
            children = []
            for child_hash in children_list[field_name]:
                child_node = node._mknode(child_msg_cls)
                child_node.load_latest(child_hash)
                child_rev = child_node.latest
                children.append(child_rev)
            assembled_children[field_name] = children
        rev = cls(branch, config_data, assembled_children)
        return rev

    def store_config(self):
        if self._config._hash in self._kv_store:
            return

        # crude serialization of config data
        blob = self._config._data.SerializeToString()
        if self.compress:
            blob = compress(blob)

        self._kv_store[self._config._hash] = blob

    @classmethod
    def load_config(cls, kv_store, msg_cls, config_hash):
        blob = kv_store[config_hash]
        if cls.compress:
            blob = decompress(blob)

        # TODO use a loader later on
        data = msg_cls()
        data.ParseFromString(blob)
        return data

def tmp_cls_loader(module_name, cls_name):
    # TODO this shall be generalized
    from voltha.protos import voltha_pb2, health_pb2, adapter_pb2, \
        logical_device_pb2, device_pb2, openflow_13_pb2, bbf_fiber_base_pb2, \
        bbf_fiber_traffic_descriptor_profile_body_pb2, \
        bbf_fiber_tcont_body_pb2, bbf_fiber_gemport_body_pb2, \
        bbf_fiber_multicast_gemport_body_pb2, \
        bbf_fiber_multicast_distribution_set_body_pb2, \
        omci_mib_db_pb2, \
        omci_alarm_db_pb2
    return getattr(locals()[module_name], cls_name)


text:
/*!
    \file kernelprofile.h

    \brief Profiling timer hardware interface
*/

#include "kerneltypes.h"
#include "mark3cfg.h"
#include "ll.h"

#ifndef __KPROFILE_H__
#define __KPROFILE_H__

#if KERNEL_USE_PROFILER

#ifdef __cplusplus
    extern "C" {
#endif

//---------------------------------------------------------------------------
#define TICKS_PER_OVERFLOW              (256)
#define CLOCK_DIVIDE                    (8)

//---------------------------------------------------------------------------
/*!
    System profiling timer interface
*/

/*!
    \fn void Init()

    Initialize the global system profiler.  Must be
    called prior to use.
*/
void Profiler_Init( void );

/*!
    \fn void Start()

    Start the global profiling timer service.
*/
void Profiler_Start( void );

/*!
    \fn void Stop()

    Stop the global profiling timer service
*/
void Profiler_Stop( void );

/*!
    \fn K_USHORT Read()

    Read the current tick count in the timer.
*/
K_USHORT Profiler_Read( void );

/*!
    Process the profiling counters from ISR.
*/
void Profiler_Process( void );

/*!
    Return the current timer epoch
*/
K_ULONG Profiler_GetEpoch( void );

#ifdef __cplusplus
    }
#endif

#endif //KERNEL_USE_PROFILER

#endif


text:
This is the heart of my Telegram Bot Randommet.

## Features
This is the translation of the help message

- Oracle: end the phrase with "?".
  Example: _Should I Study today?_
- List: write some choices divided by comma ",". It will choose the best choice.
  Example: _cinema, bowling, pub_
- Numbers: "_Choose a number between 0 and 25_", "_Choose 6 numbers without repetitions between 1 and 90_", "_Choose twelve numbers_", "_Choose a number until 10_".
- Colors: "_Choose a color_"

Remember to call Randommet if you want to use it in a group. You can do that writing `/rm@[bot.username]` at the beginning of the message. Change `bot.username` with the name of your modded bot.

## Requirements

- Python 3
- [python-telegram-bot](https://github.com/python-telegram-bot/python-telegram-bot)

## Getting started

Install dependencies

```$ pip install -r requirements.txt```

Add your token bot in the environment variable `TELEGRAM_TOKEN`

Start it

```$ python3 randommet.py```

In production mode use it instead (no log, you can close your terminal):

```nohup python3 randommet.py  </dev/null >/dev/null 2>&1```

Enjoy!

## Docker

```docker run -d --restart always -e TELEGRAM_TOKEN='<YOUR_TELEGRAM_TOKEN>' matitalatina/randommet-telegram```

## FAQ

- _Why does the bot reply in Italian?!_ Because all my friends and I are Italians! But I wrote the code in English, so feel free to change the reply messages with your language! ;)


text:
[![NuGet version](https://img.shields.io/nuget/v/HumanBytes.svg?logo=nuget)](https://www.nuget.org/packages/HumanBytes)
[![AppVeyor build](https://img.shields.io/appveyor/ci/thomaslevesque/humanbytes.svg?logo=appveyor)](https://ci.appveyor.com/project/thomaslevesque/humanbytes)
[![AppVeyor tests](https://img.shields.io/appveyor/tests/thomaslevesque/humanbytes.svg?logo=appveyor)](https://ci.appveyor.com/project/thomaslevesque/humanbytes/build/tests)

A library to convert byte sizes to a human readable form.

## Installation

Install the library via NuGet

```
PM> Install-Package HumanBytes
```

## Basic usage

The `Bytes` extension method returns an object that has a human readable string representation:

```csharp
var f = new FileInfo("TheFile.jpg");
Console.WriteLine($"The size of '{f.Name}' is {f.Length.Bytes()}");
// Prints "The size of 'TheFile.jpg' is 89 KB"
```

The value is formatted using the default formatter; you can change the default formatter settings through the `ByteSizeFormatter.Default` static property.

## More advanced usage

If you need more control, create an instance of `ByteSizeFormatter` and change its settings:

```csharp
var formatter = new ByteSizeFormatter
{
    Convention = ByteSizeConvention.Binary,
    DecimalPlaces = 1,
    NumberFormat = "#,##0.###",
    MinUnit = ByteSizeUnit.Kilobyte,
    MaxUnit = ByteSizeUnit.Gigabyte,
    RoundingRule = ByteSizeRounding.Closest,
    UseFullWordForBytes = true,
};

var f = new FileInfo("TheFile.jpg");
Console.WriteLine($"The size of '{f.Name}' is {formatter.Format(f.Length)}");
// Prints "The size of 'TheFile.jpg' is 88.7 KiB"
```

## Localization

At this stage, HumanBytes only supports English and French. However, if you need support for another language, it's very easy, as there are only 3 terms that need to be translated. Just create an instance of `ByteSizeFormatter` as shown above, and set the following properties:

- `ByteSymbol`: the symbol for byte, e.g. "B" in English.
- `ByteWord`: the word for byte, e.g. "byte" in English.
- `BytesWord`: the word for several bytes, e.g. "bytes" in English.

The values set on these properties will be used instead of the ones defined in resources.

If you would like to add permanent support for another language, you'll have to modify the library itself. Just clone the project, add a `Resources.xx.resx` file (where `xx` is the language code) in the `HumanBytes/Properties` folder, translate the terms, and build.

I'll be glad to accept pull requests to support more languages.


text:
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <link rel="SHORTCUT ICON" href="https://issues.apache.org/jira/secure/attachment/12322581/12322581_final_logo64.png">

<title>Building Derby</title>

Building Derby

About This Document

Downloads

Simple Build

Verifying the Build

Testing Derby

Customized Build

Advanced Build

About This Document

These are the instructions for building the Derby jar files
from the Derby sources.

Downloads

Before building Derby, you need to download the following:

      Prerequisite
      Description

      Derby Source

If you are reading these instructions, chances
  are you have already unpacked a Derby source distribution. However,
  if you don't have the Derby source yet, get the development source tree from subversion by following these
      instructions.

      Java Development Kit
      You need to install a Java 5 or later JDK. Probably, your machine
      already has this JDK. If not, Sun and IBM supply free JDKs for many machines.

      Ant
      You need to install the Ant build tool, version 1.7.0 or
      higher. You can get Ant here.

If you are going to run the Derby tests, then you will need to download the JUnit
test harness also:

      Prerequisite
      Description

      JUnit
      You need the JUnit test tool, version 3.8.2.
      You can get JUnit 3.8.2 here.
      Copy junit.jar into your Derby source tree, in the
      tools/java directory.

Simple Build

Before building Derby, cd
to the root of your Derby source distribution. That is the top level
directory which contains the LICENSE and NOTICE files. In addition,
make sure that the version of Java which you are using is Java 5 or
later. You can verify this by checking the output of the following command:

java -version

Now use the following Ant targets to build Derby.:

      Target
      Description
      Command

      clobber
      This target deletes all build artifacts.

ant -quiet clobber

      buildsource
      This target compiles all source files needed for the Derby
      product. Don't be alarmed by all of the compiler warnings. We'll
      show you how to tidy those up later on.

ant -quiet buildsource

      buildjars
      This target builds the Derby jar files.

ant -quiet buildjars

So, do this:

ant -quiet clobber
ant -quiet buildsource
ant -quiet buildjars

In order to build the Derby javadoc, you will need to run another target:

      Target
      Description
      Command

      javadoc
      This target builds the Derby javadoc. Be patient. The
      javadoc target takes a while.

ant -quiet javadoc

Verifying the Build

Run the sysinfo command to verify that the jars built
correctly. This program will print out the Derby build information:

java -jar jars/sane/derbyrun.jar sysinfo

Testing Derby

If you want to build and run the Derby tests, make sure that you have downloaded
the
JUnit
test framework. Then build all of the Derby sources, including the test classes:

      Target
      Description
      Command

      all
      This target compiles all Derby source files.

ant -quiet all

Putting all of this together, here's how you build the tests:

ant -quiet clobber
ant -quiet all
ant -quiet buildjars

To run the tests, consult the testing
README.

Customized Build

You can customize the Derby build by setting variables in a file
called ant.properties. The Ant tool looks for this file in your
home directory.
To find out where Ant thinks your home directory is,
issue the following command and look for "user.home" in the output:

ant -diagnostics

Alternatively, or additionally, you can place properties in a file called 'local.properties' in the top of the source tree. Properties placed in this file have precedence over those in user.home/ant.properties.

Here are some Derby-specific variables which you may want to set in ant.properties:

      Variable
      Description
      Default
      Example

      deprecation
      Turn this flag off if you don't want to see pages of
      warnings generated when the compiler encounters references to
      deprecated methods.

on

deprecation=off

      sane
      By default, this variable is set to true. This builds
      extra assertion and debugging logic into Derby classes. If you
      set this variable to false, then the Derby jar files will be
      smaller and Derby will run faster. During typical development,
      you will leave this variable set to true. However, this
      variable is set to false when building official Derby releases.

true

sane=false

Advanced Build

Derby is supposed to run in all of the following environments:

      Platform
      JDBC Level

      Java 6
      JDBC 4

      Java 5
      JDBC 3

      JDK 1.4.2
      JDBC 3

      Small Device (CDC/FP 1.1)
      JSR169

The default Derby build does NOT necessarily verify that the compile-time contract is
satisifed for any of these platforms. To get compile-time checks, you
need to make sure that the following variables are set correctly. To
see the values which the Derby build uses for these variables, build
Derby after setting the
following debug variable in your ant.properties:

printCompilerProperties=true

Here are the variables which determine whether the Derby build
enforces compile-time contracts for the supported platforms:

      Platform
      Compiler Variable
      Description
      Default Value

      Java 6
      java16compile.classpath
      The Derby build tries to find a Java 6
      JDK on your machine. The build fails if it can't find a Java 5
      or Java 6 JDK.
      The list of jars in your Java 6 JDK if the build can find them. Otherwise,
      classes/stubs/jdbc4:${java15compile.classpath}

      Java 5
      java15compile.classpath
      The Derby build tries to find a Java 5
      JDK on your machine. The build fails if it can't find a Java 5
      or Java 6 JDK.
      The list of jars in your Java 5 JDK if the build can find them. Otherwise,
      classes/stubs/jdbc3:${java16compile.classpath}

      JDK 1.4.2
      java14compile.classpath
      The Derby build tries to find a 1.4 JDK
      on your machine. Note that Sun and IBM supply free 1.4.2 JDKs for many machines.
      The list of jars in your 1.4 JDK if the build can find
      them. Otherwise,
      ${java15compile.classpath}

      Small Device (CDC/FP 1.1)
      jsr169compile.classpath
      This should be set to the list of small device libraries on
      your machine--if you have them. That is, the CDC/FP 1.1 jars and
      the jsr169 jar. To get a set of small device libraries, see
      Sun's instructions
      or download IBM's WCTME 5.7.

      classes/stubs/jsr169:${java14compile.classpath}

The preceding variables are mandatory for the Derby build.
For Mac OS X, Solaris, and many Linux and IBM machines, Derby
can figure out where the JDKs live and can therefore set the
preceding variables to reasonable values if you don't set them. For
other platforms, the Derby build may not be able to figure out where the JDKs
live. On those platforms, you can help the Derby build by setting the following optional
variables in ant.properties:

      Compiler Variable
      Description
      Default Value

      j14lib
      If you set this variable to be the directory which contains
      your 1.4 jars, then the Derby build will set
      java14compile.classpath to be the list of jars in that directory.

      Optional variable. No default value.

      j15lib
      If you set this variable to be the directory which contains
      your Java 5 jars, then the Derby build will set
      java15compile.classpath to be the list of jars in that directory.

      Optional variable. No default value.

      j16lib
      If you set this variable to be the directory which contains
      your Java 6 jars, then the Derby build will set
      java16compile.classpath to be the list of jars in that directory.

      Optional variable. No default value.

Here, for instance, are some sample settings of classpath
variables (you should omit the \ continuation markers, which are
included in these examples
simply to improve readability):

java16compile.classpath=/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Classes/charsets.jar: \
    /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Classes/classes.jar: \
    /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Classes/dt.jar: \
    /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Classes/jce.jar: \
    /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Classes/jconsole.jar: \
    /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Classes/jsse.jar: \
    /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Classes/laf.jar: \
    /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Classes/management-agent: \
    /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Classes/ui.jar

jsr169compile.classpath=/Users/myself/sw/phoneME/phoneme_advanced_mr2/lib/btclasses.zip: \
    /Users/myself/sw/phoneME/phoneme_advanced_mr2/lib/basis.jar: \
    /Users/myself/sw/jsr169Support/jdbc.jar


text:
"""
Created on 2 Apr 2018

@author: Bruno Beloff (bruno.beloff@southcoastscience.com)

example document:
{"endpoint": "xy1eszuu23.execute-api.us-west-2.amazonaws.com", "api-key": "de92c5ff-b47a-4cc4-a04c-62d684d74a1f"}
"""

from collections import OrderedDict

from scs_core.data.json import PersistentJSONable

# --------------------------------------------------------------------------------------------------------------------

class APIAuth(PersistentJSONable):
    """
    classdocs
    """

    __FILENAME = "aws_api_auth.json"

    @classmethod
    def persistence_location(cls):
        return cls.aws_dir(), cls.__FILENAME

    # ----------------------------------------------------------------------------------------------------------------

    @classmethod
    def construct_from_jdict(cls, jdict, skeleton=False):
        if not jdict:
            return None

        endpoint = jdict.get('endpoint')
        api_key = jdict.get('api-key')

        return cls(endpoint, api_key)

    # ----------------------------------------------------------------------------------------------------------------

    def __init__(self, endpoint, api_key):
        """
        Constructor
        """
        super().__init__()

        self.__endpoint = endpoint              # String
        self.__api_key = api_key                # String

    def __eq__(self, other):
        try:
            return self.endpoint == other.endpoint and self.api_key == other.api_key

        except (TypeError, AttributeError):
            return False

    # ----------------------------------------------------------------------------------------------------------------

    def as_json(self):
        jdict = OrderedDict()

        jdict['endpoint'] = self.endpoint
        jdict['api-key'] = self.api_key

        return jdict

    # ----------------------------------------------------------------------------------------------------------------

    @property
    def endpoint(self):
        return self.__endpoint

    @property
    def api_key(self):
        return self.__api_key

    # ----------------------------------------------------------------------------------------------------------------

    def __str__(self, *args, **kwargs):
        return "APIAuth:{endpoint:%s, api_key:%s}" % (self.endpoint, self.api_key)


text:
package com.renren.Wario.config;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.renren.Wario.db.MySQLHelper;

public class ConfigLoader {

	private static Logger logger = LogManager.getLogger(ConfigLoader.class
			.getName());

	private static String MAILSENDER;
	private static String MSGSENDER;

	// used for singleton
	private static ConfigLoader configLoader = null;

	private Map<Integer, JSONObject> serverObjects = new HashMap<Integer, JSONObject>();
	private Map<String, JSONArray> pluginObjects = new HashMap<String, JSONArray>();

	/**
	 * @return the serverObjects
	 */
	public Map<Integer, JSONObject> getServerObjects() {
		return serverObjects;
	}

	/**
	 * @return the pluginObjects
	 */
	public Map<String, JSONArray> getPluginObjects() {
		return pluginObjects;
	}

	private ConfigLoader() {
		MAILSENDER = ApplicationProperties.getDefaultMailsender();
		MSGSENDER = ApplicationProperties.getDefaultMsgsender();
	}

	public static synchronized ConfigLoader getInstance() {
		if (configLoader == null) {
			configLoader = new ConfigLoader();
		}
		return configLoader;
	}

	public void loadConfig() {

		try {

			loadServerConfig();

			loadPluginConfig();

		} catch (JSONException e) {
			logger.error("Load config failed! ", e);
		}
	}

	private void loadServerConfig() throws JSONException {

		Map<Integer, JSONObject> tmpServerObjects = new HashMap<Integer, JSONObject>();
		MySQLHelper helper = new MySQLHelper();
		String sql = "select id, zk_name, session_timeout, observer, observer_auth from mario_zk_info";
		try {
			helper.open();
			ResultSet rs = helper.executeQuery(sql);
			while (rs.next()) {
				int id = rs.getInt("id");
				JSONArray serverIPList = getserverIPList(id);
				int sessionTimeout = rs.getInt("session_timeout");
				String observer = rs.getString("observer").trim();
				String observerAuth = rs.getString("observer_auth").trim();

				JSONObject serverObject = new JSONObject();
				serverObject.put("serverIPList", serverIPList);
				serverObject.put("sessionTimeout", sessionTimeout);
				serverObject.put("observer", observer);
				serverObject.put("observerAuth", observerAuth);

				tmpServerObjects.put(id, serverObject);
			}
		} catch (SQLException e) {
			logger.error("MysqlHelper open failed or execute sql " + sql
					+ " failed! ", e);
		} catch (ClassNotFoundException e) {
			logger.error("MysqlHelper open failed! ", e);
		} finally {
			try {
				helper.close();
			} catch (SQLException e) {
				logger.error("MysqlHelper close failed! ", e);
			}
		}
		serverObjects = tmpServerObjects;
	}

	private JSONArray getserverIPList(int zkId) {
		JSONArray serverIPList = new JSONArray();
		MySQLHelper helper = new MySQLHelper();
		String sql = "select id, host, port from mario_server_info "
				+ "where zk_id = " + zkId;
		try {
			helper.open();
			ResultSet rs = helper.executeQuery(sql);
			while (rs.next()) {
				String host = rs.getString("host").trim();
				int port = rs.getInt("port");
				serverIPList.put(host + ":" + port);
			}
		} catch (SQLException e) {
			logger.error("MysqlHelper open failed or execute sql " + sql
					+ " failed! ", e);
		} catch (ClassNotFoundException e) {
			logger.error("MysqlHelper open failed! " , e);
		} finally {
			try {
				helper.close();
			} catch (SQLException e) {
				logger.error("MysqlHelper close failed! " , e);
			}
		}
		return serverIPList;
	}

	private void loadPluginConfig() throws JSONException {
		Map<String, JSONArray> tmpPluginObjects = new HashMap<String, JSONArray>();
		MySQLHelper helper = new MySQLHelper();
		String sql = "select distinct plugin_name from mario_plugin_info";
		try {
			helper.open();
			ResultSet rs = helper.executeQuery(sql);
			while (rs.next()) {
				String pluginName = rs.getString("plugin_name");
				tmpPluginObjects.put(pluginName, getZKArrayRunsOnPlugin(pluginName));
			}
			// Run DBPlugin and RulePlugin on all zk.
			JSONArray allZKArray = getAllZKArray();
			tmpPluginObjects.put("DBPlugin", allZKArray);
			tmpPluginObjects.put("RulePlugin", allZKArray);
		} catch (SQLException e) {
			logger.error("MysqlHelper open failed or execute sql " + sql
					+ " failed! " , e);
		} catch (ClassNotFoundException e) {
			logger.error("MysqlHelper open failed! " , e);
		} finally {
			try {
				helper.close();
			} catch (SQLException e) {
				logger.error("MysqlHelper close failed! " , e);
			}
		}
		pluginObjects = tmpPluginObjects;
	}

	private JSONArray getZKArrayRunsOnPlugin(String pluginName) throws JSONException {
		JSONArray arrary = new JSONArray();
		MySQLHelper helper = new MySQLHelper();
		String sql = "select zk_id, msg_sender, mail_sender, phone_number, email_address, args, commit from mario_plugin_info where plugin_name = '" + pluginName + "'";
		try {
			helper.open();
			ResultSet rs = helper.executeQuery(sql);
			while (rs.next()) {
				JSONObject object = new JSONObject();
				object.put("zkId", rs.getInt("zk_id"));
				object.put("msgSender", rs.getString("msg_sender"));
				object.put("mailSender", rs.getString("mail_sender"));
				object.put("phoneNumber", rs.getString("phone_number"));
				object.put("emailAddress", rs.getString("email_address"));
				object.put("args", rs.getString("args").trim());
				object.put("commit", rs.getString("commit").trim());
				arrary.put(object);
			}
		} catch (SQLException e) {
			logger.error("MysqlHelper open failed or execute sql " + sql
					+ " failed! " , e);
		} catch (ClassNotFoundException e) {
			logger.error("MysqlHelper open failed! " , e);
		} finally {
			try {
				helper.close();
			} catch (SQLException e) {
				logger.error("MysqlHelper close failed! " , e);
			}
		}
		return arrary;
	}

	private JSONArray getAllZKArray() throws JSONException {
		JSONArray arrary = new JSONArray();
		Iterator<Entry<Integer, JSONObject>> it = serverObjects.entrySet().iterator();
		while (it.hasNext()) {
			Entry<Integer, JSONObject> entry = it.next();
			JSONObject object = new JSONObject();
			object.put("zkId", entry.getKey());
			object.put("msgSender", MSGSENDER);
			object.put("mailSender", MAILSENDER);
			object.put("phoneNumber", "");
			object.put("emailAddress", "");
			object.put("args", "");
			object.put("commit", "");
			arrary.put(object);
		}
		return arrary;
	}
}


text:
package promotion.sunshine.form;

import javax.validation.constraints.NotNull;

/**
 * Created by wxd on 2017/2/8.
 */
public class GraphicMessageForm {

    @NotNull
    private String[] keywordList;//关键词列表

    @NotNull
    private String title;//图文标题

    @NotNull
    private String description;//图文描述

    @NotNull
    private String url;//图文url

    @NotNull
    private String picUrl;//图片url

    public String[] getKeywordList() {
        return keywordList;
    }

    public String getTitle() {
        return title;
    }

    public String getDescription() {
        return description;
    }

    public String getUrl() {
        return url;
    }

    public void setKeywordList(String[] keywordList) {
        this.keywordList = keywordList;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getPicUrl() {
        return picUrl;
    }

    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }
}


text:
module WulinMaster
  module GridStates
    extend ActiveSupport::Concern

    def states_for_user
      return "false" unless current_user
      current_state = GridState.current(current_user.id, name)
      is_custom_view = check_multiple_grid_states
      if current_state.nil?
        # create a new current grid
        create_current_grid(current_user.id, name)
      else
        current_state.try(:state_value).presence || GridState.get_default_grid_state_val(name, current_state.name, is_custom_view ) || {}.to_json
      end
    rescue StandardError => e
      Rails.logger.info "Exception thrown while trying to get user states: #{e.inspect}"
      "false"
    end

    def create_current_grid(current_user_id, name)
      default_state_value = GridState.get_default_grid_state_val(name)
      state_val = default_state_value ? default_state_value : {}.to_json
      current_state = GridState.find_or_initialize_by(user_id: current_user_id, grid_name: name, state_value: state_val)
      current_state.update(current: true)
      current_state.state_value
    end

    private

    def check_multiple_grid_states
      self.actions.any? { |action| action[:name] == :multiple_grid_states }
    end

  end
end


text:
require 'dohutil/app/init_from_pwd'
require 'dohroot/options'


text:
<?php
  function authenticated_session($username) {
    return sha1(md5($username));
  }
?>