text:
layout:     post
title:      "Spreetalk"
subtitle:   "Internet der Dinge. Eintagsfliegen, Einhörner oder ein Segen für alle?"
date:       2016-10-07 08:00:00
author:     "René"
header-img: "img/SpreeTalk-Referenten-Team.jpg"
tags: event talk Berlin
---

Das Internet der Dinge (IoT - Internet of Things) ist so alt wie das Internet selbst, zumindest kommt es mir so vor. Viele Unternehmen versuchen mit unterschiedlichsten Technologien die Dinge im Internet miteinander kommunuzieren zu lassen. Dafür gibt es viele gute Gründe, ist doch klar!

Ja genau... hier hört es meist auf und es folgt viel blabla. Was ist es nun wirklich, dieses Internet der Dinge? Gibt es sowas? Hat es einen Nutzen? Und lässt sich damit wirklich Geld machen? Das sind alles gute Fragen und ich freue mich, dass Cassini mich eingeladen hat, im Rahmen des Spreetalk Themenabends mit Experten über das IoT zu diskutieren. Cassini hat der Veranstaltung einen passenden Namen gegeben: "Internet der Dinge. Eintagsfliegen, Einhörner oder ein Segen für alle?"

Neben mir werden folgende Personen auf der Bühne sitzen:

* Cornel Pampu, Referatsleiter im Berliner Senat – für Digitale Wirtschaft, Medien, Kreativwirtschaft
* Moritz Diekmann, Geschäftsführer der Telefonica Next
* Oliver van der Mond, CEO von Lemonbeat

[Hier geht es zur Veranstaltungsseite](http://spreetalk.cassini.de/){:target="_blank"}

[Hier gibt es kostenlose Tickets](https://www.eventbrite.de/e/spreetalk-iot-eintagsfliegen-einhorner-oder-ein-segen-fur-alle-registrierung-27087539560)

![Spreetalk Flyer]({{ site.baseurl }}/img/spreetalkFlyer.jpg){: .center-image }


text:
git commit -a --amend -m 'Add debugging stuff'
hack/build-release.sh
hack/build-images.sh
if [ $1 != "" ]; then
  docker tag openshift/origin-haproxy-router:latest openshift3/ose-haproxy-router:$1
fi
docker stop $(docker ps | grep haproxy | cut -d ' ' -f 1)

redpajama_set_name: RedPajamaGithub


text:
<img src="https://raw.githubusercontent.com/geerlingguy/JJG-Node-Ping/master/Resources/Ping-Logo.png" alt="Ping for Node.js Logo" />

# JJG Ping

JJG Ping is a simple ping wrapper for Node.js which returns the latency and result of a ping to a given address.

Ping was created by [Jeff Geerling](http://www.lifeisaprayer.com/) of [Midwestern Mac, LLC](http://www.midwesternmac.com/) in 2013.

## Installation

Use NPM:

    $ npm install jjg-ping

## Usage

    // Use the jjg-ping library.
    var ping = require('jjg-ping');

    // Ping google.com.
    ping.system.ping('google.com', function(latency, status) {
        if (status) {
            // Host is reachable/up. Latency should have a value.
            console.log('Google is reachable (' + latency + ' ms ping).');
        }
        else {
            // Host is down. Latency should be 0.
            console.log('Google is unreachable.');
        }
    });

## Why jjg-ping?

Because npm [doesn't support namespacing](https://npmjs.org/doc/faq.html#Why-no-namespaces), and ping, node-ping, and all the other namespaces I wanted were already taken.

## License

JJG Ping is licensed under the MIT (Expat) license. See included LICENSE.md.


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using AspectCore.DynamicProxy;
using Xunit;

namespace AspectCore.Tests.DynamicProxy
{
    internal static class Extensions
    {
        public static Task<T> WrapIntoTask<T>(this T obj) => Task.FromResult(obj);
        public static ValueTask<T> WrapIntoValueTask<T>(this T obj) => new ValueTask<T>(obj);
    }

    public class UnwrapAsyncReturnValueTests : DynamicProxyTestBase
    {
        public class Interceptor : AbstractInterceptorAttribute
        {
            public override async Task Invoke(AspectContext context, AspectDelegate next)
            {
                if (context.Proxy is Service service)
                {
                    service.CurrentValue = null;
                    await context.Invoke(next);
                    var value = await context.UnwrapAsyncReturnValue();
                    service.CurrentValue = value;
                }
                else
                {
                    await context.Invoke(next);
                }
            }
        }

        public static ValueTask CreateCompletedValueTask() => new ValueTask(Task.CompletedTask);
        public static Task CompletedTask => Task.CompletedTask;

        public class Service
        {
            public object CurrentValue { get; set; }

            [Interceptor] public virtual Task Task() => CompletedTask;
            [Interceptor] public virtual Task<int> TaskT() => 1.WrapIntoTask();
            [Interceptor] public virtual Task<T> TaskT_Generic<T>() => CreateDefaultValue<T>().WrapIntoTask();
            [Interceptor] public virtual Task<Task> Task_Task() => CompletedTask.WrapIntoTask();
            [Interceptor] public virtual Task<ValueTask> Task_ValueTask() => CreateCompletedValueTask().WrapIntoTask();
            [Interceptor] public virtual Task<Task<int>> Task_TaskT() => 1.WrapIntoTask().WrapIntoTask();
            [Interceptor] public virtual Task<ValueTask<int>> Task_ValueTaskT() => 1.WrapIntoValueTask().WrapIntoTask();

            [Interceptor] public virtual ValueTask ValueTask() => CreateCompletedValueTask();
            [Interceptor] public virtual ValueTask<int> ValueTaskT() => 1.WrapIntoValueTask();
            [Interceptor] public virtual ValueTask<T> ValueTaskT_Generic<T>() => CreateDefaultValue<T>().WrapIntoValueTask();
            [Interceptor] public virtual ValueTask<Task> ValueTask_Task() => CompletedTask.WrapIntoValueTask();
            [Interceptor] public virtual ValueTask<ValueTask> ValueTask_ValueTask() => CreateCompletedValueTask().WrapIntoValueTask();
            [Interceptor] public virtual ValueTask<Task<int>> ValueTask_TaskT() => 1.WrapIntoTask().WrapIntoValueTask();
            [Interceptor] public virtual ValueTask<ValueTask<int>> ValueTask_ValueTaskT() => 1.WrapIntoValueTask().WrapIntoValueTask();

            private static T CreateDefaultValue<T>()
            {
                if (typeof(T) == typeof(InternalClass))
                    return (T)(object)new InternalClass { Value = 1 };
                if (typeof(T) == typeof(int))
                    return (T)(object)1;

                return default;
            }
        }

        internal class InternalClass
        {
            public int Value;
        }

        [Fact]
        public async Task Task_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.Task();
            Assert.Null(service.CurrentValue);
        }

        [Fact]
        public async Task TaskT_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.TaskT();
            Assert.Equal(1, service.CurrentValue);
        }

        [Fact]
        public async Task TaskT_Generic_Int_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.TaskT_Generic<int>();
            Assert.Equal(1, service.CurrentValue);
        }

        [Fact]
        public async Task TaskT_Generic_Internal_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.TaskT_Generic<InternalClass>();
            Assert.True(service.CurrentValue is InternalClass { Value: 1 });
        }

        [Fact]
        public async Task Task_Task_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.Task_Task();
            Assert.Null(service.CurrentValue);
        }

        [Fact]
        public async Task Task_ValueTask_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.Task_ValueTask();
            Assert.Null(service.CurrentValue);
        }

        [Fact]
        public async Task Task_TaskT_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.Task_TaskT();
            Assert.Equal(1, service.CurrentValue);
        }

        [Fact]
        public async Task Task_ValueTaskT_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.Task_ValueTaskT();
            Assert.Equal(1, service.CurrentValue);
        }

        [Fact]
        public async Task ValueTask_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.ValueTask();
            Assert.Null(service.CurrentValue);
        }

        [Fact]
        public async Task ValueTaskT_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.ValueTaskT();
            Assert.Equal(1, service.CurrentValue);
        }

        [Fact]
        public async Task ValueTaskT_Generic_Int_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.ValueTaskT_Generic<int>();
            Assert.Equal(1, service.CurrentValue);
        }

        [Fact]
        public async Task ValueTaskT_Generic_Internal_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.ValueTaskT_Generic<InternalClass>();
            Assert.True(service.CurrentValue is InternalClass { Value: 1 });
        }

        [Fact]
        public async Task ValueTask_Task_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.ValueTask_Task();
            Assert.Null(service.CurrentValue);
        }

        [Fact]
        public async Task ValueTask_ValueTask_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.ValueTask_ValueTask();
            Assert.Null(service.CurrentValue);
        }

        [Fact]
        public async Task ValueTask_TaskT_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.ValueTask_TaskT();
            Assert.Equal(1, service.CurrentValue);
        }

        [Fact]
        public async Task ValueTask_ValueTaskT_Test()
        {
            var service = ProxyGenerator.CreateClassProxy<Service>();
            await service.ValueTask_ValueTaskT();
            Assert.Equal(1, service.CurrentValue);
        }
    }
}


