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

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

import com.amazonaws.AmazonWebServiceRequest;

/**
 *

 * Contains the parameters for SetLoadBalancePoliciesOfListener.
 *

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

    /**
     *

     * The name of the load balancer.
     *

     */
    private String loadBalancerName;
    /**
     *

     * The external port of the load balancer.
     *

     */
    private Integer loadBalancerPort;
    /**
     *

     * The names of the policies. This list must include all policies to be enabled. If you omit a policy that is
     * currently enabled, it is disabled. If the list is empty, all current policies are disabled.
     *

     */
    private com.amazonaws.internal.SdkInternalList<String> policyNames;

    /**
     * Default constructor for SetLoadBalancerPoliciesOfListenerRequest object. Callers should use the setter or fluent
     * setter (with...) methods to initialize the object after creating it.
     */
    public SetLoadBalancerPoliciesOfListenerRequest() {
    }

    /**
     * Constructs a new SetLoadBalancerPoliciesOfListenerRequest object. Callers should use the setter or fluent setter
     * (with...) methods to initialize any additional object members.
     *
     * @param loadBalancerName
     *        The name of the load balancer.
     * @param loadBalancerPort
     *        The external port of the load balancer.
     * @param policyNames
     *        The names of the policies. This list must include all policies to be enabled. If you omit a policy that is
     *        currently enabled, it is disabled. If the list is empty, all current policies are disabled.
     */
    public SetLoadBalancerPoliciesOfListenerRequest(String loadBalancerName, Integer loadBalancerPort, java.util.List<String> policyNames) {
        setLoadBalancerName(loadBalancerName);
        setLoadBalancerPort(loadBalancerPort);
        setPolicyNames(policyNames);
    }

    /**
     *

     * The name of the load balancer.
     *

     *
     * @param loadBalancerName
     *        The name of the load balancer.
     */

    public void setLoadBalancerName(String loadBalancerName) {
        this.loadBalancerName = loadBalancerName;
    }

    /**
     *

     * The name of the load balancer.
     *

     *
     * @return The name of the load balancer.
     */

    public String getLoadBalancerName() {
        return this.loadBalancerName;
    }

    /**
     *

     * The name of the load balancer.
     *

     *
     * @param loadBalancerName
     *        The name of the load balancer.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SetLoadBalancerPoliciesOfListenerRequest withLoadBalancerName(String loadBalancerName) {
        setLoadBalancerName(loadBalancerName);
        return this;
    }

    /**
     *

     * The external port of the load balancer.
     *

     *
     * @param loadBalancerPort
     *        The external port of the load balancer.
     */

    public void setLoadBalancerPort(Integer loadBalancerPort) {
        this.loadBalancerPort = loadBalancerPort;
    }

    /**
     *

     * The external port of the load balancer.
     *

     *
     * @return The external port of the load balancer.
     */

    public Integer getLoadBalancerPort() {
        return this.loadBalancerPort;
    }

    /**
     *

     * The external port of the load balancer.
     *

     *
     * @param loadBalancerPort
     *        The external port of the load balancer.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SetLoadBalancerPoliciesOfListenerRequest withLoadBalancerPort(Integer loadBalancerPort) {
        setLoadBalancerPort(loadBalancerPort);
        return this;
    }

    /**
     *

     * The names of the policies. This list must include all policies to be enabled. If you omit a policy that is
     * currently enabled, it is disabled. If the list is empty, all current policies are disabled.
     *

     *
     * @return The names of the policies. This list must include all policies to be enabled. If you omit a policy that
     *         is currently enabled, it is disabled. If the list is empty, all current policies are disabled.
     */

    public java.util.List<String> getPolicyNames() {
        if (policyNames == null) {
            policyNames = new com.amazonaws.internal.SdkInternalList<String>();
        }
        return policyNames;
    }

    /**
     *

     * The names of the policies. This list must include all policies to be enabled. If you omit a policy that is
     * currently enabled, it is disabled. If the list is empty, all current policies are disabled.
     *

     *
     * @param policyNames
     *        The names of the policies. This list must include all policies to be enabled. If you omit a policy that is
     *        currently enabled, it is disabled. If the list is empty, all current policies are disabled.
     */

    public void setPolicyNames(java.util.Collection<String> policyNames) {
        if (policyNames == null) {
            this.policyNames = null;
            return;
        }

        this.policyNames = new com.amazonaws.internal.SdkInternalList<String>(policyNames);
    }

    /**
     *

     * The names of the policies. This list must include all policies to be enabled. If you omit a policy that is
     * currently enabled, it is disabled. If the list is empty, all current policies are disabled.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setPolicyNames(java.util.Collection)} or {@link #withPolicyNames(java.util.Collection)} if you want to
     * override the existing values.
     *

     *
     * @param policyNames
     *        The names of the policies. This list must include all policies to be enabled. If you omit a policy that is
     *        currently enabled, it is disabled. If the list is empty, all current policies are disabled.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SetLoadBalancerPoliciesOfListenerRequest withPolicyNames(String... policyNames) {
        if (this.policyNames == null) {
            setPolicyNames(new com.amazonaws.internal.SdkInternalList<String>(policyNames.length));
        }
        for (String ele : policyNames) {
            this.policyNames.add(ele);
        }
        return this;
    }

    /**
     *

     * The names of the policies. This list must include all policies to be enabled. If you omit a policy that is
     * currently enabled, it is disabled. If the list is empty, all current policies are disabled.
     *

     *
     * @param policyNames
     *        The names of the policies. This list must include all policies to be enabled. If you omit a policy that is
     *        currently enabled, it is disabled. If the list is empty, all current policies are disabled.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SetLoadBalancerPoliciesOfListenerRequest withPolicyNames(java.util.Collection<String> policyNames) {
        setPolicyNames(policyNames);
        return this;
    }

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

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

        if (obj instanceof SetLoadBalancerPoliciesOfListenerRequest == false)
            return false;
        SetLoadBalancerPoliciesOfListenerRequest other = (SetLoadBalancerPoliciesOfListenerRequest) obj;
        if (other.getLoadBalancerName() == null ^ this.getLoadBalancerName() == null)
            return false;
        if (other.getLoadBalancerName() != null && other.getLoadBalancerName().equals(this.getLoadBalancerName()) == false)
            return false;
        if (other.getLoadBalancerPort() == null ^ this.getLoadBalancerPort() == null)
            return false;
        if (other.getLoadBalancerPort() != null && other.getLoadBalancerPort().equals(this.getLoadBalancerPort()) == false)
            return false;
        if (other.getPolicyNames() == null ^ this.getPolicyNames() == null)
            return false;
        if (other.getPolicyNames() != null && other.getPolicyNames().equals(this.getPolicyNames()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getLoadBalancerName() == null) ? 0 : getLoadBalancerName().hashCode());
        hashCode = prime * hashCode + ((getLoadBalancerPort() == null) ? 0 : getLoadBalancerPort().hashCode());
        hashCode = prime * hashCode + ((getPolicyNames() == null) ? 0 : getPolicyNames().hashCode());
        return hashCode;
    }

    @Override
    public SetLoadBalancerPoliciesOfListenerRequest clone() {
        return (SetLoadBalancerPoliciesOfListenerRequest) super.clone();
    }

}


text:
package org.apache.jena.rdf.model;

import org.apache.jena.graph.* ;
import org.apache.jena.shared.* ;

/**
    Exception to throw when an RDFNode required to be a Resource isn't, or when a Node
    supposed to be a resource isn't.
*/
public class ResourceRequiredException extends JenaException
    {
    public ResourceRequiredException( RDFNode n )
        { this( n.asNode() ); }

    public ResourceRequiredException( Node n )
        { super( n.toString( PrefixMapping.Extended, true) ); }
    }

redpajama_set_name: RedPajamaGithub


text:
package simpledb

import (
	"github.com/stretchr/testify/assert"
	"net/http"
	"testing"

	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/awstesting"
)

func TestUnmarhsalErrorLeak(t *testing.T) {
	req := &request.Request{
		HTTPRequest: &http.Request{
			Header: make(http.Header),
			Body:   &awstesting.ReadCloser{Size: 2048},
		},
	}
	req.HTTPResponse = &http.Response{
		Body: &awstesting.ReadCloser{Size: 2048},
		Header: http.Header{
			"X-Amzn-Requestid": []string{"1"},
		},
		StatusCode: http.StatusOK,
	}

	reader := req.HTTPResponse.Body.(*awstesting.ReadCloser)
	unmarshalError(req)

	assert.NotNil(t, req.Error)
	assert.Equal(t, reader.Closed, true)
	assert.Equal(t, reader.Size, 0)
}


text:
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('show', '0001_initial'),
        ('venue', '0001_initial'),
        ('ticket', '0001_initial'),
    ]

    operations = [
        HStoreExtension(),
    ]


