text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * Devicesensoralarmaction Schema
 * This stores what actions can be followed in case of an alarm.
 * If it is cleared a notofication can be sent
 *
 * Actio types can be Email, Sms Or phone
 */
var DevicesensoralarmactionSchema = new Schema({
	name: {
		type: String,
		default: '',
		required: 'Please fill Devicesensoralarmaction name',
		trim: true
	},
	actiontype:{
		type: String,
		trim: true,
		enum:['email','text','phone','alert']
	},
	userid:{
		type:Schema.ObjectId,
		ref:'User'
	},
	thresholdvaluemin:{
		type: Number
	},
	thresholdvaluemax:{
		type: Number
	},
	sendonclear:{/* this is for sending notifications or not when the alert has been claered*/
		type: Boolean,
		default: false
	},
	usertonotify:{
		type: Schema.ObjectId,
		ref: 'User'
	},
	userstonotify:[{
		type: Schema.ObjectId,
		ref: 'User'
	}],
	created: {
		type: Date,
		default: Date.now
	},
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	}
});

mongoose.model('Devicesensoralarmaction', DevicesensoralarmactionSchema);


text:
/*
 * $Id$
 */
package com.ivstars.astrology.util;

import junit.framework.TestCase;

import java.util.TimeZone;
import java.text.ParseException;

import com.ivstars.astrology.ChartModel;

/**
 * TestCommandParser
 *
 * @author Fengbo Xie (fengbo.xie at gmail.com)
 *         Everything that has a beginning has an end.
 */
public class TestCommandParser extends TestCase {
    public void testTimeZoneId(){
        System.out.println(TimeZone.getTimeZone("-8:00"));

        System.out.println(TimeZone.getTimeZone("GMT-8:00"));
    }
    public void testParse() throws ParseException {
        ChartModel model =CommandParser.parse("-qb 10 28 1955 22:00 ST +8:00 122:20W 47:36N");
        System.out.println("TimeZone:\t"+model.getTimezone());
        assertEquals(TimeZone.getTimeZone("GMT-8:00"),model.getTimezone());
        System.out.println("Date:\t"+model.getFormatDate());
        System.out.println("Location:\t"+model.getLocation());
        assertEquals(47.6,model.getLatitude());
        assertTrue(Math.abs(-122.33-model.getLongitude())<0.01);

    }
}

redpajama_set_name: RedPajamaGithub


text:
title: Viewing Server Configuration Parameter Settings
---

The SQL command `SHOW` allows you to see the current server configuration parameter settings. For example, to see the settings for all parameters:

```
$ psql -c 'SHOW ALL;'
```

`SHOW` lists the settings for the master instance only. To see the value of a particular parameter across the entire system \(master and all segments\), use the `gpconfig` utility. For example:

```
$ gpconfig --show max_connections
```

**Parent topic:** [Configuring the Greenplum Database System](../topics/g-configuring-the-greenplum-system.html)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Rhaphidophora montellica Sacc.

### Remarks
null


text:
/*global jsonpfu */

/**
 * @fileoverview Used to make a {@link http://developer.yahoo.com/yql/ YQL query}
 *
 * @author Ryan LeFevre meltingice@meltingice.net
 * @version 1.0
 */

/**
 * Name: Yahoo Query Language
 * Usage:
 *	jfu.lib('yql').query(query);
 *
 * Example:
 *	jfu.lib('yql').query("select * from flickr.photos.recent", function (data) {
 *		console.log(data.results());
 *	});
 */

jsonpfu.extend('yql', function (opts, script) {

	// API helper methods for validation and querying
	var API = {
		query: function (query, query_opts, callback) {
			var query_url = 'http://query.yahooapis.com/v1/public/yql',
				data = query_opts;

			if (!query || query.length === 0) {
				throw "Missing or invalid YQL query";
			}

			data.format = 'json';
			data.q = query;

			if (opts.diagnostics && data.diagnostics === null) {
				data.diagnostics = true;
			}
			if (opts.debug && data.debug === null) {
				data.debug = true;
			}
			if (opts.env && data.env === null) {
				data.env = opts.env;
			}

			script.jsonp_query({
				url: query_url,
				data: data,
				success: function (data) {
					callback(data);
				}
			});
		}
	};

	return {
		query: function (query, opts, callback) {
			if (typeof(opts) === 'function') {
				callback = opts;
				opts = {};
			}

			API.query(query, opts, callback);
		},

		select: function (select) {
			return new YQLQuery(select);
		}
	};

});

function YQLQuery(select) {
	this.data = {
		select: select,
		from: "",
		where: [],
		env: [],
		limit: null,
		offset: 0,
		sort: []
	};

	this.query_results = null;
}

YQLQuery.prototype.from = function (from) {
	this.data.from = from;
	return this;
};

YQLQuery.prototype.where = function (where) {
	this.data.where.push(where);
	return this;
};

YQLQuery.prototype.addEnv = function (env) {
	this.data.env.push(env);
	return this;
};

YQLQuery.prototype.limit = function (limit) {
	this.data.limit = limit;
	return this;
};

YQLQuery.prototype.offset = function (offset) {
	this.data.offset = offset;
	return this;
};

YQLQuery.prototype.sort = function (field, desc) {
	if (!desc) {
		desc = 'false';
	}

	this.data.sort.push('sort(field="' + field + '", descending="' + desc + '")');
	return this;
};

YQLQuery.prototype.tail = function (count) {
	this.data.sort.push('tail(count=' + count + ')');
	return this;
};

YQLQuery.prototype.truncate = function (count) {
	this.data.sort.push('truncate(count=' + count + ')');
	return this;
};

YQLQuery.prototype.reverse = function () {
	this.data.sort.push('reverse()');
	return this;
};

YQLQuery.prototype.unique = function (field) {
	this.data.sort.push('unique(field="' + field + '")');
	return this;
};

YQLQuery.prototype.sanitize = function (field) {
	this.data.sort.push("sanitize(field='" + field + '")');
	return this;
};

YQLQuery.prototype.results = function () {
	return this.query_results.query.results;
};

YQLQuery.prototype.query = function (opts, callback) {
	var query = "SELECT ",
		that = this;

	if (typeof(opts) === 'function') {
		callback = opts;
		opts = {};
	}

	query += this.data.select;
	query += " FROM ";
	query += this.data.from;

	if (this.data.where.length > 0) {
		query += " WHERE ";
		query += this.data.where.join(' AND ');
	}

	if (this.data.limit) {
		query += " LIMIT " + this.data.limit;
	}

	if (this.data.offset && this.data.offset > 0) {
		query += " OFFSET " + this.data.offset;
	}

	if (this.data.sort.length > 0) {
		query += " | " + this.data.sort.join("|");
	}

	jfu.lib('yql').query(query, opts, function (data) {
		that.query_results = data;
		callback(that, data);
	});
};


text:
package dcd.academic.action;

import java.util.ArrayList;
import java.util.List;

import dcd.academic.model.PaperModel;
import dcd.academic.model.PublicationModel;
import dcd.academic.model.ResearcherModel;
import dcd.academic.solrj.SolrjHelper;
import dcd.academic.model.TotalListMap;

import com.opensymphony.xwork2.ActionSupport;

/**
 *
 * @author pelick
 * 对应index.jsp的三个主要搜索功能。core0,core1,core2分别对应学者元数据,论文元数据,全文
 */
public class AcademicAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	// 前端传参
	private String key;
	private String core;
	private String field = "";
	private String workplace = "";

	// 默认
	private int start = 0;
	private int rows = 20;
	private long total;

	// 返回到index.jsp页面的参数
	private String nextUrl;
	private String preUrl;
	private int curNum;
	private int curPage;
	private int allPage;
	public List<ResearcherModel> authorlist = new ArrayList<ResearcherModel>();
	public List<PublicationModel> paperlist = new ArrayList<PublicationModel>();
	public List<PaperModel> paperfulllist = new ArrayList<PaperModel>();

	public String execute(){

		// 封装后的solr类
		SolrjHelper solr = null;
		/**
		 * 根据core的不同取值,采取不同的搜索接口
		 */
		if (core.equals("core0")) {
			solr = new SolrjHelper(0);
			TotalListMap map = solr.getAuthorMetaList("name", key, field, workplace, start, rows);
			authorlist = map.getList();
			total = map.getTotal();
		} else if (core.equals("core1")) {
			solr = new SolrjHelper(1);
			TotalListMap map = solr.getPaperMetaList("title", key, start, rows);
			paperlist = map.getList();
			total = map.getTotal();
		} else if (core.equals("core2")) {
			solr = new SolrjHelper(2);
			TotalListMap map = solr.getPaperFullList("text", key, start, rows);
			paperfulllist = map.getList();
			total = map.getTotal();
		}

		// condition给搜索请求参数增加了研究领域或工作地的限制,本质是加了搜索参数
		String condition = null;
		if (field.equals("") && workplace.equals("")) {
			condition = "";
		} else if (workplace.equals("")) {
			condition = "&field="+field.replaceAll(" ", "+");
		} else if (field.equals("")) {
			condition = "&workplace="+workplace.replaceAll(" ", "+");
		} else {
			condition = "&field="+field.replaceAll(" ", "+")+"&workplace="+workplace.replaceAll(" ", "+");
		}

		// 给翻页参数赋值,翻页是另一次搜索请求,区别在于start值
		if (start + rows <= total) {
			nextUrl = "academic?key="+key.replaceAll(" ", "+")+"&core="+core+condition+"&start="+(start+rows)+"&rows="+rows;
		} else {
			nextUrl = "academic?key="+key.replaceAll(" ", "+")+"&core="+core+condition+"&start="+(start)+"&rows="+rows;
		}
		if (start - rows < 0) {
			preUrl = "academic?key="+key.replaceAll(" ", "+")+"&core="+core+condition+"&start="+(start)+"&rows="+rows;
		} else {
			preUrl = "academic?key="+key.replaceAll(" ", "+")+"&core="+core+condition+"&start="+(start-rows)+"&rows="+rows;
		}

		curNum = (int) ((start+rows) > total? total : (start+rows));
		curPage = start/rows + 1;
		allPage = (int) (total/rows + 1);

		return SUCCESS;
	}

	public String getWorkplace() {
		return workplace;
	}

	public void setWorkplace(String workplace) {
		this.workplace = workplace;
	}

	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}

	public List<PaperModel> getPaperfulllist() {
		return paperfulllist;
	}

	public void setPaperfulllist(List<PaperModel> paperfulllist) {
		this.paperfulllist = paperfulllist;
	}

	public int getCurNum() {
		return curNum;
	}

	public void setCurNum(int curNum) {
		this.curNum = curNum;
	}

	public int getCurPage() {
		return curPage;
	}

	public void setCurPage(int curPage) {
		this.curPage = curPage;
	}

	public int getAllPage() {
		return allPage;
	}

	public void setAllPage(int allPage) {
		this.allPage = allPage;
	}

	public List<ResearcherModel> getAuthorlist() {
		return authorlist;
	}

	public void setAuthorlist(List<ResearcherModel> authorlist) {
		this.authorlist = authorlist;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}
	public String getCore() {
		return core;
	}

	public void setCore(String core) {
		this.core = core;
	}

	public List<PublicationModel> getPaperlist() {
		return paperlist;
	}

	public void setPaperlist(List<PublicationModel> paperlist) {
		this.paperlist = paperlist;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public long getTotal() {
		return total;
	}

	public void setTotal(long total) {
		this.total = total;
	}

	public String getNextUrl() {
		return nextUrl;
	}

	public void setNextUrl(String nextUrl) {
		this.nextUrl = nextUrl;
	}

	public String getPreUrl() {
		return preUrl;
	}

	public void setPreUrl(String preUrl) {
		this.preUrl = preUrl;
	}

}