text:
<?php

namespace opensrs\backwardcompatibility\dataconversion\domains\provisioning;

use opensrs\backwardcompatibility\dataconversion\DataConversion;

class ProvisioningRevoke extends DataConversion
{
    // New structure for API calls handled by
    // the toolkit.
    //
    // index: field name
    // value: location of data to map to this
    //		  field from the original structure
    //
    // example 1:
    //    "cookie" => 'data->cookie'
    //	this will map ->data->cookie in the
    //	original object to ->cookie in the
    //  new format
    //
    // example 2:
    //	  ['attributes']['domain'] = 'data->domain'
    //  this will map ->data->domain in the original
    //  to ->attributes->domain in the new format
    protected $newStructure = array(
        'attributes' => array(
            'domain' => 'data->domain',
            'notes' => 'data->notes',
            ),
        );

    public function convertDataObject($dataObject, $newStructure = null)
    {
        $p = new parent();

        if (is_null($newStructure)) {
            $newStructure = $this->newStructure;
        }

        $newDataObject = $p->convertDataObject($dataObject, $newStructure);

        return $newDataObject;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/lmp-mr1-dev/frameworks/support/v7/appcompat/res/values-xlarge/bools.xml -->
    <eat-comment/>
    <bool name="abc_action_bar_expanded_action_views_exclusive">false</bool>
    <!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/lmp-mr1-dev/frameworks/support/v7/appcompat/res/values-xlarge/dimens.xml -->
    <eat-comment/>
    <dimen name="abc_search_view_text_min_width">192dip</dimen>
    <item name="dialog_fixed_height_major" type="dimen">60%</item>
    <item name="dialog_fixed_height_minor" type="dimen">90%</item>
    <item name="dialog_fixed_width_major" type="dimen">50%</item>
    <item name="dialog_fixed_width_minor" type="dimen">70%</item>
    <integer name="abc_max_action_buttons">5</integer>
</resources>


text:
local snowplow = require("snowplow")
local ss = require("lib.utils").safe_string -- Alias
local TRACKER_VERSION = require("constants").TRACKER_VERSION

local function assert_tracker(tracker, collector_url)
  assert.are.equal(tracker.emitter:get_collector_url(), collector_url)
  assert.are.equal(tracker.config.encode_base64, true)
  assert.are.equal(tracker.config.platform, "pc")
  assert.are.equal(tracker.config.version, TRACKER_VERSION)
end

describe("snowplow", function()
  -- --------------------------------------------------------------
  -- Test error handling on constructors

  it("new_tracker() should error unless passed a non-empty string", function()
    local f = function(host)
      return function()
        snowplow.new_tracker(host)
      end
    end
    local err = function(value)
      return "url is required and must be a non-empty string, not [" .. ss(value) .. "]"
    end
    assert.has_error(f(""), err(""))
    assert.has_error(f({}), err("{}"))
    assert.has_error(f(-23.04), err("-23.04"))
  end)

  -- --------------------------------------------------------------
  -- Verify constructed tracker tables

  it("new_tracker() should correctly create a tracker", function()
    local t = snowplow.new_tracker("test.invalid", "GET")
    assert_tracker(t, "https://test.invalid/i")
  end)

  it("new_tracker_for_uri() should correctly assign default protocol https", function()
    local t = snowplow.new_tracker("test.invalid")
    assert.is_equal(t.emitter:get_collector_url():sub(1, 5), "https")
  end)

  it("new_tracker_for_uri() should correctly create url with default protocol from url with port", function()
    local t = snowplow.new_tracker("http://test.invalid:9090", "GET")
    assert.is_equal("http://test.invalid:9090/i", t.emitter:get_collector_url())
  end)

  it("new_tracker() should assign correct passed protocol", function()
    local protocols = { "http", "https" }
    for _, protocol in ipairs(protocols) do
      local t = snowplow.new_tracker(protocol .. "://test.invalid")
      assert.is_equal(t.emitter:get_collector_url():sub(1, protocol:len()), protocol)
    end
  end)

  it("new_tracker() should error if passed an invalid protocol", function()
    local protocols = { "ftp", "file" }
    for _, protocol in ipairs(protocols) do
      local f = function()
        snowplow.new_tracker(protocol .. "://test.invalid")
      end
      assert.has_error(f, "protocol must be a string from the set {http, https}, not [" .. protocol .. "]")
    end
  end)
end)


text:
using System.Web.Mvc;

namespace CodeIt.Web.Areas.Administration.Controllers
{
    public class HomeController : AdministrationController
    {
        public ActionResult Index()
        {
            this.ViewBag.Message = "Hore Some statistics!";

            return this.View();
        }
    }
}


text:
package main

import (
	"context"
	"fmt"
	"github.com/nebulaim/telegramd/baselib/grpc_util/middleware/examples/helloworld"
	"google.golang.org/grpc"
	"math/rand"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano())
	conn, err := grpc.Dial("127.0.0.1:50051", grpc.WithInsecure())
	if err != nil {
		fmt.Printf("fail to dial: %v\n", err)
	}
	defer conn.Close()

	var h = "hellow world"

	client := helloworld.NewGreeterClient(conn)
	request := &helloworld.HelloRequest{Name: h}
	response, _ := client.SayHello(context.Background(), request)
	fmt.Println(response)
}


text:
package com.twitter.sdk.android.core.internal;

import android.text.TextUtils;

import com.twitter.sdk.android.core.Session;
import com.twitter.sdk.android.core.TwitterAuthConfig;

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

public class TwitterRequestHeaders {

    public static final String HEADER_USER_AGENT = "User-Agent";

    private final String method;
    private final String url;
    private final Map<String, String> postParams;
    private final TwitterAuthConfig authConfig;
    private final Session session;
    private final String userAgent;

    public TwitterRequestHeaders(String method, String url, TwitterAuthConfig authConfig,
            Session session, String userAgent, Map<String, String> postParams) {
        this.method = method;
        this.url = url;
        this.authConfig = authConfig;
        this.session = session;
        this.userAgent = userAgent;
        this.postParams = postParams;
    }

    public final Map<String, String> getHeaders() {
        final HashMap<String, String> headers = new HashMap<>();
        headers.putAll(getExtraHeaders());
        if (!TextUtils.isEmpty(userAgent)) {
            headers.put(HEADER_USER_AGENT, userAgent);
        }
        headers.putAll(getAuthHeaders());
        return headers;
    }

    /**
     * Returns a list of extra HTTP headers (besides Authorization and User-Agent) to go along with
     * this request
     */
    protected Map<String, String> getExtraHeaders() {
        return Collections.emptyMap();
    }

    /**
     * @return a map of auth headers to go along with this request. Override this method if you
     * need to provide a special Authorization header.
     */
    public Map<String, String> getAuthHeaders() {
        if (session != null && session.getAuthToken() != null) {
            return session.getAuthToken().getAuthHeaders(authConfig, getMethod(), url,
                    getPostParams());
        }
        return Collections.emptyMap();
    }

    protected String getMethod() {
        return method;
    }

    protected Map<String, String> getPostParams() {
        return postParams;
    }
}


text:
#include "ast/BinaryOperator.h"
#include "ast/NodeVisitor.h"
USE_SWALLOW_NS;

BinaryOperator::BinaryOperator()
    :Operator(NodeType::BinaryOperator)
{
    operatorType = OperatorType::InfixBinary;
}
BinaryOperator::~BinaryOperator()
{
}

void BinaryOperator::accept(NodeVisitor* visitor)
{
    accept2(visitor, &NodeVisitor::visitBinaryOperator);
}

int BinaryOperator::numChildren()
{
    return 2;
}
NodePtr BinaryOperator::get(int i)
{
    switch(i)
    {
        case 0:
            return lhs;
        case 1:
            return rhs;
        default:
            return NULL;
    }
}
void BinaryOperator::set(int i, const NodePtr& val)
{
    switch(i)
    {
        case 0:
            lhs = std::dynamic_pointer_cast<Pattern>(val);
            break;
        case 1:
            rhs = std::dynamic_pointer_cast<Pattern>(val);
            break;
        default:
            break;
    }
}


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