text:
namespace MosesTraining
{
namespace Syntax
{
namespace PostprocessEgretForests
{

ForestParser::ForestParser()
  : m_input(0)
{
}

ForestParser::ForestParser(std::istream &input)
  : m_input(&input)
{
  ++(*this);
}

ForestParser &ForestParser::operator++()
{
  if (!m_input) {
    return *this;
  }
  m_vertexSet.clear();
  m_entry.forest.vertices.clear();
  if (!std::getline(*m_input, m_tmpLine)) {
    m_input = 0;
    return *this;
  }
  // The first line contains the sentence number.
  ParseSentenceNumLine(m_tmpLine, m_entry.sentNum);
  // The second line contains the sentence string.
  std::getline(*m_input, m_entry.sentence);
  // Subsequent lines contain hyperedges -- or a blank line if there was a
  // parse failure -- terminated by a blank line.
  std::getline(*m_input, m_tmpLine);
  if (m_tmpLine == "") {  // Parse failure
    std::getline(*m_input, m_tmpLine);
    assert(m_tmpLine == "");
    return *this;
  }
  while (m_tmpLine != "") {
    ParseHyperedgeLine(m_tmpLine, m_entry.forest);
    std::getline(*m_input, m_tmpLine);
  }
  return *this;
}

boost::shared_ptr<Forest::Vertex> ForestParser::AddVertex(const VertexSP &v)
{
  std::pair<VertexSet::iterator, bool> ret = m_vertexSet.insert(v);
  if (ret.second) {
    m_entry.forest.vertices.push_back(*ret.first);
  }
  return *ret.first;
}

void ForestParser::ParseSentenceNumLine(const std::string &line,
                                        std::size_t &sentNum)
{
  const util::AnyCharacter delimiter(" \t");
  util::TokenIter<util::AnyCharacter, true> p(line, delimiter);
  if (*p != "sentence") {
    // FIXME
    throw Exception("");
  }
  ++p;
  std::string tmp;
  p->CopyToString(&tmp);
  sentNum = std::atoi(tmp.c_str());
}

void ForestParser::ParseHyperedgeLine(const std::string &line, Forest &forest)
{
  const util::AnyCharacter delimiter(" \t");
  util::TokenIter<util::AnyCharacter, true> p(line, delimiter);
  VertexSP v = AddVertex(ParseVertex(*p));
  HyperedgeSP e = boost::make_shared<Forest::Hyperedge>();
  e->head = v.get();
  ++p;
  if (*p != "=>") {
    // FIXME
    throw Exception("");
  }
  for (++p; *p != "|||"; ++p) {
    v = ParseVertex(*p);
    if (v->start == -1) {
      // Egret does not give start/end for terminals.
      v->start = v->end = e->head->start;
    }
    e->tail.push_back(AddVertex(v).get());
  }
  ++p;
  std::string tmp;
  p->CopyToString(&tmp);
  e->weight = std::atof(tmp.c_str());
  e->head->incoming.push_back(e);
}

boost::shared_ptr<Forest::Vertex> ForestParser::ParseVertex(
  const StringPiece &s)
{
  VertexSP v = boost::make_shared<Forest::Vertex>();
  std::size_t pos = s.rfind('[');
  if (pos == std::string::npos) {
    s.CopyToString(&v->symbol.value);
    v->symbol.isNonTerminal = false;
    v->start = v->end = -1;
    return v;
  }
  if (pos > 2 && s[pos-2] == '^' && s[pos-1] == 'g') {
    s.substr(0, pos-2).CopyToString(&v->symbol.value);
  } else {
    s.substr(0, pos).CopyToString(&v->symbol.value);
  }
  v->symbol.isNonTerminal = true;
  std::size_t begin = pos + 1;
  pos = s.find(',', begin+1);
  std::string tmp;
  s.substr(begin, pos-begin).CopyToString(&tmp);
  v->start = std::atoi(tmp.c_str());
  s.substr(pos+1, s.size()-pos-2).CopyToString(&tmp);
  v->end = std::atoi(tmp.c_str());
  return v;
}

bool operator==(const ForestParser &lhs, const ForestParser &rhs)
{
  // TODO Is this right?  Compare values of istreams if non-zero?
  return lhs.m_input == rhs.m_input;
}

bool operator!=(const ForestParser &lhs, const ForestParser &rhs)
{
  return !(lhs == rhs);
}

}  // namespace PostprocessEgretForests
}  // namespace Syntax
}  // namespace MosesTraining


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

<title>BrowseSearchInventoriesOfFriendsTest</title>
<meta name="date" content="2015-11-30">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

ca.ualberta.trinkettrader

Class BrowseSearchInventoriesOfFriendsTest

java.lang.Object

junit.framework.Assert

junit.framework.TestCase

android.test.InstrumentationTestCase

android.test.ActivityTestCase

android.test.ActivityInstrumentationTestCase2

ca.ualberta.trinkettrader.BrowseSearchInventoriesOfFriendsTest

All Implemented Interfaces:

junit.framework.Test

public class BrowseSearchInventoriesOfFriendsTest
extends android.test.ActivityInstrumentationTestCase2

Testing file for "Browse Search Inventories Of Friends" use cases.

Constructor Summary

Constructors

Constructor and Description

BrowseSearchInventoriesOfFriendsTest()

Method Summary

Methods

Modifier and Type
Method and Description

java.util.ArrayList<Trinket>
getDisplayedItems(android.widget.ListView view)

protected void
setUp()

void
testSearchInventoriesOfFriendsByCategorySingleFriend()

void
testSearchInventoriesOfFriendsByTextualQuery()

void
testSearchInventoriesOfFriendsSingleFriend()

void
testSharedTrinketsAreSearchableByFriends()

Methods inherited from class android.test.ActivityInstrumentationTestCase2

getActivity, runTest, setActivityInitialTouchMode, setActivityIntent, tearDown

Methods inherited from class android.test.ActivityTestCase

scrubClass, setActivity

Methods inherited from class android.test.InstrumentationTestCase

getInstrumentation, injectInsrumentation, injectInstrumentation, launchActivity, launchActivityWithIntent, runTestOnUiThread, sendKeys, sendKeys, sendRepeatedKeys

Methods inherited from class junit.framework.TestCase

countTestCases, createResult, getName, run, run, runBare, setName, toString

Methods inherited from class junit.framework.Assert

assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail, failNotEquals, failNotSame, failSame, format

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

BrowseSearchInventoriesOfFriendsTest

public BrowseSearchInventoriesOfFriendsTest()

Method Detail

setUp

protected void setUp()
              throws java.lang.Exception

Overrides:

setUp in class android.test.ActivityInstrumentationTestCase2

Throws:

java.lang.Exception

testSearchInventoriesOfFriendsSingleFriend

public void testSearchInventoriesOfFriendsSingleFriend()

getDisplayedItems

public java.util.ArrayList<Trinket> getDisplayedItems(android.widget.ListView view)

testSearchInventoriesOfFriendsByCategorySingleFriend

public void testSearchInventoriesOfFriendsByCategorySingleFriend()

testSearchInventoriesOfFriendsByTextualQuery

public void testSearchInventoriesOfFriendsByTextualQuery()

testSharedTrinketsAreSearchableByFriends