text:
<?xml version="1.0"?>
<!-- JBoss, Home of Professional Open Source Copyright 2012, Red Hat, Inc.
    and/or its affiliates, and individual contributors by the @authors tag. See
    the copyright.txt in the distribution for a full listing of individual contributors.
    Licensed under the Apache License, Version 2.0 (the "License"); you may not
    use this file except in compliance with the License. You may obtain a copy
    of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
    by applicable law or agreed to in writing, software distributed under the
    License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
    OF ANY KIND, either express or implied. See the License for the specific
    language governing permissions and limitations under the License. -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>jboss-as-ejb-asynchronous-ejb</artifactId>
    <name>JBoss AS Quickstarts: Asynchronous method invocations (EJB Jar)</name>
    <description>jboss-as-ejb-asynchronous: The application jar with an asynchronous EJB and a second EJB to demonstrate how an EJB can be used asynchronous</description>
    <packaging>ejb</packaging>

    <parent>
        <groupId>org.jboss.as.quickstarts</groupId>
        <artifactId>jboss-as-ejb-asynchronous</artifactId>
        <version>7.1.2-SNAPSHOT</version>
    </parent>

    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <distribution>repo</distribution>
            <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
        </license>
    </licenses>

    <dependencies>
        <dependency>
            <groupId>org.jboss.spec.javax.ejb</groupId>
            <artifactId>jboss-ejb-api_3.1_spec</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-ejb-plugin</artifactId>
                <version>${version.ejb.plugin}</version>
                <configuration>
                    <!-- set the EJB version to 3.1 -->
                    <ejbVersion>3.1</ejbVersion>
                    <!-- Inform Maven we need a client jar -->
                    <generateClient>true</generateClient>
                    <archive>
                        <addMavenDescriptor>false</addMavenDescriptor>
                    </archive>
                </configuration>
            </plugin>

            <!-- JBoss AS plugin to deploy jar -->
            <plugin>
                <groupId>org.jboss.as.plugins</groupId>
                <artifactId>jboss-as-maven-plugin</artifactId>
                <version>${version.org.jboss.as.plugins.maven.plugin}</version>
                <configuration>
                    <filename>${project.build.finalName}.jar</filename>
                    <skip>false</skip>
                </configuration>
            </plugin>

        </plugins>
    </build>
</project>


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#include "AppFrameworkPrivatePCH.h"
#include "SSimpleGradient.h"

/* SSimpleGradient interface
 *****************************************************************************/

void SSimpleGradient::Construct( const FArguments& InArgs )
{
	StartColor = InArgs._StartColor;
	EndColor = InArgs._EndColor;
	bHasAlphaBackground = InArgs._HasAlphaBackground.Get();
	Orientation = InArgs._Orientation.Get();
}

/* SCompoundWidget overrides
 *****************************************************************************/

int32 SSimpleGradient::OnPaint( const FPaintArgs& Args, const FGeometry& AllottedGeometry, const FSlateRect& MyClippingRect, FSlateWindowElementList& OutDrawElements, int32 LayerId, const FWidgetStyle& InWidgetStyle, bool bParentEnabled ) const
{
	const ESlateDrawEffect::Type DrawEffects = this->ShouldBeEnabled(bParentEnabled) ? ESlateDrawEffect::None : ESlateDrawEffect::DisabledEffect;

	if (bHasAlphaBackground)
	{
		const FSlateBrush* StyleInfo = FCoreStyle::Get().GetBrush("ColorPicker.AlphaBackground");

		FSlateDrawElement::MakeBox(
			OutDrawElements,
			LayerId,
			AllottedGeometry.ToPaintGeometry(),
			StyleInfo,
			MyClippingRect,
			DrawEffects
		);
	}

	TArray<FSlateGradientStop> GradientStops;

	GradientStops.Add(FSlateGradientStop(FVector2D::ZeroVector, StartColor.Get()));
	GradientStops.Add(FSlateGradientStop(AllottedGeometry.Size, EndColor.Get()));

	FSlateDrawElement::MakeGradient(
		OutDrawElements,
		LayerId + 1,
		AllottedGeometry.ToPaintGeometry(),
		GradientStops,
		Orientation,
		MyClippingRect,
		DrawEffects,
		false
	);

	return LayerId + 1;
}


text:
        Applications must register to:

Get an Application Security ID

Request Application Authorizations

Register Broadcast Topics for Parsers

Register Data You're Listening For

Register Broadcast Topics for Data Feeds

Register Data Type for Visualization

As long as all of your services, feeds, and web sites can request the same level of authorizations, you'll only need to register once for everything.

        <button type="button" class="btn large-btn" ng-click="continueRegistration(page)">Get Started</button>


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

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Get current column number for an XML parser</title>

xml_get_current_byte_index

xml_get_current_line_number

XML Parser Functions

PHP Manual

xml_get_current_column_number

(PHP 4, PHP 5)

xml_get_current_column_number —
   Get current column number for an XML parser

Description

   int xml_get_current_column_number
    ( resource $parser
   )

   Gets the current column number of the given XML parser.

Parameters

parser

       A reference to the XML parser to get column number from.

Return Values

   This function returns FALSE if parser does
   not refer to a valid parser, or else it returns which column on
   the current line (as given by
   xml_get_current_line_number()) the parser is
   currently at.

See Also

xml_get_current_byte_index() - Get current byte index for an XML parser

xml_get_current_line_number() - Get current line number for an XML parser

xml_get_current_byte_index

xml_get_current_line_number

XML Parser Functions

PHP Manual


text:
<!doctype html>

    <meta charset="utf-8">
    <title>2017-EN-02</title>

Fast Copying

Paint the white boxes containing a circle with black, and leave the other boxes in white.

First click on the "Copy Black Boxes" button, then move the copied pattern with the arrows, then paste this pattern as needed with the "Paste Pattern" button, before using the "Copy Black Boxes" button again.

You can use the "Paste Pattern" button for 7 times only.

                        <input type="button" value="Copy Black Boxes" id="copyAll" />

                           <input type="button" value="Paste Pattern" id="paste" />

                           <input type="button" value="Undo" id="undo" class="medium hard" />

<input type="button" value="Validate" id="execute" />

Solution


text:
from __future__ import division, print_function
from __future__ import absolute_import

import ujson as json
import os
import sys
import re
import hashlib

from datetime import datetime, timedelta

from . import common

def load( terms = ['.json'], data_dir = '', folder = 'news/' ):

    path = data_dir + folder

    for dirpath, subdirs, files in os.walk(path):

        for f in filter( lambda x: x.endswith('.json'), files ):

            f = os.path.join( dirpath, f )

            if any( term in f for term in terms ):

                for d in json.load( open( f ) ):

                    common_data_keys = {'_author' : 'creator',
                                        '_title' : 'text_content',
                                        '_ingress' : 'text_content',
                                        '_text' : 'text_content',
                                        '_url' : 'url',
                                        '_domain' : 'source_detail'}

                    d = common.__init_harmonize_data( d, 'news_media', common_data_keys )

                    ## ensure data is always in a list
                    if isinstance( d['_datetime_list'] , str):
                        d['_datetime_list'] = [ d['_datetime_list'] ]

                    try:
                        d['timestamp'] = common._text_to_datetime( min( d['_datetime_list'] ), ) ## should take care of the various formats
                    except Exception as e:
                        d['broken']['_datetime_list'] = e

                    d['images'] = d['_images']

                    d = common.__post_harmonize_data( d )
                    yield d


text:
{% load i18n %}
{% trans "Hi" %}
{% if new_article %}{% trans "A new article has been published" %}{% else %}{% trans "An article has been updated" %}{% endif %} {% trans "by"%} {{user.get_full_name}}:

{{story.title}}

{% trans "To read this article, click on the link below " %}:
{{url}}


text:
/*
 * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
 *
 * 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.
 */

package minio

import (
	"crypto/md5"
	"crypto/sha256"
	"fmt"
	"hash"
	"io"
	"math"
	"os"
)

// Verify if reader is *os.File
func isFile(reader io.Reader) (ok bool) {
	_, ok = reader.(*os.File)
	return
}

// Verify if reader is *minio.Object
func isObject(reader io.Reader) (ok bool) {
	_, ok = reader.(*Object)
	return
}

// Verify if reader is a generic ReaderAt
func isReadAt(reader io.Reader) (ok bool) {
	_, ok = reader.(io.ReaderAt)
	return
}

// shouldUploadPart - verify if part should be uploaded.
func shouldUploadPart(objPart objectPart, objectParts map[int]objectPart) bool {
	// If part not found should upload the part.
	uploadedPart, found := objectParts[objPart.PartNumber]
	if !found {
		return true
	}
	// if size mismatches should upload the part.
	if objPart.Size != uploadedPart.Size {
		return true
	}
	// if md5sum mismatches should upload the part.
	if objPart.ETag != uploadedPart.ETag {
		return true
	}
	return false
}

// optimalPartInfo - calculate the optimal part info for a given
// object size.
//
// NOTE: Assumption here is that for any object to be uploaded to any S3 compatible
// object storage it will have the following parameters as constants.
//
//  maxPartsCount - 10000
//  minPartSize - 5MiB
//  maxMultipartPutObjectSize - 5TiB
//
func optimalPartInfo(objectSize int64) (totalPartsCount int, partSize int64, lastPartSize int64, err error) {
	// object size is '-1' set it to 5TiB.
	if objectSize == -1 {
		objectSize = maxMultipartPutObjectSize
	}
	// object size is larger than supported maximum.
	if objectSize > maxMultipartPutObjectSize {
		err = ErrEntityTooLarge(objectSize, maxMultipartPutObjectSize, "", "")
		return
	}
	// Use floats for part size for all calculations to avoid
	// overflows during float64 to int64 conversions.
	partSizeFlt := math.Ceil(float64(objectSize / maxPartsCount))
	partSizeFlt = math.Ceil(partSizeFlt/minPartSize) * minPartSize
	// Total parts count.
	totalPartsCount = int(math.Ceil(float64(objectSize) / partSizeFlt))
	// Part size.
	partSize = int64(partSizeFlt)
	// Last part size.
	lastPartSize = objectSize - int64(totalPartsCount-1)*partSize
	return totalPartsCount, partSize, lastPartSize, nil
}

// hashCopyBuffer is identical to hashCopyN except that it doesn't take
// any size argument but takes a buffer argument and reader should be
// of io.ReaderAt interface.
//
// Stages reads from offsets into the buffer, if buffer is nil it is
// initialized to optimalBufferSize.
func (c Client) hashCopyBuffer(writer io.Writer, reader io.ReaderAt, buf []byte) (md5Sum, sha256Sum []byte, size int64, err error) {
	// MD5 and SHA256 hasher.
	var hashMD5, hashSHA256 hash.Hash
	// MD5 and SHA256 hasher.
	hashMD5 = md5.New()
	hashWriter := io.MultiWriter(writer, hashMD5)
	if c.signature.isV4() {
		hashSHA256 = sha256.New()
		hashWriter = io.MultiWriter(writer, hashMD5, hashSHA256)
	}

	// Buffer is nil, initialize.
	if buf == nil {
		buf = make([]byte, optimalReadBufferSize)
	}

	// Offset to start reading from.
	var readAtOffset int64

	// Following block reads data at an offset from the input
	// reader and copies data to into local temporary file.
	for {
		readAtSize, rerr := reader.ReadAt(buf, readAtOffset)
		if rerr != nil {
			if rerr != io.EOF {
				return nil, nil, 0, rerr
			}
		}
		writeSize, werr := hashWriter.Write(buf[:readAtSize])
		if werr != nil {
			return nil, nil, 0, werr
		}
		if readAtSize != writeSize {
			return nil, nil, 0, fmt.Errorf("Read size was not completely written to writer. wanted %d, got %d - %s", readAtSize, writeSize, reportIssue)
		}
		readAtOffset += int64(writeSize)
		size += int64(writeSize)
		if rerr == io.EOF {
			break
		}
	}

	// Finalize md5 sum and sha256 sum.
	md5Sum = hashMD5.Sum(nil)
	if c.signature.isV4() {
		sha256Sum = hashSHA256.Sum(nil)
	}
	return md5Sum, sha256Sum, size, err
}