    <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=9"/>
    <meta name="generator" content="Doxygen 1.8.6"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Generic Image Library: xxx_is_mutable</title>
    <link href="tabs.css" rel="stylesheet" type="text/css"/>

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

Main Page

Modules

Classes

Files

Classes

xxx_is_mutable
Type Analysis Metafunctions

Determines if the given pixel reference/iterator/locator/view is mutable (i.e. its pixels can be changed)
More...

Classes

struct  	pixel_reference_is_mutable< R >

 	Determines if the given pixel reference is mutable (i.e. its channels can be changed)  More...

struct  	locator_is_mutable< L >

 	Determines if the given locator is mutable (i.e. its pixels can be changed)  More...

struct  	view_is_mutable< V >

 	Determines if the given view is mutable (i.e. its pixels can be changed)  More...

struct  	iterator_is_mutable< It >

 	Metafunction predicate returning whether the given iterator allows for changing its values.  More...

Detailed Description

Determines if the given pixel reference/iterator/locator/view is mutable (i.e. its pixels can be changed)

     <address class="footer">

        Generated on Wed Dec 5 2018 20:05:50 for Generic Image Library by  doxygen 1.8.6

    </address>


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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 com.cloud.storage.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ejb.Local;

import org.apache.log4j.Logger;

import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Volume;
import com.cloud.storage.Volume.Event;
import com.cloud.storage.Volume.State;
import com.cloud.storage.Volume.Type;
import com.cloud.storage.VolumeVO;
import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.Pair;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.UpdateBuilder;
import com.cloud.utils.exception.CloudRuntimeException;

@Local(value=VolumeDao.class)
public class VolumeDaoImpl extends GenericDaoBase<VolumeVO, Long> implements VolumeDao {
    private static final Logger s_logger = Logger.getLogger(VolumeDaoImpl.class);
    protected final SearchBuilder<VolumeVO> DetachedAccountIdSearch;
    protected final SearchBuilder<VolumeVO> TemplateZoneSearch;
    protected final GenericSearchBuilder<VolumeVO, SumCount> TotalSizeByPoolSearch;
    protected final GenericSearchBuilder<VolumeVO, Long> ActiveTemplateSearch;
    protected final SearchBuilder<VolumeVO> InstanceStatesSearch;
    protected final SearchBuilder<VolumeVO> AllFieldsSearch;
    protected GenericSearchBuilder<VolumeVO, Long> CountByAccount;
    ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class);

    protected static final String SELECT_VM_SQL = "SELECT DISTINCT instance_id from volumes v where v.host_id = ? and v.mirror_state = ?";
    protected static final String SELECT_HYPERTYPE_FROM_VOLUME = "SELECT c.hypervisor_type from volumes v, storage_pool s, cluster c where v.pool_id = s.id and s.cluster_id = c.id and v.id = ?";

    private static final String ORDER_POOLS_NUMBER_OF_VOLUMES_FOR_ACCOUNT = "SELECT pool.id, SUM(IF(vol.state='Ready' AND vol.account_id = ?, 1, 0)) FROM `cloud`.`storage_pool` pool LEFT JOIN `cloud`.`volumes` vol ON pool.id = vol.pool_id WHERE pool.data_center_id = ? " +
                                                                        " AND pool.pod_id = ? AND pool.cluster_id = ? " +
                                                                        " GROUP BY pool.id ORDER BY 2 ASC ";

    @Override
    public List<VolumeVO> findDetachedByAccount(long accountId) {
    	SearchCriteria<VolumeVO> sc = DetachedAccountIdSearch.create();
    	sc.setParameters("accountId", accountId);
    	sc.setParameters("destroyed", Volume.State.Destroy);
    	return listBy(sc);
    }

    @Override
    public List<VolumeVO> findByAccount(long accountId) {
        SearchCriteria<VolumeVO> sc = AllFieldsSearch.create();
        sc.setParameters("accountId", accountId);
        sc.setParameters("state", Volume.State.Ready);
        return listBy(sc);
    }

    @Override
    public List<VolumeVO> findByInstance(long id) {
        SearchCriteria<VolumeVO> sc = AllFieldsSearch.create();
        sc.setParameters("instanceId", id);
	    return listBy(sc);
	}

    @Override
    public List<VolumeVO> findByInstanceAndDeviceId(long instanceId, long deviceId){
    	SearchCriteria<VolumeVO> sc = AllFieldsSearch.create();
    	sc.setParameters("instanceId", instanceId);
    	sc.setParameters("deviceId", deviceId);
    	return listBy(sc);
    }

    @Override
    public List<VolumeVO> findByPoolId(long poolId) {
        SearchCriteria<VolumeVO> sc = AllFieldsSearch.create();
        sc.setParameters("poolId", poolId);
        sc.setParameters("notDestroyed", Volume.State.Destroy);
        sc.setParameters("vType", Volume.Type.ROOT.toString());
	    return listBy(sc);
	}

    @Override
    public List<VolumeVO> findCreatedByInstance(long id) {
        SearchCriteria<VolumeVO> sc = AllFieldsSearch.create();
        sc.setParameters("instanceId", id);
        sc.setParameters("state", Volume.State.Ready);
        return listBy(sc);
    }

    @Override
    public List<VolumeVO> findUsableVolumesForInstance(long instanceId) {
        SearchCriteria<VolumeVO> sc = InstanceStatesSearch.create();
        sc.setParameters("instance", instanceId);
        sc.setParameters("states", Volume.State.Creating, Volume.State.Ready, Volume.State.Allocated);

        return listBy(sc);
    }

	@Override
	public List<VolumeVO> findByInstanceAndType(long id, Type vType) {
        SearchCriteria<VolumeVO> sc = AllFieldsSearch.create();
        sc.setParameters("instanceId", id);
        sc.setParameters("vType", vType.toString());
	    return listBy(sc);
	}

	@Override
	public List<VolumeVO> findByInstanceIdDestroyed(long vmId) {
		SearchCriteria<VolumeVO> sc = AllFieldsSearch.create();
		sc.setParameters("instanceId", vmId);
		sc.setParameters("destroyed", Volume.State.Destroy);
		return listBy(sc);
	}

	@Override
	public List<VolumeVO> findReadyRootVolumesByInstance(long instanceId) {
		SearchCriteria<VolumeVO> sc = AllFieldsSearch.create();
		sc.setParameters("instanceId", instanceId);
		sc.setParameters("state", Volume.State.Ready);
		sc.setParameters("vType", Volume.Type.ROOT);
		return listBy(sc);
	}

	@Override
	public List<VolumeVO> findByAccountAndPod(long accountId, long podId) {
		SearchCriteria<VolumeVO> sc = AllFieldsSearch.create();
        sc.setParameters("accountId", accountId);
        sc.setParameters("pod", podId);
        sc.setParameters("state", Volume.State.Ready);

        return listIncludingRemovedBy(sc);
	}

	@Override
	public List<VolumeVO> findByTemplateAndZone(long templateId, long zoneId) {
		SearchCriteria<VolumeVO> sc = TemplateZoneSearch.create();
		sc.setParameters("template", templateId);
		sc.setParameters("zone", zoneId);

		return listIncludingRemovedBy(sc);
	}

	@Override
	public boolean isAnyVolumeActivelyUsingTemplateOnPool(long templateId, long poolId) {
	    SearchCriteria<Long> sc = ActiveTemplateSearch.create();
	    sc.setParameters("template", templateId);
	    sc.setParameters("pool", poolId);

	    List<Long> results = customSearchIncludingRemoved(sc, null);
	    assert results.size() > 0 : "How can this return a size of " + results.size();

	    return results.get(0) > 0;
	}

    @Override
    public void deleteVolumesByInstance(long instanceId) {
        SearchCriteria<VolumeVO> sc = AllFieldsSearch.create();
        sc.setParameters("instanceId", instanceId);
        expunge(sc);
    }

    @Override
    public void attachVolume(long volumeId, long vmId, long deviceId) {
    	VolumeVO volume = createForUpdate(volumeId);
    	volume.setInstanceId(vmId);
    	volume.setDeviceId(deviceId);
    	volume.setUpdated(new Date());
    	volume.setAttached(new Date());
    	update(volumeId, volume);
    }

    @Override
    public void detachVolume(long volumeId) {
    	VolumeVO volume = createForUpdate(volumeId);
    	volume.setInstanceId(null);
        volume.setDeviceId(null);
    	volume.setUpdated(new Date());
    	volume.setAttached(null);
    	update(volumeId, volume);
    }