public void testSharedTrinketsAreSearchableByFriends()

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
class Solution(object):
    m = {}

    def findFrequentTreeSum(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        self.m = {}
        self.traverse(root)
        freq = max(self.m.values())
        return [e for e in self.m if self.m[e] == freq]

    def traverse(self, root):
        if not root:
            return
        self.traverse(root.left)
        self.traverse(root.right)
        if root.left:
            root.val += root.left.val
        if root.right:
            root.val += root.right.val
        print root.val
        self.m[root.val] = self.m.get(root.val, 0) + 1


text:
/**
 * Created by rohitgirme on 2/27/16.
 */
define([
  'views/editor/Editor'
], function (Editor) {

  'use strict';

  return {

    initialize: function () {
    },

    createEditor: function (id, container) {
      var editor = tinyMCE.EditorManager.createEditor(
        id,
        {
          inline       : true,
          menubar      : false,
          toolbar      : false,
          statusbar    : false,
          hidden_input : false,
          mode         : 'none'
        }
      );
      return new Editor({
        editorInstance: editor,
        container     : container
      });
    }

  };

});


text:
  TEXT("SOFTWARE\\Wow6432Node\\Microsoft\\Microsoft SDKs\\Windows\\")
#define REG_VS_INSTALL_PATH \
  TEXT("SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VS7")
#define REG_VC_TOOLS_PATH \
  TEXT("SOFTWARE\\Microsoft\\DevDiv\\VCForPython\\9.0")

#define MAX_VER_LEN 10

typedef struct search_t search_t;
typedef void(*query_callback_fn)(HKEY key, char* name, search_t* p);

struct search_t
{
  char path[MAX_PATH + 1];
  char version[MAX_VER_LEN + 1];
};

void get_child_count(HKEY key, DWORD* count, DWORD* largest_subkey)
{
  if(RegQueryInfoKey(key, NULL, NULL, NULL,
    count, largest_subkey, NULL, NULL, NULL, NULL, NULL, NULL) != ERROR_SUCCESS)
  {
    *count = 0;
    *largest_subkey = 0;
  }
}

bool query_registry(HKEY key, bool query_subkeys,
  query_callback_fn fn, search_t* p)
{
  DWORD sub_keys;
  DWORD largest_subkey;

  //Processing a leaf node in the registry, give it
  //to the callback.
  if(!query_subkeys)
  {
    fn(key, NULL, p);
    return true;
  }

  get_child_count(key, &sub_keys, &largest_subkey);

  if(sub_keys == 0)
    return false;

  largest_subkey += 1;

  HKEY node;
  DWORD size = largest_subkey;
  char* name = (char*)pool_alloc_size(largest_subkey);

  for(DWORD i = 0; i < sub_keys; ++i)
  {
    if(RegEnumKeyEx(key, i, name, &size,
      NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
    {
      if(RegOpenKeyEx(key, name, 0, KEY_QUERY_VALUE, &node) == ERROR_SUCCESS)
      {
        fn(node, name, p);
      }
      else
      {
        pool_free_size(largest_subkey, name);
        return false;
      }

      RegCloseKey(node);
    }
    else
    {
      pool_free_size(largest_subkey, name);
      return false;
    }

    size = largest_subkey;
  }

  pool_free_size(largest_subkey, name);
  return true;
}

static bool find_registry_key(char* path, query_callback_fn query,
  bool query_subkeys, search_t* p)
{
  bool success = true;
  HKEY key;

  //try global installations
  if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, path, 0,
    (KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE), &key) != ERROR_SUCCESS)
  {
    //try user-only installations
    if(RegOpenKeyEx(HKEY_CURRENT_USER, path, 0,
      (KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE), &key) != ERROR_SUCCESS)
    {
      success = false;
    }
  }

  if(success)
  {
    if(!query_registry(key, query_subkeys, query, p))
      success = false;
  }

  RegCloseKey(key);

  return success;
}

static void pick_vc_tools(HKEY key, char* name, search_t* p)
{
  DWORD size = MAX_PATH;

  RegGetValue(key, NULL, "InstallDir", RRF_RT_REG_SZ,
    NULL, p->path, &size);
}

static void pick_vs_tools(HKEY key, char* name, search_t* p)
{
  DWORD size = MAX_PATH;

  RegGetValue(key, NULL, p->version, RRF_RT_REG_SZ, NULL, p->path, &size);
}

static void pick_newest_sdk(HKEY key, char* name, search_t* p)
{
  //it seems to be the case that sub nodes ending
  //with an 'A' are .NET Framework SDKs
  if(name[strlen(name) - 1] == 'A')
    return;

  DWORD path_len = MAX_PATH;
  DWORD version_len = MAX_VER_LEN;
  char new_path[MAX_PATH];

  if(RegGetValue(key, NULL, "InstallationFolder", RRF_RT_REG_SZ,
    NULL, new_path, &path_len) == ERROR_SUCCESS)
  {
    char new_version[MAX_VER_LEN];

    if(RegGetValue(key, NULL, "ProductVersion",
      RRF_RT_REG_SZ, NULL, new_version, &version_len) == ERROR_SUCCESS)
    {
      if((strlen(p->version) == 0)
        || (strncmp(p->version, new_version, strlen(p->version)) < 0))
      {
        strcpy(p->path, new_path);
        strcpy(p->version, new_version);
      }
    }
  }
}

static bool find_kernel32(vcvars_t* vcvars)
{
  search_t sdk;
  memset(&sdk, 0, sizeof(search_t));

  if(!find_registry_key(REG_SDK_INSTALL_PATH, pick_newest_sdk, true, &sdk))
  {
    errorf(NULL, "unable to locate a Windows SDK");
    return false;
  }

  strcpy(vcvars->kernel32, sdk.path);
  strcat(vcvars->kernel32, "Lib\\winv6.3\\um\\x64");

  return true;
}

static bool find_executable(const char* path, const char* name, char* dest)
{
  TCHAR exe[MAX_PATH + 1];
  strcpy(exe, path);
  strcat(exe, name);

  if((GetFileAttributes(exe) != INVALID_FILE_ATTRIBUTES))
  {
    strcpy(dest, exe);
    return true;
  }
  else
  {
    errorf(NULL, "unable to locate %s", name);
    return false;
  }
}

static bool find_msvcrt_and_linker(vcvars_t* vcvars)
{
  search_t vs;

  snprintf(vs.version, sizeof(vs.version), "%d.%d",
    PLATFORM_TOOLS_VERSION / 10,
    PLATFORM_TOOLS_VERSION % 10);

  if(!find_registry_key(REG_VC_TOOLS_PATH, pick_vc_tools, false, &vs) &&
    !find_registry_key(REG_VS_INSTALL_PATH, pick_vs_tools, false, &vs))
  {
    errorf(NULL, "unable to locate VC tools or Visual Studio %s", vs.version);
    return false;
  }

  strcpy(vcvars->msvcrt, vs.path);
  strcat(vcvars->msvcrt, "VC\\lib\\amd64");

  //Find the linker relative to vs.path. We expect one to be at vs.path\bin.
  //The same applies to the lib archiver.
  bool ok = find_executable(vs.path, "VC\\bin\\link.exe", vcvars->link);
  ok &= find_executable(vs.path, "VC\\bin\\lib.exe", vcvars->ar);

  return ok;
}

bool vcvars_get(vcvars_t* vcvars)
{
  if(!find_kernel32(vcvars))
    return false;

  if(!find_msvcrt_and_linker(vcvars))
    return false;

  return true;
}

#endif


text:
class AccountInfoFetcher;
class OAuth2TokenService;
class PrefService;
class RefreshTokenAnnotationRequest;
class SigninClient;

namespace base {
class DictionaryValue;
}

// AccountTrackerService is a KeyedService that retrieves and caches GAIA
// information about Google Accounts.
class AccountTrackerService : public KeyedService,
                              public OAuth2TokenService::Observer,
                              public base::NonThreadSafe {
 public:
  // Name of the preference property that persists the account information
  // tracked by this service.
  static const char kAccountInfoPref[];

  // Name of the preference that tracks the int64 representation of the last
  // time the AccountTrackerService was updated.
  static const char kAccountTrackerServiceLastUpdate[];

  // TODO(mlerman): Remove all references to Profile::kNoHostedDomainFound in
  // favour of this.
  // Value representing no hosted domain in the kProfileHostedDomain preference.
  static const char kNoHostedDomainFound[];

  // Value representing no picture URL associated with an account.
  static const char kNoPictureURLFound[];

  // Information about a specific account.
  struct AccountInfo {
    AccountInfo();
    ~AccountInfo();

    std::string account_id;  // The account ID used by OAuth2TokenService.
    std::string gaia;
    std::string email;
    std::string full_name;
    std::string given_name;
    std::string hosted_domain;
    std::string locale;
    std::string picture_url;
    std::vector<std::string> service_flags;

    bool IsValid() const;
  };

  // Clients of AccountTrackerService can implement this interface and register
  // with AddObserver() to learn about account information changes.
  class Observer {
   public:
    virtual ~Observer() {}
    virtual void OnAccountUpdated(const AccountInfo& info) {}
    virtual void OnAccountUpdateFailed(const std::string& account_id) {}
    virtual void OnAccountRemoved(const AccountInfo& info) {}
  };

  // Possible values for the kAccountIdMigrationState preference.
  enum AccountIdMigrationState {
    MIGRATION_NOT_STARTED,
    MIGRATION_IN_PROGRESS,
    MIGRATION_DONE
  };

  AccountTrackerService();
  ~AccountTrackerService() override;

  // KeyedService implementation.
  void Shutdown() override;

  void AddObserver(Observer* observer);
  void RemoveObserver(Observer* observer);

  // Take a SigninClient rather than a PrefService and a URLRequestContextGetter
  // since RequestContext cannot be created at startup.
  // (see http://crbug.com/171406)
  void Initialize(OAuth2TokenService* token_service,
                  SigninClient* signin_client);

  // To be called after the Profile is fully initialized; permits network
  // calls to be executed.
  void EnableNetworkFetches();

  // Returns the list of known accounts and for which gaia IDs
  // have been fetched.
  std::vector<AccountInfo> GetAccounts() const;
  AccountInfo GetAccountInfo(const std::string& account_id);
  AccountInfo FindAccountInfoByGaiaId(const std::string& gaia_id);
  AccountInfo FindAccountInfoByEmail(const std::string& email);

  // Indicates if all user information has been fetched. If the result is false,
  // there are still unfininshed fetchers.
  virtual bool IsAllUserInfoFetched() const;

  // Picks the correct account_id for the specified account depending on the
  // migration state.
  std::string PickAccountIdForAccount(const std::string& gaia,
                                      const std::string& email);
  static std::string PickAccountIdForAccount(PrefService* pref_service,
                                             const std::string& gaia,
                                             const std::string& email);

  // Seeds the account whose account_id is given by PickAccountIdForAccount()
  // with its corresponding gaia id and email address.  Returns the same
  // value PickAccountIdForAccount() when given the same arguments.
  std::string SeedAccountInfo(const std::string& gaia,
                              const std::string& email);
  void SeedAccountInfo(AccountInfo info);

  AccountIdMigrationState GetMigrationState();
  static AccountIdMigrationState GetMigrationState(PrefService* pref_service);

 protected:
  // Available to be called in tests.
  void SetAccountStateFromUserInfo(
      const std::string& account_id,
      const base::DictionaryValue* user_info,
      const std::vector<std::string>* service_flags);

 private:
  friend class AccountInfoFetcher;

  // These methods are called by fetchers.
  void OnUserInfoFetchSuccess(AccountInfoFetcher* fetcher,
                              const base::DictionaryValue* user_info,
                              const std::vector<std::string>* service_flags);
  void OnUserInfoFetchFailure(AccountInfoFetcher* fetcher);

  // Refreshes the AccountInfo associated with |account_id| if it's invalid or
  // if |force_remote_fetch| is true.
  void RefreshAccountInfo(
      const std::string& account_id, bool force_remote_fetch);

  // OAuth2TokenService::Observer implementation.
  void OnRefreshTokenAvailable(const std::string& account_id) override;
  void OnRefreshTokenRevoked(const std::string& account_id) override;

  struct AccountState {
    AccountInfo info;
  };

  void NotifyAccountUpdated(const AccountState& state);
  void NotifyAccountUpdateFailed(const std::string& account_id);
  void NotifyAccountRemoved(const AccountState& state);

  void StartFetchingInvalidAccounts();
  void StartTrackingAccount(const std::string& account_id);
  void StopTrackingAccount(const std::string& account_id);

  // Virtual so that tests can override the network fetching behaviour.
  virtual void StartFetchingUserInfo(const std::string& account_id);
  void DeleteFetcher(AccountInfoFetcher* fetcher);

  // Load the current state of the account info from the preferences file.
  void LoadFromPrefs();
  void SaveToPrefs(const AccountState& account);
  void RemoveFromPrefs(const AccountState& account);

  void LoadFromTokenService();
  void RefreshFromTokenService();

  // Virtual so that tests can override the network fetching behaviour.
  virtual void SendRefreshTokenAnnotationRequest(const std::string& account_id);
  void RefreshTokenAnnotationRequestDone(const std::string& account_id);

  void ScheduleNextRefreshFromTokenService();

  OAuth2TokenService* token_service_;  // Not owned.
  SigninClient* signin_client_;  // Not owned.
  std::map<std::string, AccountInfoFetcher*> user_info_requests_;
  std::map<std::string, AccountState> accounts_;
  base::ObserverList<Observer> observer_list_;
  bool shutdown_called_;
  bool network_fetches_enabled_;
  std::list<std::string> pending_user_info_fetches_;
  base::Time last_updated_;
  base::OneShotTimer<AccountTrackerService> timer_;

  // Holds references to refresh token annotation requests keyed by account_id.
  base::ScopedPtrHashMap<std::string, scoped_ptr<RefreshTokenAnnotationRequest>>
      refresh_token_annotation_requests_;

  DISALLOW_COPY_AND_ASSIGN(AccountTrackerService);
};

#endif  // COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_TRACKER_SERVICE_H_


text:
/**
 * @file Automatically generated by barrelsby.
 */

export * from './createMissingObjectIDError';
export * from './createObjectNotFoundError';
export * from './createValidUntilNotFoundError';


text:
import torch

from fairseq import utils
from fairseq.criterions import register_criterion
from fairseq.criterions.label_smoothed_cross_entropy import (
    LabelSmoothedCrossEntropyCriterion,
    LabelSmoothedCrossEntropyCriterionConfig,
    label_smoothed_nll_loss,
)

@register_criterion(
    "speech_text_pretrain_cross_entropy",
    dataclass=LabelSmoothedCrossEntropyCriterionConfig,
)
class SpeechTextPreTrainCrossEntCriterion(LabelSmoothedCrossEntropyCriterion):
    def __init__(self, task, sentence_avg, label_smoothing, report_accuracy=False):
        super().__init__(
            task, sentence_avg, label_smoothing, report_accuracy=report_accuracy
        )

    def forward(self, model, sample, reduce=True):
        net_output = model(**sample["net_input"])
        loss, nll_loss, nsentences, ntokens, n_correct = self.compute_loss(
            model, net_output, sample, reduce=reduce
        )
        sample_size = nsentences if self.sentence_avg else ntokens
        logging_output = {
            "loss": loss.data,
            "nll_loss": nll_loss.data,
            "ntokens": ntokens,
            "nsentences": nsentences,
            "sample_size": sample_size,
        }
        if self.report_accuracy:
            logging_output["n_correct"] = utils.item(n_correct)
            logging_output["total"] = utils.item(ntokens)
        return loss, sample_size, logging_output

    def get_lprobs_and_target(self, model, net_output, sample):
        lprobs = model.get_normalized_probs(net_output, log_probs=True)
        target = model.get_targets(sample, net_output)
        assert self.ignore_prefix_size == 0
        if self.ignore_prefix_size > 0:
            if getattr(lprobs, "batch_first", False):
                lprobs = lprobs[:, self.ignore_prefix_size :, :].contiguous()
                target = target[:, self.ignore_prefix_size :].contiguous()
            else:
                lprobs = lprobs[self.ignore_prefix_size :, :, :].contiguous()
                target = target[self.ignore_prefix_size :, :].contiguous()
        return lprobs, target

    def compute_loss(self, model, net_output, sample, reduce=True):
        lprobs, target = self.get_lprobs_and_target(model, net_output, sample)
        n_correct = 0
        if isinstance(target, dict):
            t_lprobs = target["target_logprobs"]

            if not lprobs.batch_first:
                lprobs = lprobs.transpose(0, 1)
                t_lprobs = t_lprobs.transpose(0, 1)
            nsentences, seq_len = lprobs.size()[:2]
            ntokens = nsentences * seq_len
            t_probs = t_lprobs.exp()
            mask_indices = (
                net_output[1]["mask_indices"][0]
                if len(net_output[1]["mask_indices"]) > 0
                else None
            )

            # mask_indices is True for those masking frames
            if mask_indices is not None:  # B X T
                t_probs = t_probs.masked_fill(mask_indices.eq(False).unsqueeze(-1), 0)
                ntokens = mask_indices.int().sum()
            t_probs = t_probs.detach()
            t_lprobs = t_lprobs.detach()
            loss = (
                -(t_probs * (lprobs - t_lprobs)).sum()
                if reduce
                else -(t_probs * (lprobs - t_lprobs)).sum(-1, keepdim=True)
            )
            nll_loss = loss
        else:
            nsentences = target.size(0)
            mask = target.ne(self.padding_idx)
            loss, nll_loss = label_smoothed_nll_loss(
                lprobs.view(-1, lprobs.size(-1)),
                target.view(-1),
                self.eps,
                ignore_index=self.padding_idx,
                reduce=reduce,
            )
            n_correct = torch.sum(
                lprobs.argmax(-1).masked_select(mask).eq(target.masked_select(mask))
            )
            ntokens = torch.sum(mask)
        return loss, nll_loss, nsentences, ntokens, n_correct


text:
@interface ViewController ()
@property (atomic, readwrite, assign) NSInteger cellCount;
@end

@implementation ViewController

- (void)viewDidLoad {
	[super viewDidLoad];

    self.cellCount = 10;
    [self.collectionView registerClass:[Cell class] forCellWithReuseIdentifier:@"MY_CELL"];

#ifdef kPSTEnableFastAnimationTest
    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self addMoreCells];
    });