// hashCopy is identical to hashCopyN except that it doesn't take
// any size argument.
func (c Client) hashCopy(writer io.Writer, reader io.Reader) (md5Sum, sha256Sum []byte, size int64, err error) {
	// MD5 and SHA256 hasher.
	var hashMD5, hashSHA256 hash.Hash
	// MD5 and SHA256 hasher.
	hashMD5 = md5.New()
	hashWriter := io.MultiWriter(writer, hashMD5)
	if c.signature.isV4() {
		hashSHA256 = sha256.New()
		hashWriter = io.MultiWriter(writer, hashMD5, hashSHA256)
	}

	// Using copyBuffer to copy in large buffers, default buffer
	// for io.Copy of 32KiB is too small.
	size, err = io.Copy(hashWriter, reader)
	if err != nil {
		return nil, nil, 0, err
	}

	// Finalize md5 sum and sha256 sum.
	md5Sum = hashMD5.Sum(nil)
	if c.signature.isV4() {
		sha256Sum = hashSHA256.Sum(nil)
	}
	return md5Sum, sha256Sum, size, err
}

// hashCopyN - Calculates Md5sum and SHA256sum for up to partSize amount of bytes.
func (c Client) hashCopyN(writer io.Writer, reader io.Reader, partSize int64) (md5Sum, sha256Sum []byte, size int64, err error) {
	// MD5 and SHA256 hasher.
	var hashMD5, hashSHA256 hash.Hash
	// MD5 and SHA256 hasher.
	hashMD5 = md5.New()
	hashWriter := io.MultiWriter(writer, hashMD5)
	if c.signature.isV4() {
		hashSHA256 = sha256.New()
		hashWriter = io.MultiWriter(writer, hashMD5, hashSHA256)
	}

	// Copies to input at writer.
	size, err = io.CopyN(hashWriter, reader, partSize)
	if err != nil {
		// If not EOF return error right here.
		if err != io.EOF {
			return nil, nil, 0, err
		}
	}

	// Finalize md5shum and sha256 sum.
	md5Sum = hashMD5.Sum(nil)
	if c.signature.isV4() {
		sha256Sum = hashSHA256.Sum(nil)
	}
	return md5Sum, sha256Sum, size, err
}

// getUploadID - fetch upload id if already present for an object name
// or initiate a new request to fetch a new upload id.
func (c Client) getUploadID(bucketName, objectName, contentType string) (uploadID string, isNew bool, err error) {
	// Input validation.
	if err := isValidBucketName(bucketName); err != nil {
		return "", false, err
	}
	if err := isValidObjectName(objectName); err != nil {
		return "", false, err
	}

	// Set content Type to default if empty string.
	if contentType == "" {
		contentType = "application/octet-stream"
	}

	// Find upload id for previous upload for an object.
	uploadID, err = c.findUploadID(bucketName, objectName)
	if err != nil {
		return "", false, err
	}
	if uploadID == "" {
		// Initiate multipart upload for an object.
		initMultipartUploadResult, err := c.initiateMultipartUpload(bucketName, objectName, contentType)
		if err != nil {
			return "", false, err
		}
		// Save the new upload id.
		uploadID = initMultipartUploadResult.UploadID
		// Indicate that this is a new upload id.
		isNew = true
	}
	return uploadID, isNew, nil
}

// computeHash - Calculates MD5 and SHA256 for an input read Seeker.
func (c Client) computeHash(reader io.ReadSeeker) (md5Sum, sha256Sum []byte, size int64, err error) {
	// MD5 and SHA256 hasher.
	var hashMD5, hashSHA256 hash.Hash
	// MD5 and SHA256 hasher.
	hashMD5 = md5.New()
	hashWriter := io.MultiWriter(hashMD5)
	if c.signature.isV4() {
		hashSHA256 = sha256.New()
		hashWriter = io.MultiWriter(hashMD5, hashSHA256)
	}

	// If no buffer is provided, no need to allocate just use io.Copy.
	size, err = io.Copy(hashWriter, reader)
	if err != nil {
		return nil, nil, 0, err
	}

	// Seek back reader to the beginning location.
	if _, err := reader.Seek(0, 0); err != nil {
		return nil, nil, 0, err
	}

	// Finalize md5shum and sha256 sum.
	md5Sum = hashMD5.Sum(nil)
	if c.signature.isV4() {
		sha256Sum = hashSHA256.Sum(nil)
	}
	return md5Sum, sha256Sum, size, nil
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ShootR
{
    public partial class Login : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void TwitterLoginButton_Click(object sender, EventArgs e)
        {
            Context.Request.GetOwinContext().Authentication.Challenge(new string[] { "Twitter" });
        }

        protected void GoogleLoginButton_Click(object sender, EventArgs e)
        {
            Context.Request.GetOwinContext().Authentication.Challenge(new string[] { "Google" });
        }

        protected void FacebookLoginButton_Click(object sender, EventArgs e)
        {
            Context.Request.GetOwinContext().Authentication.Challenge(new string[] { "Facebook" });
        }
    }
}


text:
 <item title="True - False" ident="">
	<qticomment>
		This is a simple True/False multiple-choice example using V1.2.
		The rendering is a standard radio button style.
		Response processing is incorporated.
	</qticomment>
	<duration></duration>
	<itemmetadata>
		<qtimetadata>
			<qtimetadatafield>
				<fieldlabel>qmd_itemtype</fieldlabel>
				<fieldentry>True False</fieldentry>
			</qtimetadatafield>
			<qtimetadatafield>
				<fieldlabel>TEXT_FORMAT</fieldlabel>
				<fieldentry>HTML</fieldentry>
			</qtimetadatafield>
			<qtimetadatafield>
        <fieldlabel>ITEM_OBJECTIVE</fieldlabel>
        <fieldentry/>
      </qtimetadatafield>
      <qtimetadatafield>
        <fieldlabel>ITEM_KEYWORD</fieldlabel>
        <fieldentry/>
      </qtimetadatafield>
      <qtimetadatafield>
        <fieldlabel>ITEM_RUBRIC</fieldlabel>
        <fieldentry/>
      </qtimetadatafield>
	  <qtimetadatafield>
		<fieldlabel>ITEM_TAGS</fieldlabel>
		<fieldentry/>
	  </qtimetadatafield>
      <qtimetadatafield>
        <fieldlabel>ATTACHMENT</fieldlabel>
        <fieldentry/>
      </qtimetadatafield>
         <!--rshastri SAK 1824  -->
      <qtimetadatafield>
        <fieldlabel>hasRationale</fieldlabel>
        <fieldentry>false</fieldentry>
      </qtimetadatafield>
		</qtimetadata>
	</itemmetadata>
	<rubric>
      <material>
        <mattext/>
      </material>
    </rubric>
	<presentation label="Resp001">
		<flow>
			<material>
				<mattext></mattext>
			</material>
			<material>
				<matimage imagtype="text/html" uri=""></matimage>
			</material>
			<response_lid ident="TF02" rcardinality="Single">
				<render_choice shuffle="No">
					<response_label ident="A">
						<material>
							<mattext>True</mattext>
						</material>
					</response_label>
					<response_label ident="B">
						<material>
							<mattext>False</mattext>
						</material>
					</response_label>
				</render_choice>
			</response_lid>
		</flow>
	</presentation>
	<resprocessing>
		<outcomes>
			<decvar varname="SCORE" minvalue="0" defaultval="0" maxvalue="0" />
		</outcomes>
		<respcondition continue="No" title="Correct">
			<conditionvar>
				<varequal case="Yes" respident="TF02">A</varequal>
			</conditionvar>
			<setvar varname="SCORE" action="Add">0</setvar>
			<displayfeedback feedbacktype="Response" linkrefid="Correct" />
		</respcondition>
		<respcondition continue="No" title="InCorrect">
			<conditionvar>
				<varequal case="Yes" respident="TF02">B</varequal>
			</conditionvar>
			<setvar varname="SCORE" action="Add">0</setvar>
			<displayfeedback feedbacktype="Response" linkrefid="InCorrect" />
		</respcondition>
	</resprocessing>
	<itemfeedback ident="Correct" view="All">
		<flow_mat>
			<material>
				<mattext></mattext>
			</material>
			<material>
                <matimage imagtype="text/html" uri=""/>
            </material>
		</flow_mat>
	</itemfeedback>
	<itemfeedback ident="InCorrect" view="All">
		<flow_mat>
			<material>
				<mattext></mattext>
			</material>
			<material>
                <matimage imagtype="text/html" uri=""/>
            </material>
		</flow_mat>
	</itemfeedback>
</item>


text:
layout: post
type:
title: "Hukum Murphy"
description: If Anything Can Go Wrong, It Will
headline:
modified:
category: intermezzo
tags: [motivasi, unik]
imagefeature:
imagecredit:
imagecreditlink:
comments: true
mathjax:
---