    @Override
    @DB
	public HypervisorType getHypervisorType(long volumeId) {
		/*lookup from cluster of pool*/
    	 Transaction txn = Transaction.currentTxn();
         PreparedStatement pstmt = null;

         try {
             String sql = SELECT_HYPERTYPE_FROM_VOLUME;
             pstmt = txn.prepareAutoCloseStatement(sql);
             pstmt.setLong(1, volumeId);
             ResultSet rs = pstmt.executeQuery();
             if (rs.next()) {
                return HypervisorType.getType(rs.getString(1));
            }
             return HypervisorType.None;
         } catch (SQLException e) {
             throw new CloudRuntimeException("DB Exception on: " + SELECT_HYPERTYPE_FROM_VOLUME, e);
         } catch (Throwable e) {
             throw new CloudRuntimeException("Caught: " + SELECT_HYPERTYPE_FROM_VOLUME, e);
         }
	}

    @Override
    public ImageFormat getImageFormat(Long volumeId) {
        HypervisorType type = getHypervisorType(volumeId);
        if ( type.equals(HypervisorType.KVM)) {
            return ImageFormat.QCOW2;
        } else if ( type.equals(HypervisorType.XenServer)) {
            return ImageFormat.VHD;
        } else if ( type.equals(HypervisorType.VMware)) {
            return ImageFormat.OVA;
        } else {
            s_logger.warn("Do not support hypervisor " + type.toString());
            return null;
        }
    }

	protected VolumeDaoImpl() {
	    AllFieldsSearch = createSearchBuilder();
	    AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), Op.EQ);
        AllFieldsSearch.and("accountId", AllFieldsSearch.entity().getAccountId(), Op.EQ);
        AllFieldsSearch.and("pod", AllFieldsSearch.entity().getPodId(), Op.EQ);
        AllFieldsSearch.and("instanceId", AllFieldsSearch.entity().getInstanceId(), Op.EQ);
        AllFieldsSearch.and("deviceId", AllFieldsSearch.entity().getDeviceId(), Op.EQ);
        AllFieldsSearch.and("poolId", AllFieldsSearch.entity().getPoolId(), Op.EQ);
        AllFieldsSearch.and("vType", AllFieldsSearch.entity().getVolumeType(), Op.EQ);
        AllFieldsSearch.and("id", AllFieldsSearch.entity().getId(), Op.EQ);
        AllFieldsSearch.and("destroyed", AllFieldsSearch.entity().getState(), Op.EQ);
        AllFieldsSearch.and("notDestroyed", AllFieldsSearch.entity().getState(), Op.NEQ);
        AllFieldsSearch.and("updatedCount", AllFieldsSearch.entity().getUpdatedCount(), Op.EQ);
        AllFieldsSearch.done();

        DetachedAccountIdSearch = createSearchBuilder();
        DetachedAccountIdSearch.and("accountId", DetachedAccountIdSearch.entity().getAccountId(), Op.EQ);
        DetachedAccountIdSearch.and("destroyed", DetachedAccountIdSearch.entity().getState(), Op.NEQ);
        DetachedAccountIdSearch.and("instanceId", DetachedAccountIdSearch.entity().getInstanceId(), Op.NULL);
        DetachedAccountIdSearch.done();

        TemplateZoneSearch = createSearchBuilder();
        TemplateZoneSearch.and("template", TemplateZoneSearch.entity().getTemplateId(), Op.EQ);
        TemplateZoneSearch.and("zone", TemplateZoneSearch.entity().getDataCenterId(), Op.EQ);
        TemplateZoneSearch.done();

        TotalSizeByPoolSearch = createSearchBuilder(SumCount.class);
        TotalSizeByPoolSearch.select("sum", Func.SUM, TotalSizeByPoolSearch.entity().getSize());
        TotalSizeByPoolSearch.select("count", Func.COUNT, (Object[])null);
        TotalSizeByPoolSearch.and("poolId", TotalSizeByPoolSearch.entity().getPoolId(), Op.EQ);
        TotalSizeByPoolSearch.and("removed", TotalSizeByPoolSearch.entity().getRemoved(), Op.NULL);
        TotalSizeByPoolSearch.and("state", TotalSizeByPoolSearch.entity().getState(), Op.NEQ);
        TotalSizeByPoolSearch.done();

        ActiveTemplateSearch = createSearchBuilder(Long.class);
        ActiveTemplateSearch.and("pool", ActiveTemplateSearch.entity().getPoolId(), Op.EQ);
        ActiveTemplateSearch.and("template", ActiveTemplateSearch.entity().getTemplateId(), Op.EQ);
        ActiveTemplateSearch.and("removed", ActiveTemplateSearch.entity().getRemoved(), Op.NULL);
        ActiveTemplateSearch.select(null, Func.COUNT, null);
        ActiveTemplateSearch.done();

        InstanceStatesSearch = createSearchBuilder();
        InstanceStatesSearch.and("instance", InstanceStatesSearch.entity().getInstanceId(), Op.EQ);
        InstanceStatesSearch.and("states", InstanceStatesSearch.entity().getState(), Op.IN);
        InstanceStatesSearch.done();

        CountByAccount = createSearchBuilder(Long.class);
        CountByAccount.select(null, Func.COUNT, null);
        CountByAccount.and("account", CountByAccount.entity().getAccountId(), SearchCriteria.Op.EQ);
        CountByAccount.and("state", CountByAccount.entity().getState(), SearchCriteria.Op.NIN);
        CountByAccount.done();
	}

	@Override @DB(txn=false)
	public Pair<Long, Long> getCountAndTotalByPool(long poolId) {
        SearchCriteria<SumCount> sc = TotalSizeByPoolSearch.create();
        sc.setParameters("poolId", poolId);
        List<SumCount> results = customSearch(sc, null);
        SumCount sumCount = results.get(0);
        return new Pair<Long, Long>(sumCount.count, sumCount.sum);
	}

    @Override
	public Long countAllocatedVolumesForAccount(long accountId) {
	  	SearchCriteria<Long> sc = CountByAccount.create();
        sc.setParameters("account", accountId);
		sc.setParameters("state", Volume.State.Destroy);
        return customSearch(sc, null).get(0);
	}

	public static class SumCount {
	    public long sum;
	    public long count;
	    public SumCount() {
	    }
	}

    @Override
    public List<VolumeVO> listVolumesToBeDestroyed() {
        SearchCriteria<VolumeVO> sc = AllFieldsSearch.create();
        sc.setParameters("state", Volume.State.Destroy);

        return listBy(sc);
    }

	@Override
	public boolean updateState(com.cloud.storage.Volume.State currentState,
			Event event, com.cloud.storage.Volume.State nextState, Volume vo,
			Object data) {

	        Long oldUpdated = vo.getUpdatedCount();
	        Date oldUpdatedTime = vo.getUpdated();

	        SearchCriteria<VolumeVO> sc = AllFieldsSearch.create();
	        sc.setParameters("id", vo.getId());
	        sc.setParameters("state", currentState);
	        sc.setParameters("updatedCount", vo.getUpdatedCount());

	        vo.incrUpdatedCount();

	        UpdateBuilder builder = getUpdateBuilder(vo);
	        builder.set(vo, "state", nextState);
	        builder.set(vo, "updated", new Date());

	        int rows = update((VolumeVO)vo, sc);
	        if (rows == 0 && s_logger.isDebugEnabled()) {
	            VolumeVO dbVol = findByIdIncludingRemoved(vo.getId());
	            if (dbVol != null) {
	            	StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString());
	            	str.append(": DB Data={id=").append(dbVol.getId()).append("; state=").append(dbVol.getState()).append("; updatecount=").append(dbVol.getUpdatedCount()).append(";updatedTime=").append(dbVol.getUpdated());
	            	str.append(": New Data={id=").append(vo.getId()).append("; state=").append(nextState).append("; event=").append(event).append("; updatecount=").append(vo.getUpdatedCount()).append("; updatedTime=").append(vo.getUpdated());
	            	str.append(": stale Data={id=").append(vo.getId()).append("; state=").append(currentState).append("; event=").append(event).append("; updatecount=").append(oldUpdated).append("; updatedTime=").append(oldUpdatedTime);
	            } else {
	            	s_logger.debug("Unable to update volume: id=" + vo.getId() + ", as there is no such volume exists in the database anymore");
	            }
	        }
	        return rows > 0;
	}

    @Override
    public List<Long> listPoolIdsByVolumeCount(long dcId, Long podId, Long clusterId, long accountId) {
        Transaction txn = Transaction.currentTxn();
        PreparedStatement pstmt = null;
        List<Long> result = new ArrayList<Long>();
        try {
            String sql = ORDER_POOLS_NUMBER_OF_VOLUMES_FOR_ACCOUNT;
            pstmt = txn.prepareAutoCloseStatement(sql);
            pstmt.setLong(1, accountId);
            pstmt.setLong(2, dcId);
            pstmt.setLong(3, podId);
            pstmt.setLong(4, clusterId);

            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                result.add(rs.getLong(1));
            }
            return result;
        } catch (SQLException e) {
            throw new CloudRuntimeException("DB Exception on: " + ORDER_POOLS_NUMBER_OF_VOLUMES_FOR_ACCOUNT, e);
        } catch (Throwable e) {
            throw new CloudRuntimeException("Caught: " + ORDER_POOLS_NUMBER_OF_VOLUMES_FOR_ACCOUNT, e);
        }
    }

    @Override @DB(txn=false)
    public Pair<Long, Long> getNonDestroyedCountAndTotalByPool(long poolId) {
        SearchCriteria<SumCount> sc = TotalSizeByPoolSearch.create();
        sc.setParameters("poolId", poolId);
        sc.setParameters("state", State.Destroy);
        List<SumCount> results = customSearch(sc, null);
        SumCount sumCount = results.get(0);
        return new Pair<Long, Long>(sumCount.count, sumCount.sum);
    }

    @Override
    @DB
    public boolean remove(Long id) {
        Transaction txn = Transaction.currentTxn();
        txn.start();
        VolumeVO entry = findById(id);
        if (entry != null) {
            _tagsDao.removeByIdAndType(id, TaggedResourceType.Volume);
        }
        boolean result = super.remove(id);
        txn.commit();
        return result;
    }
}