#endif
}

///////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - PSTCollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
    return self.cellCount;
}

///////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - PSTCollectionViewDelegate

- (PSUICollectionViewCell *)collectionView:(PSUICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MY_CELL" forIndexPath:indexPath];
    return cell;
}

///////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - PSTCollectionViewDelegateFlowLayout

- (CGSize)collectionView:(PSUICollectionView *)collectionView layout:(PSUICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(200, 200);
}

- (CGFloat)collectionView:(PSUICollectionView *)collectionView layout:(PSUICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

- (CGFloat)collectionView:(PSUICollectionView *)collectionView layout:(PSUICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 50;
}

//------------------------------------------------------------------------------
#pragma mark - UIScrollViewDelegate Methods

#ifdef kPSTEnableFastAnimationTest
- (void)addMoreCells {
    if (!self.isViewLoaded || !self.view.window) return;

    // Add a cell
    self.cellCount += 1;
    [self.collectionView performBatchUpdates:^{
        NSIndexPath *path = [NSIndexPath indexPathForItem:0 inSection:0];
        [self.collectionView insertItemsAtIndexPaths:@[path]];
    } completion:nil];

    // Wait a bit to add more
    double delayInSeconds = 0.25;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self addMoreCells];
    });
}
#endif

@end


text:
package com.facebook.buck.rules;

import com.facebook.buck.event.AbstractBuckEvent;
import com.facebook.buck.event.EventKey;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.base.Optional;
import com.google.common.hash.HashCode;

/**
 * Base class for events about build rules.
 */
public abstract class BuildRuleEvent extends AbstractBuckEvent {
  private final BuildRule rule;

  protected BuildRuleEvent(BuildRule rule) {
    super(EventKey.slowValueKey("BuildRuleEvent", rule.getFullyQualifiedName()));
    this.rule = rule;
  }

  public BuildRule getBuildRule() {
    return rule;
  }

  @Override
  public String getValueString() {
    return rule.getFullyQualifiedName();
  }

  /**
   * @return The string representation of the rulekey or the error text.
   */
  public String getRuleKeySafe() {
    String ruleKey;
    ruleKey = rule.getRuleKey().toString();
    return ruleKey;
  }

  public static Started started(BuildRule rule) {
    return new Started(rule);
  }

  public static Finished finished(BuildRule rule,
      BuildRuleStatus status,
      CacheResult cacheResult,
      Optional<BuildRuleSuccessType> successType,
      Optional<HashCode> outputHash,
      Optional<Long> outputSize) {
    return new Finished(rule, status, cacheResult, successType, outputHash, outputSize);
  }

  public static Suspended suspended(BuildRule rule) {
    return new Suspended(rule);
  }

  public static Resumed resumed(BuildRule rule) {
    return new Resumed(rule);
  }

  public static class Started extends BuildRuleEvent {
    protected Started(BuildRule rule) {
      super(rule);
    }

    @Override
    public String getEventName() {
      return "BuildRuleStarted";
    }
  }

  public static class Finished extends BuildRuleEvent {

    private final BuildRuleStatus status;
    private final CacheResult cacheResult;
    private final Optional<BuildRuleSuccessType> successType;
    private final Optional<HashCode> outputHash;
    private final Optional<Long> outputSize;

    protected Finished(BuildRule rule,
        BuildRuleStatus status,
        CacheResult cacheResult,
        Optional<BuildRuleSuccessType> successType,
        Optional<HashCode> outputHash,
        Optional<Long> outputSize) {
      super(rule);
      this.status = status;
      this.cacheResult = cacheResult;
      this.successType = successType;
      this.outputHash = outputHash;
      this.outputSize = outputSize;
    }

    public BuildRuleStatus getStatus() {
      return status;
    }

    public CacheResult getCacheResult() {
      return cacheResult;
    }

    @JsonIgnore
    public Optional<BuildRuleSuccessType> getSuccessType() {
      return successType;
    }

    @JsonIgnore
    public Optional<HashCode> getOutputHash() {
      return outputHash;
    }

    @JsonIgnore
    public Optional<Long> getOutputSize() {
      return outputSize;
    }

    @Override
    public String toString() {
      RuleKey ruleKey;
      ruleKey = getBuildRule().getRuleKey();

      String success = successType.isPresent() ? successType.get().toString() : "MISSING";
      return String.format("BuildRuleFinished(%s): %s %s %s %s",
          getBuildRule(),
          getStatus(),
          getCacheResult(),
          success,
          ruleKey);
    }

    @Override
    public String getEventName() {
      return "BuildRuleFinished";
    }
  }

  public static class Suspended extends BuildRuleEvent {

    protected Suspended(BuildRule rule) {
      super(rule);
    }

    @Override
    public String getEventName() {
      return "BuildRuleSuspended";
    }

  }

  public static class Resumed extends BuildRuleEvent {

    protected Resumed(BuildRule rule) {
      super(rule);
    }

    @Override
    public String getEventName() {
      return "BuildRuleResumed";
    }

  }

}


text:
/*Generated by KISSY Module Compiler*/
config({
'editor/plugin/strike-through/cmd': {requires: ['editor','editor/plugin/font/cmd']}
});


text:
package edu.ucsb.cs56.w14.drawings.jgee.advanced;
import java.awt.geom.GeneralPath; // combinations of lines and curves
import java.awt.geom.AffineTransform; // translation, rotation, scale
import java.awt.Shape; // general class for shapes

// all imports below this line needed if you are implementing Shape
import java.awt.geom.Point2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.Rectangle;
import java.awt.geom.PathIterator;
import java.awt.geom.AffineTransform;

import edu.ucsb.cs56.w14.drawings.utilities.ShapeTransforms;
import edu.ucsb.cs56.w14.drawings.utilities.GeneralPathWrapper;

