text:
package org.cam.core.cache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.CopyStrategyConfiguration;
import net.sf.ehcache.config.PersistenceConfiguration;
import net.sf.ehcache.loader.CacheLoader;
import net.sf.ehcache.util.ClassLoaderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;

/**
 * Created by wuyaohui on 14-9-30.
 */
public class Caches {

    private Caches() {
    }

    private static CacheManager cacheManager = null;

    private static final Logger LOG = LoggerFactory.getLogger(Caches.class);

    public static final CacheLoader DEFAULT_LOADER = null;
    public static final Object DEFAULT_ARG = null;
    public static final String CORE_CACHE_MANAGER_FILE = "/ehcache-cam.xml";

    public static <V> V get(Object key, Class<V> clazz, Ehcache ehcache){
        Element ele = ehcache.get(key);
        return extractValue(ele,clazz);
    }

    public static Element getWithDefaultLoader(Object key,Ehcache ehcache){
        return getWithDefaultLoader(key,DEFAULT_ARG,ehcache);
    }

    public static Element getWithDefaultLoader(Object key,Object argument,Ehcache ehcache){
        return ehcache.getWithLoader(key,DEFAULT_LOADER,argument);
    }

    @SuppressWarnings("unchecked")
    public static <V> V extractValue(Element ele, Class<V> clazz){
        if(ele!=null){
            Object value = ele.getObjectValue();
            if(value!=null&&clazz.equals(value.getClass())){
                return (V)value;
            }
        }
        return null;
    }

    public static Element element(Object key,Object value){
        return new Element(key,value);
    }

    public static CacheManager getCacheManager(){
        synchronized (Caches.class){
            if(cacheManager==null){
                cacheManager = createCoreCacheManager();
            }
        }
        return cacheManager;
    }

    private static CacheManager createCoreCacheManager(){
        URL url = null;
        ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();
        if (standardClassloader != null) {
            url = standardClassloader.getResource(CORE_CACHE_MANAGER_FILE);
        }
        if(url != null){
            LOG.debug("Cam cache config file :{} found in standard classpath : {}",CORE_CACHE_MANAGER_FILE,url);
        }else{
            url = Caches.class.getResource(CORE_CACHE_MANAGER_FILE);
            if(url != null){
                LOG.debug("Cam cache config file :{} found in classpath : {}",CORE_CACHE_MANAGER_FILE,url);
            }else{
                throw new IllegalStateException(" Cam cache config file "+CORE_CACHE_MANAGER_FILE +" Not found.");
            }
        }

        return CacheManager.newInstance(url);
    }

    public static Cache createMemCache(String name , long maxEntriesLocalHeap, long timeToLiveSeconds,
                                       long timeToIdleSeconds){
        CacheConfiguration config = new CacheConfiguration();
        config.setName(name);
        config.setEternal(false);
        config.setMaxEntriesLocalHeap(maxEntriesLocalHeap);
        config.setTimeToLiveSeconds(timeToLiveSeconds);
        config.setTimeToIdleSeconds(timeToIdleSeconds);
        config.setCopyOnRead(false);
        config.setCopyOnWrite(true);
        config.setMemoryStoreEvictionPolicy("LRU");

        CopyStrategyConfiguration copyConfig = new CopyStrategyConfiguration();
        copyConfig.setClass("org.cam.core.cache.CloneCopyStrategy");
        config.addCopyStrategy(copyConfig);

        PersistenceConfiguration persistConfig = new PersistenceConfiguration();
        persistConfig.setStrategy("NONE");
        config.addPersistence(persistConfig);

        return new Cache(config);
    }
}


text:
using GraphQL.Types;

namespace GraphQL.Tests.Bugs;

public class Bug1156 : QueryTestBase<Bug1156Schema>
{
    [Fact]
    public void duplicated_type_names_should_throw_error()
    {
        var query = @"
{
    type1 {
        field1A
        field1B
    }

    type2 {
        field2A
        field2B
    }
}";
        var result = AssertQueryWithErrors(query, null, expectedErrorCount: 1, executed: false);
        result.Errors[0].Message.ShouldBe("Error executing document.");
        result.Errors[0].InnerException.Message.ShouldBe(@"Unable to register GraphType 'Type2' with the name 'MyType'. The name 'MyType' is already registered to 'Type1'. Check your schema configuration.");
    }
}

public sealed class Type1 : ObjectGraphType
{
    public Type1()
    {
        Name = "MyType";

        Field<StringGraphType>("Field1A").Resolve(_ => "Field1A Value");
        Field<StringGraphType>("Field1B").Resolve(_ => "Field1B Value");
    }
}

public sealed class Type2 : ObjectGraphType
{
    public Type2()
    {
        Name = "MyType";

        Field<StringGraphType>("Field2A").Resolve(_ => "Field2A Value");
        Field<StringGraphType>("Field2B").Resolve(_ => "Field1B Value");
    }
}

public sealed class QueryType : ObjectGraphType
{
    public QueryType()
    {
        Field<Type1>("type1").Resolve(x => new { });
        Field<Type2>("type2").Resolve(x => new { });
    }
}

public class Bug1156Schema : Schema
{
    public Bug1156Schema()
    {
        Query = new QueryType();
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <aws/appconfig/model/Action.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace AppConfig
{
namespace Model
{

Action::Action() :
    m_nameHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_uriHasBeenSet(false),
    m_roleArnHasBeenSet(false)
{
}

Action::Action(JsonView jsonValue) :
    m_nameHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_uriHasBeenSet(false),
    m_roleArnHasBeenSet(false)
{
  *this = jsonValue;
}

Action& Action::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("Name"))
  {
    m_name = jsonValue.GetString("Name");

    m_nameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Description"))
  {
    m_description = jsonValue.GetString("Description");

    m_descriptionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Uri"))
  {
    m_uri = jsonValue.GetString("Uri");

    m_uriHasBeenSet = true;
  }

  if(jsonValue.ValueExists("RoleArn"))
  {
    m_roleArn = jsonValue.GetString("RoleArn");

    m_roleArnHasBeenSet = true;
  }

  return *this;
}

JsonValue Action::Jsonize() const
{
  JsonValue payload;

  if(m_nameHasBeenSet)
  {
   payload.WithString("Name", m_name);

  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("Description", m_description);

  }

  if(m_uriHasBeenSet)
  {
   payload.WithString("Uri", m_uri);

  }

  if(m_roleArnHasBeenSet)
  {
   payload.WithString("RoleArn", m_roleArn);

  }

  return payload;
}

} // namespace Model
} // namespace AppConfig
} // namespace Aws


text:
directory 'C:\path_test_path'

windows_path 'C:\path_test_path' do
  action :add
end

directory 'c:\path_test_another_path'

windows_path 'C:\path_test_another_path' do
  action :add
end

directory 'c:/path_test_with_forward_slashes'

windows_path 'c:/path_test_with_forward_slashes' do
  action :add
end

powershell_script 'Log Path' do
  code <<-EOH
    $env:path -split ';' | out-file c:\\paths.txt
  EOH
end

windows_task 'testpath' do
  action [:create, :run]
  command 'powershell.exe -command $env:path > c:\\external_paths.txt'
end

ruby_block 'wait for task' do
  block do
    sleep 2
  end
end


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Nest.Tests.Unit
{
	public static class TestElasticClient
	{
		public static ElasticClient Client;
		public static ConnectionSettings Settings;
		static TestElasticClient()
		{
			Settings = new ConnectionSettings(UnitTestDefaults.Uri, UnitTestDefaults.DefaultIndex);

			Client = new ElasticClient(Settings);
		}

		public static string Serialize<T>(T obj) where T : class
		{
			return Encoding.UTF8.GetString(Client.Serializer.Serialize(obj));
		}

		public static T Deserialize<T>(string json) where T : class
		{
			return Client.Serializer.Deserialize<T>(new MemoryStream(Encoding.UTF8.GetBytes(json)));
		}
	}
}


text:
/**
 * @class nodelinux
 * This is a standalone module, originally designed for internal use in [NGN](http://github.com/thinkfirst/NGN).
 * However; it is capable of providing the same features for Node.JS scripts
 * independently of NGN.
 *
 * ### Getting node-linux
 *
 * `npm install node-linux`
 *
 * ### Using node-linux
 *
 * `var nm = require('node-linux');`
 *
 * @singleton
 * @author Corey Butler
 */
if (require('os').platform().indexOf('linux') < 0){
  throw 'node-linux is only supported on Linux.';
}

// Add daemon management capabilities
module.exports.Service = require('./daemon');


text:
/**
 * 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 org.hyperledger.api;

import com.google.protobuf.ByteString;
import org.hyperledger.common.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class APIBlock extends Block {

    public APIBlock(APIHeader header, List<? extends MerkleTreeNode> transactions) {
        super(header, transactions);
    }

    public static class Builder {
        int height;

        protected int version;
        protected BID previousHash;
        protected MerkleRoot merkleRoot;
        protected int createTime;
        protected int difficultyTarget;
        protected int nonce;
        protected List<MerkleTreeNode> transactions = new ArrayList<>();

        public Builder version(int version) {
            this.version = version;
            return this;
        }

        public Builder previousHash(BID previousHash) {
            this.previousHash = previousHash;
            return this;
        }

        public Builder merkleRoot(MerkleRoot merkleRoot) {
            this.merkleRoot = merkleRoot;
            return this;
        }

        public Builder createTime(int createTime) {
            this.createTime = createTime;
            return this;
        }

        public Builder difficultyTarget(int difficultyTarget) {
            this.difficultyTarget = difficultyTarget;
            return this;
        }

        public Builder nonce(int nonce) {
            this.nonce = nonce;
            return this;
        }

        public Builder transactions(Iterable<APITransaction> transactions) {
            transactions.forEach(this.transactions::add);
            return this;
        }

        public Builder transactions(APITransaction... transactions) {
            Collections.addAll(this.transactions, transactions);
            return this;
        }

        public Builder merkleNodes(MerkleTreeNode... nodes) {
            Collections.addAll(this.transactions, nodes);
            return this;
        }

        public Builder height(int height) {
            this.height = height;
            return this;
        }

        public APIBlock build() {
            if (merkleRoot == null)
                return new APIBlock(
                        new APIHeader(
                                new BitcoinHeader(version, previousHash, MerkleTree.computeMerkleRoot(transactions), createTime, difficultyTarget, nonce),
                                height), transactions);
            else
                return new APIBlock(
                        new APIHeader(
                                new BitcoinHeader(version, previousHash, merkleRoot, createTime, difficultyTarget, nonce),
                                height), transactions);
        }
    }

    public int getHeight() {
        return getHeader().getHeight();
    }

    @Override
    @SuppressWarnings("unchecked")
    public APIHeader getHeader() {
        return (APIHeader) super.getHeader();
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<? extends APITransaction> getTransactions() {
        return (List<? extends APITransaction>) super.getTransactions();
    }

    @SuppressWarnings("deprecation")
    public BCSAPIMessage.BLK toBCSAPIMessage() {
        BCSAPIMessage.BLK.Builder builder = BCSAPIMessage.BLK.newBuilder();
        builder.setVersion(getVersion());
        builder.setDifficulty(getDifficultyTarget());
        builder.setNonce(getNonce());
        builder.setTimestamp(getCreateTime());
        builder.setMerkleRoot(ByteString.copyFrom(getMerkleRoot().unsafeGetArray()));
        builder.setPreviousBlock(ByteString.copyFrom(getPreviousID().unsafeGetArray()));
        for (MerkleTreeNode n : getMerkleTreeNodes()) {
            if (n instanceof Transaction) {
                builder.addTransactions(BCSAPIMessage.MerkleNode.newBuilder().setTransaction(
                        ((Transaction) n).toBCSAPIMessage()
                ));
            } else {
                byte[] hash = Arrays.copyOf(n.getID().unsafeGetArray(), 33);
                hash[32] = (byte) (n.getMerkleHeight() & 0xff);
                builder.addTransactions(BCSAPIMessage.MerkleNode.newBuilder()
                        .setHash(ByteString.copyFrom(hash)));
            }
        }
        if (getHeight() >= 0) {
            builder.setHeight(getHeight());
        }
        return builder.build();
    }

    public static APIBlock fromProtobuf(BCSAPIMessage.BLK pb) throws HyperLedgerException {
        APIBlock.Builder builder = new APIBlock.Builder();
        builder.version(pb.getVersion());
        builder.difficultyTarget(pb.getDifficulty());
        builder.nonce(pb.getNonce());
        builder.createTime(pb.getTimestamp());
        builder.previousHash(BID.createFromSafeArray(pb.getPreviousBlock().toByteArray()));
        builder.merkleRoot(MerkleRoot.createFromSafeArray(pb.getMerkleRoot().toByteArray()));
        if (pb.getTransactionsCount() > 0) {
            builder.transactions(new ArrayList<>());
            for (BCSAPIMessage.MerkleNode n : pb.getTransactionsList()) {
                if (n.hasHash()) {
                    byte[] hash = Arrays.copyOf(n.getHash().toByteArray(), 33);
                    builder.merkleNodes(new PrunedNode(Hash.createFromSafeArray(Arrays.copyOf(hash, 32)), hash[33]));
                } else
                    builder.transactions(APITransaction.fromProtobuf(n.getTransaction()));
            }
        }
        if (pb.hasHeight()) {
            builder.height(pb.getHeight());
        }
        return builder.build();
    }
}


text:
package rotateit.data.model;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "teamId")
    private Team team;

    @Id
    private int userId;

    @Column(nullable = false)
    private String name;

    public Team getTeam() {
        return team;
    }

    public void setTeam(Team team) {
        this.team = team;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{team=" + team
            + ", userId=" + userId
            + ", name='" + name
            + "\'}";
    }
}


text:
declare const global, require, it;

import {TestScheduler} from 'rxjs/Rx';
import {clearWampMessages} from './wamp-testing';
import {expect} from 'chai';

export const xit: any = function (description, cb, timeout) {
    if (cb.length === 0) {
        it(description, function () {
            global.rxTestScheduler = new TestScheduler(assertDeepEqual);
            cb();
            global.rxTestScheduler.flush();
            clearWampMessages();
        });
    } else { // async test
        it.apply(this, arguments);
    }
};

function assertDeepEqual(actual, expected) {
    // console.log('expected: ', JSON.stringify(expected));
    // console.log('actual: ', JSON.stringify(actual));

    expect(actual).to.deep.equal(expected);
}


text:
<?php

namespace App\Http\Requests\Backend\Robot\QQ;

use App\Http\Requests\Request;

/**
 * Class StoreQQRequest
 * @package App\Http\Requests\Backend\Robot\QQ
 */
class StoreQQRequest extends Request
{
	/**
	 * Determine if the qq is authorized to make this request.
	 *
	 * @return bool
	 */
	public function authorize()
	{
		return access()->allow('manage-qqs');
	}