text:
import matplotlib.gridspec as gridspec
from matt_axes_cust import no_spines
import pdb
import numpy as np
import matplotlib.pyplot as plt
from signal_tools import bwfiltfilt
from mp_scale_bars import AnchoredScaleBar, DraggableScaleBar
import os
import copy

def trace_axes(ax):
    from matplotlib.pyplot import setp
    for loc, spine in ax.spines.items():
        spine.set_color('none') # don't draw spine
    setp(ax.get_xticklabels(), visible = False)
    setp(ax.get_yticklabels(), visible = False)
    ax.xaxis.set_ticks([])
    ax.yaxis.set_ticks([])

class abf_chunker_plotter(object):
    def __init__(self, _abf_chunker):
        self.num_chunks = _abf_chunker.num_chunk_rows
        self._abf_chunker = _abf_chunker
        self.set_fig_size_inches((8,3))
        self._ylim = {}
        self.set_linewidth()

    def set_ylim(self, **kwds):
        for kwd in kwds.keys():
            if kwd in ['cells','neurgrms']:
                self._ylim[kwd] = kwds[kwd]

    def set_fig_size_inches(self, size):
        #size in inches / number chunks(float)
        self.indiv_fig_width = float(size[0]) /\
                                 (self._abf_chunker.frct_chunks)
        self.indiv_fig_height = float(size[1])

    def set_linewidth(self, width = False):
        ''' trail and error, seems that narrower pens can be used for shorter
        segments, and thick pen must be used for longer segments'''
        if width!=False:
            self.linethickness = width
            return

        total_time = self._abf_chunker.get_range_seconds()
        sample_rate = self._abf_chunker.abr.sample_rate()
        wickets = np.r_[0:110:10, 120:240:20, 220:1050:50]
        thickness = np.r_[0.4:0.8:0.005]
        left_wicket = np.where(wickets<total_time)[0][-1]
        self.linethickness = thickness[left_wicket-1]

    def plot(self, dpi, cell_list, neurgrm_list, **kwds):

        # sample scale pars in keyword
        # kwds['scale_bars'] = {'shared':{'bbox_to_anchor' : (0.3,0.4),
        #                                 'xsep' : 1,
        #                                 'ysep' : 1,
        #                                 'pad' : 1,
        #                                 'prop' : FP(size=6),
        #                                 'borderpad':0},
        #                       'cell':[{'sizex' : 0.5,
        #                                'labelx' : '0.5 sec',
        #                                'sizey' : 20,
        #                                'labely' : '20 nA'}]*num_cells,
        #                       'neurgrm':[{'sizex' : 0.5,
        #                                   'labelx' : '0.5 sec',
        #                                   'sizey' : 20,
        #                                   'labely' : '20 nA'}]*num_neurgrms}

        # most of the plot will be for intracell

        # the ratio that cell signals will be bigger than neurogram signals
        if 'cell_bias' in kwds.keys():
            cell_bias = kwds['cell_bias']
        else:
            cell_bias = 4/1.

        # calc the fraction of the fig that will be for cells vs neurgrms,
        # using above fraction
        nrgrm_height = len(neurgrm_list)
        cell_height = len(cell_list) * cell_bias
        tot_height =  nrgrm_height + cell_height

        celltop = 1
        cellbtm = 1 - (cell_height / tot_height)

        #neurograms will only take up about bottom thrid
        nrgtop = cellbtm - 0.025 # give a small (vertical 2.5% pad)
        nrgbtm = 0

        #if there is a image_type keyword, pop and set
        if 'image_type' in kwds.keys():
            image_type = kwds.pop('image_type')
        else:
            image_type = 'png'

        #if there is a image_name keyword, pop and set
        if 'image_name' in kwds.keys():
            image_name = kwds.pop('image_name')
        else:
            image_name = 'tmp'

        # if there is a color keyword, pop and set
        if 'color' in kwds.keys():
            col = kwds.pop('color')
        else:
            col = 'black'

        # if there is a color keyword, pop and set
        if 'plt_kwargs' not in kwds.keys():
            kwds['plt_kwargs'] = {'color':col,
                                  'linewidth':self.linethickness}
        else:
            kwds['plt_kwargs']['color']=col

        import subprocess
        tmp_files = []
        for i, d in enumerate(self._abf_chunker):
            fig = plt.figure()
            width_frct = float(len(d))/self._abf_chunker.chunk_row_size
            gs_cells = gridspec.GridSpec(len(cell_list), 1)
            gs_cells.update(left = 0, right = 1,
                            top = celltop, bottom = cellbtm, hspace = 0.05)
            gs_neurgrm = gridspec.GridSpec(len(neurgrm_list), 1)
            gs_neurgrm.update(left = 0, right = 1,
                              top = nrgtop, bottom = nrgbtm, hspace = 0.05)
            if 'scale_bars' in kwds.keys():
                # make a copy to avoid shitty side effects
                sb = copy.deepcopy(kwds['scale_bars'])
                dsbs = []
                # need to adjust the x to data points here
                try:
                    for SclBarDict in sb['cell']:
                        try:
                            assert SclBarDict['correctdx'] is True
                        except (KeyError, AssertionError):
                            SclBarDict['sizex'] *= self._abf_chunker.abr.sample_rate()
                            SclBarDict['xstep'] = 1/self._abf_chunker.abr.sample_rate()
                            SclBarDict['correctdx'] = True
                    # kludge need to pop this temp keyword off again
                    for SclBarDict in sb['cell']:
                        try:
                            SclBarDict.pop('correctdx')
                        except KeyError:
                            pass
                except KeyError:
                    pass
                try:
                    for SclBarDict in sb['neurgrm']:
                        try:
                            assert SclBarDict['correctdx'] is True
                        except (KeyError, AssertionError):
                            SclBarDict['sizex'] *= self._abf_chunker.abr.sample_rate()
                            SclBarDict['xstep'] = 1/self._abf_chunker.abr.sample_rate()
                            SclBarDict['correctdx'] = True
                    # kludge need to pop this temp keyword off again
                    for SclBarDict in sb['neurgrm']:
                        try:
                            SclBarDict.pop('correctdx')
                        except KeyError:
                            pass
                except KeyError:
                    pass

            for cell_num, cell in enumerate(cell_list):
                data = d[:,cell]
                ax = plt.subplot(gs_cells[cell_num, 0])
                if 'axisbg' in kwds.keys():
                    ax.set_axis_bgcolor(kwds['axisbg'])
                    trace_axes(ax)
                else:
                    ax.set_axis_off()
                if 'lp_filt' in kwds.keys():
                    if kwds['lp_filt'][cell_num] is False:
                        pass
                    else:
                        data = bwfiltfilt(data,
                                          self._abf_chunker.abr.sample_rate(),
                                          kwds['lp_filt'][cell_num])
                    if np.any(np.isnan(data)):
                        raise ValueError('data has NaNs, probably filter is bad')
                if 'scale_bars' not in kwds.keys():
                    if type(kwds['plt_kwargs']) is list:
                        ax.plot(data, **kwds['plt_kwargs'][cell_num])
                    else:
                        ax.plot(data, **kwds['plt_kwargs'])
                ax.set_ylim(self._ylim['cells'][cell_num])
                ax.set_xlim((0,len(d)))
                if 'scale_bars' in kwds.keys():
                    ASB = AnchoredScaleBar(plt.gca().transData,
                                           plt.gcf().dpi_scale_trans,
                                           bbox_transform = plt.gca().transAxes,
                                           **dict(sb['shared'], **sb['cell'][cell_num]))
                    ax.add_artist(ASB)
            for neurgrm_num, neurgrm in enumerate(neurgrm_list):
                data = d[:,neurgrm]
                ax = plt.subplot(gs_neurgrm[neurgrm_num, 0])
                if 'axisbg' in kwds.keys():
                    ax.set_axis_bgcolor(kwds['axisbg'])
                    trace_axes(ax)
                else:
                    ax.set_axis_off()
                if 'scale_bars' not in kwds.keys():
                    ax.plot(data, **kwds['plt_kwargs'])
                ax.set_ylim(self._ylim['neurgrms'][neurgrm_num])
                ax.set_xlim((0,len(d)))
                if 'scale_bars' in kwds.keys():
                    ASB = AnchoredScaleBar(plt.gca().transData,
                                           plt.gcf().dpi_scale_trans,
                                           bbox_transform = plt.gca().transAxes,
                                           **dict(sb['shared'].items(),**sb['neurgrm'][neurgrm_num]))
                    ax.add_artist(ASB)
            print(fig.get_size_inches())
            del d
            filname = "%s_%03d.%s" % ('tmp', i, image_type)
            print(filname)
            if 'scale_bars' in kwds.keys():
                scale_bar = kwds.pop('scale_bars')
                plt.gcf().set_size_inches(( self.indiv_fig_width * width_frct,
                                            self.indiv_fig_height))
                plt.gcf().savefig(filname, dpi = dpi, transparent = True)
                plt.close()
            else:
                fig.set_size_inches(( self.indiv_fig_width * width_frct, self.indiv_fig_height))
                if 'axisbg' in kwds.keys():
                    fig.patch.set_color(kwds['axisbg'])
                    fig.savefig(filname, dpi = dpi,
                                facecolor = kwds['axisbg'],
                                edgecolor = kwds['axisbg'])
                else:
                    fig.savefig(filname, dpi = dpi, transparent = True)
            ### the order that these are cleared is very important, otherwise have memleaks.
            tmp_files.append(filname)
            plt.clf()
            del ax
            plt.close(fig)
            del fig

        if self._abf_chunker.num_chunk_rows<1:
            image_name = "%s.%s" % (image_name, image_type)
            if os.path.exists(image_name):
                os.remove(image_name)
            os.rename(filname, image_name)
            return 0

        # this is so cool, calling ImageMagic as a subprocess!!

        # the montage command should be same more or less always
        # montage -tile x1 -background transparent -mode Concatenate `ls *.png` out.png