Dalil Murphy ( Murphy's Law ) memang tidak serupa dengan dalil Archimedes atau dalil Pithagoras misalnya. Dia tidak membutuhkan pembuktian empiris untuk mendukungnya. Namun akurasinya tak perlu diragukan lagi. Dan kalau rumus dalil-dalil ilmu fisika atau mekanika itu bisa membuat kening kita berkerut, maka dalil yang satu ini justru membuat kita tertawa bahkan kadangkala menertawakan diri kita sendiri.

Konon Dalil Murphy ini dipopulerkan pada tahun 1949 oleh seorang perwira Angkatan Udara AS bernama Kapten Edward Murphy yang ditugasi untuk melakukan penelitian akan kemampuan manusia menahan deselerasi mendadak misalnya pada saat tabrakan. Maka lahirlah ungkapannya yang terkenal

> "If anything can go wrong, it will."
>Murphy's Law

(terjemahan bebasnya : Kalau sesuatu bisa jadi berantakan, dia pasti akan)

Kita lihat dari pengalaman sehari-hari. Anda sedang tergesa-gesa hendak membuka pintu gudang yang terkunci. Di tangan anda ada segepok anak kunci yang tidak diberi tanda. Berarti anda harus mencobai satu per satu anak kunci itu. Dan lihatlah anak kunci yang pas untuk membuka pintu itu justru anak kunci yang terakhir dari 10 kunci yang anda coba. Mengapa bukan anak kunci yang kedua atau ketiga, protes anda dalam hati. Inilah yang disebut *Murphy's Law*.

Atau yang lain ini. Anda mencari peniti untuk mengikat kaitan celana yang putus kancingnya. Semua laci dan sudut-sudut lemari sudah anda telusuri namun tetap tidak ketemu. Padahal sehari-hari pada saat anda tidak membutuhkan peniti-peniti itu selalu anda lihat.
Jadi bunyi dalil Murphynya :

> "Semakin dicari sesuatu barang, semakin tidak ketemu barang itu."

Ada rumus lain lagi di bidang perlalu-lintasan.

> "Kalau anda sedang terburu-buru semua lampu lalu-lintas berwarna merah, kalau anda tidak terburu semua lampu berwarna hijau"

Dan mengenai kendaraan :

> "Berapapun panjangnya masa garansi kendaraan anda, pada hari garansi mobil anda habis, mobil anda akan mogok"

Atau dejavu berikut ini :

> "Begitu anda selesai mencuci mobil hujanpun turun. Padahal berhari-hari anda tidak mencuci mobil cuaca panas terik.
Mencuci mobil identik dengan ritual tarian hujan orang Indian yang memanggil dewa hujan.

Dan yang ini :

> "Ban mobil akan kempes pada saat anda tidak membawa ban serep"

Dalil Murphy ini memang mencakup segala aspek kehidupan manusia dan kadang-kadang disertai pula dengan simbol-simbol matematika. Coba kita lihat salah satu 'rumus' yang berbicara tentang kecantikan wanita.

> "Cantik dari jauh = Jauh dari cantik."

Atau rumusan mengenai anak balita :

> "Intensitas ngambeknya (tantrum) berbanding lurus dengan jumlah orang yang menontonnya"
dan satu lainnya :

> "Kalau kita mau menggendongnya, dia minta jalan. Kalau kita mengajak dia jalan, dia minta digendong"

Ada pula yang bergaya ilmu statistik seperti :

> "Semakin seksi seorang pria semakin tinggi probabilitasnya dia seorang gay"

Dan bicara soal seks :

> "Jangan bercinta di halaman belakang, cinta memang buta, tetapi tetanggamu tidak" :D

Dan dalil soal pernikahan:

> "Bila seorang pria ingin isterinya mendengarkannya, dia tidak mendengarkan. Bila pria itu ingin tidak didengar oleh isterinya, maka dia akan pasang telinga lebar-lebar".

Dan untuk penutup dalil Murphy ini kita simak salah satu dalam bahasa Inggris:

>  Kids in cars cause accidents
>  Accidents in cars cause kids.

Apa komentar anda ?


text:
from __future__ import unicode_literals

from pkg_resources import iter_entry_points

from ....package.canonical import name as canon
from ....package.loader import load
from ....schema import Attribute
from ....schema.compat import str, unicode

from .base import Field

class PluginReference(Field):
	"""A Python object reference.

	Generally, for safety sake, you want this to come from a list of available plugins in a given namespace. If a
	namespace is given, the default for `explicit` will be `False`.  If `explicit` is `True` (or no namespace is
	defined) object assignments and literal paths will be allowed.
	"""

	namespace = Attribute(default=None)  # The plugin namespace to use when loading.
	explicit = Attribute()  # Allow explicit, non-plugin references.
	mapping = Attribute(default=None)  # To ease support for legacy records, textual replacements.

	__foreign__ = {'string'}

	def __init__(self, *args, **kw):
		if args:
			kw['namespace'] = args[0]
			args = args[1:]

		super(PluginReference, self).__init__(*args, **kw)

	def to_native(self, obj, name, value):  # pylint:disable=unused-argument
		"""Transform the MongoDB value into a Marrow Mongo value."""

		if self.mapping:
			for original, new in self.mapping.items():
				value = value.replace(original, new)

		return load(value, self.namespace)

	def to_foreign(self, obj, name, value):  # pylint:disable=unused-argument
		"""Transform to a MongoDB-safe value."""

		namespace = self.namespace

		try:
			explicit = self.explicit
		except AttributeError:
			explicit = not namespace

		if not isinstance(value, (str, unicode)):
			value = canon(value)

		if namespace and ':' in value:  # Try to reduce to a known plugin short name.
			for point in iter_entry_points(namespace):  # TODO: Isolate.
				qualname = point.module_name

				if point.attrs:
					qualname += ':' + '.'.join(point.attrs)

				if qualname == value:
					value = point.name
					break

		if ':' in value:
			if not explicit:
				raise ValueError("Explicit object references not allowed.")

			return value

		if namespace and value not in (i.name for i in iter_entry_points(namespace)):
			raise ValueError('Unknown plugin "' + value + '" for namespace "' + namespace + '".')

		return value


text:
package org.bouncycastle.crypto.tls;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.Signer;
import org.bouncycastle.crypto.io.SignerInputStream;
import org.bouncycastle.crypto.params.DHParameters;

public class TlsDHEKeyExchange
    extends TlsDHKeyExchange
{
    protected TlsSignerCredentials serverCredentials = null;

    public TlsDHEKeyExchange(int keyExchange, Vector supportedSignatureAlgorithms, DHParameters dhParameters)
    {
        super(keyExchange, supportedSignatureAlgorithms, dhParameters);
    }

    public void processServerCredentials(TlsCredentials serverCredentials)
        throws IOException
    {
        if (!(serverCredentials instanceof TlsSignerCredentials))
        {
            throw new TlsFatalAlert(AlertDescription.internal_error);
        }

        processServerCertificate(serverCredentials.getCertificate());

        this.serverCredentials = (TlsSignerCredentials)serverCredentials;
    }

    public byte[] generateServerKeyExchange()
        throws IOException
    {
        if (this.dhParameters == null)
        {
            throw new TlsFatalAlert(AlertDescription.internal_error);
        }

        ByteArrayOutputStream buf = new ByteArrayOutputStream();

        this.dhAgreeServerPrivateKey = TlsDHUtils.generateEphemeralServerKeyExchange(context.getSecureRandom(),
            this.dhParameters, buf);

        byte[] digestInput = buf.toByteArray();

        Digest d = new CombinedHash();
        SecurityParameters securityParameters = context.getSecurityParameters();
        d.update(securityParameters.clientRandom, 0, securityParameters.clientRandom.length);
        d.update(securityParameters.serverRandom, 0, securityParameters.serverRandom.length);
        d.update(digestInput, 0, digestInput.length);

        byte[] hash = new byte[d.getDigestSize()];
        d.doFinal(hash, 0);

        byte[] signature = serverCredentials.generateCertificateSignature(hash);

        /*
         * TODO RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2
         */
        DigitallySigned signed_params = new DigitallySigned(null, signature);
        signed_params.encode(buf);

        return buf.toByteArray();
    }

    public void processServerKeyExchange(InputStream input)
        throws IOException
    {
        SecurityParameters securityParameters = context.getSecurityParameters();

        Signer signer = initVerifyer(tlsSigner, securityParameters);
        InputStream sigIn = new SignerInputStream(input, signer);

        ServerDHParams params = ServerDHParams.parse(sigIn);

        DigitallySigned signed_params = DigitallySigned.parse(context, input);

        if (!signer.verifySignature(signed_params.getSignature()))
        {
            throw new TlsFatalAlert(AlertDescription.decrypt_error);
        }

        this.dhAgreeServerPublicKey = TlsDHUtils.validateDHPublicKey(params.getPublicKey());
    }

    protected Signer initVerifyer(TlsSigner tlsSigner, SecurityParameters securityParameters)
    {
        Signer signer = tlsSigner.createVerifyer(this.serverPublicKey);
        signer.update(securityParameters.clientRandom, 0, securityParameters.clientRandom.length);
        signer.update(securityParameters.serverRandom, 0, securityParameters.serverRandom.length);
        return signer;
    }
}


text:
. $PSScriptRoot\BuildCore.ps1

function Describe
{
    param(
        [Parameter(Position = 0)]
        $Name,

        [Parameter(Position = 1)]
        $ScriptBlock,

        [Parameter(Mandatory = $false)]
        [string[]]$Tag
    )

    Pester\Describe $Name -Tag:$Tag {
        try
        {
            # When executing all tests, Pester may mocking Write-Log
            # on every test may lead to Pester accidentally deleting the mock.
            # Bypass that by allowing Write-Log, but instructing it not to do
            # anything.
            $global:prtgBuildDisableLog = $true

            & $ScriptBlock
        }
        finally
        {
            $global:prtgBuildDisableLog = $false
        }
    }
}

function It
{
    [CmdletBinding(DefaultParameterSetName = 'Normal')]
    param(
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$name,

        [Parameter(Mandatory = $true, Position = 1)]
        [ScriptBlock] $script,

        [Parameter(Mandatory = $false)]
        [System.Collections.IDictionary[]] $TestCases,

        [Parameter(Mandatory = $false)]
        [switch]$Skip
    )

    Pester\It $name -TestCases $TestCases -Skip:$Skip {

        Write-LogInfo "Processing test '$name'"

        try
        {
            & $script @args
        }
        catch
        {
            Write-LogError "Error: $($_.Exception.Message)"

            throw
        }
        finally
        {
            #RemoveMocks
        }
    }
}

function RemoveMocks
{
    $pester = gmo pester

    if($pester.Version.Major -ne 3)
    {
        Write-Warning "Not removing It mocks as Pester is running $($pester.Version) instead of version 3"

        return
    }

    InModuleScope "Pester" {

        $currentScope = $pester.Scope

        $scriptBlock =
        {
            param (
                [string] $CommandName,
                [string] $Scope,
                [string] $Alias
            )
            $ExecutionContext.InvokeProvider.Item.Remove("Function:\$CommandName", $false, $true, $true)
            if ($ExecutionContext.InvokeProvider.Item.Exists("Function:\PesterIsMocking_$CommandName", $true, $true))
            {
                $ExecutionContext.InvokeProvider.Item.Rename([System.Management.Automation.WildcardPattern]::Escape("Function:\PesterIsMocking_$CommandName"), "$Scope$CommandName", $true)
            }

            if ($Alias -and $ExecutionContext.InvokeProvider.Item.Exists("Alias:$Alias", $true, $true))
            {
                $ExecutionContext.InvokeProvider.Item.Remove("Alias:$Alias", $false, $true, $true)
            }
        }

        $mockKeys = [string[]]$mockTable.Keys

        foreach ($mockKey in $mockKeys)
        {
            $mock = $mockTable[$mockKey]
            $mock.Blocks = @($mock.Blocks | & $SafeCommands['Where-Object'] {$_.Scope -ne $currentScope})

            $null = Invoke-InMockScope -SessionState $mock.SessionState -ScriptBlock $scriptBlock -ArgumentList $mock.CommandName, $mock.FunctionScope, $mock.Alias
            $mockTable.Remove($mockKey)
        }
    }
}

function global:EvaluateExpression($expr, $ie)
{
    # Get the full command (with arguments) that will be executed
    $trimmed = $expr.ToString().Trim()

    $str = $trimmed.TrimStart('&').Trim()

    $space = $str.IndexOf(' ')

    if($space -gt 0)
    {
        $command = $str.Substring(0, $space)
        $arguments = $str.Substring($space + 1) #todo: test a command that has no arguments
    }
    else
    {
        $command = $str
        $arguments = $null
    }

    $command = EscapeString $command
    $arguments = EscapeString $arguments

    $command = & $ie "`"$command`""

    if($arguments.StartsWith("@"))
    {
        $table = & $ie $arguments

        $arguments = $table -join " "
    }
    else
    {
        $arguments = & $ie "`"$arguments`""
    }

    $result = $command

    if($arguments -ne $null)
    {
        $result += " $arguments"
    }

    if($trimmed.StartsWith("&"))
    {
        $result = "& $result"
    }

    return $result
}