	/**
	 * Get the validation rules that apply to the request.
	 *
	 * @return array
	 */
	public function rules()
	{
		return [
			//
		];
	}
}


text:
import mongoose, {Schema} from 'mongoose'

const lessonSchema = new Schema({

  createdTime: Date,
  pingTime: Date,
  closeTime: Date,
  participants: [{type: Schema.Types.ObjectId, ref: 'User', index: true}]

}, {
  toJSON: {
    transform: function(doc, ret, options) {
      ret.id = ret._id
      delete ret._id
      delete ret.__v

      const now = new Date()
      const closed = doc.closeTime || (now - doc.pingTime > 2 * 60 * 1000)
      const closeTime = closed ? doc.closeTime || doc.pingTime : now
      ret.active = !closed
      ret.duration = closeTime - doc.createdTime

      delete ret.pingTime
      delete ret.closeTime

      return ret
    }
  }
})

export default mongoose.model('Lesson', lessonSchema)


text:
//
//  CodeViolationRootVC.m
//  CodeViolation
//

#import "CodeViolationRootVC.h"
#import "CodeViolationMapVC.h"

@implementation CodeViolationRootVC

@synthesize navigationController, objSearchBar, violationsTableView, objCodeViolationMapVC,
violationsFeaturesArray, objCodeViolationFeatureDetailsVC, searchActivityIndicator,
violationsQueryTask, violationsQuery, violationsFieldAliasDictionary, inspectionsQueryTask, inspectionsQuery, addressLocator;

@synthesize violationGrahicNew;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {

	self.violationsFieldAliasDictionary = [[NSMutableDictionary alloc] init];

	if(self.objCodeViolationFeatureDetailsVC == nil)
	{
		self.objCodeViolationFeatureDetailsVC = [[CodeViolationFeatureDetailsVC alloc] initWithNibName:@"CodeViolationFeatureDetailsVC" bundle:nil];
	}
	self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);

	// Violations QueryTask
	self.violationsQueryTask = [AGSQueryTask queryTaskWithURL:[NSURL URLWithString:[CodeViolationConfigSettings violationFeatureLayerUrl]]];
	self.violationsQueryTask.delegate = self;

	self.violationsQuery = [AGSQuery query];
	self.violationsQuery.outFields = [NSArray arrayWithObjects:@"*", nil];

	self.addressLocator = [AGSLocator locatorWithURL:[NSURL URLWithString:[CodeViolationConfigSettings locatorUrl]]];
	self.addressLocator.delegate = self;

	[super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated {

	self.title = [CodeViolationConfigSettings panelTitle];
	self.navigationController.contentSizeForViewInPopover = CGSizeMake(319.0, 599.0);
	self.navigationController.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);

	[self.objCodeViolationMapVC.objGraphicsLayer removeAllGraphics];

	[super viewWillAppear:animated];
}

// Ensure that the view controller supports rotation and that the split view can therefore show in both portrait and landscape.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

#pragma mark -
#pragma mark UISearchBarDelegate Methods

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {

	[self.objSearchBar resignFirstResponder];
	[self.searchActivityIndicator startAnimating];
	 if (![[UIApplication sharedApplication] isIgnoringInteractionEvents])
	[[UIApplication sharedApplication] beginIgnoringInteractionEvents];

	NSString *trimmedSearchString = [searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

	if([trimmedSearchString length] == 0)
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"ErrorTitle", @"ErrorTitle Item")
														message:NSLocalizedString(@"EnterValidData", @"EnterValidData Item")
													   delegate:nil
											  cancelButtonTitle:NSLocalizedString(@"OKTitle", @"OKTitle Item")
											  otherButtonTitles:nil];
		[alert show];
		[alert release];

		[self.searchActivityIndicator stopAnimating];
		if([[UIApplication sharedApplication] isIgnoringInteractionEvents])
		{
			[[UIApplication sharedApplication] endIgnoringInteractionEvents];
		}
	}
	else {

        NSArray *searchStringArray = [[NSString stringWithFormat:@"%@", searchBar.text] componentsSeparatedByString:@" "];

        if(!([searchStringArray count]>1))
        {
          searchStringArray = [[NSString stringWithFormat:@"%@", searchBar.text] componentsSeparatedByString:@","];
        }

		if ([searchStringArray count] > 1) {

			// Geocode
			NSArray *returnFields = [[CodeViolationConfigSettings locatorFields] componentsSeparatedByString:@","];

            NSDictionary *address = [NSDictionary dictionaryWithObject:searchBar.text forKey:@"SingleLine"];

            [self.addressLocator locationsForAddress:address returnFields:returnFields outSpatialReference:self.objCodeViolationMapVC.mapView.spatialReference];

		}
		else {

			// Search by violation type
			self.violationsQuery.where = [NSString stringWithFormat:@"%@ like '%%%@%%' and %@", [CodeViolationConfigSettings violationTypeField], searchBar.text, self.objCodeViolationMapVC.violationsFeatureLayer.definitionExpression];

			self.violationsQuery.returnGeometry = NO;

			if (self.objCodeViolationMapVC.mapView.visibleArea.envelope!=nil) {
				self.violationsQuery.geometry = self.objCodeViolationMapVC.mapView.visibleArea.envelope;
			}

			[self.violationsQueryTask executeWithQuery:self.violationsQuery];

		}
	}

}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
	[self.objSearchBar resignFirstResponder];
}

#pragma mark -
#pragma mark SearchFunctionality

- (NSArray*) formatAddress:(NSString *)addressString {
	NSArray *addressFields = [addressString componentsSeparatedByString:@","];
	NSMutableArray *addressFields1 = [NSMutableArray arrayWithObjects:@"",@"",@"",@"",nil];

	for (int i=0;i<[addressFields count]; i++) {
		if (i>3) {
			break;
		}
		NSString *field = [addressFields objectAtIndex:i];
		// if numeric and has length of 5 then it is zip code
		if ([self isZipCode:field]) {
			[addressFields1 replaceObjectAtIndex:3 withObject:field];
			break;
		}
		else if([field length] == 2){
			[addressFields1 replaceObjectAtIndex:2 withObject:[NSString stringWithFormat:@"%@",field]];
		}

		else {
			[addressFields1 replaceObjectAtIndex:i withObject:field];
		}
	}

	return addressFields1;
}

- (BOOL) isZipCode:(NSString *)field
{
	for (int i=0; i<[field length]; i++) {
		int asciiCode = (int)[field characterAtIndex:i];
		if ((asciiCode<48) || (asciiCode>57)){
			return NO;
		}
	}

	return([field length]==5)?YES:NO;
}

#pragma mark -
#pragma mark AGSLocatorDelegate

- (void)locator:(AGSLocator *)locator operation:(NSOperation *)op didFindLocationsForAddress:(NSArray *)candidates
{

    //check and see if we didn't get any results
	if (candidates == nil || [candidates count] == 0)
	{
        //show alert if we didn't get results
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
														message:NSLocalizedString(@"NoResultsFoundByLocator", @"NoResultsFoundByLocator Item")
													   delegate:nil
											  cancelButtonTitle:NSLocalizedString(@"OKTitle", @"OKTitle Item")
											  otherButtonTitles:nil];

        [alert show];
        [alert release];
	}
	else
	{
		AGSAddressCandidate *tempCandidate = [candidates objectAtIndex:0];

		if (tempCandidate.score >= 50) {

			AGSPoint *point = tempCandidate.location;

			if ([self.objCodeViolationMapVC.currentBaseMapServiceLayer.fullEnvelope containsPoint:point]) {

				AGSEnvelope *tempEnv = self.objCodeViolationMapVC.currentBaseMapServiceLayer.fullEnvelope;
				AGSMutableEnvelope *envelope = [AGSMutableEnvelope envelopeWithXmin:tempEnv.xmin ymin:tempEnv.ymin xmax:tempEnv.xmax ymax:tempEnv.ymax spatialReference:self.objCodeViolationMapVC.mapView.spatialReference];

				[envelope expandByFactor:[[CodeViolationConfigSettings ExpandFactorForSearch] doubleValue] withAnchorPoint:point];

				AGSPictureMarkerSymbol *newViolationPictureSymbol = [AGSPictureMarkerSymbol pictureMarkerSymbolWithImage:[UIImage imageNamed:@"MapPointPin.png"]] ;

                newViolationPictureSymbol.offset = CGPointMake(8, -18);

				AGSGraphic *violationGraphicNew = [AGSGraphic graphicWithGeometry:point
																		   symbol:newViolationPictureSymbol
																	   attributes:nil
															 infoTemplateDelegate:nil];

                [self.objCodeViolationMapVC.objGraphicsLayer removeAllGraphics];

				[self.objCodeViolationMapVC.objGraphicsLayer addGraphic:violationGraphicNew];

				[self.objCodeViolationMapVC.mapView zoomToEnvelope:envelope animated:NO];

			}
			else {
				UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
																message:NSLocalizedString(@"ResultsFoundAreOutsideMap", @"ResultsFoundAreOutsideMap Item")
															   delegate:nil
													  cancelButtonTitle:NSLocalizedString(@"OKTitle", @"OKTitle Item")
													  otherButtonTitles:nil];

				[alert show];
				[alert release];
			}

		}
	}

	[self.searchActivityIndicator stopAnimating];
	if([[UIApplication sharedApplication] isIgnoringInteractionEvents])
	{
		[[UIApplication sharedApplication] endIgnoringInteractionEvents];
	}
}