#        graphics magick is acting wonky
#        montage_cmmnd = ['gm', 'montage','-tile','x1','-background','transparent','-mode','Concatenate']
        montage_cmmnd = ['magick', 'montage', '-density', "%s" % dpi, '-tile','x1','-background','transparent','-mode','Concatenate']

        # add the files to stitch
        montage_cmmnd.extend(tmp_files)
        # add the output file name
        image_name = "%s.%s" % (image_name, image_type)
        print(image_name)
        montage_cmmnd.extend([image_name])

        # do the command with a subprocess
        subprocess.call(montage_cmmnd)

        # remove the temporary files
        tmp_files = map(os.path.abspath, tmp_files)
        map(os.remove, tmp_files)

        # display
        # make the display command platform specific
        # import platform
        # out_path = os.path.abspath('out.png')
        # if platform.system() == 'Windows':
        #     dsply_cmnd = ['gmdisplay', out_path]
        # else:
        #     dsply_cmnd = ['display', out_path]
        # subprocess.call(dsply_cmnd)
        # return os.path.abspath('out.png')


text:
#region Licence

#endregion

using System;
using Paramore.Brighter;
using TinyIoC;

namespace TaskMailer.WindowsService.Adapters.ServiceHost
{
    internal class TinyIoCMessageMapperFactory : IAmAMessageMapperFactory
    {
        private readonly TinyIoCContainer _container;

        public TinyIoCMessageMapperFactory(TinyIoCContainer container)
        {
            _container = container;
        }

        public IAmAMessageMapper Create(Type messageMapperType)
        {
            return (IAmAMessageMapper)_container.Resolve(messageMapperType);
        }
    }
}


text:
@interface EditableCell : UITableViewCell {
	IBOutlet UILabel *title;
	IBOutlet UITextField *textField;

	CGRect *textFieldRect;
}

-(void) setData:(NSMutableDictionary *)dict;

@property (nonatomic, retain) IBOutlet UILabel *title;
@property (nonatomic, retain) IBOutlet UITextField *textField;

@end


text:
import Tkinter
from nltk.draw import tree as drawTree, CanvasFrame

"""A class that draws parse trees in a simple Tk window."""

class TreeView:
	def __init__(self, trees, root=None):
		newroot = False
		if root is None:
			root = Tkinter.Tk()
			window = root
			newroot = True
		else:
			window = Tkinter.Toplevel(root)

		window.title("Parse Tree")
		window.geometry("600x400")
		self.cf = CanvasFrame(window)
		self.cf.pack(side='top', expand=1, fill='both')
		buttons = Tkinter.Frame(window)
		buttons.pack(side='bottom', fill='x')

		self.spin = Tkinter.Spinbox(buttons, from_=1, to=len(trees),
			command=self.showtree, width=3)
		if len(trees) > 1: self.spin.pack(side='left')
		self.label = Tkinter.Label(buttons, text="of %d" % len(trees))
		if len(trees) > 1: self.label.pack(side='left')
		self.done = Tkinter.Button(buttons, text="Done", command=window.destroy)
		self.done.pack(side='right')
		self.printps = Tkinter.Button(buttons, text="Print to Postscript", command=self.cf.print_to_file)
		self.printps.pack(side='right')

		self.trees = trees
		self.treeWidget = None
		self.showtree()
		if newroot: root.mainloop()

	def showtree(self):
		try: n = int(self.spin.get())
		except ValueError: n=1
		if self.treeWidget is not None: self.cf.destroy_widget(self.treeWidget)
		self.treeWidget = drawTree.TreeWidget(self.cf.canvas(),
		self.trees[n-1], draggable=1, shapeable=1)
		self.cf.add_widget(self.treeWidget, 0, 0)


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.

#if FEATURE_FULL_CRYPTO // SHA384, SHA512

using System;
using System.Collections.Generic;
using System.Security.Cryptography;

using Microsoft.Scripting.Runtime;

using IronPython.Runtime;

[assembly: PythonModule("_sha512", typeof(IronPython.Modules.PythonSha512))]
namespace IronPython.Modules {
    [Documentation("SHA512 hash algorithm")]
    public static class PythonSha512 {
        private const int BLOCK_SIZE = 128;

        public const string __doc__ = "SHA512 hash algorithm";

        public static Sha512Object sha512(object data) {
            return new Sha512Object(data);
        }

        public static Sha512Object sha512(ArrayModule.array data) {
            return new Sha512Object(data);
        }

        public static Sha512Object sha512(Bytes data) {
            return new Sha512Object((IList<byte>)data);
        }

        public static Sha512Object sha512(PythonBuffer data) {
            return new Sha512Object((IList<byte>)data);
        }

        public static Sha512Object sha512(ByteArray data) {
            return new Sha512Object((IList<byte>)data);
        }

        public static Sha512Object sha512() {
            return new Sha512Object();
        }

        public static Sha384Object sha384(object data) {
            return new Sha384Object(data);
        }

        public static Sha384Object sha384(ArrayModule.array data) {
            return new Sha384Object(data);
        }

        public static Sha384Object sha384(Bytes data) {
            return new Sha384Object((IList<byte>)data);
        }

        public static Sha384Object sha384(PythonBuffer data) {
            return new Sha384Object((IList<byte>)data);
        }

        public static Sha384Object sha384(ByteArray data) {
            return new Sha384Object((IList<byte>)data);
        }

        public static Sha384Object sha384() {
            return new Sha384Object();
        }

        [PythonHidden]
        public sealed class Sha384Object : HashBase<SHA384> {
            internal Sha384Object() : base("SHA384", BLOCK_SIZE, 48) { }

            internal Sha384Object(object initialData) : this() {
                update(initialData);
            }

            internal Sha384Object(IList<byte> initialBytes) : this() {
                update(initialBytes);
            }

            protected override void CreateHasher() {
                _hasher = SHA384.Create();
            }

            [Documentation("copy() -> object (copy of this md5 object)")]
            public override HashBase<SHA384> copy() {
                Sha384Object res = new Sha384Object();
                res._hasher = CloneHasher();
                return res;
            }
        }