public class Glass extends GeneralPathWrapper  implements Shape {

/** Constructor

@param x x coord of lower left corner of glass
@param y y coord of lower left corner of glass
@param width width of glass
@param height height of glass
*/
	public Glass(double x, double y, double width, double height) {
		Line2D.Double leftSide = new Line2D.Double(x,y,x,y+height);
		Line2D.Double rightSide = new Line2D.Double(x+width,y+height,x+width,y);
		Ellipse2D.Double rim = new Ellipse2D.Double(x,y,width,5);
		GeneralPath wholeGlass = this.get();
		wholeGlass.append(leftSide, false);
		wholeGlass.append(rightSide, true);
		wholeGlass.append(rim, false);
	}
}


text:
[![Build Status](https://travis-ci.org/develme/Nimble.svg?branch=master)](https://travis-ci.org/develme/Nimble)
[![GitHub version](https://badge.fury.io/gh/develme%2FNimble.svg)](http://badge.fury.io/gh/develme%2FNimble)

## Nimble - A NodeJS Framework

Nimble is a web application stack that puts the feeling of enjoyment and accomplishment back into developing. Nimble encompasses common tasks used in the majority of web applications, making the process of going from development to production a painless one. All of this, without sacrificing functionality within your projects.

Sound a lot like [Laravel](http://www.laravel.com)? We are huge fans of the aforementioned PHP framework! In fact, if it makes more sense to use PHP instead of NodeJS, we recommend taking advantage of the cool features Laravel has to offer.

## Documentation

The framework currently does not have any documentation.

## License

The Nimble framework is licensed under the [MIT license](http://opensource.org/licenses/MIT)


text:
import time
import threading
import shared
import hashlib
import random
from struct import unpack, pack
import sys
import string
from subprocess import call  # used when the API must execute an outside program
import traceback
from binascii import hexlify

from pyelliptic.openssl import OpenSSL
import highlevelcrypto
from addresses import *
from bmconfigparser import BMConfigParser
import helper_generic
from helper_generic import addDataPadding
import helper_bitcoin
import helper_inbox
import helper_msgcoding
import helper_sent
from helper_sql import *
from helper_ackPayload import genAckPayload
import protocol
import queues
import state
import tr
from debug import logger
import l10n

class objectProcessor(threading.Thread):
    """
    The objectProcessor thread, of which there is only one, receives network
    objects (msg, broadcast, pubkey, getpubkey) from the receiveDataThreads.
    """
    def __init__(self):
        threading.Thread.__init__(self, name="objectProcessor")
        """
        It may be the case that the last time Bitmessage was running, the user
        closed it before it finished processing everything in the
        objectProcessorQueue. Assuming that Bitmessage wasn't closed forcefully,
        it should have saved the data in the queue into the objectprocessorqueue
        table. Let's pull it out.
        """
        queryreturn = sqlQuery(
            '''SELECT objecttype, data FROM objectprocessorqueue''')
        for row in queryreturn:
            objectType, data = row
            queues.objectProcessorQueue.put((objectType,data))
        sqlExecute('''DELETE FROM objectprocessorqueue''')
        logger.debug('Loaded %s objects from disk into the objectProcessorQueue.' % str(len(queryreturn)))

    def run(self):
        while True:
            objectType, data = queues.objectProcessorQueue.get()

            self.checkackdata(data)

            try:
                if objectType == 0: # getpubkey
                    self.processgetpubkey(data)
                elif objectType == 1: #pubkey
                    self.processpubkey(data)
                elif objectType == 2: #msg
                    self.processmsg(data)
                elif objectType == 3: #broadcast
                    self.processbroadcast(data)
                elif objectType == 'checkShutdownVariable': # is more of a command, not an object type. Is used to get this thread past the queue.get() so that it will check the shutdown variable.
                    pass
                else:
                    if isinstance(objectType, int):
                        logger.info('Don\'t know how to handle object type 0x%08X', objectType)
                    else:
                        logger.info('Don\'t know how to handle object type %s', objectType)
            except helper_msgcoding.DecompressionSizeException as e:
                logger.error("The object is too big after decompression (stopped decompressing at %ib, your configured limit %ib). Ignoring", e.size, BMConfigParser().safeGetInt("zlib", "maxsize"))
            except varintDecodeError as e:
                logger.debug("There was a problem with a varint while processing an object. Some details: %s" % e)
            except Exception as e:
                logger.critical("Critical error within objectProcessorThread: \n%s" % traceback.format_exc())

            if state.shutdown:
                time.sleep(.5) # Wait just a moment for most of the connections to close
                numberOfObjectsThatWereInTheObjectProcessorQueue = 0
                with SqlBulkExecute() as sql:
                    while queues.objectProcessorQueue.curSize > 0:
                        objectType, data = queues.objectProcessorQueue.get()
                        sql.execute('''INSERT INTO objectprocessorqueue VALUES (?,?)''',
                                   objectType,data)
                        numberOfObjectsThatWereInTheObjectProcessorQueue += 1
                logger.debug('Saved %s objects from the objectProcessorQueue to disk. objectProcessorThread exiting.' % str(numberOfObjectsThatWereInTheObjectProcessorQueue))
                state.shutdown = 2
                break

    def checkackdata(self, data):
        # Let's check whether this is a message acknowledgement bound for us.
        if len(data) < 32:
            return

        # bypass nonce and time, retain object type/version/stream + body
        readPosition = 16

        if data[readPosition:] in shared.ackdataForWhichImWatching:
            logger.info('This object is an acknowledgement bound for me.')
            del shared.ackdataForWhichImWatching[data[readPosition:]]
            sqlExecute('UPDATE sent SET status=?, lastactiontime=? WHERE ackdata=?',
                       'ackreceived',
                       int(time.time()),
                       data[readPosition:])
            queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (data[readPosition:], tr._translate("MainWindow",'Acknowledgement of the message received %1').arg(l10n.formatTimestamp()))))
        else:
            logger.debug('This object is not an acknowledgement bound for me.')

    def processgetpubkey(self, data):
        if len(data) > 200:
            logger.info('getpubkey is abnormally long. Sanity check failed. Ignoring object.')
            return
        readPosition = 20  # bypass the nonce, time, and object type
        requestedAddressVersionNumber, addressVersionLength = decodeVarint(
            data[readPosition:readPosition + 10])
        readPosition += addressVersionLength
        streamNumber, streamNumberLength = decodeVarint(
            data[readPosition:readPosition + 10])
        readPosition += streamNumberLength

        if requestedAddressVersionNumber == 0:
            logger.debug('The requestedAddressVersionNumber of the pubkey request is zero. That doesn\'t make any sense. Ignoring it.')
            return
        elif requestedAddressVersionNumber == 1:
            logger.debug('The requestedAddressVersionNumber of the pubkey request is 1 which isn\'t supported anymore. Ignoring it.')
            return
        elif requestedAddressVersionNumber > 4:
            logger.debug('The requestedAddressVersionNumber of the pubkey request is too high. Can\'t understand. Ignoring it.')
            return

        myAddress = ''
        if requestedAddressVersionNumber <= 3 :
            requestedHash = data[readPosition:readPosition + 20]
            if len(requestedHash) != 20:
                logger.debug('The length of the requested hash is not 20 bytes. Something is wrong. Ignoring.')
                return
            logger.info('the hash requested in this getpubkey request is: %s' % hexlify(requestedHash))
            if requestedHash in shared.myAddressesByHash:  # if this address hash is one of mine
                myAddress = shared.myAddressesByHash[requestedHash]
        elif requestedAddressVersionNumber >= 4:
            requestedTag = data[readPosition:readPosition + 32]
            if len(requestedTag) != 32:
                logger.debug('The length of the requested tag is not 32 bytes. Something is wrong. Ignoring.')
                return
            logger.debug('the tag requested in this getpubkey request is: %s' % hexlify(requestedTag))
            if requestedTag in shared.myAddressesByTag:
                myAddress = shared.myAddressesByTag[requestedTag]

        if myAddress == '':
            logger.info('This getpubkey request is not for any of my keys.')
            return

        if decodeAddress(myAddress)[1] != requestedAddressVersionNumber:
            logger.warning('(Within the processgetpubkey function) Someone requested one of my pubkeys but the requestedAddressVersionNumber doesn\'t match my actual address version number. Ignoring.')
            return
        if decodeAddress(myAddress)[2] != streamNumber:
            logger.warning('(Within the processgetpubkey function) Someone requested one of my pubkeys but the stream number on which we heard this getpubkey object doesn\'t match this address\' stream number. Ignoring.')
            return
        if BMConfigParser().safeGetBoolean(myAddress, 'chan'):
            logger.info('Ignoring getpubkey request because it is for one of my chan addresses. The other party should already have the pubkey.')
            return
        try:
            lastPubkeySendTime = int(BMConfigParser().get(
                myAddress, 'lastpubkeysendtime'))
        except:
            lastPubkeySendTime = 0
        if lastPubkeySendTime > time.time() - 2419200:  # If the last time we sent our pubkey was more recent than 28 days ago...
            logger.info('Found getpubkey-requested-item in my list of EC hashes BUT we already sent it recently. Ignoring request. The lastPubkeySendTime is: %s' % lastPubkeySendTime)
            return
        logger.info('Found getpubkey-requested-hash in my list of EC hashes. Telling Worker thread to do the POW for a pubkey message and send it out.')
        if requestedAddressVersionNumber == 2:
            queues.workerQueue.put((
                'doPOWForMyV2Pubkey', requestedHash))
        elif requestedAddressVersionNumber == 3:
            queues.workerQueue.put((
                'sendOutOrStoreMyV3Pubkey', requestedHash))
        elif requestedAddressVersionNumber == 4:
            queues.workerQueue.put((
                'sendOutOrStoreMyV4Pubkey', myAddress))

    def processpubkey(self, data):
        pubkeyProcessingStartTime = time.time()
        shared.numberOfPubkeysProcessed += 1
        queues.UISignalQueue.put((
            'updateNumberOfPubkeysProcessed', 'no data'))
        embeddedTime, = unpack('>Q', data[8:16])
        readPosition = 20  # bypass the nonce, time, and object type
        addressVersion, varintLength = decodeVarint(
            data[readPosition:readPosition + 10])
        readPosition += varintLength
        streamNumber, varintLength = decodeVarint(
            data[readPosition:readPosition + 10])
        readPosition += varintLength
        if addressVersion == 0:
            logger.debug('(Within processpubkey) addressVersion of 0 doesn\'t make sense.')
            return
        if addressVersion > 4 or addressVersion == 1:
            logger.info('This version of Bitmessage cannot handle version %s addresses.' % addressVersion)
            return
        if addressVersion == 2:
            if len(data) < 146:  # sanity check. This is the minimum possible length.
                logger.debug('(within processpubkey) payloadLength less than 146. Sanity check failed.')
                return
            bitfieldBehaviors = data[readPosition:readPosition + 4]
            readPosition += 4
            publicSigningKey = data[readPosition:readPosition + 64]
            # Is it possible for a public key to be invalid such that trying to
            # encrypt or sign with it will cause an error? If it is, it would
            # be easiest to test them here.
            readPosition += 64
            publicEncryptionKey = data[readPosition:readPosition + 64]
            if len(publicEncryptionKey) < 64:
                logger.debug('publicEncryptionKey length less than 64. Sanity check failed.')
                return
            readPosition += 64
            dataToStore = data[20:readPosition] # The data we'll store in the pubkeys table.
            sha = hashlib.new('sha512')
            sha.update(
                '\x04' + publicSigningKey + '\x04' + publicEncryptionKey)
            ripeHasher = hashlib.new('ripemd160')
            ripeHasher.update(sha.digest())
            ripe = ripeHasher.digest()

            logger.debug('within recpubkey, addressVersion: %s, streamNumber: %s \n\
                        ripe %s\n\
                        publicSigningKey in hex: %s\n\
                        publicEncryptionKey in hex: %s' % (addressVersion,
                                                           streamNumber,
                                                           hexlify(ripe),
                                                           hexlify(publicSigningKey),
                                                           hexlify(publicEncryptionKey)
                                                           )
                        )

            address = encodeAddress(addressVersion, streamNumber, ripe)

            queryreturn = sqlQuery(
                '''SELECT usedpersonally FROM pubkeys WHERE address=? AND usedpersonally='yes' ''', address)
            if queryreturn != []:  # if this pubkey is already in our database and if we have used it personally:
                logger.info('We HAVE used this pubkey personally. Updating time.')
                t = (address, addressVersion, dataToStore, int(time.time()), 'yes')
            else:
                logger.info('We have NOT used this pubkey personally. Inserting in database.')
                t = (address, addressVersion, dataToStore, int(time.time()), 'no')
            sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
            self.possibleNewPubkey(address)
        if addressVersion == 3:
            if len(data) < 170:  # sanity check.
                logger.warning('(within processpubkey) payloadLength less than 170. Sanity check failed.')
                return
            bitfieldBehaviors = data[readPosition:readPosition + 4]
            readPosition += 4
            publicSigningKey = '\x04' + data[readPosition:readPosition + 64]
            readPosition += 64
            publicEncryptionKey = '\x04' + data[readPosition:readPosition + 64]
            readPosition += 64
            specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint(
                data[readPosition:readPosition + 10])
            readPosition += specifiedNonceTrialsPerByteLength
            specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint(
                data[readPosition:readPosition + 10])
            readPosition += specifiedPayloadLengthExtraBytesLength
            endOfSignedDataPosition = readPosition
            dataToStore = data[20:readPosition] # The data we'll store in the pubkeys table.
            signatureLength, signatureLengthLength = decodeVarint(
                data[readPosition:readPosition + 10])
            readPosition += signatureLengthLength
            signature = data[readPosition:readPosition + signatureLength]
            if highlevelcrypto.verify(data[8:endOfSignedDataPosition], signature, hexlify(publicSigningKey)):
                logger.debug('ECDSA verify passed (within processpubkey)')
            else:
                logger.warning('ECDSA verify failed (within processpubkey)')
                return

            sha = hashlib.new('sha512')
            sha.update(publicSigningKey + publicEncryptionKey)
            ripeHasher = hashlib.new('ripemd160')
            ripeHasher.update(sha.digest())
            ripe = ripeHasher.digest()

            logger.debug('within recpubkey, addressVersion: %s, streamNumber: %s \n\
                        ripe %s\n\
                        publicSigningKey in hex: %s\n\
                        publicEncryptionKey in hex: %s' % (addressVersion,
                                                           streamNumber,
                                                           hexlify(ripe),
                                                           hexlify(publicSigningKey),
                                                           hexlify(publicEncryptionKey)
                                                           )
                        )

            address = encodeAddress(addressVersion, streamNumber, ripe)
            queryreturn = sqlQuery('''SELECT usedpersonally FROM pubkeys WHERE address=? AND usedpersonally='yes' ''', address)
            if queryreturn != []:  # if this pubkey is already in our database and if we have used it personally:
                logger.info('We HAVE used this pubkey personally. Updating time.')
                t = (address, addressVersion, dataToStore, int(time.time()), 'yes')
            else:
                logger.info('We have NOT used this pubkey personally. Inserting in database.')
                t = (address, addressVersion, dataToStore, int(time.time()), 'no')
            sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
            self.possibleNewPubkey(address)

        if addressVersion == 4:
            if len(data) < 350:  # sanity check.
                logger.debug('(within processpubkey) payloadLength less than 350. Sanity check failed.')
                return

            tag = data[readPosition:readPosition + 32]
            if tag not in state.neededPubkeys:
                logger.info('We don\'t need this v4 pubkey. We didn\'t ask for it.')
                return

            # Let us try to decrypt the pubkey
            toAddress, cryptorObject = state.neededPubkeys[tag]
            if shared.decryptAndCheckPubkeyPayload(data, toAddress) == 'successful':
                # At this point we know that we have been waiting on this pubkey.
                # This function will command the workerThread to start work on
                # the messages that require it.
                self.possibleNewPubkey(toAddress)

        # Display timing data
        timeRequiredToProcessPubkey = time.time(
        ) - pubkeyProcessingStartTime
        logger.debug('Time required to process this pubkey: %s' % timeRequiredToProcessPubkey)

    def processmsg(self, data):
        messageProcessingStartTime = time.time()
        shared.numberOfMessagesProcessed += 1
        queues.UISignalQueue.put((
            'updateNumberOfMessagesProcessed', 'no data'))
        readPosition = 20 # bypass the nonce, time, and object type
        msgVersion, msgVersionLength = decodeVarint(data[readPosition:readPosition + 9])
        if msgVersion != 1:
            logger.info('Cannot understand message versions other than one. Ignoring message.')
            return
        readPosition += msgVersionLength

        streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint(
            data[readPosition:readPosition + 9])
        readPosition += streamNumberAsClaimedByMsgLength
        inventoryHash = calculateInventoryHash(data)
        initialDecryptionSuccessful = False

        # This is not an acknowledgement bound for me. See if it is a message
        # bound for me by trying to decrypt it with my private keys.

        for key, cryptorObject in sorted(shared.myECCryptorObjects.items(), key=lambda x: random.random()):
            try:
                if initialDecryptionSuccessful: # continue decryption attempts to avoid timing attacks
                    cryptorObject.decrypt(data[readPosition:])
                else:
                    decryptedData = cryptorObject.decrypt(data[readPosition:])
                    toRipe = key  # This is the RIPE hash of my pubkeys. We need this below to compare to the destination_ripe included in the encrypted data.
                    initialDecryptionSuccessful = True
                    logger.info('EC decryption successful using key associated with ripe hash: %s.' % hexlify(key))
            except Exception as err:
                pass
        if not initialDecryptionSuccessful:
            # This is not a message bound for me.
            logger.info('Length of time program spent failing to decrypt this message: %s seconds.' % (time.time() - messageProcessingStartTime,))
            return

        # This is a message bound for me.
        toAddress = shared.myAddressesByHash[
            toRipe]  # Look up my address based on the RIPE hash.
        readPosition = 0
        sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += sendersAddressVersionNumberLength
        if sendersAddressVersionNumber == 0:
            logger.info('Cannot understand sendersAddressVersionNumber = 0. Ignoring message.')
            return
        if sendersAddressVersionNumber > 4:
            logger.info('Sender\'s address version number %s not yet supported. Ignoring message.' % sendersAddressVersionNumber)
            return
        if len(decryptedData) < 170:
            logger.info('Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.')
            return
        sendersStreamNumber, sendersStreamNumberLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        if sendersStreamNumber == 0:
            logger.info('sender\'s stream number is 0. Ignoring message.')
            return
        readPosition += sendersStreamNumberLength
        behaviorBitfield = decryptedData[readPosition:readPosition + 4]
        readPosition += 4
        pubSigningKey = '\x04' + decryptedData[
            readPosition:readPosition + 64]
        readPosition += 64
        pubEncryptionKey = '\x04' + decryptedData[
            readPosition:readPosition + 64]
        readPosition += 64
        if sendersAddressVersionNumber >= 3:
            requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
                decryptedData[readPosition:readPosition + 10])
            readPosition += varintLength
            logger.info('sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is %s' % requiredAverageProofOfWorkNonceTrialsPerByte)
            requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
                decryptedData[readPosition:readPosition + 10])
            readPosition += varintLength
            logger.info('sender\'s requiredPayloadLengthExtraBytes is %s' % requiredPayloadLengthExtraBytes)
        endOfThePublicKeyPosition = readPosition  # needed for when we store the pubkey in our database of pubkeys for later use.
        if toRipe != decryptedData[readPosition:readPosition + 20]:
            logger.info('The original sender of this message did not send it to you. Someone is attempting a Surreptitious Forwarding Attack.\n\
                See: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html \n\
                your toRipe: %s\n\
                embedded destination toRipe: %s' % (hexlify(toRipe), hexlify(decryptedData[readPosition:readPosition + 20]))
                       )
            return
        readPosition += 20
        messageEncodingType, messageEncodingTypeLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += messageEncodingTypeLength
        messageLength, messageLengthLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += messageLengthLength
        message = decryptedData[readPosition:readPosition + messageLength]
        # print 'First 150 characters of message:', repr(message[:150])
        readPosition += messageLength
        ackLength, ackLengthLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += ackLengthLength
        ackData = decryptedData[readPosition:readPosition + ackLength]
        readPosition += ackLength
        positionOfBottomOfAckData = readPosition  # needed to mark the end of what is covered by the signature
        signatureLength, signatureLengthLength = decodeVarint(
            decryptedData[readPosition:readPosition + 10])
        readPosition += signatureLengthLength
        signature = decryptedData[
            readPosition:readPosition + signatureLength]
        signedData = data[8:20] + encodeVarint(1) + encodeVarint(streamNumberAsClaimedByMsg) + decryptedData[:positionOfBottomOfAckData]

        if not highlevelcrypto.verify(signedData, signature, hexlify(pubSigningKey)):
            logger.debug('ECDSA verify failed')
            return
        logger.debug('ECDSA verify passed')
        logger.debug('As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person: %s  ..and here is the testnet address: %s. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.' %
                     (helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey), helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey))
                     )
        sigHash = hashlib.sha512(hashlib.sha512(signature).digest()).digest()[32:] # Used to detect and ignore duplicate messages in our inbox

        # calculate the fromRipe.
        sha = hashlib.new('sha512')
        sha.update(pubSigningKey + pubEncryptionKey)
        ripe = hashlib.new('ripemd160')
        ripe.update(sha.digest())
        fromAddress = encodeAddress(
            sendersAddressVersionNumber, sendersStreamNumber, ripe.digest())

        # Let's store the public key in case we want to reply to this
        # person.
        sqlExecute(
            '''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
            fromAddress,
            sendersAddressVersionNumber,
            decryptedData[:endOfThePublicKeyPosition],
            int(time.time()),
            'yes')

        # Check to see whether we happen to be awaiting this
        # pubkey in order to send a message. If we are, it will do the POW
        # and send it.
        self.possibleNewPubkey(fromAddress)

        # If this message is bound for one of my version 3 addresses (or
        # higher), then we must check to make sure it meets our demanded
        # proof of work requirement. If this is bound for one of my chan
        # addresses then we skip this check; the minimum network POW is
        # fine.
        if decodeAddress(toAddress)[1] >= 3 and not BMConfigParser().safeGetBoolean(toAddress, 'chan'):  # If the toAddress version number is 3 or higher and not one of my chan addresses:
            if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress):  # If I'm not friendly with this person:
                requiredNonceTrialsPerByte = BMConfigParser().getint(
                    toAddress, 'noncetrialsperbyte')
                requiredPayloadLengthExtraBytes = BMConfigParser().getint(
                    toAddress, 'payloadlengthextrabytes')
                if not protocol.isProofOfWorkSufficient(data, requiredNonceTrialsPerByte, requiredPayloadLengthExtraBytes):
                    logger.info('Proof of work in msg is insufficient only because it does not meet our higher requirement.')
                    return
        blockMessage = False  # Gets set to True if the user shouldn't see the message according to black or white lists.
        if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':  # If we are using a blacklist
            queryreturn = sqlQuery(
                '''SELECT label FROM blacklist where address=? and enabled='1' ''',
                fromAddress)
            if queryreturn != []:
                logger.info('Message ignored because address is in blacklist.')

                blockMessage = True
        else:  # We're using a whitelist
            queryreturn = sqlQuery(
                '''SELECT label FROM whitelist where address=? and enabled='1' ''',
                fromAddress)
            if queryreturn == []:
                logger.info('Message ignored because address not in whitelist.')
                blockMessage = True

        toLabel = BMConfigParser().get(toAddress, 'label')
        if toLabel == '':
            toLabel = toAddress

        try:
            decodedMessage = helper_msgcoding.MsgDecode(messageEncodingType, message)
        except helper_msgcoding.MsgDecodeException:
            return
        subject = decodedMessage.subject
        body = decodedMessage.body

        # Let us make sure that we haven't already received this message
        if helper_inbox.isMessageAlreadyInInbox(sigHash):
            logger.info('This msg is already in our inbox. Ignoring it.')
            blockMessage = True
        if not blockMessage:
            if messageEncodingType != 0:
                t = (inventoryHash, toAddress, fromAddress, subject, int(
                    time.time()), body, 'inbox', messageEncodingType, 0, sigHash)
                helper_inbox.insert(t)

                queues.UISignalQueue.put(('displayNewInboxMessage', (
                    inventoryHash, toAddress, fromAddress, subject, body)))

            # If we are behaving as an API then we might need to run an
            # outside command to let some program know that a new message
            # has arrived.
            if BMConfigParser().safeGetBoolean('bitmessagesettings', 'apienabled'):
                try:
                    apiNotifyPath = BMConfigParser().get(
                        'bitmessagesettings', 'apinotifypath')
                except:
                    apiNotifyPath = ''
                if apiNotifyPath != '':
                    call([apiNotifyPath, "newMessage"])

            # Let us now check and see whether our receiving address is
            # behaving as a mailing list
            if BMConfigParser().safeGetBoolean(toAddress, 'mailinglist') and messageEncodingType != 0:
                try:
                    mailingListName = BMConfigParser().get(
                        toAddress, 'mailinglistname')
                except:
                    mailingListName = ''
                # Let us send out this message as a broadcast
                subject = self.addMailingListNameToSubject(
                    subject, mailingListName)
                # Let us now send this message out as a broadcast
                message = time.strftime("%a, %Y-%m-%d %H:%M:%S UTC", time.gmtime(
                )) + '   Message ostensibly from ' + fromAddress + ':\n\n' + body
                fromAddress = toAddress  # The fromAddress for the broadcast that we are about to send is the toAddress (my address) for the msg message we are currently processing.
                # We don't actually need the ackdata for acknowledgement since this is a broadcast message but we can use it to update the user interface when the POW is done generating.
                streamNumber = decodeAddress(fromAddress)[2]

                ackdata = genAckPayload(streamNumber, 0)
                toAddress = '[Broadcast subscribers]'
                ripe = ''

                # We really should have a discussion about how to
                # set the TTL for mailing list broadcasts. This is obviously
                # hard-coded.
                TTL = 2*7*24*60*60 # 2 weeks
                t = ('',
                     toAddress,
                     ripe,
                     fromAddress,
                     subject,
                     message,
                     ackdata,
                     int(time.time()), # sentTime (this doesn't change)
                     int(time.time()), # lastActionTime
                     0,
                     'broadcastqueued',
                     0,
                     'sent',
                     messageEncodingType,
                     TTL)
                helper_sent.insert(t)

                queues.UISignalQueue.put(('displayNewSentMessage', (
                    toAddress, '[Broadcast subscribers]', fromAddress, subject, message, ackdata)))
                queues.workerQueue.put(('sendbroadcast', ''))

        # Don't send ACK if invalid, blacklisted senders, invisible messages, disabled or chan
        if self.ackDataHasAValidHeader(ackData) and \
            not blockMessage and \
            messageEncodingType != 0 and \
            not BMConfigParser().safeGetBoolean(toAddress, 'dontsendack') and \
            not BMConfigParser().safeGetBoolean(toAddress, 'chan'):
            shared.checkAndShareObjectWithPeers(ackData[24:])

        # Display timing data
        timeRequiredToAttemptToDecryptMessage = time.time(
        ) - messageProcessingStartTime
        shared.successfullyDecryptMessageTimings.append(
            timeRequiredToAttemptToDecryptMessage)
        sum = 0
        for item in shared.successfullyDecryptMessageTimings:
            sum += item
        logger.debug('Time to decrypt this message successfully: %s\n\
                     Average time for all message decryption successes since startup: %s.' %
                     (timeRequiredToAttemptToDecryptMessage, sum / len(shared.successfullyDecryptMessageTimings))
                     )

    def processbroadcast(self, data):
        messageProcessingStartTime = time.time()
        shared.numberOfBroadcastsProcessed += 1
        queues.UISignalQueue.put((
            'updateNumberOfBroadcastsProcessed', 'no data'))
        inventoryHash = calculateInventoryHash(data)
        readPosition = 20  # bypass the nonce, time, and object type
        broadcastVersion, broadcastVersionLength = decodeVarint(
            data[readPosition:readPosition + 9])
        readPosition += broadcastVersionLength
        if broadcastVersion < 4 or broadcastVersion > 5:
            logger.info('Cannot decode incoming broadcast versions less than 4 or higher than 5. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.')
            return
        cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint(
            data[readPosition:readPosition + 10])
        readPosition += cleartextStreamNumberLength
        if broadcastVersion == 4:
            """
            v4 broadcasts are encrypted the same way the msgs are encrypted. To see if we are interested in a
            v4 broadcast, we try to decrypt it. This was replaced with v5 broadcasts which include a tag which
            we check instead, just like we do with v4 pubkeys.
            """
            signedData = data[8:readPosition]
            initialDecryptionSuccessful = False
            for key, cryptorObject in sorted(shared.MyECSubscriptionCryptorObjects.items(), key=lambda x: random.random()):
                try:
                    if initialDecryptionSuccessful: # continue decryption attempts to avoid timing attacks
                        cryptorObject.decrypt(data[readPosition:])
                    else:
                        decryptedData = cryptorObject.decrypt(data[readPosition:])
                        toRipe = key  # This is the RIPE hash of the sender's pubkey. We need this below to compare to the RIPE hash of the sender's address to verify that it was encrypted by with their key rather than some other key.
                        initialDecryptionSuccessful = True
                        logger.info('EC decryption successful using key associated with ripe hash: %s' % hexlify(key))
                except Exception as err:
                    pass
                    # print 'cryptorObject.decrypt Exception:', err
            if not initialDecryptionSuccessful:
                # This is not a broadcast I am interested in.
                logger.debug('Length of time program spent failing to decrypt this v4 broadcast: %s seconds.' % (time.time() - messageProcessingStartTime,))
                return
        elif broadcastVersion == 5:
            embeddedTag = data[readPosition:readPosition+32]
            readPosition += 32
            if embeddedTag not in shared.MyECSubscriptionCryptorObjects:
                logger.debug('We\'re not interested in this broadcast.')
                return
            # We are interested in this broadcast because of its tag.
            signedData = data[8:readPosition] # We're going to add some more data which is signed further down.
            cryptorObject = shared.MyECSubscriptionCryptorObjects[embeddedTag]
            try:
                decryptedData = cryptorObject.decrypt(data[readPosition:])
                logger.debug('EC decryption successful')
            except Exception as err:
                logger.debug('Broadcast version %s decryption Unsuccessful.' % broadcastVersion)
                return
        # At this point this is a broadcast I have decrypted and am
        # interested in.
        readPosition = 0
        sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
            decryptedData[readPosition:readPosition + 9])
        if broadcastVersion == 4:
            if sendersAddressVersion < 2 or sendersAddressVersion > 3:
                logger.warning('Cannot decode senderAddressVersion other than 2 or 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.')
                return
        elif broadcastVersion == 5:
            if sendersAddressVersion < 4:
                logger.info('Cannot decode senderAddressVersion less than 4 for broadcast version number 5. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.')
                return
        readPosition += sendersAddressVersionLength
        sendersStream, sendersStreamLength = decodeVarint(
            decryptedData[readPosition:readPosition + 9])
        if sendersStream != cleartextStreamNumber:
            logger.info('The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.')
            return
        readPosition += sendersStreamLength
        behaviorBitfield = decryptedData[readPosition:readPosition + 4]
        readPosition += 4
        sendersPubSigningKey = '\x04' + \
            decryptedData[readPosition:readPosition + 64]
        readPosition += 64
        sendersPubEncryptionKey = '\x04' + \
            decryptedData[readPosition:readPosition + 64]
        readPosition += 64
        if sendersAddressVersion >= 3:
            requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
                decryptedData[readPosition:readPosition + 10])
            readPosition += varintLength
            logger.debug('sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is %s' % requiredAverageProofOfWorkNonceTrialsPerByte)
            requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
                decryptedData[readPosition:readPosition + 10])
            readPosition += varintLength
            logger.debug('sender\'s requiredPayloadLengthExtraBytes is %s' % requiredPayloadLengthExtraBytes)
        endOfPubkeyPosition = readPosition

        sha = hashlib.new('sha512')
        sha.update(sendersPubSigningKey + sendersPubEncryptionKey)
        ripeHasher = hashlib.new('ripemd160')
        ripeHasher.update(sha.digest())
        calculatedRipe = ripeHasher.digest()

        if broadcastVersion == 4:
            if toRipe != calculatedRipe:
                logger.info('The encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.')
                return
        elif broadcastVersion == 5:
            calculatedTag = hashlib.sha512(hashlib.sha512(encodeVarint(
                sendersAddressVersion) + encodeVarint(sendersStream) + calculatedRipe).digest()).digest()[32:]
            if calculatedTag != embeddedTag:
                logger.debug('The tag and encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.')
                return
        messageEncodingType, messageEncodingTypeLength = decodeVarint(
            decryptedData[readPosition:readPosition + 9])
        if messageEncodingType == 0:
            return
        readPosition += messageEncodingTypeLength
        messageLength, messageLengthLength = decodeVarint(
            decryptedData[readPosition:readPosition + 9])
        readPosition += messageLengthLength
        message = decryptedData[readPosition:readPosition + messageLength]
        readPosition += messageLength
        readPositionAtBottomOfMessage = readPosition
        signatureLength, signatureLengthLength = decodeVarint(
            decryptedData[readPosition:readPosition + 9])
        readPosition += signatureLengthLength
        signature = decryptedData[
            readPosition:readPosition + signatureLength]
        signedData += decryptedData[:readPositionAtBottomOfMessage]
        if not highlevelcrypto.verify(signedData, signature, hexlify(sendersPubSigningKey)):
            logger.debug('ECDSA verify failed')
            return
        logger.debug('ECDSA verify passed')
        sigHash = hashlib.sha512(hashlib.sha512(signature).digest()).digest()[32:] # Used to detect and ignore duplicate messages in our inbox

        fromAddress = encodeAddress(
            sendersAddressVersion, sendersStream, calculatedRipe)
        logger.info('fromAddress: %s' % fromAddress)

        # Let's store the public key in case we want to reply to this person.
        sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
                   fromAddress,
                   sendersAddressVersion,
                   decryptedData[:endOfPubkeyPosition],
                   int(time.time()),
                   'yes')

        # Check to see whether we happen to be awaiting this
        # pubkey in order to send a message. If we are, it will do the POW
        # and send it.
        self.possibleNewPubkey(fromAddress)

        fromAddress = encodeAddress(
            sendersAddressVersion, sendersStream, calculatedRipe)
        logger.debug('fromAddress: ' + fromAddress)

        try:
            decodedMessage = helper_msgcoding.MsgDecode(messageEncodingType, message)
        except helper_msgcoding.MsgDecodeException:
            return
        subject = decodedMessage.subject
        body = decodedMessage.body

        toAddress = '[Broadcast subscribers]'
        if helper_inbox.isMessageAlreadyInInbox(sigHash):
            logger.info('This broadcast is already in our inbox. Ignoring it.')
            return
        t = (inventoryHash, toAddress, fromAddress, subject, int(
            time.time()), body, 'inbox', messageEncodingType, 0, sigHash)
        helper_inbox.insert(t)

        queues.UISignalQueue.put(('displayNewInboxMessage', (
            inventoryHash, toAddress, fromAddress, subject, body)))

        # If we are behaving as an API then we might need to run an
        # outside command to let some program know that a new message
        # has arrived.
        if BMConfigParser().safeGetBoolean('bitmessagesettings', 'apienabled'):
            try:
                apiNotifyPath = BMConfigParser().get(
                    'bitmessagesettings', 'apinotifypath')
            except:
                apiNotifyPath = ''
            if apiNotifyPath != '':
                call([apiNotifyPath, "newBroadcast"])

        # Display timing data
        logger.info('Time spent processing this interesting broadcast: %s' % (time.time() - messageProcessingStartTime,))

    def possibleNewPubkey(self, address):
        """
        We have inserted a pubkey into our pubkey table which we received from a
        pubkey, msg, or broadcast message. It might be one that we have been
        waiting for. Let's check.
        """

        # For address versions <= 3, we wait on a key with the correct address version,
        # stream number, and RIPE hash.
        status, addressVersion, streamNumber, ripe = decodeAddress(address)
        if addressVersion <=3:
            if address in state.neededPubkeys:
                del state.neededPubkeys[address]
                self.sendMessages(address)
            else:
                logger.debug('We don\'t need this pub key. We didn\'t ask for it. For address: %s' % address)
        # For address versions >= 4, we wait on a pubkey with the correct tag.
        # Let us create the tag from the address and see if we were waiting
        # for it.
        elif addressVersion >= 4:
            tag = hashlib.sha512(hashlib.sha512(encodeVarint(
                addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()[32:]
            if tag in state.neededPubkeys:
                del state.neededPubkeys[tag]
                self.sendMessages(address)

    def sendMessages(self, address):
        """
        This function is called by the possibleNewPubkey function when
        that function sees that we now have the necessary pubkey
        to send one or more messages.
        """
        logger.info('We have been awaiting the arrival of this pubkey.')
        sqlExecute(
            '''UPDATE sent SET status='doingmsgpow', retrynumber=0 WHERE toaddress=? AND (status='awaitingpubkey' or status='doingpubkeypow') AND folder='sent' ''',
            address)
        queues.workerQueue.put(('sendmessage', ''))

    def ackDataHasAValidHeader(self, ackData):
        if len(ackData) < protocol.Header.size:
            logger.info('The length of ackData is unreasonably short. Not sending ackData.')
            return False

        magic,command,payloadLength,checksum = protocol.Header.unpack(ackData[:protocol.Header.size])
        if magic != 0xE9BEB4D9:
            logger.info('Ackdata magic bytes were wrong. Not sending ackData.')
            return False
        payload = ackData[protocol.Header.size:]
        if len(payload) != payloadLength:
            logger.info('ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.')
            return False
        if payloadLength > 1600100: # ~1.6 MB which is the maximum possible size of an inv message.
            """
            The largest message should be either an inv or a getdata message at 1.6 MB in size.
            That doesn't mean that the object may be that big. The
            shared.checkAndShareObjectWithPeers function will verify that it is no larger than
            2^18 bytes.
            """
            return False
        if checksum != hashlib.sha512(payload).digest()[0:4]:  # test the checksum in the message.
            logger.info('ackdata checksum wrong. Not sending ackdata.')
            return False
        command = command.rstrip('\x00')
        if command != 'object':
            return False
        return True

    def addMailingListNameToSubject(self, subject, mailingListName):
        subject = subject.strip()
        if subject[:3] == 'Re:' or subject[:3] == 'RE:':
            subject = subject[3:].strip()
        if '[' + mailingListName + ']' in subject:
            return subject
        else:
            return '[' + mailingListName + '] ' + subject

    def decodeType2Message(self, message):
        bodyPositionIndex = string.find(message, '\nBody:')
        if bodyPositionIndex > 1:
            subject = message[8:bodyPositionIndex]
            # Only save and show the first 500 characters of the subject.
            # Any more is probably an attack.
            subject = subject[:500]
            body = message[bodyPositionIndex + 6:]
        else:
            subject = ''
            body = message
        # Throw away any extra lines (headers) after the subject.
        if subject:
            subject = subject.splitlines()[0]
        return subject, body


text:
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoNSubstitute;
using Ploeh.AutoFixture.Xunit2;
using Sitecore.FakeDb.AutoFixture;

namespace Sitecore.Feature.LayoutSimulator.Tests.Attributes
{
    internal class AutoDbDataAttribute : AutoDataAttribute
    {
        public AutoDbDataAttribute()
              : base(new Fixture()
                .Customize(new AutoNSubstituteCustomization())
                .Customize(new AutoDbCustomization()))
        {
        }
    }
}