- (void)locator:(AGSLocator *)locator operation:(NSOperation *)op didFailLocationsForAddress:(NSError *)error
{
    //The location operation failed, display the error
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"LocatorFailed",@"LocatorFailed Item")
                    message:[NSString stringWithFormat:@"Error: %@", error.description] delegate:nil
                    cancelButtonTitle:NSLocalizedString(@"OKTitle", @"OKTitle Item") otherButtonTitles:nil];

    [alert show];
    [alert release];

	[self.searchActivityIndicator stopAnimating];

	if([[UIApplication sharedApplication] isIgnoringInteractionEvents])
	{
		[[UIApplication sharedApplication] endIgnoringInteractionEvents];
	}
}

#pragma mark -
#pragma mark AGSQueryTaskDelegate Methods

- (void)queryTask:(AGSQueryTask *)queryTask operation:(NSOperation *)op
didExecuteWithFeatureSetResult:(AGSFeatureSet *)featureSet {
	//get feature, and load in to table

	if (queryTask == self.violationsQueryTask) {

		self.violationsFeaturesArray = (NSMutableArray *)featureSet.features;

		[self.violationsTableView reloadData];

		[self.searchActivityIndicator stopAnimating];

		if([[UIApplication sharedApplication] isIgnoringInteractionEvents]) {

			[[UIApplication sharedApplication] endIgnoringInteractionEvents];
		}

		if ([self.violationsFeaturesArray count] == 0) {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                        message:NSLocalizedString(@"NoResultsFoundforViolationType", @"NoResultsFoundforViolationType Item")
                        delegate:nil cancelButtonTitle:NSLocalizedString(@"OKTitle", @"OKTitle Item") otherButtonTitles:nil];

			[alert show];
			[alert release];
		}

	}

}

- (void)queryTask:(AGSQueryTask *) queryTask operation:(NSOperation *) op didFailWithError:(NSError *) error {

	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"ErrorTitle", @"ErrorTitle Item")
                    message:NSLocalizedString(@"QueryTaskfailwitherror", @"QueryTaskfailwitherror Item")
                    delegate:nil cancelButtonTitle:NSLocalizedString(@"OKTitle", @"OKTitle Item") otherButtonTitles:nil];

	[alert show];
	[alert release];

	[self.searchActivityIndicator stopAnimating];

	if([[UIApplication sharedApplication] isIgnoringInteractionEvents]) {

		[[UIApplication sharedApplication] endIgnoringInteractionEvents];
	}

}

#pragma mark -