        [PythonHidden]
        public sealed class Sha512Object : HashBase<SHA512> {
            internal Sha512Object() : base("SHA512", BLOCK_SIZE, 64) { }

            internal Sha512Object(object initialData) : this() {
                update(initialData);
            }

            internal Sha512Object(IList<byte> initialBytes) : this() {
                update(initialBytes);
            }

            protected override void CreateHasher() {
                _hasher = SHA512.Create();
            }

            [Documentation("copy() -> object (copy of this md5 object)")]
            public override HashBase<SHA512> copy() {
                Sha512Object res = new Sha512Object();
                res._hasher = CloneHasher();
                return res;
            }
        }
    }
}
#endif


text:
|	** File:		CLine.lua
|	** Type:		Client
|	** Author: 		N1kS
|	** Discription:	DxLine content
]]

CLine = inherit( CDxObject );

function CLine:constructor( X, Y, XTo, YTo, Color, Alpha, Width, Parent )
	self.m_X = X;
	self.m_Y = Y;
	self.m_XTo = XTo;
	self.m_YTo = YTo;
	if Parent then
		self.m_X = self.m_X + Parent.m_X;
		self.m_Y = self.m_Y + Parent.m_Y;
		self.m_XTo = self.m_XTo + Parent.m_X;
		self.m_YTo = self.m_YTo + Parent.m_Y;
	end

	self.m_Color = Color;
	self.m_Alpha = Alpha;
	self.m_Width = Width or 1;
	self.m_Parent = Parent or false;
	self.m_Type = "Line";
	self:init();
	self.m_FunctionRender = bind( CLine.onRender, self );
	addEventHandler( "onClientRender", root, self.m_FunctionRender );
end

function CLine:destructor()
	if self.m_FunctionRender then
		removeEventHandler( "onClientRender", root, self.m_FunctionRender );
	end
end

function CLine:onRender()
	dxDrawLine( self.m_X, self.m_Y, self.m_XTo, self.m_YTo, tocolor( self.m_Color[1], self.m_Color[2], self.m_Color[3], self.m_Alpha ), self.m_Width, GetDefinesValue( "PostGUI" ) );
end


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>
#include <assert.h>
#include <exception>

// UnityEngine.SpringJoint
struct SpringJoint_t558455091;

#include "codegen/il2cpp-codegen.h"