function global:EscapeString($str)
{
    # Convert a command like "blahblah (Get-Stuff) blahblah" to ""blahblah" $(Get-Stuff) "blahblah""
    return $str -replace "(.*?)(\(.+?\))(.*?)",'$1"$$$2"$3' -replace "`"","```""
}

function Mock-AllProcess($expected, $scriptBlock) {
    InModuleScope PrtgAPI.Build {

        $mockBlock = Get-MockProcessScriptBlock

        Mock Start-Process $mockBlock -Verifiable
    }

    Mock-InvokeProcess $expected $scriptBlock -Operator "Match"
}

function Mock-InvokeProcess
{
    param(
        [Parameter(Mandatory = $true, Position = 0)]
        $Expected,

        [Parameter(Mandatory = $true, Position = 1)]
        $ScriptBlock,

        [Parameter(Mandatory = $false)]
        $Operator = "Be"
    )

    $outerBlock = $ScriptBlock

    WithExpected $Expected {

        $mockBlock = Get-MockProcessScriptBlock

        Mock Invoke-CIProcess $mockBlock -ModuleName CI -Verifiable

        & $outerBlock
    } -Operator $Operator
}

function WithExpected
{
    param(
        [Parameter(Mandatory = $true, Position = 0)]
        $Expected,

        [Parameter(Mandatory = $true, Position = 1)]
        $ScriptBlock,

        [Parameter(Mandatory = $false)]
        $Operator = "Be"
    )

    PrepareGlobalExpected $Expected -Operator $Operator

    & $ScriptBlock

    Assert-VerifiableMocks
}

function PrepareGlobalExpected
{
    param(
        [Parameter(Mandatory = $true, Position = 0)]
        $Expected,

        [Parameter(Mandatory = $false)]
        $Operator = "Be"
    )

    if(!($Expected[0] -is [array]))
    {
        # Create a multi dimensional array
        $Expected = ,@($Expected)
    }

    for($i = 0; $i -lt $Expected.Length; $i++)
    {
        if($Operator -eq "Match")
        {
            $escaped = [regex]::Escape($Expected[$i])

            $regexExpressions = [regex]::Matches($escaped, "<regex>.+?</regex>")

            foreach($match in $regexExpressions)
            {
                $escaped = $escaped.Replace($match.Value, [regex]::Unescape($match.Value))
            }

            $escaped = $escaped -replace "<regex>","" -replace "</regex>",""

            $Expected[$i] = $escaped.Replace("/", "\/")
        }
    }

    $global:expected = $Expected
    $global:expectedIndex = 0
    $global:operator = $Operator
}

function Mock-StartProcess
{
    Mock "Start-Process" {

        $result = @(
            $FilePath
            $ArgumentList
        ) -join " "

        if($global:expectedIndex -ge $global:expected.Length)
        {
            throw "Did not expect command '$result' to be executed"
        }

        $expectedValue = $global:expected[$global:expectedIndex]

        if($expectedValue -is [array])
        {
            $expectedValue = $expectedValue -join " "
        }

        $result | Should $global:operator $expectedValue | Out-Null

        $global:expectedIndex++

        $process = New-Object PSObject
        $process | Add-Member ExitCode 0
        $process | Add-Member ScriptMethod WaitForExit {}

        return $process
    } -ModuleName CI
}

function global:Get-MockProcessScriptBlock
{
    $mockBlock = {

        # In Start-Process, $args[1] is the arguments; otherwise, we want the ScriptBlock from Invoke-Process
        $val = $args[1]

        if($ScriptBlock)
        {
            $val = $ScriptBlock
        }

        $result = EvaluateExpression $val {
            param($v)

            if($v.StartsWith("@"))
            {
                $value = Get-Variable $v.TrimStart("@") -ValueOnly

                return $value
            }

            $ie = Get-Command Invoke-Expression -CommandType Cmdlet

            & $ie $v
        }

        if($global:expectedIndex -ge $global:expected.Length)
        {
            throw "Did not expect command '$result' to be executed"
        }

        $expectedValue = $global:expected[$global:expectedIndex]

        if($expectedValue -is [array])
        {
            $expectedValue = $expectedValue -join " "
        }

        $result | Should $global:operator $expectedValue | Out-Null

        $global:expectedIndex++
    }

    return $mockBlock
}

function Mock-InstallDotnet
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true, ParameterSetName = "Windows")]
        [switch]$Windows,

        [Parameter(Mandatory = $true, ParameterSetName = "Unix")]
        [switch]$Unix
    )

    if($Windows)
    {
        InModuleScope "CI" {
            Mock Invoke-WebRequest {
                param($Uri)

                $Uri | Should Be "https://dot.net/v1/dotnet-install.ps1"
            } -ParameterFilter { $Uri -like "*dotnet*" } -Verifiable:($env:CI -eq $null)

            if($PSEdition -eq "Core" -and $IsWindows)
            {
                Mock Unblock-File { }
            }

            Mock Invoke-Expression {
                param($Command)

                $temp = [IO.Path]::GetTempPath()
                $dotnetInstall = Join-Path $temp "dotnet-install.ps1"
                $root = Get-SolutionRoot
                $dotnetSdk = Join-Path $root "packages\dotnet-sdk"

                $Command | Should Be "& '$dotnetInstall' -InstallDir '$dotnetSdk' -NoPath"
            } -ParameterFilter { $Command -like "*dotnet*" }

            Mock "Test-CIIsWindows" {
                return $true
            }
        }
    }
    else
    {
        InModuleScope "CI" {
            Mock Invoke-WebRequest {
                param($Uri)

                $Uri | Should Be "https://dot.net/v1/dotnet-install.sh"
            } -ParameterFilter { $Uri -like "*dotnet*" } -Verifiable:($env:CI -eq $null)

            Mock Test-CIIsWindows {
                return $false
            }

            Mock Invoke-Expression {
                param($Command)

                $temp = [IO.Path]::GetTempPath()
                $dotnetInstall = Join-Path $temp "dotnet-install.sh"
                $root = Get-SolutionRoot
                $dotnetSdk = Join-Path $root "packages\dotnet-sdk"

                $Command | Should Be "chmod +x '$dotnetInstall'; & '$dotnetInstall' --install-dir '$dotnetSdk' --no-path"
            } -ParameterFilter { $Command -like "*dotnet*" }
        }
    }

    Mock Test-Path {
        return $false
    } -ModuleName CI -ParameterFilter { $Path -like "*dotnet*" }

    $mockCommandArgs = @{
        CommandName = "Get-Command"
        MockWith = {
            param($Name)

            if($ErrorActionPreference -eq "SilentlyContinue")
            {
                # We're checking whether dotnet.exe exists so we can install it if necessary
                return
            }

            return [PSCustomObject]@{
                CommandType = "Application"
                Name = "dotnet.exe"
                Source = "C:\dotnet.exe"
            }
        }
        ParameterFilter = { $Name -eq "dotnet" }
    }

    Mock @mockCommandArgs -ModuleName CI
    Mock @mockCommandArgs -ModuleName PrtgAPI.Build
    Mock @mockCommandArgs
}

function Mock-NuGet
{
    InModuleScope "CI" {
        Mock "Get-ChocolateyCommand" {
            return "C:\ProgramData\chocolatey\bin\nuget.exe"
        } -ParameterFilter { $CommandName -eq "nuget" }

        Mock "Get-Item" {
            return [PSCustomObject]@{
                VersionInfo = [PSCustomObject]@{
                    FileVersion = "9999.0.0.0"
                }
            }
        } -ParameterFilter { $Path -like "*nuget.exe" }
    }
}

function Mock-InstallReferenceAssemblies
{
    InModuleScope "CI" {

        Mock "Test-Path" {
            return $false
        } -ParameterFilter { $Path -like "*Reference Assemblies*" }

        Mock "Invoke-WebRequest" {} -ParameterFilter { $Uri -like "*NDP452*" } -Verifiable
        Mock "Invoke-WebRequest" {} -ParameterFilter { $Uri -like "*NDP461*" } -Verifiable

        if($PSEdition -eq "Core" -and !$IsWindows)
        {
            Mock "Get-ProgramFiles" {
                return "/Program Files"
            }
        }
    }
}

function Get-Net452
{
    $temp = [IO.Path]::GetTempPath()

    $expected = @(
        Join-Path $temp "NDP452-KB2901951-x86-x64-DevPack.exe"
        "/quiet"
        "/norestart"
    )

    return $expected
}

function Get-Net461
{
    $temp = [IO.Path]::GetTempPath()

    $expected = @(
        Join-Path $temp "NDP461-DevPack-KB3105179-ENU.exe"
        "/quiet"
        "/norestart"
    )

    return $expected
}

function global:MockGetChocolateyCommand
{
    Mock "Get-ChocolateyCommand" {
        param($CommandName)

        if(!$CommandName.EndsWith(".exe"))
        {
            $CommandName = "$CommandName.exe"
        }

        return "C:\ProgramData\chocolatey\bin\$CommandName"
    } -ModuleName CI

    Mock "Get-Item" {
        return [PSCustomObject]@{
            VersionInfo = [PSCustomObject]@{
                FileVersion = "9999.0.0.0"
            }
        }
    } -ModuleName "CI" -ParameterFilter { $Path -like "*chocolatey*" }
}

function global:FSRoot
{
    if($PSEdition -ne "Core" -or $IsWindows)
    {
        return "C:\"
    }
    else
    {
        return "/"
    }
}


text:
package com.ameron32.rpgbuilder.app.tools;

import java.util.ArrayList;
import java.util.List;

public class Debugger {

	private static List<String> debuggerString = new ArrayList<String>();

	public static void addToDebuggerText(String s, boolean separator) {
		debuggerString.add(s + "\n");
		if (separator) {
			debuggerString.add("\n");
		}
	}

	public static void clearDebuggerText() {
		debuggerString = new ArrayList<String>();
	}

	public static List<String> getDebuggerText() {
		return debuggerString;
	}

}


text:
package org.apache.sysds.runtime.transform.encode;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sysds.api.DMLScript;
import org.apache.sysds.common.Types.ValueType;
import org.apache.sysds.runtime.matrix.data.FrameBlock;
import org.apache.sysds.runtime.matrix.data.MatrixBlock;
import org.apache.sysds.runtime.transform.TfUtils;
import org.apache.sysds.runtime.transform.TfUtils.TfMethod;
import org.apache.sysds.runtime.transform.meta.TfMetaUtils;
import org.apache.sysds.runtime.util.IndexRange;
import org.apache.sysds.runtime.util.UtilFunctions;
import org.apache.sysds.utils.Statistics;
import org.apache.wink.json4j.JSONException;
import org.apache.wink.json4j.JSONObject;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class EncoderOmit extends LegacyEncoder {
	/*
	 * THIS CLASS IS ONLY FOR LEGACY SUPPORT!!! and will be fazed out slowly.
	 */

	protected static final Log LOG = LogFactory.getLog(Encoder.class.getName());
	private static final long serialVersionUID = 1978852120416654195L;
	private boolean _federated = false;
	private boolean[] _rmRows = new boolean[0];

	public EncoderOmit(JSONObject parsedSpec, String[] colnames, int clen, int minCol, int maxCol)
		throws JSONException {
		this(null, clen);
		if(!parsedSpec.containsKey(TfMethod.OMIT.toString()))
			return;
		int[] collist = TfMetaUtils.parseJsonIDList(parsedSpec, colnames, TfMethod.OMIT.toString(), minCol, maxCol);
		initColList(collist);
		_federated = minCol != -1 || maxCol != -1;
	}

	public EncoderOmit() {
		super(new int[0], 0);
	}

	public EncoderOmit(int[] colList, int clen) {
		super(colList, clen);
	}

	public EncoderOmit(boolean federated) {
		this();
		_federated = federated;
	}

	private EncoderOmit(int[] colList, int clen, boolean[] rmRows) {
		this(colList, clen);
		_rmRows = rmRows;
		_federated = true;
	}

	public int initColList(int[] colList) {
		_colList = colList;
		return _colList.length;
	}

	/**
	 * Indicates if this encoder is applicable, i.e, if there is at least one column to encode.
	 *
	 * @return true if at least one column to encode
	 */
	public boolean isApplicable() {
		return(_colList != null && _colList.length > 0);
	}

	public int getNumRemovedRows(boolean[] rmRows) {
		int cnt = 0;
		for(boolean v : rmRows)
			cnt += v ? 1 : 0;
		return cnt;
	}

	public int getNumRemovedRows() {
		return getNumRemovedRows(_rmRows);
	}

	public boolean omit(String[] words, TfUtils agents) {
		if(!isApplicable())
			return false;

		for (int colID : _colList) {
			if (TfUtils.isNA(agents.getNAStrings(), UtilFunctions.unquote(words[colID - 1].trim())))
				return true;
		}
		return false;
	}

	public MatrixBlock encode(FrameBlock in, MatrixBlock out) {
		return apply(in, out);
	}

	public void build(FrameBlock in) {
		if(_federated)
			_rmRows = computeRmRows(in);
	}

	public MatrixBlock apply(FrameBlock in, MatrixBlock out) {
		// local rmRows for broadcasting encoder in spark
		long t0 = DMLScript.STATISTICS ? System.nanoTime() : 0;
		boolean[] rmRows;
		if(_federated)
			rmRows = _rmRows;
		else
			rmRows = computeRmRows(in);

		// determine output size
		int numRows = out.getNumRows() - getNumRemovedRows(rmRows);

		// copy over valid rows into the output
		MatrixBlock ret = new MatrixBlock(numRows, out.getNumColumns(), false);
		int pos = 0;
		for(int i = 0; i < in.getNumRows(); i++) {
			// copy row if necessary
			if(!rmRows[i]) {
				for(int j = 0; j < out.getNumColumns(); j++)
					ret.quickSetValue(pos, j, out.quickGetValue(i, j));
				pos++;
			}
		}

		_rmRows = rmRows;
		if(DMLScript.STATISTICS)
			Statistics.incTransformOmitApplyTime(System.nanoTime()-t0);
		return ret;
	}

	private boolean[] computeRmRows(FrameBlock in) {
		boolean[] rmRows = new boolean[in.getNumRows()];
		ValueType[] schema = in.getSchema();
		// TODO perf evaluate if column-wise scan more efficient
		// (sequential but less impact of early abort)
		for(int i = 0; i < in.getNumRows(); i++) {
			for(int colID : _colList) {
				Object val = in.get(i, colID - 1);
				if(val == null || (schema[colID - 1] == ValueType.STRING && val.toString().isEmpty())) {
					rmRows[i] = true;
					break; // early abort
				}
			}
		}
		return rmRows;
	}

	public EncoderOmit subRangeEncoder(IndexRange ixRange) {
		int[] colList = subRangeColList(ixRange);
		if(colList.length == 0)
			// empty encoder -> sub range encoder does not exist
			return null;
		boolean[] rmRows = _rmRows;
		if(_rmRows.length > 0)
			rmRows = Arrays.copyOfRange(rmRows, (int) ixRange.rowStart - 1, (int) ixRange.rowEnd - 1);

		return new EncoderOmit(colList, (int) (ixRange.colSpan()), rmRows);
	}

	protected int[] subRangeColList(IndexRange ixRange) {
		List<Integer> cols = new ArrayList<>();
		for(int col : _colList) {
			if(ixRange.inColRange(col)) {
				// add the correct column, removed columns before start
				// colStart - 1 because colStart is 1-based
				cols.add(col);
			}
		}
		return cols.stream().mapToInt(i -> i).toArray();
	}

	public void mergeAt(EncoderOmit other, int row, int col) {
		mergeColumnInfo(other, col);
		_rmRows = Arrays.copyOf(_rmRows, Math.max(_rmRows.length, (row - 1) + other._rmRows.length));
		for(int i = 0; i < other._rmRows.length; i++)
			_rmRows[(row - 1) + 1] |= other._rmRows[i];
	}

	public void updateIndexRanges(long[] beginDims, long[] endDims) {
		// first update begin dims
		int numRowsToRemove = 0;
		for(int i = 0; i < beginDims[0] - 1 && i < _rmRows.length; i++)
			if(_rmRows[i])
				numRowsToRemove++;
		beginDims[0] -= numRowsToRemove;
		// update end dims
		for(int i = 0; i < endDims[0] - 1 && i < _rmRows.length; i++)
			if(_rmRows[i])
				numRowsToRemove++;
		endDims[0] -= numRowsToRemove;
	}

	public FrameBlock getMetaData(FrameBlock out) {
		// do nothing
		return out;
	}

	public void initMetaData(FrameBlock meta) {
		// do nothing
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		super.writeExternal(out);
		out.writeBoolean(_federated);
		out.writeInt(_rmRows.length);
		for(boolean r : _rmRows)
			out.writeBoolean(r);
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException {
		super.readExternal(in);
		if(_rmRows.length == 0) {
			_federated = in.readBoolean();
			_rmRows = new boolean[in.readInt()];
			for(int i = 0; i < _rmRows.length; i++)
				_rmRows[i] = in.readBoolean();
		}
	}

	public boolean equals(Object o) {
		if(this == o)
			return true;
		if(o == null || getClass() != o.getClass())
			return false;
		EncoderOmit that = (EncoderOmit) o;
		return _federated == that._federated && Arrays.equals(_rmRows, that._rmRows);
	}

	public int hashCode() {
		int result = Objects.hash(_federated);
		result = 31 * result + Arrays.hashCode(_rmRows);
		return result;
	}
}


text:
package auth.sso.oidc.custom;

import org.pac4j.core.util.CommonHelper;
import org.pac4j.oidc.client.OidcClient;
import org.pac4j.oidc.config.OidcConfiguration;
import org.pac4j.oidc.credentials.extractor.OidcExtractor;
import org.pac4j.oidc.logout.OidcLogoutActionBuilder;
import org.pac4j.oidc.profile.OidcProfile;
import org.pac4j.oidc.profile.creator.OidcProfileCreator;
import org.pac4j.oidc.redirect.OidcRedirectActionBuilder;

public class CustomOidcClient extends OidcClient<OidcProfile, OidcConfiguration> {

  public CustomOidcClient(final OidcConfiguration configuration) {
    setConfiguration(configuration);
  }

  @Override
  protected void clientInit() {
    CommonHelper.assertNotNull("configuration", getConfiguration());
    getConfiguration().init();

    defaultRedirectActionBuilder(new OidcRedirectActionBuilder(getConfiguration(), this));
    defaultCredentialsExtractor(new OidcExtractor(getConfiguration(), this));
    defaultAuthenticator(new CustomOidcAuthenticator(getConfiguration(), this));
    defaultProfileCreator(new OidcProfileCreator<>(getConfiguration()));
    defaultLogoutActionBuilder(new OidcLogoutActionBuilder<>(getConfiguration()));
  }
}


text:
#ifndef __NMR_MODELREADERNODE100_VERTICES
#define __NMR_MODELREADERNODE100_VERTICES

#include "Model/Reader/NMR_ModelReaderNode.h"
#include "Model/Classes/NMR_ModelComponent.h"
#include "Model/Classes/NMR_ModelObject.h"

namespace NMR {

	class CModelReaderNode100_Vertices : public CModelReaderNode {
	private:
		CMesh * m_pMesh;
	protected:
		virtual void OnAttribute(_In_z_ const nfWChar * pAttributeName, _In_z_ const nfWChar * pAttributeValue);
		virtual void OnChildElement(_In_z_ const nfWChar * pChildName, _In_ CXmlReader * pXMLReader);
	public:
		CModelReaderNode100_Vertices() = delete;
		CModelReaderNode100_Vertices(_In_ CMesh * pMesh, _In_ PModelReaderWarnings pWarnings);

		virtual void parseXML(_In_ CXmlReader * pXMLReader);
	};

	typedef std::shared_ptr <CModelReaderNode100_Vertices> PModelReaderNode100_Vertices;

}

#endif // __NMR_MODELREADERNODE100_VERTICES


text:
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Infinite from 'react-infinite';
import { likeImage, unlikeImage } from '/imports/api/images/methods';
import DataLoader from '/imports/ui/components/Loader/DataLoader';
import { zoomerOpen, snackBarOpen } from '/imports/ui/redux/actions';
import ImageHolder from '/imports/ui/components/ImageHolder';
import Tip from './Tip';

class InfiniteImageList extends PureComponent {
  static propTypes = {
    User: PropTypes.object,
    images: PropTypes.array.isRequired,
    offset: PropTypes.number,
    disabled: PropTypes.bool,
    isLoadedAll: PropTypes.bool,
    onInfiniteLoad: PropTypes.func.isRequired,
    device: PropTypes.object.isRequired,
    snackBarOpen: PropTypes.func.isRequired,
    zoomerOpen: PropTypes.func.isRequired,
  }

  static defaultProps = {
    offset: -32, // 允许再多滚动32px,因为Topbar默认64px
    disabled: false, // 是否禁止InfiniteLoad
    isLoadedAll: false, // 是否全部加载完
  }

  getImageHeights() {
    const { images, device } = this.props;
    const heights = images.map(image => {
      const imageHeight = Math.round((image.dimension[1] / image.dimension[0]) * device.width);
      return imageHeight + 152; // 80 + 52 + 20 --> title + footer + padding
    });
    return heights;
  }

  _handleToggleLike = async (like, image) => {
    const { User } = this.props;
    if (!User) {
      this.props.snackBarOpen('您还尚未登录');
    }
    try {
      const api = like ? likeImage : unlikeImage;
      const model = like
        ? { imageId: image._id, liker: User.username }
        : { imageId: image._id, unliker: User.username };
      await api.callPromise(model);
    } catch (err) {
      console.warn(err);
      const msg = like ? `点赞失败 ${err.error}` : `撤销点赞失败 ${err.error}`;
      this.props.snackBarOpen(msg);
    }
  }

  render() {
    const {
      images,
      offset,
      disabled,
      isLoadedAll,
    } = this.props;
    return [
      <Infinite
        key="Infinite__ImageList"
        elementHeight={this.getImageHeights()}
        onInfiniteLoad={this.props.onInfiniteLoad}
        loadingSpinnerDelegate={<DataLoader bottom />}
        infiniteLoadBeginEdgeOffset={disabled ? undefined : offset}
        useWindowAsScrollContainer
      >
        {
          images.map(image => (
            <ImageHolder
              key={image._id}
              image={image}
              onToggleLike={this._handleToggleLike}
              onMediaClick={this.props.zoomerOpen}
            />
          ))
        }
      </Infinite>,
      isLoadedAll && <Tip key="Infinite_Tip" />,
    ];
  }
}

const mapStateToProps = ({ sessions, device }) => ({
  device,
  User: sessions.User,
});

const mapDispatchToProps = (dispatch) => bindActionCreators({
  snackBarOpen,
  zoomerOpen,
}, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(InfiniteImageList);


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
J. Hattori bot. Lab. 77: 118 (1994)

#### Original name
Lecanora novae-hollandiae Lumbsch

### Remarks
null


text:
var WebpackDevServer = require('webpack-dev-server')
var webpack = require('webpack')
var config = require('./webpack.dev.conf')

config.entry.app.unshift("webpack-dev-server/client?http://localhost:8080", "webpack/hot/dev-server")
config.plugins.push(new webpack.HotModuleReplacementPlugin())

var app = new WebpackDevServer(webpack(config), {
  publicPath: config.output.publicPath,
  stats: {
    colors: true,
    chunks: false
  },
  hot: true,
  proxy: {
    "/api/*": {target: "http://www.shapaozi.me", host: "www.shapaozi.me"}
  }
})

app.listen(8080, 'localhost', function (err) {
  if (err) {
    console.log(err)
    return
  }
  console.log('Listening at http://localhost:8080')
})


text:
package com.julun.vehicle.activity.examples;

import android.content.Context;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;

import com.julun.annotations.views.AfterInitView;
import com.julun.annotations.views.ContentLayout;
import com.julun.container.uicontroller.BaseActivity;
import com.julun.vehicle.R;
import com.julun.widgets.adapters.listview.BaseListViewAdapter;
import com.julun.widgets.viewholder.listview.ViewHolder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import butterknife.Bind;

/**
 * Created by danjp on 2015/12/17.
 */
@ContentLayout(R.layout.example_danjp_listview)
public class DanjpRemoteListViewExampleActivity extends BaseActivity {

    @Bind(R.id.listview)
    ListView listView;
    private MyAdapter myAdapter = null;
    private ArrayList<Prod> items = new ArrayList<>();

    @AfterInitView
    public void vewiInit() {
        myAdapter = new MyAdapter(this, R.layout.example_danjp_listview_item);
        myAdapter.addAll(items);
        listView.setAdapter(myAdapter);

        final MyHandler myHandler = new MyHandler();
        new Thread() {
            public void run() {
                HttpURLConnection conn = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("http://120.26.67.181:8088/icar/data/myCart.jsp");
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(6 * 1000);
                    conn.connect();
                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuffer sb = new StringBuffer();
                    String readLine = null;
                    while ((readLine = reader.readLine()) != null) {
                        sb.append(readLine);
                    }
                    Log.d("DANJP", sb.toString());
//                    Prod prod = JsonHelper.fromJson(sb.toString(), Prod.class);

                    JSONArray arr = new JSONArray(sb.toString());
                    Prod prod = null;
                    for(int i=0,length=arr.length();i<length;i++){
                        JSONObject obj = arr.getJSONObject(i);
                        prod = new Prod();
                        prod.prodId = obj.getString("prodId");
                        prod.prodName = obj.getString("prodName");
                        prod.prodImageUrl = obj.getString("prodImageUrl");
                        prod.marketPrice = obj.getDouble("marketPrice");
                        prod.buyPrice = obj.getDouble("buyPrice");
                        prod.buyCount = obj.getInt("buyCount");
                        prod.selectedDesc = obj.getString("selectedDesc");
                        items.add(prod);
                    }

                    Message message = myHandler.obtainMessage();
                    myHandler.sendEmptyMessage(1);

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }.start();
    }

    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 1) {
                myAdapter.addAll(items);
                myAdapter.notifyDataSetChanged();
            }
        }
    }

    class Prod {
        String prodId;
        String prodName;
        String prodImageUrl;
        double marketPrice;
        double buyPrice;
        int buyCount;
        String selectedDesc;
        Prod(){}

        @Override
        public String toString() {
            return "ProdId="+prodId+"  ProdName="+prodName;
        }
    }

    class MyAdapter extends BaseListViewAdapter<Prod> {
        public MyAdapter(Context context, int itemResId) {
            super(context, itemResId);
        }

        @Override
        public void convert(ViewHolder vh, Prod prod) {
            //直接加载图片,肯定错误
            vh.setImageUrl(R.id.prod_image, prod.prodImageUrl);
            vh.setTextViewText(R.id.prod_name, prod.prodName);
            vh.setTextViewText(R.id.prod_price, "¥" + prod.buyPrice);

            TextView tv = vh.getView(R.id.prod_price);
            tv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

            vh.setTextViewText(R.id.market_price, "¥"+prod.marketPrice+"");
            vh.setTextViewText(R.id.buy_count, prod.buyCount+"人购买");
            vh.setTextViewText(R.id.pingjia, "5人评价");
        }
    }

}


text:
import datetime as dt
from nose.tools import with_setup

from billy.core import db
from billy.importers import events
from .. import fixtures

def setup_func():
    db.events.drop()
    db.event_ids.drop()
    fixtures.load_metadata()

@with_setup(setup_func)
def test_import_event_guid():
    event = {'state': 'ex', 'description': 'TBD',
             'when': dt.datetime.now(), 'end': 'never', 'type': 'party',
             '_guid': 'xx-yy-zz'}

    # test insert
    events.import_event(event)
    db_event = db.events.find_one({'_id': 'EXE00000001'})
    assert db_event['created_at'] == db_event['updated_at']
    assert db_event['description'] == 'TBD'

    # test update
    event['description'] = 'Determined.'
    events.import_event(event)
    assert db.events.count() == 1
    db_event = db.events.find_one({'_id': 'EXE00000001'})
    assert db_event['created_at'] < db_event['updated_at']
    assert db_event['description'] == 'Determined.'

@with_setup(setup_func)
def test_import_event_no_guid():
    event = {'state': 'ex', 'description': 'TBD',
             'when': dt.datetime.now(), 'end': 'never', 'type': 'party'}

    # test insert
    events.import_event(event)
    db_event = db.events.find_one({'_id': 'EXE00000001'})
    assert db_event['created_at'] == db_event['updated_at']
    assert db_event['description'] == 'TBD'

    # test update
    event['new_field'] = 'extra info'
    events.import_event(event)
    assert db.events.count() == 1
    db_event = db.events.find_one({'_id': 'EXE00000001'})
    assert db_event['created_at'] < db_event['updated_at']
    assert 'new_field' in db_event

    # update to description looks like new event without GUID
    event['description'] = 'break this thing'
    events.import_event(event)
    assert db.events.count() == 2


text:
package hudson.plugins.jira.extension;

import com.atlassian.jira.rest.client.api.VersionRestClient;
import io.atlassian.util.concurrent.Promise;

import java.net.URI;

public interface ExtendedVersionRestClient extends VersionRestClient {
    Promise<ExtendedVersion> getExtendedVersion(URI versionUri);
    Promise<ExtendedVersion> createExtendedVersion(ExtendedVersionInput versionInput);
    Promise<ExtendedVersion> updateExtendedVersion(URI versionUri, ExtendedVersionInput versionInput);
}


text:
//
//  FDDataReader.m
//  WeChatExport
//
//  Created by weichao on 2016/11/7.
//  Copyright © 2016年 FatGragon. All rights reserved.
//

#import "FDDataReader.h"

static sqlite3 *database = NULL;

@implementation FDDataReader
- (NSMutableArray *)publicQueryDataWithsql:(NSString *)sql dataColumns:(NSArray *)dataColumns {
    if (!sql || sql.length == 0) {
        return nil;
    }
    if (!dataColumns || dataColumns.count == 0) {
        return nil;
    }
    BOOL isExistsDatabase = [self isExistsDatabase];
    NSMutableArray *result = nil;
    if (isExistsDatabase) {
        [self openDatabase];
        result = [self queryDataWithsql:sql dataColumns:dataColumns];
        [self closeDatabase];
    }
    else{
        NSLog(@"CurrentPath:%@ is not Exists",self.databasePath);
    }
    return result;
}

- (BOOL)isExistsDatabase{
    NSString *databasePath = [self databasePath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    bool isExist = [fileManager fileExistsAtPath:databasePath];
    return isExist;
}

- (void)openDatabase {
    NSString *databasePath = [self databasePath];
    // 是否打开成功
    if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
        NSLog(@"Opening Database");
    }
    else {
        // 打开数据库失败
        sqlite3_close(database);
        NSAssert1(0, @"Failed to open database: '%s'.", sqlite3_errmsg(database));
    }
}

//返回数据里面是字典
- (NSMutableArray *)queryDataWithsql:(NSString *)sql dataColumns:(NSArray *)dataColumns {
    sqlite3_stmt *statement;
    int sqlResult = sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL);
    // 装查询结果的可变数组
    NSMutableArray *mutableResult = [NSMutableArray array];
    // 结果状态为OK时,开始取出每条数据
    if ( sqlResult == SQLITE_OK) {
        // 只要还有下一行,就取出数据。
        while (sqlite3_step(statement) == SQLITE_ROW) {
            NSMutableDictionary *element = [[NSMutableDictionary alloc] init];
            for (NSNumber *indexNumber in dataColumns) {
                //此处是不是可以有办法获取,一共多少列,这样就可以去除这个参数dataColumns
                char *field = (char *)sqlite3_column_text(statement, [indexNumber intValue]);
                NSString *fieldString = [self stringWithCharString:field];
                if (fieldString && fieldString.length > 0) {
                    [element setValue:fieldString forKey:[indexNumber stringValue]];
                }
            }
            [mutableResult addObject:element];
        }
        // 完成后释放prepare创建的准备语句
        sqlite3_finalize(statement);
    }
    else
    {
        NSLog(@"Problem with database:%d",sqlResult);
    }
    return mutableResult;

}

/** C字符串转换OC字符串 */
- (NSString *)stringWithCharString:(char *)string {
    return (string) ? [NSString stringWithUTF8String:string] : @"";
}

- (void)closeDatabase {
    if (sqlite3_close(database) != SQLITE_OK) {
        NSAssert1(0, @"Failed to close database: '%s'.", sqlite3_errmsg(database));
    }
}
@end


text:
.. This file is part of the OpenDSA eTextbook project. See
.. http://algoviz.org/OpenDSA for more details.
.. Copyright (c) 2012-2013 by the OpenDSA Project Contributors, and
.. distributed under an MIT open source license.

.. avmetadata::
   :author: Erich Brungraber
   :prerequisites: Knapsack
   :topic: Algorithms

Edit Distance [Draft]
=====================

:dfn:`Edit Distance` is an algorithm for computing the minimum number
of changes from one string to another.  The two non-interesting cases
are: if both strings are of length zero (or identical), then zero
operations are needed; and if one string is of zero length, then the
number of operations needed is the length of the non-zero length
string.

Following the dynamic programming approach, the first step is solve
the problem recursively.  Like most recursive solutions, this
algorithm is easy to follow.  First, some symbols and their defintions
to make the description easier to understand.

+--------------+------------------------------------------+
|  Symbol      | Definition                               |
+==============+==========================================+
|S             |is the starting string                    |
+--------------+------------------------------------------+
|T             |is the ending string                      |
+--------------+------------------------------------------+
|m             |the length of the starting string         |
+--------------+------------------------------------------+
|n             |the length of the ending string           |
+--------------+------------------------------------------+
|S\(i\)        |is the character in S at the ith position |
+--------------+------------------------------------------+
|T\(j\)        |is the character in T at the jth position |
+--------------+------------------------------------------+
|ED\(S,T,i,j\) |i:[1..m], j:[1..n], the minimum number of |
|              |changes when comparing S\(i\) with T\(j\) |
+--------------+------------------------------------------+

The recursive algorithm is as follows:

1.  Base case check.  The base case for this algorithm is simply when you run out of characters to compare in either *S* or *T*.  If you run out of characters for both, the number that is returned will be zero.  However if you run out of characters of one but not the other, the value returned is the remaining number of characters in the non-zero length string.
2.  Check to see if *S\(i\) == T\(j\)*.
	a. 1\)	If they match, recurse to *ED\(S,T,i-1,j-1\)*.  Since they match, nothing needs to be done at this position, so no operation count is added to this value.
	b. 2\)	If they don't match, three recursive calls are necessary.  In order:

		- A\) Substitution: recurse to *ED\(S,T,i-1,j-1\)* and add one\*.
		- B\) Insertion: 	recurse to *ED\(S,T,i,j-1\)* and add one\*.
		- C\) Deletion:  	recurse to *ED\(S,T,i-1,j\)* and add one\*.
		- D\) Choose which operation to take.  Since Edit Distance is a minimum-returning function, simply find the operation that yields the minimum number of changes (operation counts).  If there is a tie, follow the order of precedence established by the ordering of recursive calls:  Substition, Insertion, Deletion.

\* Since each of these recursive calls refer to a specific operation, the op count, or value returned by each recursive call is incremented by 1.

The initial function call appears as *ED\(S,T,m,n\)*.  Note that for the purposes of this algorithm, standard 0-base array enumeration isn't used; the strings start at character position **1**, not **0**.

Operation Description:

	Substitution
		The current character in the starting string becomes the current character in the ending string.  *S\(i\) = T\(j\)*

	Example:

	| Starting string: sit
	| Ending string: sat
	| For the second character comparison on both strings, the "i" becomes an "a", a substitution.

	Insertion
		The ending string is longer than the starting string, so the current character of the ending string is inserted at the current character of the starting string's position. *S.insert\(i,T\(j\)\)*

	Example:

	| Starting string: red
	| Ending string: read
	| At the second to last character comparison for both strings, an "a" is inserted to make the strings match.

	Deletion
		The starting string is longer than the ending string, so the current character of the starting string is removed. *S.remove\(i\)*

	Example:

	| Starting string: 123456
	| Ending string: 13456
	| The second character of the starting string "2" needs to be deleted for the strings to match.

The following is the Edit Distance algorithm handled recursively in Java. ::

	int editDistance(String S, String T, int i, int j)
	{
		//base cases
		if (i === 0)
			return j;
		if (j === 0)
			return i;

		//recursive call, start with match check
		if (S.charAt(i) == T.charAt(j))
			return editDistance(S, T, i-1, j-1);
	    	else
		{	//no match, recurse three times

			int sub = editDistance(S, T, i-1, j-1) + 1;
			int ins = editDistance(S, T, i, j-1) + 1;
			int del = editDistance(S, T, i-1, j) + 1;

			return Math.min(Math.min(sub, ins), del);
	    	}
	}

This recursive algorithm handles Edit Distance, but as the string length increases, the call stack increases exponentially.  Why it increases exponentially is due to the fact that at any given character comparision, there might be as many as three recursive calls, so :math:`O(3^{max(m,n)})`.  The recursive call tree can be seen by the following animation.

Note that for these animations, the starting string is *"cat"* and the ending string is *"kate"*.  The numbers in each node refer to the recursive function call parameters, in this case the character positions for comparison of the starting and ending strings, respectively.  For simplicity's sake, assume the starting and ending string are globally defined.

.. avembed:: AV/Development/editRCT.html pe

Obviously, to compare any sizeable strings together, a recursive solution is not optimal.  As was seen by the previous demonstrations of dynamic programming, a dynamic approach to this problem will make things run more efficiently \(i.e., in linear time\).

The following animation demonstrates, just as the previous demonstrations of N-Choose-K and 0/1 Knapsack, the process of plucking the recursive call tree to fill in the dynamic grid.

Note that due to the similarity in approach, the majority of the code that operates this next animation is of an abstracted form that actually runs the second animations of all three dynamic programming problem visualizations.  You've already seen this animation if you've viewed N-Choose-K and the 0/1 Knapsack problems, just with a different algorithm being visualized.  If you don't see the similarity, don't worry.  The point of these three algorithm demonstrations, N-Choose-K, 0/1 Knapsack, and Edit Distance, is to reveal the same abstracted approach to creating dynamic solutions for problems.  Since the second step is virtually identical for all three of these demonstrations, we've created one animation to handle them all.

.. avembed:: AV/Development/editPrune.html pe

As you can see, the efficiency of this dynamic approach is :math:`O(m*n)`, which is obviously better than the recursive's efficiency of :math:`O(3^{max(m,n)})`.  In fact, for this particular example, of the original 19 function calls, the dynamic approach eliminated 10 of those calls, a 52.6% saving on efficiency, and this was for a **small** example!

Once the grid is filled, the last part of the dynamic solution approach is to identify the optimal path to the solution.  The following animation does just that.  Pay attention to the transitional text, as it describes which operation is done at each comparison.  Understanding which positions of the next cells relates to which operation is key.  For simplicity's sake, top-left means substitution, left means insertion, and top means deletion.

Note that for this animation, there are no deletions.  If the starting string was of greater length than the ending string, then there would be no insertions, but one or more deletions.

.. avembed:: AV/Development/editOptimal.html pe

The following is the same Edit Distance algorithm as above, but implemented dynamically.  As you can see, memoization is used to provide the means for a look-up table, storing the repeated function calls.  The initial setup of the grid might be the hardest part to understand.  This code will generate a two-dimensional array of the same type as seen in previous animations' grids, sans the initial row and column used for displaying the strings to be compared. ::

	int editDistance(String start, String end)
	{
		int startMax = start.length;
		int endMax = end.length;
		int array[][] = new int[startMax + 1][endMax + 1]

		//initialize all array values to zero
		for (int i = 0; i <= startMax; i++)
		{
			for (int j = 0; j <= endMax; j++)
			{
				array[i][j] = 0;
			}
		}

		//initialize the base cases
		for (int i = 1; i <= startMax; i++)
		{
			array[i][0] = i;
		}

		for (int j = 1; j <= endMax; j++)
		{
			array[0][j] = j;
		}

		//fill in the grid
		for (int i = 1; i <= startMax; i++)
		{
			for(int j = 1; j <= endMax; j++)
			{
				//match check
				if (start.charAt(i-1) == end.charAt(j-1))
					array[i][j] = array[i-1][j-1];
				else
				{
					int sub = array[i-1][j-1] + 1;
					int ins = array[i][j-1] + 1;
					int del = array[i-1][j] + 1;

					array[i][j] = Math.min(Math.min(sub, ins), del);
				}
			}
		}

	    	return array[startMax][endMax];
	}

One major difference between the recursive Edit Distance and this
particular dynamic Edit Distance is the minimum filling of the grid.
As was seen above in the second animation, not every cell received a
value.  These missing values were entirely unnecessary for determining
the actual Edit Distance between the two strings, and were therefore
bypassed.  This dynamic implementation, as was seen by the third
animation, will actually fill in every cell with its appropriate
value.  Perhaps you can think of a way to only fill in the necessary
cells using the dynamic method.

Now that you've seen the algorithms in action, you should hopefully
understand where the grid gets its values.  More than this, you should
understand how the algorithm chooses which operation to do next.  For
the following quiz, the key to completing it is understanding
ultimately which operation will be done at any point.  For any given
cell, identify which operation will yield the lowest total operation
count.

.. avembed:: Exercises/Development/edit-KA1.html ka

On this next quiz, identify the correct value that would go in the
highlighted cell.

.. avembed:: Exercises/Development/edit-KA2.html ka


text:
// Dstl (c) Crown Copyright 2017
package uk.gov.dstl.baleen.annotators.cleaners;

import java.util.Collection;
import java.util.Collections;

import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;

import com.google.common.collect.ImmutableSet;

import uk.gov.dstl.baleen.core.pipelines.orderers.AnalysisEngineAction;
import uk.gov.dstl.baleen.types.common.Money;
import uk.gov.dstl.baleen.uima.BaleenAnnotator;

/**
 * Finds Money values without an assigned currency, and tries to determine what currency they are by
 * matching against a list of currency symbols and terms
 */
public class CurrencyDetection extends BaleenAnnotator {

  @Override
  public void doProcess(JCas jCas) throws AnalysisEngineProcessException {
    Collection<Money> money = JCasUtil.select(jCas, Money.class);

    for (Money m : money) {
      if (m.getCurrency() == null || m.getCurrency().isEmpty()) {
        String value = m.getValue().toUpperCase();

        if (value.contains("£") || value.contains("GBP")) {
          m.setCurrency("GBP");
        } else if (value.contains("$") || value.contains("USD")) {
          m.setCurrency("USD");
        } else if (value.contains("€") || value.contains("EUR")) {
          m.setCurrency("EUR");
        }
      }
    }
  }

  @Override
  public AnalysisEngineAction getAction() {
    return new AnalysisEngineAction(ImmutableSet.of(Money.class), Collections.emptySet());
  }
}


text:
cask "pushplaylabs-sidekick" do
  version "87.7.42.7010,65eac33"
  sha256 "132ac1e201ba00b9f148830b82e24a612e8c028c0e296c4c6388c44efc73b209"

  url "https://cdn.meetsidekick.com/builds/sidekick-mac-release-x64-#{version.before_comma}-#{version.after_comma}-df.dmg"
  name "Sidekick"
  desc "Browser designed for modern work"
  homepage "https://www.meetsidekick.com/"

  livecheck do
    url "https://api.meetsidekick.com/downloads/df/mac"
    strategy :header_match do |headers|
      match = headers["location"].match(/-(\d+(?:\.\d+)*)-(.*?)-df.dmg/)
      "#{match[1]},#{match[2]}"
    end
  end

  app "Sidekick.app"

  zap trash: [
    "~/Library/Application Support/Sidekick",
    "~/Library/Caches/Sidekick",
    "~/Library/Preferences/com.pushplaylabs.sidekick.plist",
    "~/Library/Saved Application State/com.pushplaylabs.sidekick.savedState",
  ]
end


text:
<?php

namespace Ionic;

use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use Ionic\API\Interfaces\API as APIInterface;
use Ionic\Exceptions\AuthorizationException;

class Command implements \Ionic\Interfaces\Command {
    /** @var string */
    private $name;
    /** @var mixed */
    private $data;

    /**
     * @var \Ionic\Interfaces\Client
     */
    private $client;
    /**
     * @var APIInterface
     */
    private $api;

    /**
     * Accepts an associative array of command options, including:
     *
     * - @http: (array) Associative array of transfer options.
     *
     * @param string            $name       Name of the command
     * @param array             $args       Arguments to pass to the command
     * @param ClientInterface   $handler    Handler for command
     * @param APIInterface               $api        API
     */
    public function __construct($name, array $args = [], ClientInterface $handler = null, APIInterface $api)
    {
        $this->name = $name;
        $this->data = $args;
        $this->client = $handler;
        $this->api = $api;
    }

    /**
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function resolve() {
        $request = $this->api->getRequest($this->name, $this->data);
        $fetch = $this->client->sendAsync($request);

        $promise = $fetch->then(function ($results) {
            return $this->api->processOutput($this->name, $results);
        }, function (RequestException $error) {
            if ($error->getCode() == 401) {
                throw new AuthorizationException("Unauthorized bad request or bad api_token in Client configuration.", 401, $error);
            }
            throw $error;
        });
        return $promise;
    }
}


text:
package graphql.language;

public interface Definition extends Node {
}


text:
cask :v1 => 'transmit' do
  version '4.4.8'
  sha256 '3547a5e8baabffd18c4e21c766362cd4295d878d391ce48bb8f8f4d6eabd9ef9'

  url "https://www.panic.com/transmit/d/Transmit%20#{version}.zip"
  appcast 'http://www.panic.com/updates/update.php'
  name 'Transmit'
  homepage 'http://panic.com/transmit'
  license :unknown    # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder

  app 'Transmit.app'

  zap :delete => [
                  '~/Library/Preferences/com.panic.Transmit.plist',
                  '~/Library/Application Support/Transmit',
                 ]
end


text:
require 'spec_helper'

describe S2Netbox::Commands::Credential do
  describe 'add' do
    before :each do
      configure

      stub_request(:post, "https://test-s2.some.net/goforms/nbapi").
          with(:body => "APIcommand=<NETBOX-API><COMMAND name='AddCredential' num='1'><PARAMS><PERSONID>8a806ed6-0246-49d0-b7a7-ab6402da01e3</PERSONID><ENCODEDNUM>8232</ENCODEDNUM><CARDFORMAT>26 bit Wiegand</CARDFORMAT></PARAMS></COMMAND></NETBOX-API>").
          to_return(:status => 200, :body => "<NETBOX><RESPONSE command='AddCredential' num=\"1\">SUCCESS<PERSONID>8a806ed6-0246-49d0-b7a7-ab6402da01e3</PERSONID></RESPONSE></NETBOX>", :headers => {})

      @result = S2Netbox::Commands::Credential.add({
                                                              :person_id => '8a806ed6-0246-49d0-b7a7-ab6402da01e3',
                                                              :encodednum => '8232',
                                                              :card_format => '26 bit Wiegand'
                                                          })
    end

    it 'should be a S2Netbox::ApiResponse' do
      expect(@result).to be_a(S2Netbox::ApiResponse)
    end

    it 'should return the correct details' do
      expect(@result.details['PERSONID']).to eq('8a806ed6-0246-49d0-b7a7-ab6402da01e3')
    end
  end

  describe 'modify' do
    before :each do
      configure

      stub_request(:post, "https://test-s2.some.net/goforms/nbapi").
          with(:body => "APIcommand=<NETBOX-API sessionid='session_id'><COMMAND name='ModifyCredential' num='1'><PARAMS><ENCODEDNUM>8232</ENCODEDNUM><CARDFORMAT>26 bit Wiegand</CARDFORMAT><DISABLED>1</DISABLED></PARAMS></COMMAND></NETBOX-API>").
          to_return(:status => 200, :body => "<NETBOX><RESPONSE command='ModifyCredential' num=\"1\">SUCCESS</RESPONSE></NETBOX>", :headers => {})

      @result = S2Netbox::Commands::Credential.modify({
                                                                 :encodednum => '8232',
                                                                 :card_format => '26 bit Wiegand',
                                                                 :disabled => '1'
                                                             }, 'session_id')
    end

    it 'should be a S2Netbox::ApiResponse' do
      expect(@result).to be_a(S2Netbox::ApiResponse)
    end
  end

  describe 'remove' do
    before :each do
      configure

      stub_request(:post, "https://test-s2.some.net/goforms/nbapi").
          with(:body => "APIcommand=<NETBOX-API sessionid='session_id'><COMMAND name='RemoveCredential' num='1'><PARAMS><ENCODEDNUM>8232</ENCODEDNUM></PARAMS></COMMAND></NETBOX-API>").
          to_return(:status => 200, :body => "<NETBOX><RESPONSE command='RemoveCredential' num=\"1\">SUCCESS</RESPONSE></NETBOX>", :headers => {})

      @result = S2Netbox::Commands::Credential.remove({
                                                          :encoded_num => '8232'
                                                      }, 'session_id')
    end

    it 'should be a S2Netbox::ApiResponse' do
      expect(@result).to be_a(S2Netbox::ApiResponse)
    end
  end
end