#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	if ([self.violationsFeaturesArray count] > 0) {
		return [self.violationsFeaturesArray count];
	}
	else {
		return 0;
	}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	[cell setSelectionStyle:UITableViewCellSelectionStyleBlue];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...

	if ([self.violationsFeaturesArray count] > 0)
	{
		NSArray *violationsDisplayFields = [CodeViolationConfigSettings violationsDisplayFields];

		// Check Null Fields

		if ([[((AGSGraphic *)[self.violationsFeaturesArray objectAtIndex:indexPath.row]) attributeForKey:[violationsDisplayFields objectAtIndex:0]] isKindOfClass:[NSNull class]] ||
			[((AGSGraphic *)[self.violationsFeaturesArray objectAtIndex:indexPath.row]) attributeForKey:[violationsDisplayFields objectAtIndex:0]] == nil ||
			[[NSString stringWithFormat:@"%@", [((AGSGraphic *)[self.violationsFeaturesArray objectAtIndex:indexPath.row]) attributeForKey:[violationsDisplayFields objectAtIndex:0]]] isEqualToString:@""])
		{
			cell.textLabel.text = NSLocalizedString(@"NoData", @"NoData Item");
		}
		else {

			cell.textLabel.text = [NSString stringWithFormat:@"%@", [((AGSGraphic *)[self.violationsFeaturesArray objectAtIndex:indexPath.row]) attributeForKey:[violationsDisplayFields objectAtIndex:0]]];
		}

		if ([[((AGSGraphic *)[self.violationsFeaturesArray objectAtIndex:indexPath.row]) attributeForKey:[violationsDisplayFields objectAtIndex:1]] isKindOfClass:[NSNull class]] ||
			[((AGSGraphic *)[self.violationsFeaturesArray objectAtIndex:indexPath.row]) attributeForKey:[violationsDisplayFields objectAtIndex:1]] == nil ||
			[[NSString stringWithFormat:@"%@", [((AGSGraphic *)[self.violationsFeaturesArray objectAtIndex:indexPath.row]) attributeForKey:[violationsDisplayFields objectAtIndex:1]]] isEqualToString:@""])
		{
			cell.detailTextLabel.text = NSLocalizedString(@"NoData", @"NoData Item");
		}
		else {

			cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", [((AGSGraphic *)[self.violationsFeaturesArray objectAtIndex:indexPath.row]) attributeForKey:[violationsDisplayFields objectAtIndex:1]]];
		}

		UIImage *image = nil;
		AGSGraphic *currentGraphic = (AGSGraphic *)[self.violationsFeaturesArray objectAtIndex:indexPath.row];

		if ([[NSString stringWithFormat:@"%@", [currentGraphic attributeForKey:[CodeViolationConfigSettings statusField]]] isEqualToString:@"Open"]) {
			image = [UIImage imageNamed:@"openViolation.png"];
		}
		else {
			image = [UIImage imageNamed:@"closeViolation.png"];
		}

		UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
		button.tag = indexPath.row;
		CGRect frame = CGRectMake(0.0, 0.0, 36, 36);
		button.frame = frame;	// match the button's size with the image size

		[button setBackgroundImage:image forState:UIControlStateNormal];

		// set the button's target to this table view controller so we can interpret touch events and map that to a NSIndexSet
		[button addTarget:self action:@selector(accessoryButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
		cell.backgroundColor = [UIColor clearColor];
		cell.accessoryView = button;

		if ([[currentGraphic attributeForKey:@"OBJECTID"] integerValue] == [[self.violationGrahicNew attributeForKey:@"OBJECTID"] integerValue]) {

			[self.violationsTableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
			self.violationGrahicNew = nil;
		}
	}

	return cell;

}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    /*
     When a row is selected, set the detail view controller's detail item to the item associated with the selected row.
     */

	// Load Violations

    //nav added

	if ([self.violationsFieldAliasDictionary count] > 0) {
		[self showViolationGraphicDetail:indexPath];
	}
	else {
		[self.objCodeViolationMapVC executeQueryWithCondition];
		[self performSelector:@selector(showViolationGraphicDetail:) withObject:indexPath afterDelay:1.5];
	}

}

#pragma mark -
#pragma mark Actions

-(void)accessoryButtonTapped:(id)sender {

	NSIndexPath *indexPath = [NSIndexPath indexPathForRow:((UIButton *)sender).tag inSection:0];

	/*
     When a row is selected, set the detail view controller's detail item to the item associated with the selected row.
     */

	// Load Violations
	if ([self.violationsFieldAliasDictionary count] > 0) {
		[self showViolationGraphicDetail:indexPath];
	}
	else {
		[self.objCodeViolationMapVC executeQueryWithCondition];
		[self performSelector:@selector(showViolationGraphicDetail:) withObject:indexPath afterDelay:1.5];
	}
}

- (void) showViolationGraphicDetail :(NSIndexPath *)indexPath {

	[self.navigationController pushViewController:self.objCodeViolationFeatureDetailsVC animated:YES];

	AGSGraphic *currentGraphic = [self.violationsFeaturesArray objectAtIndex:indexPath.row];
	AGSGraphic *ringGraphic = [AGSGraphic graphicWithGeometry:currentGraphic.geometry
                        symbol:nil attributes:nil infoTemplateDelegate:nil];

	[self.objCodeViolationMapVC addRingForSelectedViolation:ringGraphic];
	[self reloadFeatureDetails:currentGraphic];
}

-(void)reloadFeatureDetails:(AGSGraphic *)currentGraphic {

	if (([[currentGraphic attributeForKey:@"OBJECTID"] intValue] != [[self.objCodeViolationFeatureDetailsVC.selectedViolationGraphic attributeForKey:@"OBJECTID"] intValue]) || (self.objCodeViolationFeatureDetailsVC.didUpdateViolation == YES)) {

		self.objCodeViolationFeatureDetailsVC.selectedViolationGraphic = currentGraphic;
		self.objCodeViolationFeatureDetailsVC.didUpdateViolation = NO;

		if (self.objCodeViolationFeatureDetailsVC.inspectionsQueryTask == nil) {

			self.objCodeViolationFeatureDetailsVC.inspectionsQueryTask = [AGSQueryTask queryTaskWithURL:[NSURL URLWithString:[CodeViolationConfigSettings inspectionFeatureLayerUrl]]];
			self.objCodeViolationFeatureDetailsVC.inspectionsQueryTask.delegate = self.objCodeViolationFeatureDetailsVC;

			// Load Inspections

			self.objCodeViolationFeatureDetailsVC.inspectionsQuery = [AGSQuery query];
			self.objCodeViolationFeatureDetailsVC.inspectionsQuery.outFields = [NSArray arrayWithObjects:@"*", nil];
			self.objCodeViolationFeatureDetailsVC.inspectionsQuery.returnGeometry = NO;

			AGSSpatialReference *sr = ((CodeViolationMapVC *)((CodeViolationAppDelegate *)[UIApplication sharedApplication].delegate).objCodeViolationMapVC).mapView.spatialReference;

			self.objCodeViolationFeatureDetailsVC.inspectionsQuery.outSpatialReference = sr;

		}

		// check for same graphic
		self.objCodeViolationFeatureDetailsVC.inspectionsFeaturesArray = nil;
		[self.objCodeViolationFeatureDetailsVC.inspectionDetailsTableView reloadData];

		[self.objCodeViolationFeatureDetailsVC.loadingInspectionsIndicator startAnimating];

		self.objCodeViolationFeatureDetailsVC.inspectionsQuery.where = [NSString stringWithFormat:@"VIOLATEKEY='%@'", [self.objCodeViolationFeatureDetailsVC.selectedViolationGraphic attributeForKey:@"VIOLATIONID"]];

		[self.objCodeViolationFeatureDetailsVC.inspectionsQueryTask executeWithQuery:self.objCodeViolationFeatureDetailsVC.inspectionsQuery];

	}
	else {
		if ([self.objCodeViolationFeatureDetailsVC.inspectionsFeaturesArray count] > 0) {
			[self.objCodeViolationFeatureDetailsVC.inspectionDetailsTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
		}
	}

	if ([[self.objCodeViolationFeatureDetailsVC.selectedViolationGraphic attributeForKey:@"STATUS"] isEqualToString:@"Open"]) {

		self.objCodeViolationFeatureDetailsVC.editViolationButton.enabled = YES;

        if (([self.objCodeViolationFeatureDetailsVC.actionDomainValues count]>0) ||([self.objCodeViolationFeatureDetailsVC.inspectionStatusDomainValues count]>0)) {

            self.objCodeViolationFeatureDetailsVC.addInspectionButton.enabled = YES;
        }
        else {
            [self.objCodeViolationFeatureDetailsVC.loadingInspectionsIndicatorForButton startAnimating];

            self.objCodeViolationFeatureDetailsVC.addInspectionButton.enabled = NO;
        }

	}
	else if ([[self.objCodeViolationFeatureDetailsVC.selectedViolationGraphic attributeForKey:@"STATUS"] isEqualToString:@"Closed"]) {

		self.objCodeViolationFeatureDetailsVC.editViolationButton.enabled = NO;
		self.objCodeViolationFeatureDetailsVC.addInspectionButton.enabled = NO;
	}

	// Violation Details Display Fields

	self.objCodeViolationFeatureDetailsVC.violationDetailsDisplayFieldsArray = [CodeViolationConfigSettings violationDetailsDisplayFields];
	self.objCodeViolationFeatureDetailsVC.violationsFieldAliasDictionary = self.violationsFieldAliasDictionary;

	// Inspection Details Display Fields

	self.objCodeViolationFeatureDetailsVC.inspectionDetailsDisplayFieldsArray = [CodeViolationConfigSettings inspectionDetailsDisplayFields];

	[self.objCodeViolationFeatureDetailsVC.violationDetailsTableView reloadData];
	[self.objCodeViolationFeatureDetailsVC.violationDetailsTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];

}

#pragma mark -

#pragma mark Memory management

- (void)viewDidUnload {

	self.navigationController = nil;
	self.objSearchBar = nil;
	self.violationsTableView = nil;
	self.objCodeViolationMapVC = nil;
	self.violationsFeaturesArray = nil;
	self.objCodeViolationFeatureDetailsVC = nil;
	self.searchActivityIndicator = nil;
	self.violationsQueryTask = nil;
	self.violationsQuery = nil;
	self.violationsFieldAliasDictionary = nil;
	self.inspectionsQueryTask = nil;
	self.inspectionsQuery = nil;
	self.addressLocator = nil;
	self.violationGrahicNew = nil;

	[super viewDidUnload];
}

- (void)dealloc {

	[self.navigationController release];
	[self.objSearchBar release];
	[self.violationsTableView release];
	[self.objCodeViolationMapVC release];
	[self.violationsFeaturesArray release];
	[self.objCodeViolationFeatureDetailsVC release];
	[self.searchActivityIndicator release];
	[self.violationsQueryTask release];
	[self.violationsQuery release];
	[self.violationsFieldAliasDictionary release];
	[self.inspectionsQueryTask release];
	[self.inspectionsQuery release];
	[self.addressLocator release];
	[self.violationGrahicNew release];

    [super dealloc];
}

#pragma mark -

@end


text:
package com.jiubang.goscreenlock.theme.cjpcardcool.weather.bean;

import com.jiubang.goscreenlock.theme.cjpcardcool.weather.common.CommonConstants;

/**
 * 未来七天的天气预报
 *
 * @author liuwenqin
 *
 */
public class ForecastInfo
{
	/**
	 * 预报日期(由mLongDate代替)
	 */
	@Deprecated
	private String	mDate;
	/**
	 * 星期几
	 */
	private String	mWeekDate;
	/**
	 * 天气状态:晴、雨等
	 */
	private String	mStatus;
	/**
	 * 各种天气状态对应的天气类型
	 */
	private int		mStatusType;
	/**
	 * 最高温度
	 */
	private float	mHigh;
	/**
	 * 最低温度
	 */
	private float	mLow;
	/**
	 * 风向
	 */
	private String	mWindDir;
	/**
	 * 风力
	 */
	private String	mWindStrength;
	/**
	 * 风力数值
	 */
	private float	mWindStrengthValue;
	/**
	 * 自定义风向类型
	 */
	private int		mWindDirType;
	/**
	 * 降水概率
	 */
	private int		mPop;
	/**
	 * 白天天气预报描述
	 */
	private String	mDayStatus;
	/**
	 * 夜晚天气预报描述
	 */
	private String	mNightStatus;
	/**
	 * 预报时间,包括年份。以当地时间为准
	 */
	private String	mLongDate;

	public ForecastInfo()
	{
		// 默认为无效天气信息
		mDate = CommonConstants.UNKNOWN_VALUE_STRING;
		mWeekDate = CommonConstants.UNKNOWN_VALUE_STRING;
		mStatus = CommonConstants.UNKNOWN_VALUE_STRING;
		mStatusType = CommonConstants.UNKNOWN_WEATHER_TYPE;
		mHigh = CommonConstants.UNKNOWN_VALUE_INT;
		mLow = CommonConstants.UNKNOWN_VALUE_INT;
		mWindDir = CommonConstants.UNKNOWN_VALUE_STRING;
		mWindDirType = CommonConstants.UNKNOWN_WIND_DIR_TYPE;
		mWindStrength = CommonConstants.UNKNOWN_VALUE_STRING;
		mWindStrengthValue = CommonConstants.UNKNOWN_VALUE_FLOAT;
		mPop = CommonConstants.UNKNOWN_VALUE_INT;
	}

	public float getWindStrengthValue()
	{
		return mWindStrengthValue;
	}

	/** 设置风力数值 */
	public void setWindStrengthInt(float windStrengthValue)
	{
		this.mWindStrengthValue = windStrengthValue;
	}

	public int getWindDirType()
	{
		return mWindDirType;
	}

	/** 设置风向类型 */
	public void setWindDirType(int wind_dir_type)
	{
		this.mWindDirType = wind_dir_type;
	}

	/**
	 * 设置风向
	 */
	public void setWindDir(String wind_dir)
	{
		this.mWindDir = wind_dir;
	}

	public String getWindDir()
	{
		return this.mWindDir;
	}

	/**
	 * 设置风力
	 */
	public void setWindStrength(String wind_strength)
	{
		this.mWindStrength = wind_strength;
	}

	public String getWindStrength()
	{
		return this.mWindStrength;
	}

	public String getDate()
	{ // getDate2
		return mDate;
	}

	public void setDate(String date)
	{
		this.mDate = date;
	}

	public String getWeekDate()
	{
		return mWeekDate;
	}

	public void setWeekDate(String week_date)
	{
		this.mWeekDate = week_date;
	}

	public String getStatus()
	{
		return mStatus;
	}

	public void setStatus(String status)
	{
		this.mStatus = status;
	}

	public int getStatusType()
	{
		return mStatusType;
	}

	public void setStatusType(int status_type)
	{
		this.mStatusType = status_type;
	}

	public float getHigh()
	{
		return mHigh;
	}

	public void setHigh(float high)
	{
		this.mHigh = high;
	}

	public float getLow()
	{
		return mLow;
	}

	public void setLow(float low)
	{
		this.mLow = low;
	}

	public void setPop(int pop)
	{
		this.mPop = pop;
	}

	public int getPop()
	{
		return this.mPop;
	}

	public String getDayStatus()
	{
		return mDayStatus;
	}

	public void setDayStatus(String dayStatus)
	{
		this.mDayStatus = dayStatus;
	}

	public String getNightStatus()
	{
		return mNightStatus;
	}

	public void setNightStatus(String nightStatus)
	{
		this.mNightStatus = nightStatus;
	}

	public String getLongDate()
	{
		return mLongDate;
	}

	public void setLongDate(String longDate)
	{
		this.mLongDate = longDate;
	}
}


text:
/* this file defines the profile structure in the profile shared
   memory area */

#define PROF_SHMEM_KEY ((key_t)0x07021999)
#define PROF_SHM_MAGIC 0x6349985
#define PROF_SHM_VERSION 1

struct profile_struct {
	int prof_shm_magic;
	int prof_shm_version;
	unsigned smb_count; /* how many SMB packets we have processed */
	unsigned uid_changes; /* how many times we change our effective uid */
};

extern struct profile_struct *profile_p;


text:
🚧 This library is early in development. 🚧

This library is early in development, and the API may change at any time until version 1.0.0. We hope to stabilize the API soon, providing the core functionality on an as-needed basis. If you need an API integrated, please open an issue.

This library provides an easy-to-use overlay for the automatically generated [Go SDK for oVirt](https://github.com/ovirt/go-ovirt). It does *not* replace the Go SDK. It implements the functions of the SDK only partially and is primarily used by the [oVirt Terraform provider](https://github.com/ovirt/terraform-provider-ovirt/).

## Using this library

To use this library you will have to include it as a Go module dependency:

```
go get github.com/ovirt/go-ovirt-client
```

You can then create a client instance like this:

```go
package main

import (
	"crypto/x509"

	"github.com/ovirt/go-client-log"
	"github.com/ovirt/go-ovirt-client"
)

func main() {
	// Create a logger that logs to the standard Go log here:
	logger := ovirtclientlog.NewGoLogLogger(nil)

	// Create an ovirtclient.TLSProvider implementation. This allows for simple
	// TLS configuration.
	tls := ovirtclient.TLS()

	// Add certificates from an in-memory byte slice. Certificates must be in PEM format.
	tls.CACertsFromMemory(caCerts)

	// Add certificates from a single file. Certificates must be in PEM format.
	tls.CACertsFromFile("/path/to/file.pem")

	// Add certificates from a directory. Optionally, regular expressions can be passed that must match the file
	// names.
	tls.CACertsFromDir(
		"/path/to/certs",
		regexp.MustCompile(`\.pem`),
	)

	// Add system certificates. This doesn't work on Windows.
	tls.CACertsFromSystem()

	// Add a custom cert pool as a source of certificates. This option is
	// incompatible with CACertsFromSystem.
	// tls.CACertsFromCertPool(x509.NewCertPool())

	// Disable certificate verification. This is a bad idea, please don't do this.
	tls.Insecure()

	// Create a new goVirt instance:
	client, err := ovirtclient.New(
		// URL to your oVirt engine API here:
		"https://your-ovirt-engine/ovirt-engine/api/",
		// Username here:
		"admin@internal",
		// Password here:
		"password-here",
		// Pass the TLS provider here:
		tls,
		// Pass the logger here:
		logger,
		// Pass in extra settings here. Must implement the ovirtclient.ExtraSettings interface.
		nil,
	)
	if err != nil {
		// Handle error, here in a really crude way:
		panic(err)
	}
	// Use client. Please use the code completion in your IDE to
	// discover the functions. Each is well documented.
	upload, err := client.StartUploadToNewDisk(
		//...
	)
	//....
}
```

## Test helper

The test helper can work in two ways:

Either it sets up test fixtures in the mock client, or it sets up a live connection and identifies a usable storage
domain, cluster, etc. for testing purposes.

The easiest way to set up the test helper is using environment variables. To do that, you can use the
`ovirtclient.NewTestHelperFromEnv()` function:

```go
helper := ovirtclient.NewTestHelperFromEnv(ovirtclientlog.NewNOOPLogger())
```

This function will inspect environment variables to determine if a connection to a live oVirt engine can be estabilshed.
The following environment variables are supported:

- `OVIRT_URL`: URL of the oVirt engine API.
- `OVIRT_USERNAME`: The username for the oVirt engine.
- `OVIRT_PASSWORD`: The password for the oVirt engine
- `OVIRT_CAFILE`: A file containing the CA certificate in PEM format.
- `OVIRT_CA_BUNDLE`: Provide the CA certificate in PEM format directly.
- `OVIRT_INSECURE`: Disable certificate verification if set. Not recommended.
- `OVIRT_CLUSTER_ID`: The cluster to use for testing. Will be automatically chosen if not provided.
- `OVIRT_BLANK_TEMPLATE_ID`: ID of the blank template. Will be automatically chosen if not provided.
- `OVIRT_STORAGE_DOMAIN_ID`: Storage domain to use for testing. Will be automatically chosen if not provided.
- `OVIRT_VNIC_PROFILE_ID`: VNIC profile to use for testing. Will be automatically chosen if not provided.

You can also create the test helper manually:

```go
import (
    "os"
    "testing"

    ovirtclient "github.com/ovirt/go-ovirt-client"
    ovirtclientlog "github.com/ovirt/go-ovirt-client-log"
)

func TestSomething(t *testing.T) {
    // Create a logger that logs to the standard Go log here
    logger := ovirtclientlog.NewTestLogger(t)

    // Set to true to use in-memory mock, otherwise this will use a live connection.
    mock := false

    // Create the test helper
    helper, err := ovirtclient.NewTestHelper(
        "https://localhost/ovirt-engine/api",
        "admin@internal",
        "super-secret",
        ovirtclient.TLS().CACertsFromSystem(),
        // The following parameters define which infrastructure parts to use for testing.
        // Leave these empty for auto-detection / fixture setup.
        os.Getenv("OVIRT_CLUSTER_ID"),
        os.Getenv("OVIRT_BLANK_TEMPLATE_ID"),
        os.Getenv("OVIRT_STORAGE_DOMAIN_ID"),
        os.Getenv("OVIRT_VNIC_PROFILE_ID"),
        mock,
        logger,
    )
    if err != nil {
        t.Fatal(err)
    }
    // Fetch the cluster ID for testing
    clusterID := helper.GetClusterID()
    //...
}
```

**Tip:** You can use any logger that satisfies the `Logger` interface described in [go-ovirt-client-log](https://github.com/oVirt/go-ovirt-client-log)

## Retries

This library attempts to retry API calls that can be retried if possible. Each function has a sensible retry policy. However, you may want to customize the retries by passing one or more retry flags. The following retry flags are supported:

- `ovirtclient.ContextStrategy(ctx)`: this strategy will stop retries when the context parameter is canceled.
- `ovirtclient.ExponentialBackoff(factor)`: this strategy adds a wait time after each time, which is increased by the given factor on each try. The default is a backoff with a factor of 2.
- `ovirtclient.AutoRetry()`: this strategy will cancel retries if the error in question is a permanent error. This is enabled by default.
- `ovirtclient.MaxTries(tries)`: this strategy will abort retries if a maximum number of tries is reached. On complex calls the retries are counted per underlying API call.
- `ovirtclient.Timeout(duration)`: this strategy will abort retries if a certain time has been elapsed for the higher level call.
- `ovirtclient.CallTimeout(duration)`: this strategy will abort retries if a certain underlying API call takes longer than the specified duration.

## Mock client

This library also provides a mock oVirt client that doesn't need working oVirt engine to function. It stores all information in-memory and simulates a working oVirt system. You can instantiate the mock client like so:

```go
client := ovirtclient.NewMock()
```

We recommend using the `ovirtclient.Client` interface as a means to declare it as a dependency in your factory so you can pass both the mock and the real connection as a parameter:

```go
func NewMyoVirtUsingUtility(
    client ovirtclient.Client,
) *myOVirtUsingUtility {
    return &myOVirtUsingUtility{
        client: client,
    }
}
```

## FAQ

### Why doesn't the library return the underlying oVirt SDK objects?

It's a painful decision we made. We want to encourage anyone who needs a certain function to submit a PR instead of simply relying on the SDK objects. This will lead to some overhead when a new function needs to be added, but leads to cleaner code in the end and makes this library more comprehensive. It also makes it possible to create the mock client, which would not be possibly if we had to simulate all parts of the oVirt engine.

If you need to access the oVirt SDK client you can do so from the `ovirtclient.New()` function:

```go
client, err := ovirtclient.New(
    //...
)
if err != nil {
    //...
}
sdkClient := client.GetSDKClient()
```

You can also get a properly preconfigured HTTP client if you need it:

```go
httpClient := client.GetHTTPClient()
```

**🚧 Warning:** If your code relies on the SDK or HTTP clients you will not be able to use the mock functionality described above for testing.

## Contributing

You want to help out? Awesome! Please head over to our [contribution guide](CONTRIBUTING.md), which explains how this library is built in detail.


text:
from __future__ import division

import numpy as np

from . import common_args
from . import sobol_sequence
from ..util import scale_samples, read_param_file

# Generate matrix of samples for derivative-based global sensitivity measure (dgsm)
# start from a QMC (sobol) sequence and finite difference with delta % steps
def sample(problem, N, delta=0.01, seed=None):
    if seed:
        np.random.seed(seed)

    D = problem['num_vars']

    # How many values of the Sobol sequence to skip
    skip_values = 1000

    # Create base sequence - could be any type of sampling
    base_sequence = sobol_sequence.sample(N + skip_values, D)
    # scale before finite differencing
    scale_samples(base_sequence, problem['bounds'])
    dgsm_sequence = np.zeros([N * (D + 1), D])

    index = 0

    for i in range(skip_values, N + skip_values):

        # Copy the initial point
        dgsm_sequence[index, :] = base_sequence[i, :]
        index += 1

        for j in range(D):
            temp = np.zeros(D)
            temp[j] = base_sequence[i, j] * delta
            dgsm_sequence[index, :] = base_sequence[i, :] + temp
            dgsm_sequence[index, j] = min(
                dgsm_sequence[index, j], problem['bounds'][j][1])
            dgsm_sequence[index, j] = max(
                dgsm_sequence[index, j], problem['bounds'][j][0])
            index += 1

    return dgsm_sequence

def cli_parse(parser):
    """Add method specific options to CLI parser.

    Parameters
    ----------
    parser : argparse object

    Returns
    ----------
    Updated argparse object
    """
    parser.add_argument('-d', '--delta', type=float,
                        required=False, default=0.01,
                        help='Finite difference step size (percent)')
    parser.add_argument('-n', '--samples', type=int,
                        required=True, help='Number of Samples')
    return parser

def cli_action(args):
    """Run sampling method

    Parameters
    ----------
    args : argparse namespace
    """
    problem = read_param_file(args.paramfile)
    param_values = sample(problem, args.samples, args.delta, seed=args.seed)
    np.savetxt(args.output, param_values, delimiter=args.delimiter,
               fmt='%.' + str(args.precision) + 'e')

if __name__ == "__main__":
    common_args.run_cli(cli_parse, cli_action)


text:
package autopilot

import (
	"bytes"
	"encoding/hex"
	"net"
	"sort"
	"sync/atomic"
	"time"

	"github.com/btcsuite/btcd/btcec/v2"
	"github.com/btcsuite/btcd/btcec/v2/ecdsa"
	"github.com/btcsuite/btcd/btcutil"
	"github.com/lightningnetwork/lnd/channeldb"
	"github.com/lightningnetwork/lnd/kvdb"
	"github.com/lightningnetwork/lnd/lnwire"
	"github.com/lightningnetwork/lnd/routing/route"
)

var (
	testRBytes, _ = hex.DecodeString("8ce2bc69281ce27da07e6683571319d18e949ddfa2965fb6caa1bf0314f882d7")
	testSBytes, _ = hex.DecodeString("299105481d63e0f4bc2a88121167221b6700d72a0ead154c03be696a292d24ae")
	testRScalar   = new(btcec.ModNScalar)
	testSScalar   = new(btcec.ModNScalar)
	_             = testRScalar.SetByteSlice(testRBytes)
	_             = testSScalar.SetByteSlice(testSBytes)
	testSig       = ecdsa.NewSignature(testRScalar, testSScalar)

	chanIDCounter uint64 // To be used atomically.
)

// databaseChannelGraph wraps a channeldb.ChannelGraph instance with the
// necessary API to properly implement the autopilot.ChannelGraph interface.
//
// TODO(roasbeef): move inmpl to main package?
type databaseChannelGraph struct {
	db *channeldb.ChannelGraph
}

// A compile time assertion to ensure databaseChannelGraph meets the
// autopilot.ChannelGraph interface.
var _ ChannelGraph = (*databaseChannelGraph)(nil)

// ChannelGraphFromDatabase returns an instance of the autopilot.ChannelGraph
// backed by a live, open channeldb instance.
func ChannelGraphFromDatabase(db *channeldb.ChannelGraph) ChannelGraph {
	return &databaseChannelGraph{
		db: db,
	}
}

// type dbNode is a wrapper struct around a database transaction an
// channeldb.LightningNode. The wrapper method implement the autopilot.Node
// interface.
type dbNode struct {
	tx kvdb.RTx

	node *channeldb.LightningNode
}

// A compile time assertion to ensure dbNode meets the autopilot.Node
// interface.
var _ Node = (*dbNode)(nil)

// PubKey is the identity public key of the node. This will be used to attempt
// to target a node for channel opening by the main autopilot agent. The key
// will be returned in serialized compressed format.
//
// NOTE: Part of the autopilot.Node interface.
func (d dbNode) PubKey() [33]byte {
	return d.node.PubKeyBytes
}

// Addrs returns a slice of publicly reachable public TCP addresses that the
// peer is known to be listening on.
//
// NOTE: Part of the autopilot.Node interface.
func (d dbNode) Addrs() []net.Addr {
	return d.node.Addresses
}

// ForEachChannel is a higher-order function that will be used to iterate
// through all edges emanating from/to the target node. For each active
// channel, this function should be called with the populated ChannelEdge that
// describes the active channel.
//
// NOTE: Part of the autopilot.Node interface.
func (d dbNode) ForEachChannel(cb func(ChannelEdge) error) error {
	return d.node.ForEachChannel(d.tx, func(tx kvdb.RTx,
		ei *channeldb.ChannelEdgeInfo, ep, _ *channeldb.ChannelEdgePolicy) error {

		// Skip channels for which no outgoing edge policy is available.
		//
		// TODO(joostjager): Ideally the case where channels have a nil
		// policy should be supported, as autopilot is not looking at
		// the policies. For now, it is not easily possible to get a
		// reference to the other end LightningNode object without
		// retrieving the policy.
		if ep == nil {
			return nil
		}

		edge := ChannelEdge{
			ChanID:   lnwire.NewShortChanIDFromInt(ep.ChannelID),
			Capacity: ei.Capacity,
			Peer: dbNode{
				tx:   tx,
				node: ep.Node,
			},
		}

		return cb(edge)
	})
}

// ForEachNode is a higher-order function that should be called once for each
// connected node within the channel graph. If the passed callback returns an
// error, then execution should be terminated.
//
// NOTE: Part of the autopilot.ChannelGraph interface.
func (d *databaseChannelGraph) ForEachNode(cb func(Node) error) error {
	return d.db.ForEachNode(func(tx kvdb.RTx, n *channeldb.LightningNode) error {
		// We'll skip over any node that doesn't have any advertised
		// addresses. As we won't be able to reach them to actually
		// open any channels.
		if len(n.Addresses) == 0 {
			return nil
		}

		node := dbNode{
			tx:   tx,
			node: n,
		}
		return cb(node)
	})
}

// addRandChannel creates a new channel two target nodes. This function is
// meant to aide in the generation of random graphs for use within test cases
// the exercise the autopilot package.
func (d *databaseChannelGraph) addRandChannel(node1, node2 *btcec.PublicKey,
	capacity btcutil.Amount) (*ChannelEdge, *ChannelEdge, error) {

	fetchNode := func(pub *btcec.PublicKey) (*channeldb.LightningNode, error) {
		if pub != nil {
			vertex, err := route.NewVertexFromBytes(
				pub.SerializeCompressed(),
			)
			if err != nil {
				return nil, err
			}

			dbNode, err := d.db.FetchLightningNode(vertex)
			switch {
			case err == channeldb.ErrGraphNodeNotFound:
				fallthrough
			case err == channeldb.ErrGraphNotFound:
				graphNode := &channeldb.LightningNode{
					HaveNodeAnnouncement: true,
					Addresses: []net.Addr{
						&net.TCPAddr{
							IP: bytes.Repeat([]byte("a"), 16),
						},
					},
					Features: lnwire.NewFeatureVector(
						nil, lnwire.Features,
					),
					AuthSigBytes: testSig.Serialize(),
				}
				graphNode.AddPubKey(pub)
				if err := d.db.AddLightningNode(graphNode); err != nil {
					return nil, err
				}
			case err != nil:
				return nil, err
			}

			return dbNode, nil
		}

		nodeKey, err := randKey()
		if err != nil {
			return nil, err
		}
		dbNode := &channeldb.LightningNode{
			HaveNodeAnnouncement: true,
			Addresses: []net.Addr{
				&net.TCPAddr{
					IP: bytes.Repeat([]byte("a"), 16),
				},
			},
			Features: lnwire.NewFeatureVector(
				nil, lnwire.Features,
			),
			AuthSigBytes: testSig.Serialize(),
		}
		dbNode.AddPubKey(nodeKey)
		if err := d.db.AddLightningNode(dbNode); err != nil {
			return nil, err
		}

		return dbNode, nil
	}

	vertex1, err := fetchNode(node1)
	if err != nil {
		return nil, nil, err
	}

	vertex2, err := fetchNode(node2)
	if err != nil {
		return nil, nil, err
	}

	var lnNode1, lnNode2 *btcec.PublicKey
	if bytes.Compare(vertex1.PubKeyBytes[:], vertex2.PubKeyBytes[:]) == -1 {
		lnNode1, _ = vertex1.PubKey()
		lnNode2, _ = vertex2.PubKey()
	} else {
		lnNode1, _ = vertex2.PubKey()
		lnNode2, _ = vertex1.PubKey()
	}

	chanID := randChanID()
	edge := &channeldb.ChannelEdgeInfo{
		ChannelID: chanID.ToUint64(),
		Capacity:  capacity,
	}
	edge.AddNodeKeys(lnNode1, lnNode2, lnNode1, lnNode2)
	if err := d.db.AddChannelEdge(edge); err != nil {
		return nil, nil, err
	}
	edgePolicy := &channeldb.ChannelEdgePolicy{
		SigBytes:                  testSig.Serialize(),
		ChannelID:                 chanID.ToUint64(),
		LastUpdate:                time.Now(),
		TimeLockDelta:             10,
		MinHTLC:                   1,
		MaxHTLC:                   lnwire.NewMSatFromSatoshis(capacity),
		FeeBaseMSat:               10,
		FeeProportionalMillionths: 10000,
		MessageFlags:              1,
		ChannelFlags:              0,
	}

	if err := d.db.UpdateEdgePolicy(edgePolicy); err != nil {
		return nil, nil, err
	}
	edgePolicy = &channeldb.ChannelEdgePolicy{
		SigBytes:                  testSig.Serialize(),
		ChannelID:                 chanID.ToUint64(),
		LastUpdate:                time.Now(),
		TimeLockDelta:             10,
		MinHTLC:                   1,
		MaxHTLC:                   lnwire.NewMSatFromSatoshis(capacity),
		FeeBaseMSat:               10,
		FeeProportionalMillionths: 10000,
		MessageFlags:              1,
		ChannelFlags:              1,
	}
	if err := d.db.UpdateEdgePolicy(edgePolicy); err != nil {
		return nil, nil, err
	}

	return &ChannelEdge{
			ChanID:   chanID,
			Capacity: capacity,
			Peer: dbNode{
				node: vertex1,
			},
		},
		&ChannelEdge{
			ChanID:   chanID,
			Capacity: capacity,
			Peer: dbNode{
				node: vertex2,
			},
		},
		nil
}

func (d *databaseChannelGraph) addRandNode() (*btcec.PublicKey, error) {
	nodeKey, err := randKey()
	if err != nil {
		return nil, err
	}
	dbNode := &channeldb.LightningNode{
		HaveNodeAnnouncement: true,
		Addresses: []net.Addr{
			&net.TCPAddr{
				IP: bytes.Repeat([]byte("a"), 16),
			},
		},
		Features: lnwire.NewFeatureVector(
			nil, lnwire.Features,
		),
		AuthSigBytes: testSig.Serialize(),
	}
	dbNode.AddPubKey(nodeKey)
	if err := d.db.AddLightningNode(dbNode); err != nil {
		return nil, err
	}

	return nodeKey, nil

}

// memChannelGraph is an implementation of the autopilot.ChannelGraph backed by
// an in-memory graph.
type memChannelGraph struct {
	graph map[NodeID]*memNode
}

// A compile time assertion to ensure memChannelGraph meets the
// autopilot.ChannelGraph interface.
var _ ChannelGraph = (*memChannelGraph)(nil)

// newMemChannelGraph creates a new blank in-memory channel graph
// implementation.
func newMemChannelGraph() *memChannelGraph {
	return &memChannelGraph{
		graph: make(map[NodeID]*memNode),
	}
}

// ForEachNode is a higher-order function that should be called once for each
// connected node within the channel graph. If the passed callback returns an
// error, then execution should be terminated.
//
// NOTE: Part of the autopilot.ChannelGraph interface.
func (m memChannelGraph) ForEachNode(cb func(Node) error) error {
	for _, node := range m.graph {
		if err := cb(node); err != nil {
			return err
		}
	}

	return nil
}

// randChanID generates a new random channel ID.
func randChanID() lnwire.ShortChannelID {
	id := atomic.AddUint64(&chanIDCounter, 1)
	return lnwire.NewShortChanIDFromInt(id)
}

// randKey returns a random public key.
func randKey() (*btcec.PublicKey, error) {
	priv, err := btcec.NewPrivateKey()
	if err != nil {
		return nil, err
	}

	return priv.PubKey(), nil
}

// addRandChannel creates a new channel two target nodes. This function is
// meant to aide in the generation of random graphs for use within test cases
// the exercise the autopilot package.
func (m *memChannelGraph) addRandChannel(node1, node2 *btcec.PublicKey,
	capacity btcutil.Amount) (*ChannelEdge, *ChannelEdge, error) {

	var (
		vertex1, vertex2 *memNode
		ok               bool
	)

	if node1 != nil {
		vertex1, ok = m.graph[NewNodeID(node1)]
		if !ok {
			vertex1 = &memNode{
				pub: node1,
				addrs: []net.Addr{
					&net.TCPAddr{
						IP: bytes.Repeat([]byte("a"), 16),
					},
				},
			}
		}
	} else {
		newPub, err := randKey()
		if err != nil {
			return nil, nil, err
		}
		vertex1 = &memNode{
			pub: newPub,
			addrs: []net.Addr{
				&net.TCPAddr{
					IP: bytes.Repeat([]byte("a"), 16),
				},
			},
		}
	}

	if node2 != nil {
		vertex2, ok = m.graph[NewNodeID(node2)]
		if !ok {
			vertex2 = &memNode{
				pub: node2,
				addrs: []net.Addr{
					&net.TCPAddr{
						IP: bytes.Repeat([]byte("a"), 16),
					},
				},
			}
		}
	} else {
		newPub, err := randKey()
		if err != nil {
			return nil, nil, err
		}
		vertex2 = &memNode{
			pub: newPub,
			addrs: []net.Addr{
				&net.TCPAddr{
					IP: bytes.Repeat([]byte("a"), 16),
				},
			},
		}
	}

	edge1 := ChannelEdge{
		ChanID:   randChanID(),
		Capacity: capacity,
		Peer:     vertex2,
	}
	vertex1.chans = append(vertex1.chans, edge1)

	edge2 := ChannelEdge{
		ChanID:   randChanID(),
		Capacity: capacity,
		Peer:     vertex1,
	}
	vertex2.chans = append(vertex2.chans, edge2)

	m.graph[NewNodeID(vertex1.pub)] = vertex1
	m.graph[NewNodeID(vertex2.pub)] = vertex2

	return &edge1, &edge2, nil
}

func (m *memChannelGraph) addRandNode() (*btcec.PublicKey, error) {
	newPub, err := randKey()
	if err != nil {
		return nil, err
	}
	vertex := &memNode{
		pub: newPub,
		addrs: []net.Addr{
			&net.TCPAddr{
				IP: bytes.Repeat([]byte("a"), 16),
			},
		},
	}
	m.graph[NewNodeID(newPub)] = vertex

	return newPub, nil
}

// databaseChannelGraphCached wraps a channeldb.ChannelGraph instance with the
// necessary API to properly implement the autopilot.ChannelGraph interface.
type databaseChannelGraphCached struct {
	db *channeldb.ChannelGraph
}

// A compile time assertion to ensure databaseChannelGraphCached meets the
// autopilot.ChannelGraph interface.
var _ ChannelGraph = (*databaseChannelGraphCached)(nil)

// ChannelGraphFromCachedDatabase returns an instance of the
// autopilot.ChannelGraph backed by a live, open channeldb instance.
func ChannelGraphFromCachedDatabase(db *channeldb.ChannelGraph) ChannelGraph {
	return &databaseChannelGraphCached{
		db: db,
	}
}

// dbNodeCached is a wrapper struct around a database transaction for a
// channeldb.LightningNode. The wrapper methods implement the autopilot.Node
// interface.
type dbNodeCached struct {
	node     route.Vertex
	channels map[uint64]*channeldb.DirectedChannel
}

// A compile time assertion to ensure dbNodeCached meets the autopilot.Node
// interface.
var _ Node = (*dbNodeCached)(nil)

// PubKey is the identity public key of the node.
//
// NOTE: Part of the autopilot.Node interface.
func (nc dbNodeCached) PubKey() [33]byte {
	return nc.node
}

// Addrs returns a slice of publicly reachable public TCP addresses that the
// peer is known to be listening on.
//
// NOTE: Part of the autopilot.Node interface.
func (nc dbNodeCached) Addrs() []net.Addr {
	// TODO: Add addresses to be usable by autopilot.
	return []net.Addr{}
}

// ForEachChannel is a higher-order function that will be used to iterate
// through all edges emanating from/to the target node. For each active
// channel, this function should be called with the populated ChannelEdge that
// describes the active channel.
//
// NOTE: Part of the autopilot.Node interface.
func (nc dbNodeCached) ForEachChannel(cb func(ChannelEdge) error) error {
	for cid, channel := range nc.channels {
		edge := ChannelEdge{
			ChanID:   lnwire.NewShortChanIDFromInt(cid),
			Capacity: channel.Capacity,
			Peer: dbNodeCached{
				node: channel.OtherNode,
			},
		}

		if err := cb(edge); err != nil {
			return err
		}
	}

	return nil
}

// ForEachNode is a higher-order function that should be called once for each
// connected node within the channel graph. If the passed callback returns an
// error, then execution should be terminated.
//
// NOTE: Part of the autopilot.ChannelGraph interface.
func (dc *databaseChannelGraphCached) ForEachNode(cb func(Node) error) error {
	return dc.db.ForEachNodeCached(func(n route.Vertex,
		channels map[uint64]*channeldb.DirectedChannel) error {

		if len(channels) > 0 {
			node := dbNodeCached{
				node:     n,
				channels: channels,
			}
			return cb(node)
		}
		return nil
	})
}

// memNode is a purely in-memory implementation of the autopilot.Node
// interface.
type memNode struct {
	pub *btcec.PublicKey

	chans []ChannelEdge

	addrs []net.Addr
}

// A compile time assertion to ensure memNode meets the autopilot.Node
// interface.
var _ Node = (*memNode)(nil)

// PubKey is the identity public key of the node. This will be used to attempt
// to target a node for channel opening by the main autopilot agent.
//
// NOTE: Part of the autopilot.Node interface.
func (m memNode) PubKey() [33]byte {
	var n [33]byte
	copy(n[:], m.pub.SerializeCompressed())

	return n
}

// Addrs returns a slice of publicly reachable public TCP addresses that the
// peer is known to be listening on.
//
// NOTE: Part of the autopilot.Node interface.
func (m memNode) Addrs() []net.Addr {
	return m.addrs
}

// ForEachChannel is a higher-order function that will be used to iterate
// through all edges emanating from/to the target node. For each active
// channel, this function should be called with the populated ChannelEdge that
// describes the active channel.
//
// NOTE: Part of the autopilot.Node interface.
func (m memNode) ForEachChannel(cb func(ChannelEdge) error) error {
	for _, channel := range m.chans {
		if err := cb(channel); err != nil {
			return err
		}
	}

	return nil
}

// Median returns the median value in the slice of Amounts.
func Median(vals []btcutil.Amount) btcutil.Amount {
	sort.Slice(vals, func(i, j int) bool {
		return vals[i] < vals[j]
	})

	num := len(vals)
	switch {
	case num == 0:
		return 0

	case num%2 == 0:
		return (vals[num/2-1] + vals[num/2]) / 2

	default:
		return vals[num/2]
	}
}


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>
Uses of Interface org.apache.hadoop.io.compress.CompressionCodec (Apache Hadoop Main 2.5.2 API)
</TITLE>

<META NAME="date" CONTENT="2014-11-14">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
org.apache.hadoop.io.compress.CompressionCodec

Packages that use CompressionCodec

org.apache.hadoop.io
Generic i/o code for use when reading and writing data to the network,
to databases, and to files.

org.apache.hadoop.io.compress

org.apache.hadoop.mapred

org.apache.hadoop.mapreduce.lib.output

Uses of CompressionCodec in org.apache.hadoop.io

Methods in org.apache.hadoop.io with parameters of type CompressionCodec

static org.apache.hadoop.io.SequenceFile.Writer
SequenceFile.createWriter(Configuration conf,
                         FSDataOutputStream out,
                         Class keyClass,
                         Class valClass,
                         org.apache.hadoop.io.SequenceFile.CompressionType compressionType,
                         CompressionCodec codec)

          Deprecated. Use SequenceFile.createWriter(Configuration, Writer.Option...)
     instead.

static org.apache.hadoop.io.SequenceFile.Writer
SequenceFile.createWriter(Configuration conf,
                         FSDataOutputStream out,
                         Class keyClass,
                         Class valClass,
                         org.apache.hadoop.io.SequenceFile.CompressionType compressionType,
                         CompressionCodec codec,
                         org.apache.hadoop.io.SequenceFile.Metadata metadata)

          Deprecated. Use SequenceFile.createWriter(Configuration, Writer.Option...)
     instead.

static org.apache.hadoop.io.SequenceFile.Writer
SequenceFile.createWriter(FileContext fc,
                         Configuration conf,
                         Path name,
                         Class keyClass,
                         Class valClass,
                         org.apache.hadoop.io.SequenceFile.CompressionType compressionType,
                         CompressionCodec codec,
                         org.apache.hadoop.io.SequenceFile.Metadata metadata,
                         EnumSet<CreateFlag> createFlag,
                         org.apache.hadoop.fs.Options.CreateOpts... opts)

          Construct the preferred type of SequenceFile Writer.

static org.apache.hadoop.io.SequenceFile.Writer
SequenceFile.createWriter(FileSystem fs,
                         Configuration conf,
                         Path name,
                         Class keyClass,
                         Class valClass,
                         int bufferSize,
                         short replication,
                         long blockSize,
                         boolean createParent,
                         org.apache.hadoop.io.SequenceFile.CompressionType compressionType,
                         CompressionCodec codec,
                         org.apache.hadoop.io.SequenceFile.Metadata metadata)

          Deprecated.

static org.apache.hadoop.io.SequenceFile.Writer
SequenceFile.createWriter(FileSystem fs,
                         Configuration conf,
                         Path name,
                         Class keyClass,
                         Class valClass,
                         int bufferSize,
                         short replication,
                         long blockSize,
                         org.apache.hadoop.io.SequenceFile.CompressionType compressionType,
                         CompressionCodec codec,
                         Progressable progress,
                         org.apache.hadoop.io.SequenceFile.Metadata metadata)

          Deprecated. Use SequenceFile.createWriter(Configuration, Writer.Option...)
     instead.

static org.apache.hadoop.io.SequenceFile.Writer
SequenceFile.createWriter(FileSystem fs,
                         Configuration conf,
                         Path name,
                         Class keyClass,
                         Class valClass,
                         org.apache.hadoop.io.SequenceFile.CompressionType compressionType,
                         CompressionCodec codec)

          Deprecated. Use SequenceFile.createWriter(Configuration, Writer.Option...)
     instead.

static org.apache.hadoop.io.SequenceFile.Writer
SequenceFile.createWriter(FileSystem fs,
                         Configuration conf,
                         Path name,
                         Class keyClass,
                         Class valClass,
                         org.apache.hadoop.io.SequenceFile.CompressionType compressionType,
                         CompressionCodec codec,
                         Progressable progress)

          Deprecated. Use SequenceFile.createWriter(Configuration, Writer.Option...)
     instead.

static org.apache.hadoop.io.SequenceFile.Writer
SequenceFile.createWriter(FileSystem fs,
                         Configuration conf,
                         Path name,
                         Class keyClass,
                         Class valClass,
                         org.apache.hadoop.io.SequenceFile.CompressionType compressionType,
                         CompressionCodec codec,
                         Progressable progress,
                         org.apache.hadoop.io.SequenceFile.Metadata metadata)

          Deprecated. Use SequenceFile.createWriter(Configuration, Writer.Option...)
     instead.

Uses of CompressionCodec in org.apache.hadoop.io.compress

Subinterfaces of CompressionCodec in org.apache.hadoop.io.compress

 interface
DirectDecompressionCodec

          This class encapsulates a codec which can decompress direct bytebuffers.

 interface
SplittableCompressionCodec

          This interface is meant to be implemented by those compression codecs
 which are capable to compress / de-compress a stream starting at any
 arbitrary position.

Classes in org.apache.hadoop.io.compress that implement CompressionCodec

 class
BZip2Codec

          This class provides output and input streams for bzip2 compression
 and decompression.

 class
DefaultCodec

 class
GzipCodec

          This class creates gzip compressors/decompressors.

Methods in org.apache.hadoop.io.compress that return CompressionCodec

 CompressionCodec
CompressionCodecFactory.getCodec(Path file)

          Find the relevant compression codec for the given file based on its
 filename suffix.

 CompressionCodec
CompressionCodecFactory.getCodecByClassName(String classname)

          Find the relevant compression codec for the codec's canonical class name.

 CompressionCodec
CompressionCodecFactory.getCodecByName(String codecName)

          Find the relevant compression codec for the codec's canonical class name
 or by codec alias.

Methods in org.apache.hadoop.io.compress that return types with arguments of type CompressionCodec

 Class<? extends CompressionCodec>
CompressionCodecFactory.getCodecClassByName(String codecName)

          Find the relevant compression codec for the codec's canonical class name
 or by codec alias and returns its implemetation class.

static List<Class<? extends CompressionCodec>>
CompressionCodecFactory.getCodecClasses(Configuration conf)

          Get the list of codecs discovered via a Java ServiceLoader, or
 listed in the configuration.

Methods in org.apache.hadoop.io.compress with parameters of type CompressionCodec

static Compressor
CodecPool.getCompressor(CompressionCodec codec)

static Compressor
CodecPool.getCompressor(CompressionCodec codec,
                           Configuration conf)

          Get a Compressor for the given CompressionCodec from the
 pool or a new one.

static Decompressor
CodecPool.getDecompressor(CompressionCodec codec)

          Get a Decompressor for the given CompressionCodec from the
 pool or a new one.

static int
CodecPool.getLeasedCompressorsCount(CompressionCodec codec)

          Return the number of leased Compressors for this
 CompressionCodec

static int
CodecPool.getLeasedDecompressorsCount(CompressionCodec codec)

          Return the number of leased Decompressors for this
 CompressionCodec

Uses of CompressionCodec in org.apache.hadoop.mapred

Methods in org.apache.hadoop.mapred that return types with arguments of type CompressionCodec

 Class<? extends CompressionCodec>
JobConf.getMapOutputCompressorClass(Class<? extends CompressionCodec> defaultValue)

          Get the CompressionCodec for compressing the map outputs.

static Class<? extends CompressionCodec>
FileOutputFormat.getOutputCompressorClass(JobConf conf,
                                                 Class<? extends CompressionCodec> defaultValue)

          Get the CompressionCodec for compressing the job outputs.

Method parameters in org.apache.hadoop.mapred with type arguments of type CompressionCodec

 Class<? extends CompressionCodec>
JobConf.getMapOutputCompressorClass(Class<? extends CompressionCodec> defaultValue)

          Get the CompressionCodec for compressing the map outputs.

static Class<? extends CompressionCodec>
FileOutputFormat.getOutputCompressorClass(JobConf conf,
                                                 Class<? extends CompressionCodec> defaultValue)

          Get the CompressionCodec for compressing the job outputs.

 void
JobConf.setMapOutputCompressorClass(Class<? extends CompressionCodec> codecClass)

          Set the given class as the  CompressionCodec for the map outputs.

static void
FileOutputFormat.setOutputCompressorClass(JobConf conf,
                                                 Class<? extends CompressionCodec> codecClass)

          Set the CompressionCodec to be used to compress job outputs.

Uses of CompressionCodec in org.apache.hadoop.mapreduce.lib.output

Methods in org.apache.hadoop.mapreduce.lib.output that return types with arguments of type CompressionCodec

static Class<? extends CompressionCodec>
FileOutputFormat.getOutputCompressorClass(JobContext job,
                                                 Class<? extends CompressionCodec> defaultValue)

          Get the CompressionCodec for compressing the job outputs.

Method parameters in org.apache.hadoop.mapreduce.lib.output with type arguments of type CompressionCodec

static Class<? extends CompressionCodec>
FileOutputFormat.getOutputCompressorClass(JobContext job,
                                                 Class<? extends CompressionCodec> defaultValue)

          Get the CompressionCodec for compressing the job outputs.

static void
FileOutputFormat.setOutputCompressorClass(Job job,
                                                 Class<? extends CompressionCodec> codecClass)

          Set the CompressionCodec to be used to compress job outputs.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2014 Apache Software Foundation. All Rights Reserved.


text:
<title>SupportCaseListDisplayItem</title>

_#= mID =#_

_#= mStatus =#_

_#= mTitle =#_

_#= mCSR =#_


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Mantle.BlobStorage.Interfaces;
using Mantle.Configuration.Attributes;
using Mantle.Extensions;

namespace Mantle.BlobStorage.FileSystem.Clients
{
    public class FileSystemBlobStorageClient : IBlobStorageClient
    {
        [Configurable(IsRequired = true)]
        public string Path { get; set; }

        public bool BlobExists(string blobName)
        {
            blobName.Require(nameof(blobName));

            if (Directory.Exists(Path) == false)
                return false;

            return (File.Exists(System.IO.Path.Combine(Path, blobName)));
        }

        public void DeleteBlob(string blobName)
        {
            blobName.Require(nameof(blobName));

            if (Directory.Exists(Path) == false)
                throw new InvalidOperationException($"Directory [{Path}] does not exist.");

            var filePath = System.IO.Path.Combine(Path, blobName);

            if (File.Exists(filePath) == false)
                throw new InvalidOperationException($"File [{filePath}] does not exist.");

            File.Delete(filePath);
        }

        public Stream DownloadBlob(string blobName)
        {
            blobName.Require(nameof(blobName));

            if (Directory.Exists(Path) == false)
                throw new InvalidOperationException($"Directory [{Path}] does not exist.");

            var filePath = System.IO.Path.Combine(Path, blobName);

            if (File.Exists(filePath) == false)
                throw new InvalidOperationException($"File [{filePath}] does not exist.");

            return (new MemoryStream(File.ReadAllBytes(filePath)) {Position = 0});
        }

        public IEnumerable<string> ListBlobs()
        {
            if (Directory.Exists(Path) == false)
                throw new InvalidOperationException($"Directory [{Path}] does not exist.");

            return Directory.GetFiles(Path).Select(System.IO.Path.GetFileName);
        }

        public void UploadBlob(Stream blob, string blobName)
        {
            blob.Require(nameof(blob));
            blobName.Require(nameof(blobName));

            if (Directory.Exists(Path) == false)
                throw new InvalidOperationException($"Directory [{Path}] does not exist.");

            blob.TryToRewind();

            using (var fileStream = File.Create(System.IO.Path.Combine(Path, blobName)))
                blob.CopyTo(fileStream);
        }
    }
}


text:
<!DOCTYPE>

	<title>Galeria de videos</title>
	<link rel="stylesheet" href="css/varios.css">
	<meta charset="utf-8">

 		<video class="polaroid RotarDer centrado" width="300" height="315"
 			src="video/gta.mp4" type="video/mp4" controls></video>

Ejemplo de mp4 en el servidor con la etiqueta vídeo

		<video  class="polaroid RotarDer centrado" width="300" height="315"
			data="https://www.youtube.com/embed/Wcu_d62jn0w" controls></video>

Ejemplo de fichero en youtube (?) con la etiqueta vídeo

Ejemplo de mp4 en el servidor con la etiqueta iframe

		<object  class="centrado polaroidContenedor RotarIzq" width="300" height="315"
			data="https://www.youtube.com/embed/Wcu_d62jn0w"></object>

Ejemplo de fichero en youtube (?) con la etiqueta object

    	<embed src="https://www.youtube.com/embed/Wcu_d62jn0w"
	    	allowfullscreen="false" allowscriptaccess="always" />

Ejemplo de fichero en youtube (?) con la etiqueta embed/figcaption>

		<address>

Aleajndro L. Cerezo

Cle Formacion

alcerezo@movistar.es

		</address>


text:
'use strict';
(function(){
  /*
   * Lightweight JSONP fetcher
   * Usage:
   *
   * postman.get( 'someUrl.php', {param1:'123', param2:'456'}, function(data){
   *   //do something with data, which is the JSON object you should retrieve from someUrl.php
   * });
   */
  var postman = (function(){
    var counter = 0, head, config = {};
    function load(url, pfnError) {
      var script = document.createElement('script'),
          done = false;
      script.src = url;
      script.async = true;

      var errorHandler = pfnError || config.error;
      if ( typeof errorHandler === 'function' ) {
        script.onerror = function(ex){
          errorHandler({url: url, event: ex});
        };
      }

      script.onload = script.onreadystatechange = function() {
        if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) {
          done = true;
          script.onload = script.onreadystatechange = null;
          if ( script && script.parentNode ) {
            script.parentNode.removeChild( script );
          }
        }
      };

      if ( !head ) {
        head = document.getElementsByTagName('head')[0];
      }
      head.appendChild( script );
    }
    function encode(str) {
      return encodeURIComponent(str);
    }
    function jsonp(url, params, callback, callbackName) {
      var query = (url||'').indexOf('?') === -1 ? '?' : '&', key;

      callbackName = (callbackName||config['callbackName']||'callback');
      var uniqueName = callbackName + "_json" + (++counter);

      params = params || {};
      for ( key in params ) {
        if ( params.hasOwnProperty(key) ) {
          query += encode(key) + "=" + encode(params[key]) + "&";
        }
      }
      window[ uniqueName ] = function(data){
        callback(data);
        try {
          delete window[ uniqueName ];
        } catch (e) {}
        window[ uniqueName ] = null;
      };

      load(url + query + callbackName + '=' + uniqueName);
      return uniqueName;
    }
    function setDefaults(obj){
      config = obj;
    }
    return {
      get:jsonp,
      init:setDefaults
    };
  }());

  if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = postman;
  }
  else {
    if (typeof define === 'function' && define.amd) {
      define([], function() {
        return postman;
      });
    }
    else {
      window.postman = postman;
    }
  }
})();


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Acta Horti Gothob. 1:118. 1924

#### Original name
null

### Remarks
null


text: INSERT INTO admin(user_id) VALUES ("admin");


text:
package com.sequenceiq.freeipa.controller.mapper;

import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;

import javax.ws.rs.core.Response.Status;

import org.springframework.stereotype.Component;

import com.sequenceiq.cloudbreak.cloud.service.GetCloudParameterException;
import com.sequenceiq.cloudbreak.exception.mapper.BaseExceptionMapper;

@Component
public class GetCloudParameterExceptionMapper extends BaseExceptionMapper<GetCloudParameterException> {

    @Override
    public Status getResponseStatus(GetCloudParameterException exception) {
        return INTERNAL_SERVER_ERROR;
    }

    @Override
    public Class<GetCloudParameterException> getExceptionType() {
        return GetCloudParameterException.class;
    }

    @Override
    protected boolean logException() {
        return false;
    }
}


text:
package com.gzmelife.app.activity;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback.CancelledException;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gzmelife.app.R;
import com.gzmelife.app.UrlInterface;
import com.gzmelife.app.adapter.CookFoodBeanAdapter;
import com.gzmelife.app.adapter.GvSecondClassifyAdapter;
import com.gzmelife.app.bean.CoonFoodMenuBean;
import com.gzmelife.app.tools.pop_dlg;
import com.gzmelife.app.tools.pop_dlg.dialog;
import com.gzmelife.app.views.MyListView;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;

@ContentView(R.layout.activity_second_food_classify)
public class SecondFoodClassifyActivity extends BaseActivity {
	@ViewInject(R.id.rv_goodfood)
	GridView gv_food;
	GvSecondClassifyAdapter secondClassifyAdapter;
	@ViewInject(R.id.tv_title)
	TextView tv_title;

	private List<CoonFoodMenuBean> categoryCoonFoodMenuBeanList;
	private String TAG="SecondFoodClassifyActivity";
	private String categoryId;

	@Override
	protected void onCreate(Bundle arg0) {

		super.onCreate(arg0);
		String name = getIntent().getStringExtra("name");
		categoryId = getIntent().getStringExtra("categoryId");
		tv_title.setText(name);
		Log.i(TAG, "onCreate  name:"+name+"categoryId:"+categoryId);
		gv_food.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Log.i(TAG, "gv_food.setOnItemClickListener->onItemClick");
				Intent intent = new Intent(SecondFoodClassifyActivity.this,
						NetCookBookDetailActivity.class);
				Log.i(TAG, "跳转NetCookBookDetailActivity");
				String number = categoryCoonFoodMenuBeanList.get(position)
						.getClickNumber();
				int num = Integer.valueOf(number);
				num++;
				intent.putExtra("number", num);
				intent.putExtra("menuBookId",
						categoryCoonFoodMenuBeanList.get(position).getId());
				secondClassifyAdapter.notifyDataSetChanged();
				startActivityForResult(intent, 12008);

			}
		});

		showCookBook();
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		if (arg1 == RESULT_OK) {
			int num = arg2.getIntExtra("nunber", 0);
			super.onActivityResult(arg0, arg1, arg2);
			switch (arg0) {
			case 12008:
				showCookBook();
				break;

			default:
				break;
			}
		}
	}

	private void showCookBook() {
		// 美食最新、最热、推荐菜谱
		showDlg();
		RequestParams params = new RequestParams(UrlInterface.URL_FINDMENUBOOKBYFOODSTORE);
		params.addBodyParameter("foodStoreId", categoryId);

		x.http().post(params, new CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.i(TAG, "net showCookBook->onSuccess"+result);
				closeDlg();
				Gson gson = new Gson();
				JSONObject obj;
				try {
					obj = new JSONObject(result);
					categoryCoonFoodMenuBeanList = gson.fromJson(obj
							.getJSONObject("data").getJSONArray("menubooks")
							.toString(),
							new TypeToken<List<CoonFoodMenuBean>>() {
							}.getType());

					if(categoryCoonFoodMenuBeanList.size()==0){
						pop_dlg dlg=new pop_dlg(SecondFoodClassifyActivity.this, new dialog() {

							@Override
							public void onclick(pop_dlg pop, View v) {
								// TODO Auto-generated method stub
								SecondFoodClassifyActivity.this.finish();
								pop.dismiss();
							}

							@Override
							public View initLayout(pop_dlg pop, LayoutInflater flater) {
								// TODO Auto-generated method stub
								View v=flater.inflate(R.layout.dialog_tishi1, null);
								TextView ok=(TextView) v.findViewById(R.id.ok);
								ok.setOnClickListener(pop);
								return v;
							}
						});
					}
					secondClassifyAdapter = new GvSecondClassifyAdapter(
							SecondFoodClassifyActivity.this,
							categoryCoonFoodMenuBeanList);

					gv_food.setAdapter(secondClassifyAdapter);

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				// TODO Auto-generated method stub
				closeDlg();
			}

			@Override
			public void onCancelled(CancelledException cex) {
				// TODO Auto-generated method stub
				closeDlg();
			}

			@Override
			public void onFinished() {
				// TODO Auto-generated method stub
				closeDlg();
			}

		});

	}

}