// System.Void UnityEngine.SpringJoint::set_spring(System.Single)
extern "C"  void SpringJoint_set_spring_m3720718841 (SpringJoint_t558455091 * __this, float ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.SpringJoint::set_damper(System.Single)
extern "C"  void SpringJoint_set_damper_m3309877369 (SpringJoint_t558455091 * __this, float ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.SpringJoint::set_maxDistance(System.Single)
extern "C"  void SpringJoint_set_maxDistance_m68119509 (SpringJoint_t558455091 * __this, float ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR;


text:
package foo {
  class Foo

  object Test {
    new Foo().huzzah
  }
}

package object foo {
  // Crasher: No synthetics for method EnrichedFoo2: synthetics contains
  implicit class EnrichedFoo2(value: Foo) {
    def huzzah = ""
  }
}


text:
{% extends "base.html" %}
{% spaceless %}
{% block title %}{{ page.name }} {% endblock title %}
{% endspaceless %}

{% block main %}
  {{ page.content|safe }}
{% endblock main %}

{% block leftnav %}{% endblock %}


text:
var Log = require('log');
var fs = require('fs');

module.exports.logger = new Log('debug', '');

module.exports.projectLogger = function (dataDir) {
  this.file = fs.createWriteStream(dataDir + '/build.log');
  this.logger = new Log('info', this.file);

  this.end = function () {
    this.file.end();
    this.logger = null;
  };

  this.info = function (msg) {
    if (this.logger) {
      this.logger.info(msg);
    }
  };

  this.error = function (msg) {
    if (this.logger) {
      this.logger.error(msg);
    }
  };

  this.errorAndClose = function (msg) {
    if (this.logger) {
      this.logger.error(msg);
      this.end();
    }
  };

};


text:
module Simplabs #:nodoc:

  module ReportsAsSparkline #:nodoc:

    # A special report class that cumulates all data (see Simplabs::ReportsAsSparkline::Report)
    #
    # ==== Examples
    #
    # When Simplabs::ReportsAsSparkline::Report returns
    #
    #  [[<DateTime today>, 1], [<DateTime yesterday>, 2], etc.]
    #
    # Simplabs::ReportsAsSparkline::CumulatedReport returns
    #
    #  [[<DateTime today>, 3], [<DateTime yesterday>, 2], etc.]
    class CumulatedReport < Report

      # Runs the report (see Simplabs::ReportsAsSparkline::Report#run)
      def run(options = {})
        cumulate(super, options_for_run(options))
      end

      protected

        def cumulate(data, options)
          first_reporting_period = ReportingPeriod.first(options[:grouping], options[:limit], options[:end_date])
          acc = initial_cumulative_value(first_reporting_period.date_time, options)
          result = []
          data.each do |element|
            acc += element[1].to_f
            result << [element[0], acc]
          end
          result
        end

        def initial_cumulative_value(date, options)
          conditions = setup_conditions(nil, date, options[:conditions])
          @klass.send(@aggregation, @value_column, :conditions => conditions)
        end

    end

  end

end


text:
import THREE = require("three")
import "../typings";

import { Box2DManager } from "./";
import { Box2D } from "../thirdparty/box2d";

/**
 * Base class for an object that has three.js visuals and a Box2D body.
 */
export class PhysicsLinkedObject extends THREE.Object3D
{
	public body: Box2D.b2Body;

	private static tempVector3: THREE.Vector3 = new THREE.Vector3();

	constructor(
		protected physicsManager: Box2DManager,
		body?: Box2D.b2Body)
	{
		super();

		this.physicsManager.AllObjects.push(this);

		if (body)
		{
			this.linkBody(body);
		}
	}

	protected linkBody(body : Box2D.b2Body)
	{
		this.body = body;
		this.body.SetUserData(this);
		this.syncTransformToBody(true);
	}

	/**
	 * Undestroys a soft-destroyed object (for pooling).
	 */
	public undestroy(): void
	{
		this.physicsManager.AllObjects.push(this);
		if (this.body)
		{
			this.body.SetActive(true);
		}
	}

	/**
	 * Destroys this object.
	 * @param {boolean} soft If set, does not actually destroy memory (for pooling).
	 */
	public destroy(soft? : boolean): void
	{
		if (this.parent)
		{
			this.parent.remove(this);
		}

		var index = this.physicsManager.AllObjects.indexOf(this);
		if (index >= 0)
		{
			this.physicsManager.AllObjects.splice(index, 1);
		}

		if (soft) this.body.SetActive(false);
		else this.destroyBody();
	}

	/**
	 * Destroys the body associated with this object.
	 */
	public destroyBody(): void
	{
		if (this.body)
		{
			this.body.GetWorld().DestroyBody(this.body);
			this.body.SetUserData(undefined);
			this.body = undefined;
		}
	}

	/**
	 * Updates this object once per frame.
	 */
	public update(deltaSec: number): void
	{
		this.syncTransformToBody(false);
	}

	/**
	 * Moves the object to match the body position.
	 */
	public syncTransformToBody(force): void
	{
		//TODO: check that body has actually moved?
		if (this.body && (force || this.body.IsAwake()))
		{
			var z = this.position.z;
			var physicsPos = this.body.GetPosition();
			this.position.set(physicsPos.x, physicsPos.y, 0);
			this.position.applyMatrix4(this.physicsManager.Box2DToGame);
			this.rotation.z = this.body.GetAngle(); //TODO: matrix
			this.position.z = z;
			//this.updateMatrix();
		}
	}

	/**
	 * Moves the body position to match the object.
	 */
	public syncBodyToTransform(): void
	{
		if (this.body)
		{
			PhysicsLinkedObject.tempVector3.copy(this.position);
			PhysicsLinkedObject.tempVector3.z = 0;
			PhysicsLinkedObject.tempVector3.applyMatrix4(this.physicsManager.GameToBox2D);
			this.physicsManager.tempVector2.x = PhysicsLinkedObject.tempVector3.x;
			this.physicsManager.tempVector2.y = PhysicsLinkedObject.tempVector3.y;
			this.body.SetPositionAndAngle(this.physicsManager.tempVector2, this.rotation.z); //TODO: matrix rotation
		}
	}

	/**
	 * Moves the body to the specified position.
	 */
	public setPosition(position: Box2D.b2Vec2): void
	{
		if (this.body) this.body.SetPosition(position);
		this.syncTransformToBody(true);
	}

	/**
	 * Applies the specified impulse to the center of the body.
	 * @param {Box2D.b2Vec2} impulse
	 */
	public applyLinearImpulse(impulse: Box2D.b2Vec2): void
	{
		if (impulse.x == 0 && impulse.y == 0) return;

		var velocity = this.body.GetLinearVelocity();
		if (this.body.GetType() == Box2D.b2Body.b2_kinematicBody)
		{
			velocity.x += impulse.x;
			velocity.y += impulse.y;
			this.body.SetLinearVelocity(velocity);
		}
		else
		{
			this.body.ApplyImpulse(impulse, this.body.GetPosition());
		}
	}

	/**
	 * Applies the specified impulse to the center of the body, but does not allow it to
	 * increase the velocity above 'maxSpeed'. If the velocity is already above that, it can stay there.
	 * @param {Box2D.b2Vec2} impulse
	 * @param {Number} maxSpeed
	 */
	public applyLinearImpulseWithVelocityCap(impulse: Box2D.b2Vec2, maxSpeed: number): void
	{
		var velocity = this.body.GetLinearVelocity();
		var velocityLength = velocity.Length();
		this.applyLinearImpulse(impulse);
		this.limitSpeed(Math.max(maxSpeed, velocityLength));
	}

	/**
	 * Reduces the object's velocity to be no greater than the specified speed.
	 * @param {Number} maxSpeed
	 */
	public limitSpeed(maxSpeed: number): void
	{
		var postVelocity = this.body.GetLinearVelocity();
		var postVelocityLength = postVelocity.Length();
		if (postVelocityLength > maxSpeed)
		{
			postVelocity.x = maxSpeed * postVelocity.x / postVelocityLength;
			postVelocity.y = maxSpeed * postVelocity.y / postVelocityLength;
			this.body.SetLinearVelocity(postVelocity);
		}
	}

	/**
	 * Called by box2d when this object starts touching another.
	 * You cannot create or destroy bodies in here.
	 * @param {Box2D.b2Contact} contact
	 * @param {Box2D.b2Fixture} otherFixture
	 */
	public onBeginContact(contact: Box2D.b2Contact, otherFixture: Box2D.b2Fixture): void
	{

	}

	/**
	 * Called by box2d when this object stops touching another.
	 * You cannot create or destroy bodies in here.
	 * @param {Box2D.b2Contact} contact
	 * @param {Box2D.b2Fixture} otherFixture
	 */
	public onEndContact(contact: Box2D.b2Contact, otherFixture: Box2D.b2Fixture): void
	{

	}

	/**
	 * Called by box2d each frame this body is touching another body, before the response is calculated.
	 * The response can be disabled here.
	 * You cannot create or destroy bodies in here.
	 * @param {Box2D.b2Contact} contact
	 * @param {Box2D.b2Manifold} oldManifold
	 * @param {Box2D.b2Fixture} otherFixture
	 */
	public onPreSolve(contact: Box2D.b2Contact, oldManifold: Box2D.b2Manifold, otherFixture: Box2D.b2Fixture): void
	{

	}

	/**
	 * Called by box2d each frame this body is touching another body, after the response is calculated.
	 * You cannot create or destroy bodies in here.
	 * @param {Box2D.b2Contact} contact
	 * @param {Box2D.b2Impulse} impulse
	 * @param {Box2D.b2Fixture} otherFixture
	 */
	public onPostSolve(contact: Box2D.b2Contact, impulse: Box2D.b2ContactImpulse, otherFixture: Box2D.b2Fixture): void
	{

	}
};


text:
package helpers

import (
	"github.com/paulmach/go.geo"
	"github.com/paulmach/go.geo/clustering"
)

// RemoveOutlierPointersByQuadkey will bucket all pointers by quad key (defined by the level)
// and remove the buckets with less than threshold pointers. The buckets become the resulting point_clustering.Clusters.
func RemoveOutlierPointersByQuadkey(pointers []geo.Pointer, level, threshold int) []*clustering.Cluster {

	buckets := make(map[int64][]geo.Pointer)
	for _, p := range pointers {
		key := p.Point().Quadkey(level)

		buckets[key] = append(buckets[key], p)
	}

	clusters := make([]*clustering.Cluster, 0, len(buckets))
	for _, b := range buckets {
		if len(b) >= threshold {
			clusters = append(clusters, clustering.NewCluster(b...))
		}
	}

	return clusters
}


text:
import assert from 'node:assert'
import fs from 'node:fs'
import path from 'node:path'
import test from 'tape'
import {remark} from 'remark'
import remarkSlug from 'remark-slug'
import remarkHtml from 'remark-html'
import remarkAutolinkHeadings from '../index.js'

/**
 * @param {string} name
 */
const base = function (name) {
  return fs.readFileSync(path.join('test', 'fixtures', name), 'utf-8')
}

/** @type {['append', 'prepend', 'after', 'before', 'wrap']} */
const behaviors = ['append', 'prepend', 'after', 'before', 'wrap']

test('remarkAutolinkHeadings', (t) => {
  let index = -1
  while (++index < behaviors.length) {
    const b = behaviors[index]
    t.is(
      remark()
        .use(remarkSlug)
        .use(remarkHtml)
        .use(remarkAutolinkHeadings, {behavior: b})
        .processSync(base('input.md'))
        .toString(),
      base('output.' + b + '.html'),
      'should autolink headings (' + b + ')'
    )
  }

  t.is(
    remark()
      .use(remarkSlug)
      .use(remarkHtml)
      .use(remarkAutolinkHeadings, {content: {type: 'text', value: '#'}})
      .processSync('# method')
      .toString(),
    '
#method
\n',
    'should accept custom content'
  )

  t.is(
    remark()
      .use(remarkSlug)
      .use(remarkHtml)
      .use(remarkAutolinkHeadings, {content: [{type: 'text', value: '#'}]})
      .processSync('# method')
      .toString(),
    '
#method
\n',
    'should accept custom content as an array'
  )

  t.is(
    remark()
      .use(remarkSlug)
      .use(remarkHtml)
      .use(remarkAutolinkHeadings, {
        content(node) {
          const head = node.children[0]
          assert(head.type === 'text')
          return {
            type: 'text',
            value: 'Read the "' + head.value + '" section'
          }
        },
        linkProperties: {}
      })
      .processSync('# method')
      .toString(),
    '
Read the "method" sectionmethod
\n',
    'should accept custom content as a function'
  )

  t.is(
    remark()
      .use(remarkSlug)
      .use(remarkHtml)
      .use(remarkAutolinkHeadings, {linkProperties: {hidden: true}})
      .processSync('# method')
      .toString(),
    '
method
\n',
    'should accept link properties'
  )

  t.is(
    remark()
      .use(remarkSlug)
      .use(remarkHtml)
      .use(remarkAutolinkHeadings, {
        group: {
          type: 'element',
          tagName: 'div',
          properties: {className: ['heading-group']},
          children: []
        },
        behavior: 'before'
      })
      .processSync('# method')
      .toString(),
    '

method

\n',
    'should accept a custom group'
  )

  t.is(
    remark()
      .use(remarkSlug)
      .use(remarkHtml)
      .use(remarkAutolinkHeadings, {
        group(node) {
          return {
            type: 'element',
            tagName: 'div',
            properties: {className: ['heading-' + node.depth + '-group']},
            children: []
          }
        },
        behavior: 'after'
      })
      .processSync('# method')
      .toString(),
    '

method

\n',
    'should accept a custom group as a function'
  )

  t.is(
    remark()
      .use(remarkAutolinkHeadings)
      .use(remarkHtml)
      .processSync(base('input.md'))
      .toString(),
    base('output.html'),
    'should do nothing if slugs are not used'
  )

  t.throws(
    () => {
      remark()
        .use(remarkSlug)
        .use(remarkHtml)
        // @ts-expect-error: invalid group.
        .use(remarkAutolinkHeadings, {
          group() {
            return {type: 'text', value: 'x'}
          },
          behavior: 'after'
        })
        .processSync('# method')
        .toString()
    },
    /Expected element as grouping/,
    'should throw when `group` is not an element'
  )

  t.is(
    remark()
      .use(remarkSlug)
      .use(remarkAutolinkHeadings, {behavior: 'wrap'})
      .use(remarkHtml)
      .processSync('# [Hello](#), **world**!')
      .toString(),
    '
Hello, world!
\n',
    'should unravel interactive content when wrapping'
  )

  t.end()
})


text:
package edu.isi.karma.cleaning;

public interface PartitionClassifierType {
	//public void addTrainingData(String value, double[] val ,String label);
	public void addTrainingData(String value,String label);
	public String learnClassifer();

	public String getLabel(String value);
	public void init();
}