text:
"""Base classes for artifacts."""

import logging

from grr.lib import aff4
from grr.lib import artifact_registry
from grr.lib import artifact_utils
from grr.lib import config_lib
from grr.lib import flow
from grr.lib import parsers
from grr.lib import rdfvalue
from grr.lib import registry
from grr.lib import utils
from grr.lib.aff4_objects import aff4_grr
from grr.lib.aff4_objects import software
from grr.lib.rdfvalues import anomaly
from grr.lib.rdfvalues import client as rdf_client
from grr.lib.rdfvalues import protodict as rdf_protodict
from grr.lib.rdfvalues import structs as rdf_structs
from grr.proto import flows_pb2

class AFF4ResultWriter(object):
  """A wrapper class to allow writing objects to the AFF4 space."""

  def __init__(self, path, aff4_type, aff4_attribute, mode):
    self.path = path
    self.aff4_type = aff4_type
    self.aff4_attribute = aff4_attribute
    self.mode = mode

def GetArtifactKnowledgeBase(client_obj, allow_uninitialized=False):
  """This generates an artifact knowledge base from a GRR client.

  Args:
    client_obj: A GRRClient object which is opened for reading.
    allow_uninitialized: If True we accept an uninitialized knowledge_base.

  Returns:
    A KnowledgeBase semantic value.

  Raises:
    ArtifactProcessingError: If called when the knowledge base has not been
    initialized.
    KnowledgeBaseUninitializedError: If we failed to initialize the knowledge
    base.

  This is needed so that the artifact library has a standardized
  interface to the data that is actually stored in the GRRClient object in
  the GRR datastore.

  We expect that the client KNOWLEDGE_BASE is already filled out through the,
  KnowledgeBaseInitialization flow, but attempt to make some intelligent
  guesses if things failed.
  """
  client_schema = client_obj.Schema
  kb = client_obj.Get(client_schema.KNOWLEDGE_BASE)
  if not allow_uninitialized:
    if not kb:
      raise artifact_utils.KnowledgeBaseUninitializedError(
          "KnowledgeBase empty for %s." % client_obj.urn)
    if not kb.os:
      raise artifact_utils.KnowledgeBaseAttributesMissingError(
          "KnowledgeBase missing OS for %s. Knowledgebase content: %s" %
          (client_obj.urn, kb))
  if not kb:
    kb = client_schema.KNOWLEDGE_BASE()
    SetCoreGRRKnowledgeBaseValues(kb, client_obj)

  if kb.os == "Windows":
    # Add fallback values.
    if not kb.environ_allusersappdata and kb.environ_allusersprofile:
      # Guess if we don't have it already.
      if kb.os_major_version >= 6:
        kb.environ_allusersappdata = u"c:\\programdata"
        kb.environ_allusersprofile = u"c:\\programdata"
      else:
        kb.environ_allusersappdata = (u"c:\\documents and settings\\All Users\\"
                                      "Application Data")
        kb.environ_allusersprofile = u"c:\\documents and settings\\All Users"

  return kb

def SetCoreGRRKnowledgeBaseValues(kb, client_obj):
  """Set core values from GRR into the knowledgebase."""
  client_schema = client_obj.Schema
  kb.hostname = utils.SmartUnicode(client_obj.Get(client_schema.FQDN, ""))
  if not kb.hostname:
    kb.hostname = utils.SmartUnicode(client_obj.Get(client_schema.HOSTNAME, ""))
  versions = client_obj.Get(client_schema.OS_VERSION)
  if versions and versions.versions:
    kb.os_major_version = versions.versions[0]
    kb.os_minor_version = versions.versions[1]
  client_os = client_obj.Get(client_schema.SYSTEM)
  if client_os:
    kb.os = utils.SmartUnicode(client_obj.Get(client_schema.SYSTEM))

class CollectArtifactDependenciesArgs(rdf_structs.RDFProtoStruct):
  protobuf = flows_pb2.CollectArtifactDependenciesArgs

class CollectArtifactDependencies(flow.GRRFlow):
  """Collect knowledgebase dependencies for a list of artifacts.

  We determine what knowledgebase attributes are required to collect and parse
  the given list of artifacts. They are then collected and stored in the
  knowledgebase.

  We don't try to fulfill dependencies in the tree order, the reasoning is that
  some artifacts may fail, and some artifacts provide the same dependency.

  Instead we take an iterative approach and keep requesting artifacts until
  all dependencies have been met.  If there is more than one artifact that
  provides a dependency we will collect them all as they likely have
  different performance characteristics, e.g. accuracy and client impact.

  Note that running a full KnowledgeBaseInitializationFlow is the most complete
  way to ensure all dependencies have been collected.  We collect explicit
  dependencies here, but for example if a registry key value retrieved contains
  an environment variable not already collected it may not get expanded.
  """
  category = "/Collectors/"
  behaviours = flow.GRRFlow.behaviours + "ADVANCED"
  args_type = CollectArtifactDependenciesArgs

  @flow.StateHandler(next_state=["ProcessBase"])
  def Start(self):
    """For each artifact, create subflows for each collector."""
    self.state.Register("knowledge_base", None)
    self.state.Register("fulfilled_deps", [])
    self.state.Register("partial_fulfilled_deps", set())
    self.state.Register("all_deps", set())
    self.state.Register("in_flight_artifacts", [])
    self.state.Register("awaiting_deps_artifacts", [])
    self.state.Register("completed_artifacts", [])

    self.InitializeKnowledgeBase()
    first_flows = self.GetFirstFlowsForCollection()

    # Send each artifact independently so we can track which artifact produced
    # it when it comes back.
    # TODO(user): tag SendReplys with the flow that
    # generated them.
    for artifact_name in first_flows:
      self.state.in_flight_artifacts.append(artifact_name)
      self.CallFlow("ArtifactCollectorFlow", artifact_list=[artifact_name],
                    knowledge_base=self.state.knowledge_base,
                    store_results_in_aff4=False, next_state="ProcessBase",
                    request_data={"artifact_name": artifact_name})

  def GetFirstFlowsForCollection(self):
    """Initialize dependencies and calculate first round of flows.

    Returns:
      set of artifact names with no dependencies that should be collected first.
    """
    artifact_set = set(self.args.artifact_list)

    deps = artifact_registry.REGISTRY.SearchDependencies(
        self.state.knowledge_base.os, artifact_set)
    name_deps, self.state.all_deps = deps

    # Find the any dependencies that don't have dependencies themselves as our
    # starting point.
    check_deps = name_deps.union(artifact_set)
    no_deps_names = artifact_registry.REGISTRY.GetArtifactNames(
        os_name=self.state.knowledge_base.os, name_list=check_deps,
        exclude_dependents=True)

    # If the only artifacts with no dependencies are the ones we want to collect
    # that means there is nothing to do.
    if no_deps_names == artifact_set:
      return []

    # We're going to collect everything that doesn't have a dependency first.
    # Anything else we're waiting on a dependency before we can collect.

    # We exclude the original artifacts since we're just fulfilling
    # dependencies, the original flow will collect the artifacts once the
    # dependencies are ready.
    self.state.awaiting_deps_artifacts = list(name_deps - no_deps_names -
                                              artifact_set)
    return no_deps_names

  def InitializeKnowledgeBase(self):
    """Get the existing KB or create a new one if none exists."""
    self.client = aff4.FACTORY.Open(self.client_id, token=self.token)
    self.state.knowledge_base = GetArtifactKnowledgeBase(
        self.client, allow_uninitialized=True)

    if not self.state.knowledge_base.os:
      # If we don't know what OS this is, there is no way to proceed.
      raise flow.FlowError("Client OS not set for: %s, cannot initialize"
                           " KnowledgeBase" % self.client_id)

  def _ScheduleCollection(self):
    # Schedule any new artifacts for which we have now fulfilled dependencies.
    for artifact_name in self.state.awaiting_deps_artifacts:
      artifact_obj = artifact_registry.REGISTRY.GetArtifact(
          artifact_name)
      deps = artifact_obj.GetArtifactPathDependencies()
      if set(deps).issubset(self.state.fulfilled_deps):
        self.state.in_flight_artifacts.append(artifact_name)
        self.state.awaiting_deps_artifacts.remove(artifact_name)
        self.CallFlow("ArtifactCollectorFlow", artifact_list=[artifact_name],
                      store_results_in_aff4=False, next_state="ProcessBase",
                      request_data={"artifact_name": artifact_name},
                      knowledge_base=self.state.knowledge_base)

    # If we're not done but not collecting anything, start accepting the partial
    # dependencies as full, and see if we can complete.
    if (self.state.awaiting_deps_artifacts and
        not self.state.in_flight_artifacts):
      if self.state.partial_fulfilled_deps:
        partial = self.state.partial_fulfilled_deps.pop()
        self.Log("Accepting partially fulfilled dependency: %s", partial)
        self.state.fulfilled_deps.append(partial)
        self._ScheduleCollection()

  @flow.StateHandler(next_state="ProcessBase")
  def ProcessBase(self, responses):
    """Process any retrieved artifacts."""
    artifact_name = responses.request_data["artifact_name"]
    self.state.in_flight_artifacts.remove(artifact_name)
    self.state.completed_artifacts.append(artifact_name)

    if not responses.success:
      self.Log("Failed to get artifact %s. Status: %s", artifact_name,
               responses.status)
    else:
      deps = self.SetKBValue(responses.request_data["artifact_name"],
                             responses)
      if deps:
        # If we fulfilled a dependency, make sure we have collected all
        # artifacts that provide the dependency before marking it as fulfilled.
        for dep in deps:
          required_artifacts = (
              artifact_registry.REGISTRY.GetArtifactNames(
                  os_name=self.state.knowledge_base.os,
                  provides=[dep]))
          if required_artifacts.issubset(self.state.completed_artifacts):
            self.state.fulfilled_deps.append(dep)
          else:
            self.state.partial_fulfilled_deps.add(dep)
      else:
        self.Log("Failed to get artifact %s. Artifact failed to return value.",
                 artifact_name)

    if self.state.awaiting_deps_artifacts:
      # Schedule any new artifacts for which we have now fulfilled dependencies.
      self._ScheduleCollection()

      # If we fail to fulfil deps for things we're supposed to collect, raise
      # an error.
      if (self.state.awaiting_deps_artifacts and
          not self.state.in_flight_artifacts):
        missing_deps = list(self.state.all_deps.difference(
            self.state.fulfilled_deps))

        if self.args.require_complete:
          raise flow.FlowError("KnowledgeBase initialization failed as the "
                               "following artifacts had dependencies that could"
                               " not be fulfilled %s. Missing: %s" %
                               (self.state.awaiting_deps_artifacts,
                                missing_deps))
        else:
          self.Log("Storing incomplete KnowledgeBase. The following artifacts"
                   "had dependencies that could not be fulfilled %s. "
                   "Missing: %s. Completed: %s" % (
                       self.state.awaiting_deps_artifacts, missing_deps,
                       self.state.completed_artifacts))

  def SetKBValue(self, artifact_name, responses):
    """Set values in the knowledge base based on responses."""
    artifact_obj = artifact_registry.REGISTRY.GetArtifact(artifact_name)
    if not responses:
      return None

    provided = set()  # Track which deps have been provided.

    for response in responses:
      if isinstance(response, anomaly.Anomaly):
        logging.error("Artifact %s returned an Anomaly: %s", artifact_name,
                      response)
        continue
      if isinstance(response, rdf_client.KnowledgeBaseUser):
        # MergeOrAddUser will update or add a user based on the attributes
        # returned by the artifact in the KnowledgeBaseUser.
        attrs_provided, merge_conflicts = (
            self.state.knowledge_base.MergeOrAddUser(response))
        provided.update(attrs_provided)
        for key, old_val, val in merge_conflicts:
          self.Log("KnowledgeBaseUser merge conflict in %s. Old value: %s, "
                   "Newly written value: %s", key, old_val, val)

      else:
        artifact_provides = artifact_obj.provides
        if isinstance(response, rdf_protodict.Dict):
          # Attempting to fulfil provides with a Dict response means we are
          # supporting multiple provides based on the keys of the dict.
          kb_dict = response.ToDict()
        else:
          if len(artifact_provides) == 1:
            # If its not a dict we only support a single value.
            kb_dict = {artifact_provides[0]: response}
          else:
            raise RuntimeError("Attempt to set a knowledge base value with "
                               "multiple provides clauses without using Dict."
                               ": %s" % artifact_obj)

        for provides, value in kb_dict.iteritems():
          if provides not in artifact_provides:
            raise RuntimeError("Attempt to provide knowledge base value %s "
                               "without this being set in the artifact "
                               "provides setting: %s" % (
                                   provides, artifact_obj))

          if isinstance(value, rdfvalue.RDFString):
            value = utils.SmartStr(value)
          elif hasattr(value, "registry_data"):
            value = value.registry_data.GetValue()

          if value:
            logging.debug("Set KB %s to %s", provides, value)
            self.state.knowledge_base.Set(provides, value)
            provided.add(provides)
          else:
            logging.debug("Empty KB return value for %s", provides)

    return provided

  def CopyUsersFromKnowledgeBase(self, client):
    """Copy users from knowledgebase to USER.

    TODO(user): deprecate USER completely in favour of KNOWLEDGE_BASE.user

    Args:
      client: client object open for writing
    """
    usernames = []
    user_list = client.Schema.USER()
    for kbuser in self.state.knowledge_base.users:
      user_list.Append(rdf_client.User().FromKnowledgeBaseUser(kbuser))

      if kbuser.username:
        usernames.append(kbuser.username)

    # Store it now
    client.AddAttribute(client.Schema.USER, user_list)
    client.AddAttribute(client.Schema.USERNAMES(
        " ".join(usernames)))

  def CopyOSReleaseFromKnowledgeBase(self, client):
    """Copy os release and version from KB to client object."""
    if self.state.knowledge_base.os_release:
      os_release = self.state.knowledge_base.os_release
      client.Set(client.Schema.OS_RELEASE(os_release))

      # Override OS version field too.
      # TODO(user): this actually results in incorrect versions for things
      #                like Ubuntu (14.4 instead of 14.04). I don't think zero-
      #                padding is always correct, however.
      os_version = "%d.%d" % (self.state.knowledge_base.os_major_version,
                              self.state.knowledge_base.os_minor_version)
      client.Set(client.Schema.OS_VERSION(os_version))

  @flow.StateHandler()
  def End(self, unused_responses):
    """Finish up and write the results."""
    client = aff4.FACTORY.Open(self.client_id, mode="rw", token=self.token)
    client.Set(client.Schema.KNOWLEDGE_BASE, self.state.knowledge_base)
    self.CopyUsersFromKnowledgeBase(client)
    self.CopyOSReleaseFromKnowledgeBase(client)
    client.Flush()
    self.Notify("ViewObject", client.urn, "Knowledge Base Updated.")
    self.SendReply(self.state.knowledge_base)

class KnowledgeBaseInitializationArgs(rdf_structs.RDFProtoStruct):
  protobuf = flows_pb2.KnowledgeBaseInitializationArgs

class KnowledgeBaseInitializationFlow(CollectArtifactDependencies):
  """Flow that atttempts to initialize the knowledge base.

  This flow processes all artifacts specified by the Artifacts.knowledge_base
  config.  It it is a CollectArtifactDependencies flow with slightly different
  setup.
  """
  category = "/Collectors/"
  behaviours = flow.GRRFlow.behaviours + "ADVANCED"
  args_type = KnowledgeBaseInitializationArgs

  def GetFirstFlowsForCollection(self):
    """Initialize dependencies and calculate first round of flows.

    Returns:
      set of artifact names with no dependencies that should be collected first.

    Raises:
      RuntimeError: On bad artifact configuration parameters.
    """
    kb_base_set = set(config_lib.CONFIG["Artifacts.knowledge_base"])
    kb_add = set(config_lib.CONFIG["Artifacts.knowledge_base_additions"])
    kb_skip = set(config_lib.CONFIG["Artifacts.knowledge_base_skip"])
    if self.args.lightweight:
      kb_skip.update(
          config_lib.CONFIG["Artifacts.knowledge_base_heavyweight"])
    kb_set = kb_base_set.union(kb_add) - kb_skip

    for artifact_name in kb_set:
      if artifact_registry.REGISTRY.GetArtifact(artifact_name) is None:
        raise RuntimeError("Attempt to specify unknown artifact %s in "
                           "artifact configuration parameters. You may need"
                           " to sync the artifact repo by running make in the"
                           " artifacts directory." % artifact_name)

    no_deps_names = artifact_registry.REGISTRY.GetArtifactNames(
        os_name=self.state.knowledge_base.os, name_list=kb_set,
        exclude_dependents=True)

    name_deps, self.state.all_deps = (
        artifact_registry.REGISTRY.SearchDependencies(
            self.state.knowledge_base.os, kb_set))

    # We only retrieve artifacts that are explicitly listed in
    # Artifacts.knowledge_base + additions - skip.
    name_deps = name_deps.intersection(kb_set)

    # We're going to collect everything that doesn't have a dependency first.
    # Anything else we're waiting on a dependency before we can collect.
    self.state.awaiting_deps_artifacts = list(name_deps - no_deps_names)

    return no_deps_names

  def InitializeKnowledgeBase(self):
    """Get the existing KB or create a new one if none exists."""
    self.client = aff4.FACTORY.Open(self.client_id, token=self.token)

    # Always create a new KB to override any old values.
    self.state.knowledge_base = rdf_client.KnowledgeBase()
    SetCoreGRRKnowledgeBaseValues(self.state.knowledge_base, self.client)
    if not self.state.knowledge_base.os:
      # If we don't know what OS this is, there is no way to proceed.
      raise flow.FlowError("Client OS not set for: %s, cannot initialize"
                           " KnowledgeBase" % self.client_id)

def ApplyParserToResponses(processor_obj, responses, source, state, token):
  """Parse responses using the specified processor and the right args.

  Args:
    processor_obj: A Processor object that inherits from Parser.
    responses: A list of, or single response depending on the processors
       process_together setting.
    source: The source responsible for producing the responses.
    state: The current state of an artifact collection flow.
    token: The token used in an artifact collection flow.

  Raises:
    RuntimeError: On bad parser.

  Returns:
    An iterator of the processor responses.
  """
  if not processor_obj:
    # We don't do any parsing, the results are raw as they came back.
    # If this is an RDFValue we don't want to unpack it further
    if isinstance(responses, rdfvalue.RDFValue):
      result_iterator = [responses]
    else:
      result_iterator = responses

  else:
    # We have some processors to run.
    if processor_obj.process_together:
      # We are processing things in a group which requires specialized
      # handling by the parser. This is used when multiple responses need to
      # be combined to parse successfully. E.g parsing passwd and shadow files
      # together.
      parse_method = processor_obj.ParseMultiple
    else:
      parse_method = processor_obj.Parse

    if isinstance(processor_obj, parsers.CommandParser):
      # Command processor only supports one response at a time.
      response = responses
      result_iterator = parse_method(
          cmd=response.request.cmd,
          args=response.request.args,
          stdout=response.stdout,
          stderr=response.stderr,
          return_val=response.exit_status,
          time_taken=response.time_used,
          knowledge_base=state.knowledge_base)

    elif isinstance(processor_obj, parsers.WMIQueryParser):
      query = source["attributes"]["query"]
      result_iterator = parse_method(query, responses, state.knowledge_base)

    elif isinstance(processor_obj, parsers.FileParser):
      if processor_obj.process_together:
        file_objects = [aff4.FACTORY.Open(r.aff4path, token=token)
                        for r in responses]
        result_iterator = parse_method(responses, file_objects,
                                       state.knowledge_base)
      else:
        fd = aff4.FACTORY.Open(responses.aff4path, token=token)
        result_iterator = parse_method(responses, fd, state.knowledge_base)

    elif isinstance(processor_obj, (parsers.RegistryParser,
                                    parsers.RekallPluginParser,
                                    parsers.RegistryValueParser,
                                    parsers.GenericResponseParser,
                                    parsers.GrepParser)):
      result_iterator = parse_method(responses, state.knowledge_base)

    elif isinstance(processor_obj, (parsers.ArtifactFilesParser)):
      result_iterator = parse_method(responses, state.knowledge_base,
                                     state.path_type)

    else:
      raise RuntimeError("Unsupported parser detected %s" % processor_obj)
  return result_iterator

def UploadArtifactYamlFile(file_content, base_urn=None, token=None,
                           overwrite=True):
  """Upload a yaml or json file as an artifact to the datastore."""
  _ = overwrite
  loaded_artifacts = []
  if not base_urn:
    base_urn = aff4.ROOT_URN.Add("artifact_store")
  registry_obj = artifact_registry.REGISTRY

  with aff4.FACTORY.Create(base_urn, aff4_type="RDFValueCollection",
                           token=token, mode="rw") as artifact_coll:

    # Iterate through each artifact adding it to the collection.
    for artifact_value in registry_obj.ArtifactsFromYaml(file_content):
      artifact_value.ValidateSyntax()
      artifact_coll.Add(artifact_value)
      registry_obj.RegisterArtifact(
          artifact_value, source="datastore:%s" % base_urn,
          overwrite_if_exists=overwrite)
      loaded_artifacts.append(artifact_value)
      logging.info("Uploaded artifact %s to %s", artifact_value.name, base_urn)

  # Once all artifacts are loaded we can validate, as validation of dependencies
  # requires the group are all loaded before doing the validation.
  for artifact_value in loaded_artifacts:
    artifact_value.Validate()

  return base_urn

class ArtifactFallbackCollectorArgs(rdf_structs.RDFProtoStruct):
  protobuf = flows_pb2.ArtifactFallbackCollectorArgs

class ArtifactFallbackCollector(flow.GRRFlow):
  """Abstract class for artifact fallback flows.

  If an artifact can't be collected by normal means a flow can be registered
  with a fallback means of collection by subclassing this class. This is useful
  when an artifact is critical to the collection of other artifacts so we want
  to try harder to make sure its collected.

  The flow will be called from
  lib.flows.general.collectors.ArtifactCollectorFlow. The flow should SendReply
  the artifact value in the same format as would have been returned by the
  original artifact collection.
  """
  __metaclass__ = registry.MetaclassRegistry
  args_type = ArtifactFallbackCollectorArgs

  # List of artifact names for which we are registering as the fallback
  artifacts = []

class GRRArtifactMappings(object):
  """SemanticProto to AFF4 storage mappings.

  Class defining mappings between RDFValues collected by Artifacts, and the
  location they are stored in the AFF4 hierarchy.

  Each entry in the map contains:
    1. Location stored relative to the client.
    2. Name of the AFF4 type.
    3. Name of the attribute to be changed.
    4. Method for adding the RDFValue to the Attribute (Overwrite, Append)
  """

  rdf_map = {
      "SoftwarePackage": (
          "info/software", software.InstalledSoftwarePackages.__name__,
          "INSTALLED_PACKAGES", "Append"),
      "Volume": (
          "", aff4_grr.VFSGRRClient.__name__, "VOLUMES", "Append"),
      "HardwareInfo": (
          "", aff4_grr.VFSGRRClient.__name__, "HARDWARE_INFO", "Overwrite")
  }

class ArtifactLoader(registry.InitHook):
  """Loads artifacts from the datastore and from the filesystem.

  Datastore gets loaded second so it can override Artifacts in the files.
  """

  pre = ["AFF4InitHook"]

  def RunOnce(self):
    for path in config_lib.CONFIG["Artifacts.artifact_dirs"]:
      artifact_registry.REGISTRY.AddDirSource(path)

    artifact_registry.REGISTRY.AddDatastoreSources(
        [aff4.ROOT_URN.Add("artifact_store")])


text:
package org.thingsboard.server.common.data.asset;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.Value;
import org.thingsboard.server.common.data.EntityInfo;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.id.DashboardId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.EntityIdFactory;

import java.util.UUID;

@Value
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true, exclude = "image")
public class AssetProfileInfo extends EntityInfo {

    @ApiModelProperty(position = 3, value = "Either URL or Base64 data of the icon. Used in the mobile application to visualize set of asset profiles in the grid view. ")
    private final String image;
    @ApiModelProperty(position = 4, value = "Reference to the dashboard. Used in the mobile application to open the default dashboard when user navigates to asset details.")
    private final DashboardId defaultDashboardId;

    @JsonCreator
    public AssetProfileInfo(@JsonProperty("id") EntityId id,
                             @JsonProperty("name") String name,
                             @JsonProperty("image") String image,
                             @JsonProperty("defaultDashboardId") DashboardId defaultDashboardId) {
        super(id, name);
        this.image = image;
        this.defaultDashboardId = defaultDashboardId;
    }

    public AssetProfileInfo(UUID uuid, String name, String image, UUID defaultDashboardId) {
        super(EntityIdFactory.getByTypeAndUuid(EntityType.ASSET_PROFILE, uuid), name);
        this.image = image;
        this.defaultDashboardId = defaultDashboardId != null ? new DashboardId(defaultDashboardId) : null;
    }

    public AssetProfileInfo(AssetProfile profile) {
        this(profile.getId(), profile.getName(), profile.getImage(), profile.getDefaultDashboardId());
    }

}

redpajama_set_name: RedPajamaGithub


text:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;

public class P09CustomComparator {
    public static void main(String[] args) throws IOException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        Integer[] sequence = Arrays.stream(reader.readLine().split("\\s+"))
                .mapToInt(Integer::parseInt)
                .boxed()
                .toArray(Integer[]::new);

        Comparator<Integer> evenBeforeOdd = (a, b) -> {
            if (a % 2 != 0 && b % 2 == 0) {
                return 1;
            } else if (a % 2 == 0 && b % 2 != 0) {
                return -1;
            } else {
                return a.compareTo(b);
            }
        };

        Arrays.sort(sequence, evenBeforeOdd);

        for (Integer integer : sequence) {
            System.out.print(integer + " ");
        }
    }
}


text:
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { selectReddit, fetchPostsIfNeeded, invalidateReddit } from '../actions';
import Picker from '../components/Picker';
import Posts from '../components/Posts';

class AsyncApp extends Component {
  constructor (props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.handleRefreshClick = this.handleRefreshClick.bind(this);
  }

  componentDidMount () {
    const { dispatch, selectedReddit } = this.props;

    dispatch(fetchPostsIfNeeded(selectedReddit));
  }

  componentWillReceiveProps (nextProps) {
    if (nextProps.selectedReddit !== this.props.selectedReddit) {
      const { dispatch, selectedReddit } = nextProps;

      dispatch(fetchPostsIfNeeded(selectedReddit));
    }
  }

  handleChange (nextReddit) {
    this.props.dispatch(selectReddit(nextReddit));
  }

  handleRefreshClick (e) {
    e.preventDefault();

    const { dispatch, selectedReddit } = this.props;

    dispatch(invalidateReddit(selectedReddit));
    dispatch(fetchPostsIfNeeded(selectedReddit));
  }

  render () {
    const { selectedReddit, posts, isFetching, lastUpdated } = this.props;

    return (

        <Picker value={selectedReddit}
                onChange={this.handleChange}
                options={['reactjs', 'frontend', 'vancouver']} />

          {lastUpdated &&

              Last updated at {new Date(lastUpdated).toLocaleTimeString()}.
              {' '}

          }
          {!isFetching &&

              Refresh

          }

        {isFetching && posts.length === 0 &&

Loading...

        }
        {!isFetching && posts.length === 0 &&

Empty.

        }
        {posts.length > 0 &&

            <Posts posts={posts} />

        }

    );
  }
}

AsyncApp.propTypes = {
  selectedReddit: PropTypes.string.isRequired,
  posts: PropTypes.array.isRequired,
  isFetching: PropTypes.bool.isRequired,
  lastUpdated: PropTypes.number,
  dispatch: PropTypes.func.isRequired
};

function mapStateToProps (state) {
  const { selectedReddit, postsByReddit } = state;
  const {
    isFetching,
    lastUpdated,
    items: posts
  } = postsByReddit[selectedReddit] || {
    isFetching: true,
    items: []
  };

  return {
    selectedReddit,
    posts,
    isFetching,
    lastUpdated
  };
}

export default connect(mapStateToProps)(AsyncApp);


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tjs.tuneramblr"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="11" />

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-feature android:name="android.hardware.camera" />

    <application
        android:debuggable="true"
        android:icon="@drawable/tr_logo"
        android:label="@string/app_name" >
        <activity
            android:name="TuneramblrMobileActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- RECEIVERS -->
        <receiver android:name=".receivers.BootReceiver" >
        </receiver>
        <receiver android:name=".receivers.ConnectivityChangedReceiver" >
        </receiver>
        <receiver android:name=".receivers.LocationChangedReceiver" >
        </receiver>
        <receiver android:name=".receivers.PassiveLocationChangedReceiver" >
        </receiver>
        <receiver android:name=".receivers.NewCheckinReceiver" >
        </receiver>
        <receiver android:name=".receivers.PowerStateChangedReceiver" >
        </receiver>
        <receiver android:name=".meta.music.MetaMediaRequester" >
            <intent-filter>

                <!-- stock music player and google music -->
                <action android:name="com.android.music.metachanged" />
                <action android:name="com.android.music.playstatechanged" />
                <action android:name="com.android.music.playbackcomplete" />
                <action android:name="com.android.music.queuechanged" />

                <!-- MIUI music player -->
                <action android:name="com.miui.player.metachanged" />
                <action android:name="com.miui.player.playstatechanged" />
                <action android:name="com.miui.player.playbackcomplete" />
                <action android:name="com.miui.player.queuechanged" />

                <!-- HTC music player -->
                <action android:name="com.htc.music.metachanged" />
                <action android:name="com.htc.music.playstatechanged" />
                <action android:name="com.htc.music.playbackcomplete" />
                <action android:name="com.htc.music.queuechanged" />

                <!-- WinAmp music player -->
                <action android:name="com.nullsoft.winamp.metachanged" />
                <action android:name="com.nullsoft.winamp.playstatechanged" />
                <action android:name="com.nullsoft.winamp.playbackcomplete" />
                <action android:name="com.nullsoft.winamp.queuechanged" />

                <!-- MyTouch4G stock music player -->
                <action android:name="com.real.IMP.metachanged" />
                <action android:name="com.real.IMP.playstatechanged" />
                <action android:name="com.real.IMP.playbackcomplete" />
                <action android:name="com.real.IMP.queuechanged" />

                <!-- Amazon MP3 -->
                <action android:name="com.amazon.mp3.metachanged" />
                <action android:name="com.amazon.mp3.playstatechanged" />
                <action android:name="com.amazon.mp3.queuechanged" />
                <action android:name="com.amazon.mp3.playbackcomplete" />

                <!-- rdio -->
                <action android:name="com.rdio.android.metachanged" />
                <action android:name="com.rdio.android.playstatechanged" />
                <action android:name="com.rdio.android.queuechanged" />
                <action android:name="com.rdio.android.playbackcomplete" />
            </intent-filter>
        </receiver>
        <receiver android:name=".receivers.tracks.MediaInfoReceiver" >
            <intent-filter>
                <action android:name="com.android.music.metachanged" />
                <action android:name="com.miui.player.metachanged" />
                <action android:name="com.htc.music.metachanged" />
                <action android:name="com.nullsoft.winamp.metachanged" />
                <action android:name="com.real.IMP.metachanged" />
                <action android:name="com.amazon.mp3.metachanged" />
                <action android:name="com.rdio.android.metachanged" />

                <action android:name="com.android.music.playstatechanged" />
                <action android:name="com.miui.player.playstatechanged" />
                <action android:name="com.htc.music.playstatechanged" />
                <action android:name="com.nullsoft.winamp.playstatechanged" />
                <action android:name="com.real.IMP.playstatechanged" />
                <action android:name="com.amazon.mp3.playstatechanged" />
                <action android:name="com.rdio.android.playstatechanged" />
            </intent-filter>
        </receiver>

        <!-- SERVICES -->
        <service android:name=".services.TrackCheckinNotificationService" >
        </service>
        <service android:name=".services.TrackCheckinService" >
        </service>
        <service
            android:name=".services.LoginService"
            android:label="LoginService" >
        </service>
        <activity android:name="SettingsActivity" android:screenOrientation="portrait"></activity>
    </application>

</manifest>


text:
## bunyan 0.14.6

- Export `bunyan.safeCycles()`. This may be useful for custom `type == "raw"`
  streams that may do JSON stringification of log records themselves. Usage:

        var str = JSON.stringify(rec, bunyan.safeCycles());

- [issue #49] Allow a `log.child()` to specify the level of inherited streams.
  For example:

        # Before
        var childLog = log.child({...});
        childLog.level('debug');

        # After
        var childLog = log.child({..., level: 'debug'});

- Improve the crash message to make it easier to provide relevant details in a
  bug report.

## bunyan 0.14.5

- Fix a bug in the long-stack-trace error serialization added in 0.14.4. The
  symptom:

        bunyan@0.14.4: .../node_modules/bunyan/lib/bunyan.js:1002
          var ret = ex.stack || ex.toString();
                      ^
        TypeError: Cannot read property 'stack' of undefined
            at getFullErrorStack (.../node_modules/bunyan/lib/bunyan.js:1002:15)
            ...

## bunyan 0.14.4

- **Bad release. Use 0.14.5 instead.**
- Improve error serialization to walk the chain of `.cause()` errors
  from the likes of `WError` or `VError` error classes from
  [verror](https://github.com/davepacheco/node-verror) and
  [restify v2.0](https://github.com/mcavage/node-restify). Example:

        [2012-10-11T00:30:21.871Z] ERROR: imgapi/99612 on 0525989e-2086-4270-b960-41dd661ebd7d: my-message
            ValidationFailedError: my-message; caused by TypeError: cause-error-message
                at Server.apiPing (/opt/smartdc/imgapi/lib/app.js:45:23)
                at next (/opt/smartdc/imgapi/node_modules/restify/lib/server.js:550:50)
                at Server.setupReq (/opt/smartdc/imgapi/lib/app.js:178:9)
                at next (/opt/smartdc/imgapi/node_modules/restify/lib/server.js:550:50)
                at Server.parseBody (/opt/smartdc/imgapi/node_modules/restify/lib/plugins/body_parser.js:15:33)
                at next (/opt/smartdc/imgapi/node_modules/restify/lib/server.js:550:50)
                at Server.parseQueryString (/opt/smartdc/imgapi/node_modules/restify/lib/plugins/query.js:40:25)
                at next (/opt/smartdc/imgapi/node_modules/restify/lib/server.js:550:50)
                at Server._run (/opt/smartdc/imgapi/node_modules/restify/lib/server.js:579:17)
                at Server._handle.log.trace.req (/opt/smartdc/imgapi/node_modules/restify/lib/server.js:480:38)
            Caused by: TypeError: cause-error-message
                at Server.apiPing (/opt/smartdc/imgapi/lib/app.js:40:25)
                at next (/opt/smartdc/imgapi/node_modules/restify/lib/server.js:550:50)
                at Server.setupReq (/opt/smartdc/imgapi/lib/app.js:178:9)
                at next (/opt/smartdc/imgapi/node_modules/restify/lib/server.js:550:50)
                at Server.parseBody (/opt/smartdc/imgapi/node_modules/restify/lib/plugins/body_parser.js:15:33)
                at next (/opt/smartdc/imgapi/node_modules/restify/lib/server.js:550:50)
                at Server.parseQueryString (/opt/smartdc/imgapi/node_modules/restify/lib/plugins/query.js:40:25)
                at next (/opt/smartdc/imgapi/node_modules/restify/lib/server.js:550:50)
                at Server._run (/opt/smartdc/imgapi/node_modules/restify/lib/server.js:579:17)
                at Server._handle.log.trace.req (/opt/smartdc/imgapi/node_modules/restify/lib/server.js:480:38)

## bunyan 0.14.2

- [issue #45] Fix bunyan CLI (default output mode) to not crash on a 'res'
  field that isn't a response object, but a string.

## bunyan 0.14.1

- [issue #44] Fix the default `bunyan` CLI output of a `res.body` that is an
  object instead of a string. See issue#38 for the same with `req.body`.

## bunyan 0.14.0

- [pull #41] Safe `JSON.stringify`ing of emitted log records to avoid blowing
  up on circular objects (by Isaac Schlueter).

## bunyan 0.13.5

- [issue #39] Fix a bug with `client_req` handling in the default output
  of the `bunyan` CLI.

## bunyan 0.13.4

- [issue #38] Fix the default `bunyan` CLI output of a `req.body` that is an
  object instead of a string.

## bunyan 0.13.3

- Export `bunyan.resolveLevel(NAME-OR-NUM)` to resolve a level name or number
  to its log level number value:

        > bunyan.resolveLevel('INFO')
        30
        > bunyan.resolveLevel('debug')
        20

  A side-effect of this change is that the uppercase level name is now allowed
  in the logger constructor.

## bunyan 0.13.2

- [issue #35] Ensure that an accidental `log.info(BUFFER)`, where BUFFER is
  a node.js Buffer object, doesn't blow up.

## bunyan 0.13.1

- [issue #34] Ensure `req.body`, `res.body` and other request/response fields
  are emitted by the `bunyan` CLI (mostly by Rob Gulewich).

## bunyan 0.13.0

- [issue #31] Re-instate defines for the (uppercase) log level names (TRACE,
  DEBUG, etc.) in `bunyan -c "..."` filtering condition code. E.g.:

        $ ... | bunyan -c 'level >= ERROR'

## bunyan 0.12.0

- [pull #32] `bunyan -o short` for more concise output (by Dave Pacheco). E.g.:

        22:56:52.856Z  INFO myservice: My message

  instead of:

        [2012-02-08T22:56:52.856Z]  INFO: myservice/123 on example.com: My message

## bunyan 0.11.3

- Add '--strict' option to `bunyan` CLI to suppress all but legal Bunyan JSON
  log lines. By default non-JSON, and non-Bunyan lines are passed through.

## bunyan 0.11.2

- [issue #30] Robust handling of 'req' field without a 'headers' subfield
  in `bunyan` CLI.
- [issue #31] Pull the TRACE, DEBUG, et al defines from `bunyan -c "..."`
  filtering code. This was added in v0.11.1, but has a significant adverse
  affect.

## bunyan 0.11.1

- **Bad release. The TRACE et al names are bleeding into the log records
  when using '-c'.**
- Add defines for the (uppercase) log level names (TRACE, DEBUG, etc.) in
  `bunyan -c "..."` filtering condition code. E.g.:

        $ ... | bunyan -c 'level >= ERROR'

## bunyan 0.11.0

- [pull #29] Add -l/--level for level filtering, and -c/--condition for
  arbitrary conditional filtering (by github.com/isaacs):

        $ ... | bunyan -l error   # filter out log records below error
        $ ... | bunyan -l 50      # numeric value works too
        $ ... | bunyan -c 'level===50'              # equiv with -c filtering
        $ ... | bunyan -c 'pid===123'               # filter on any field
        $ ... | bunyan -c 'pid===123' -c '_audit'   # multiple filters

## bunyan 0.10.0

- [pull #24] Support for gzip'ed log files in the bunyan CLI (by
  github.com/mhart):

        $ bunyan foo.log.gz
        ...

## bunyan 0.9.0

- [pull #16] Bullet proof the `bunyan.stdSerializers` (by github.com/rlidwka).

- [pull #15] The `bunyan` CLI will now chronologically merge multiple log
  streams when it is given multiple file arguments. (by github.com/davepacheco)

        $ bunyan foo.log bar.log
        ... merged log records ...

- [pull #15] A new `bunyan.RingBuffer` stream class that is useful for
  keeping the last N log messages in memory. This can be a fast way to keep
  recent, and thus hopefully relevant, log messages. (by @dapsays,
  github.com/davepacheco)

  Potential uses: Live debugging if a running process could inspect those
  messages. One could dump recent log messages at a finer log level than is
  typically logged on
  [`uncaughtException`](http://nodejs.org/docs/latest/api/all.html#all_event_uncaughtexception).

        var ringbuffer = new bunyan.RingBuffer({ limit: 100 });
        var log = new bunyan({
            name: 'foo',
            streams: [{
                type: 'raw',
                stream: ringbuffer,
                level: 'debug'
            }]
        });

        log.info('hello world');
        console.log(ringbuffer.records);

- Add support for "raw" streams. This is a logging stream that is given
  raw log record objects instead of a JSON-stringified string.

        function Collector() {
            this.records = [];
        }
        Collector.prototype.write = function (rec) {
            this.records.push(rec);
        }
        var log = new Logger({
            name: 'mylog',
            streams: [{
                type: 'raw',
                stream: new Collector()
            }]
        });

  See "examples/raw-stream.js". I expect raw streams to be useful for
  piping Bunyan logging to separate services (e.g. <http://www.loggly.com/>,
  <https://github.com/etsy/statsd>) or to separate in-process handling.

- Add test/corpus/*.log files (accidentally excluded) so the test suite
  actually works(!).

## bunyan 0.8.0

- [pull #21] Bunyan loggers now re-emit `fs.createWriteStream` error events.
  By github.com/EvanOxfeld. See "examples/handle-fs-error.js" and
  "test/error-event.js" for details.

        var log = new Logger({name: 'mylog', streams: [{path: FILENAME}]});
        log.on('error', function (err, stream) {
            // Handle error writing to or creating FILENAME.
        });

- jsstyle'ing (via `make check`)

## bunyan 0.7.0

- [issue #12] Add `bunyan.createLogger(OPTIONS)` form, as is more typical in
  node.js APIs.  This'll eventually become the preferred form.

## bunyan 0.6.9

- Change `bunyan` CLI default output to color "src" info red. Before the "src"
  information was uncolored. The "src" info is the filename, line number and
  function name resulting from using `src: true` in `Logger` creation. I.e.,
  the `(/Users/trentm/tm/node-bunyan/examples/hi.js:10)` in:

        [2012-04-10T22:28:58.237Z]  INFO: myapp/39339 on banana.local (/Users/trentm/tm/node-bunyan/examples/hi.js:10): hi

- Tweak `bunyan` CLI default output to still show an "err" field if it doesn't
  have a "stack" attribute.

## bunyan 0.6.8

- Fix bad bug in `log.child({...}, true);` where the added child fields **would
  be added to the parent's fields**. This bug only existed for the "fast child"
  path (that second `true` argument). A side-effect of fixing this is that
  the "fast child" path is only 5 times as fast as the regular `log.child`,
  instead of 10 times faster.

## bunyan 0.6.7

- [issue #6] Fix bleeding 'type' var to global namespace. (Thanks Mike!)

## bunyan 0.6.6

- Add support to the `bunyan` CLI taking log file path args, `bunyan foo.log`,
  in addition to the usual `cat foo.log | bunyan`.
- Improve reliability of the default output formatting of the `bunyan` CLI.
  Before it could blow up processing log records missing some expected
  fields.

## bunyan 0.6.5

- ANSI coloring output from `bunyan` CLI tool (for the default output mode/style).
  Also add the '--color' option to force coloring if the output stream is not
  a TTY, e.g. `cat my.log | bunyan --color | less -R`. Use `--no-color` to
  disable coloring, e.g. if your terminal doesn't support ANSI codes.
- Add 'level' field to log record before custom fields for that record. This
  just means that the raw record JSON will show the 'level' field earlier,
  which is a bit nicer for raw reading.

## bunyan 0.6.4

- [issue #5] Fix `log.info() -> boolean` to work properly. Previous all were
  returning false. Ditto all trace/debug/.../fatal methods.

## bunyan 0.6.3

- Allow an optional `msg` and arguments to the `log.info(<Error> err)` logging
  form. For example, before:

        log.debug(my_error_instance)            // good
        log.debug(my_error_instance, "boom!")   // wasn't allowed

  Now the latter is allowed if you want to expliciting set the log msg. Of course
  this applies to all the `log.{trace|debug|info...}()` methods.

- `bunyan` cli output: clarify extra fields with quoting if empty or have
  spaces. E.g. 'cmd' and 'stderr' in the following:

        [2012-02-12T00:30:43.736Z] INFO: mo-docs/43194 on banana.local: buildDocs results (req_id=185edca2-2886-43dc-911c-fe41c09ec0f5, route=PutDocset, error=null, stderr="", cmd="make docs")

## bunyan 0.6.2

- Fix/guard against unintended inclusion of some files in npm published package
  due to <https://github.com/isaacs/npm/issues/2144>

## bunyan 0.6.1

- Internal: starting jsstyle usage.
- Internal: add .npmignore. Previous packages had reams of bunyan crud in them.

## bunyan 0.6.0

- Add 'pid' automatic log record field.

## bunyan 0.5.3

- Add 'client_req' (HTTP client request) standard formatting in `bunyan` CLI
  default output.
- Improve `bunyan` CLI default output to include *all* log record keys. Unknown keys
  are either included in the first line parenthetical (if short) or in the indented
  subsequent block (if long or multiline).

## bunyan 0.5.2

- [issue #3] More type checking of `new Logger(...)` and `log.child(...)`
  options.
- Start a test suite.

## bunyan 0.5.1

- [issue #2] Add guard on `JSON.stringify`ing of log records before emission.
  This will prevent `log.info` et al throwing on record fields that cannot be
  represented as JSON. An error will be printed on stderr and a clipped log
  record emitted with a 'bunyanMsg' key including error details. E.g.:

        bunyan: ERROR: could not stringify log record from /Users/trentm/tm/node-bunyan/examples/unstringifyable.js:12: TypeError: Converting circular structure to JSON
        {
          "name": "foo",
          "hostname": "banana.local",
          "bunyanMsg": "bunyan: ERROR: could not stringify log record from /Users/trentm/tm/node-bunyan/examples/unstringifyable.js:12: TypeError: Converting circular structure to JSON",
        ...

  Some timing shows this does effect log speed:

        $ node tools/timeguard.js     # before
        Time try/catch-guard on JSON.stringify:
         - log.info:  0.07365ms per iteration
        $ node tools/timeguard.js     # after
        Time try/catch-guard on JSON.stringify:
         - log.info:  0.07368ms per iteration

## bunyan 0.5.0

- Use 10/20/... instead of 1/2/... for level constant values. Ostensibly this
  allows for intermediary levels from the defined "trace/debug/..." set.
  However, that is discouraged. I'd need a strong user argument to add
  support for easily using alternative levels. Consider using a separate
  JSON field instead.
- s/service/name/ for Logger name field. "service" is unnecessarily tied
  to usage for a service. No need to differ from log4j Logger "name".
- Add `log.level(...)` and `log.levels(...)` API for changing logger stream
  levels.
- Add `TRACE|DEBUG|INFO|WARN|ERROR|FATAL` level constants to exports.
- Add `log.info(err)` special case for logging an `Error` instance. For
  example `log.info(new TypeError("boom")` will produce:

        ...
        "err": {
          "message": "boom",
          "name": "TypeError",
          "stack": "TypeError: boom\n    at Object.<anonymous> ..."
        },
        "msg": "boom",
        ...

## bunyan 0.4.0

- Add `new Logger({src: true})` config option to have a 'src' attribute be
  automatically added to log records with the log call source info. Example:

        "src": {
          "file": "/Users/trentm/tm/node-bunyan/examples/src.js",
          "line": 20,
          "func": "Wuzzle.woos"
        },

## bunyan 0.3.0

- `log.child(options[, simple])` Added `simple` boolean arg. Set `true` to
  assert that options only add fields (no config changes). Results in a 10x
  speed increase in child creation. See "tools/timechild.js". On my Mac,
  "fast child" creation takes about 0.001ms. IOW, if your app is dishing
  10,000 req/s, then creating a log child for each request will take
  about 1% of the request time.
- `log.clone` -> `log.child` to better reflect the relationship: streams and
  serializers are inherited. Streams can't be removed as part of the child
  creation. The child doesn't own the parent's streams (so can't close them).
- Clean up Logger creation. The goal here was to ensure `log.child` usage
  is fast. TODO: measure that.
- Add `Logger.stdSerializers.err` serializer which is necessary to get good
  Error object logging with node 0.6 (where core Error object properties
  are non-enumerable).

## bunyan 0.2.0

- Spec'ing core/recommended log record fields.
- Add `LOG_VERSION` to exports.
- Improvements to request/response serializations.

## bunyan 0.1.0

First release.


text:
layout: page
title: "George Sen Lim"
comments: true
description: "blanks"
keywords: "George Sen Lim,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Architecture and Planning

**Classes taught**: ENVD 4300, ENVD 4322, ENVD 4764

#### ENVD 4300: Advanced Design Lab 2

**Terms taught**: Spring 2014

**Instructor rating**: 0.0

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.36

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 0.0

**Standard deviation in workload** (raw): 0.0

#### ENVD 4322: Special Topics: Graphics

**Terms taught**: Fall 2006, Fall 2007, Fall 2008, Fall 2009, Fall 2010, Fall 2011, Spring 2013, Fall 2013

**Instructor rating**: 5.38

**Standard deviation in instructor rating**: 0.16

**Average grade** (4.0 scale): 3.68

**Standard deviation in grades** (4.0 scale): 0.14

**Average workload** (raw): 1.99

**Standard deviation in workload** (raw): 0.27

#### ENVD 4764: Special Topics: Theory and Criticism in Environmental Design

**Terms taught**: Fall 2013

**Instructor rating**: 6.0

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.83

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.0

**Standard deviation in workload** (raw): 0.0


text:
require 'spec_helper'

shared_examples 'check total store credit from payments' do
  context 'with valid payments' do
    subject { order }

    let(:order) { payment.order }
    let!(:payment) { create(:store_credit_payment) }
    let!(:second_payment) { create(:store_credit_payment, order: order) }

    it 'returns the sum of the payment amounts' do
      expect(subject.total_applicable_store_credit).to eq (payment.amount + second_payment.amount)
    end
  end

  context 'without valid payments' do
    subject { order }

    let(:order) { create(:order) }

    it 'returns 0' do
      expect(subject.total_applicable_store_credit).to be_zero
    end
  end
end

describe 'Order' do
  describe '#covered_by_store_credit' do
    context "order doesn't have an associated user" do
      subject { create(:store_credits_order_without_user) }

      it 'returns false' do
        expect(subject.covered_by_store_credit).to be false
      end
    end

    context 'order has an associated user' do
      subject { create(:order, user: user) }

      let(:user) { create(:user) }

      context 'user has enough store credit to pay for the order' do
        before do
          allow(user).to receive(:total_available_store_credit).and_return(10.0)
          allow(subject).to receive(:total).and_return(5.0)
        end

        it 'returns true' do
          expect(subject.covered_by_store_credit).to be true
        end
      end

      context 'user does not have enough store credit to pay for the order' do
        before do
          allow(user).to receive(:total_available_store_credit).and_return(0.0)
          allow(subject).to receive(:total).and_return(5.0)
        end

        it 'returns false' do
          expect(subject.covered_by_store_credit).to be false
        end
      end
    end
  end

  describe '#total_available_store_credit' do
    context 'order does not have an associated user' do
      subject { create(:store_credits_order_without_user) }

      it 'returns 0' do
        expect(subject.total_available_store_credit).to be_zero
      end
    end

    context 'order has an associated user' do
      subject { create(:order, user: user) }

      let(:user) { create(:user) }
      let(:available_store_credit) { 25.0 }

      before do
        allow(user).to receive(:total_available_store_credit).and_return(available_store_credit)
      end

      it "returns the user's available store credit" do
        expect(subject.total_available_store_credit).to eq available_store_credit
      end
    end
  end

  describe '#could_use_store_credit?' do
    let!(:store_credit_payment_method) { create(:store_credit_payment_method) }

    context 'order does not have an associated user' do
      subject { create(:store_credits_order_without_user) }

      it { expect(subject.could_use_store_credit?).to be false }
    end

    context 'order has an associated user' do
      subject { create(:order, user: user) }

      let(:user) { create(:user) }

      context 'without store credit' do
        it { expect(subject.could_use_store_credit?).to be false }
      end

      context 'with store credit' do
        let(:available_store_credit) { 25.0 }

        before do
          allow(user).to receive(:total_available_store_credit).and_return(available_store_credit)
        end

        it { expect(subject.could_use_store_credit?).to be true }
      end

      context 'without active Store Credit Payment' do
        let(:available_store_credit) { 25.0 }

        before do
          allow(user).to receive(:total_available_store_credit).and_return(available_store_credit)
          store_credit_payment_method.update_attribute(:active, false)
        end

        it { expect(subject.could_use_store_credit?).to be false }
      end

      context 'without Store Credit Payment' do
        let(:available_store_credit) { 25.0 }

        before do
          allow(user).to receive(:total_available_store_credit).and_return(available_store_credit)
          store_credit_payment_method.destroy
        end

        it { expect(subject.could_use_store_credit?).to be false }
      end
    end
  end

  describe '#order_total_after_store_credit' do
    subject { create(:order, total: order_total) }

    let(:order_total) { 100.0 }

    before do
      allow(subject).to receive(:total_applicable_store_credit).and_return(applicable_store_credit)
    end

    context "order's user has store credits" do
      let(:applicable_store_credit) { 10.0 }

      it 'deducts the applicable store credit' do
        expect(subject.order_total_after_store_credit).to eq (order_total - applicable_store_credit)
      end
    end

    context "order's user does not have any store credits" do
      let(:applicable_store_credit) { 0.0 }

      it 'returns the order total' do
        expect(subject.order_total_after_store_credit).to eq order_total
      end
    end
  end

  describe '#total_applicable_store_credit' do
    context 'order is in the confirm state' do
      before { order.update(state: 'confirm') }

      include_examples 'check total store credit from payments'
    end

    context 'order is completed' do
      before { order.update(state: 'complete') }

      include_examples 'check total store credit from payments'
    end

    context 'order is in any state other than confirm or complete' do
      context 'the associated user has store credits' do
        subject { order }

        let(:store_credit) { create(:store_credit) }
        let(:order) { create(:order, user: store_credit.user) }

        context 'the store credit is more than the order total' do
          let(:order_total) { store_credit.amount - 1 }

          before { order.update(total: order_total) }

          it 'returns the order total' do
            expect(subject.total_applicable_store_credit).to eq order_total
          end
        end

        context 'the store credit is less than the order total' do
          let(:order_total) { store_credit.amount * 10 }

          before { order.update(total: order_total) }

          it 'returns the store credit amount' do
            expect(subject.total_applicable_store_credit).to eq store_credit.amount
          end
        end
      end

      context 'the associated user does not have store credits' do
        subject { order }

        let(:order) { create(:order) }

        it 'returns 0' do
          expect(subject.total_applicable_store_credit).to be_zero
        end
      end

      context 'the order does not have an associated user' do
        subject { create(:store_credits_order_without_user) }

        it 'returns 0' do
          expect(subject.total_applicable_store_credit).to be_zero
        end
      end
    end
  end

  describe '#total_applied_store_credit' do
    context 'with valid payments' do
      subject { order }

      let(:order) { payment.order }
      let!(:payment) { create(:store_credit_payment) }
      let!(:second_payment) { create(:store_credit_payment, order: order) }

      it 'returns the sum of the payment amounts' do
        expect(subject.total_applied_store_credit).to eq (payment.amount + second_payment.amount)
      end
    end

    context 'without valid payments' do
      subject { order }

      let(:order) { create(:order) }

      it 'returns 0' do
        expect(subject.total_applied_store_credit).to be_zero
      end
    end
  end

  describe '#using_store_credit?' do
    subject { create(:order) }

    context 'order has store credit payment' do
      before { allow(subject).to receive(:total_applied_store_credit).and_return(10.0) }

      it { expect(subject.using_store_credit?).to be true }
    end

    context 'order has no store credit payments' do
      before { allow(subject).to receive(:total_applied_store_credit).and_return(0.0) }

      it { expect(subject.using_store_credit?).to be false }
    end
  end

  describe '#display_total_applicable_store_credit' do
    subject { create(:order) }

    let(:total_applicable_store_credit) { 10.00 }

    before do
      allow(subject).to receive(:total_applicable_store_credit).and_return(total_applicable_store_credit)
    end

    it 'returns a money instance' do
      expect(subject.display_total_applicable_store_credit).to be_a(Spree::Money)
    end

    it 'returns a negative amount' do
      expect(subject.display_total_applicable_store_credit.amount_in_cents).to eq (total_applicable_store_credit * -100.0)
    end
  end

  describe '#display_total_applied_store_credit' do
    subject { create(:order) }

    let(:total_applied_store_credit) { 10.00 }

    before do
      allow(subject).to receive(:total_applied_store_credit).and_return(total_applied_store_credit)
    end

    it 'returns a money instance' do
      expect(subject.display_total_applied_store_credit).to be_a(Spree::Money)
    end

    it 'returns a negative amount' do
      expect(subject.display_total_applied_store_credit.amount_in_cents).to eq (total_applied_store_credit * -100.0)
    end
  end

  describe '#display_order_total_after_store_credit' do
    subject { create(:order) }

    let(:order_total_after_store_credit) { 10.00 }

    before do
      allow(subject).to receive(:order_total_after_store_credit).and_return(order_total_after_store_credit)
    end

    it 'returns a money instance' do
      expect(subject.display_order_total_after_store_credit).to be_a(Spree::Money)
    end

    it 'returns the order_total_after_store_credit amount' do
      expect(subject.display_order_total_after_store_credit.amount_in_cents).to eq (order_total_after_store_credit * 100.0)
    end
  end

  describe '#display_total_available_store_credit' do
    subject { create(:order) }

    let(:total_available_store_credit) { 10.00 }

    before do
      allow(subject).to receive(:total_available_store_credit).and_return(total_available_store_credit)
    end

    it 'returns a money instance' do
      expect(subject.display_total_available_store_credit).to be_a(Spree::Money)
    end

    it 'returns the total_available_store_credit amount' do
      expect(subject.display_total_available_store_credit.amount_in_cents).to eq (total_available_store_credit * 100.0)
    end
  end

  describe '#display_store_credit_remaining_after_capture' do
    subject { create(:order) }

    let(:total_available_store_credit)  { 10.00 }
    let(:total_applicable_store_credit) { 5.00 }

    before do
      allow(subject).to receive(:total_available_store_credit).and_return(total_available_store_credit)
      allow(subject).to receive(:total_applicable_store_credit).and_return(total_applicable_store_credit)
    end

    it 'returns a money instance' do
      expect(subject.display_store_credit_remaining_after_capture).to be_a(Spree::Money)
    end

    it "returns all of the user's available store credit minus what's applied to the order amount" do
      amount_remaining = total_available_store_credit - total_applicable_store_credit
      expect(subject.display_store_credit_remaining_after_capture.amount_in_cents).to eq (amount_remaining * 100.0)
    end
  end
end


text:
layout: feature
title: 'FocusType'
shortdef: 'focus type'
udver: '2'
---

  Values:
  Compl
  Subj
  Verb

Wolof has three focus conjugations of its [auxiliaries](u-pos/AUX): subject focus, verb focus, and complement
focus. The form of the auxiliary varies according to the syntactic function of the focused
constituent: subject, verb, or complement. The latter has a broad meaning and refers in general
to any constituent which is neither subject nor main verb.

### `Subj`: subject focus

The auxiliary indicates that the subject of the clause is in focus.

#### Examples

*  _maa lekk jën_ "I ate fish (it's me who ate fish)"
*  _yaa lekk jën_ "you ate fish (it's you who ate fish)"
*  _Faatu moo lekk jën_ "Faatu ate fish (it's Faatu who ate fish)"
*  _noo lekk jën_ "we ate fish (it's us who ate fish)"
*  _yeena lekk jën_ "you ate fish (it's you guys who ate fish)"
*  _ñoo lekk jën_ "they ate fish (it's them who ate fish)"

### `Verb`: verb focus

The auxiliary indicates that the main verb of the clause is in focus.

#### Examples

*  _dama lekk jën_ "I ate fish (what I did is eat fish)"
*  _danga lekk jën_ "you ate fish (what you did is eat fish)"
*  _Faatu dafa lekk jën_ "Faatu ate fish (what Faatu did is eat fish)"
*  _danu lekk jën_ "we ate fish (what we did is eat fish)"
*  _dangeen lekk jën_ "you ate fish (what you guys did is eat fish)"
*  _dañu lekk jën_ "they ate fish (what they did is eat fish)"

### `Compl`: complement focus

The auxiliary indicates that the constituent in focus is neither the subject nor the main verb.

#### Examples

*  _jën laa lekk_ "I ate fish (it's fish what I ate)"
*  _jën nga lekk_ "you ate fish (it's fish what you ate)"
*  _jën la Faatu lekk_ "Faatu ate fish (it's fish what Faatu ate)"
*  _jën lanu lekk_ "we ate fish (it's fish what we ate)"
*  _jën ngeen lekk_ "you ate fish (it's fish what you guys ate)"
*  _jën lañu lekk_ "they ate fish (it's fish what they ate)"


text:
package com.cmcm.greendamexplorer.entity;

/**
 * 收藏夹信息
 *
 * @author Administrator
 *
 */
public class Favorite {
    private String canonicalPath = null;
    private String name = null;
    private String appName = null;
    private int fileType;
    private long favoriteTime = 0;
    private long size = 0;
    private String extra = null;
    private boolean isChecked = false;

    public Favorite() {
    }

    public Favorite(String canonicalPath, String name, String appName, int fileType, long favoriteTime, long size, String extra) {
        this.canonicalPath = canonicalPath;
        this.name = name;
        this.appName = appName;
        this.fileType = fileType;
        this.favoriteTime = favoriteTime;
        this.size = size;
        this.extra = extra;
    }

    public boolean isChecked() {
        return isChecked;
    }

    public void setChecked(boolean isChecked) {
        this.isChecked = isChecked;
    }

    public String getCanonicalPath() {
        return canonicalPath;
    }

    public void setCanonicalPath(String canonicalPath) {
        this.canonicalPath = canonicalPath;
    }

    public String getName() {
        return name;
    }

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

    public String getAppName() {
        return appName;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }

    public int getFileType() {
        return fileType;
    }

    public void setFileType(int fileType) {
        this.fileType = fileType;
    }

    public long getFavoriteTime() {
        return favoriteTime;
    }

    public void setFavoriteTime(long favoriteTime) {
        this.favoriteTime = favoriteTime;
    }

    public long getSize() {
        return size;
    }

    public void setSize(long size) {
        this.size = size;
    }

    public String getExtra() {
        return extra;
    }

    public void setExtra(String extra) {
        this.extra = extra;
    }

    @Override
    public String toString() {
        return "Favorite [canonicalPath=" + canonicalPath + ", name=" + name + ", appName=" + appName + ", fileType=" + fileType + ", favoriteTime="
                + favoriteTime + ", size=" + size + ", extra=" + extra + ", isChecked=" + isChecked + "]";
    }

}


text:
set(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
  "/usr/local/relion/src/apps/particle_sort_mpi.cpp" "/usr/local/relion/build/src/apps/CMakeFiles/particle_sort_mpi.dir/particle_sort_mpi.cpp.o"
  )
set(CMAKE_CXX_COMPILER_ID "Clang")

# Preprocessor definitions for this target.
set(CMAKE_TARGET_DEFINITIONS_CXX
  "HAVE___SINCOS"
  "INSTALL_LIBRARY_DIR=/usr/local/lib/"
  "SOURCE_DIR=/usr/local/relion/src/"
  )

# The include file search paths:
set(CMAKE_CXX_TARGET_INCLUDE_PATH
  "/usr/local/include"
  "../"
  "../external/fftw/include"
  "../external/fltk/include"
  )

# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
  "/usr/local/relion/build/src/apps/CMakeFiles/relion_lib.dir/DependInfo.cmake"
  )

# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2006, 2007, 2008, 2009 Ferdinando Ametrano
 Copyright (C) 2006 Katiuscia Manzoni
 Copyright (C) 2005 Eric Ehlers
 Copyright (C) 2005 Plamen Neykov

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#if defined(HAVE_CONFIG_H)
    #include <qlo/config.hpp>
#endif

#include <ql/termstructures/yieldtermstructure.hpp>
#include <qlo/objects/obj_indexes.hpp>

#include <ql/indexes/swap/chfliborswap.hpp>
#include <ql/indexes/swap/eurliborswap.hpp>
#include <ql/indexes/swap/gbpliborswap.hpp>
#include <ql/indexes/swap/jpyliborswap.hpp>
#include <ql/indexes/swap/usdliborswap.hpp>

namespace QuantLibAddin {

    LiborSwap::LiborSwap(
            const boost::shared_ptr<reposit::ValueObject>& properties,
            const QuantLib::Currency& currency,
            SwapIndex::FixingType fixingType,
            const QuantLib::Period& p,
            const QuantLib::Handle<QuantLib::YieldTermStructure>& f,
            const QuantLib::Handle<QuantLib::YieldTermStructure>& d,
            bool permanent) : SwapIndex(properties, permanent)
    {
        switch (currency.numericCode()) {
          case 978: // EUR
            switch (fixingType) {
              case IsdaFixA:
                libraryObject_ = boost::shared_ptr<QuantLib::EurLiborSwapIsdaFixA>(new
                    QuantLib::EurLiborSwapIsdaFixA(p, f, d));
                break;
              case IsdaFixB:
                libraryObject_ = boost::shared_ptr<QuantLib::EurLiborSwapIsdaFixB>(new
                    QuantLib::EurLiborSwapIsdaFixB(p, f, d));
                break;
              case IfrFix:
                libraryObject_ = boost::shared_ptr<QuantLib::EurLiborSwapIfrFix>(new
                    QuantLib::EurLiborSwapIfrFix(p, f, d));
                break;
              default:
                  QL_FAIL(currency << " Libor Swap " << fixingType << " is not defined");
            }
            break;
          case 840: // USD
            switch (fixingType) {
              case IsdaFixAm:
                libraryObject_ = boost::shared_ptr<QuantLib::UsdLiborSwapIsdaFixAm>(new
                    QuantLib::UsdLiborSwapIsdaFixAm(p, f, d));
                break;
              case IsdaFixPm:
                libraryObject_ = boost::shared_ptr<QuantLib::UsdLiborSwapIsdaFixPm>(new
                    QuantLib::UsdLiborSwapIsdaFixPm(p, f, d));
                break;
              default:
                  QL_FAIL(currency << " Libor Swap " << fixingType << " is not defined");
            }
            break;
          case 826: // GBP
            switch (fixingType) {
              case Isda:
                libraryObject_ = boost::shared_ptr<QuantLib::GbpLiborSwapIsdaFix>(new
                    QuantLib::GbpLiborSwapIsdaFix(p, f, d));
                break;
              default:
                  QL_FAIL(currency << " Libor Swap " << fixingType << " is not defined");
            }
            break;
          case 756: // CHF
            switch (fixingType) {
              case Isda:
                libraryObject_ = boost::shared_ptr<QuantLib::ChfLiborSwapIsdaFix>(new
                    QuantLib::ChfLiborSwapIsdaFix(p, f, d));
                break;
              default:
                  QL_FAIL(currency << " Libor Swap " << fixingType << " is not defined");
            }
            break;
          case 392: // JPY
            switch (fixingType) {
              case IsdaFixAm:
                libraryObject_ = boost::shared_ptr<QuantLib::JpyLiborSwapIsdaFixAm>(new
                    QuantLib::JpyLiborSwapIsdaFixAm(p, f, d));
                break;
              case IsdaFixPm:
                libraryObject_ = boost::shared_ptr<QuantLib::JpyLiborSwapIsdaFixPm>(new
                    QuantLib::JpyLiborSwapIsdaFixPm(p, f, d));
                break;
              default:
                  QL_FAIL(currency << " Libor Swap " << fixingType << " is not defined");
            }
            break;
          default:
              QL_FAIL("Unhandled currency " << currency);
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to Apereo under one or more contributor license
    agreements. See the NOTICE file distributed with this work
    for additional information regarding copyright ownership.
    Apereo licenses this file to you under the Apache License,
    Version 2.0 (the "License"); you may not use this file
    except in compliance with the License.  You may obtain a
    copy of the License at the following location:

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

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

-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
                        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

    <import resource="classpath:commonTestContext.xml"/>

    <bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list merge="true">
                <value>classpath:/dataSource.properties</value>
            </list>
        </property>
    </bean>

    <bean id="TestDb" abstract="true" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${hibernate.connection.driver_class}" />
        <property name="url" value="${hibernate.connection.url}" />
        <property name="username" value="${hibernate.connection.username}" />
        <property name="password" value="${hibernate.connection.password}" />

        <property name="maxActive" value="50" />
        <property name="maxIdle" value="10" />
        <property name="maxWait" value="1000" />
        <property name="removeAbandoned" value="true" />
        <property name="removeAbandonedTimeout" value="300" />
        <property name="logAbandoned" value="true" />
        <property name="poolPreparedStatements" value="false" />
    </bean>

    <bean id="factoryBean" class="org.jasig.portal.jpa.EventingLocalContainerEntityManagerFactoryBean" depends-on="" autowire="byType">
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
        <property name="persistenceUnitName" value="${persistenceUnitName}" />
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.cache.use_query_cache">false</prop>
                <prop key="hibernate.cache.use_second_level_cache">false</prop>
                <prop key="persistenceUnitName">${persistenceUnitName}</prop>
                <!-- Uncomment for testing with a cache
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                -->
            </props>
        </property>
    </bean>

    <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="generateDdl" value="true" />
    </bean>

    <bean id="jpaInterceptor" class="org.springframework.orm.jpa.JpaInterceptor">
        <property name="entityManagerFactory" ref="factoryBean" />
    </bean>

    <bean class="org.jasig.portal.hibernate.HibernateConfigurationAwareInjector" />

    <bean class="org.jasig.portal.jpa.OpenEntityManagerAspect" />

    <!-- This mimics what <tx:annotation-driven/> does but uses our custom TransactionManagerCachingTransactionInterceptor -->
    <bean id="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0"
            class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource"/>
    <bean id="org.springframework.transaction.interceptor.TransactionInterceptor#0"
            class="org.jasig.portal.spring.tx.DialectAwareTransactionInterceptor">
        <property name="transactionAttributeSource" ref="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0" />
        <property name="transactionManagerBeanName" value="transactionManager" />
    </bean>
    <bean id="org.springframework.transaction.config.internalTransactionAdvisor"
            class="org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor">
        <property name="transactionAttributeSource" ref="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0" />
        <property name="adviceBeanName" value="org.springframework.transaction.interceptor.TransactionInterceptor#0" />
    </bean>

    <aop:config>
        <aop:pointcut id="daoExecution"
            expression="within(@org.springframework.stereotype.Repository *) && execution(* org.jasig.portal..*.*(..))"/>

        <aop:aspect ref="sqlNextExceptionLoggerAspect">
            <aop:after-throwing pointcut-ref="daoExecution" method="logBatchUpdateExceptions" throwing="t"/>
        </aop:aspect>
    </aop:config>

    <bean id="sqlNextExceptionLoggerAspect" class="org.jasig.portal.portlet.dao.jpa.SQLNextExceptionLoggerAspect" />

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" lazy-init="false" />

    <bean class="org.jasig.portal.jpa.cache.EntityManagerCacheImpl">
        <property name="contentCache">
            <bean id="portalInfoProvider" class="org.jasig.portal.spring.MockitoFactoryBean">
                <constructor-arg value="net.sf.ehcache.Ehcache" />
            </bean>
        </property>
    </bean>

    <bean id="taggedCacheEntryPurger" class="org.jasig.portal.spring.MockitoFactoryBean">
        <constructor-arg value="org.jasig.portal.utils.cache.TaggedCacheEntryPurger" />
    </bean>
</beans>


text:
package com.google.security.zynamics.binnavi.Gui.MainWindow.ViewSearcher;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.security.zynamics.binnavi.CUtilityFunctions;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntLoadDataException;
import com.google.security.zynamics.binnavi.Gui.Actions.CActionProxy;
import com.google.security.zynamics.binnavi.Gui.Debug.GraphSelectionDialog.CGraphSelectionTableModel;
import com.google.security.zynamics.binnavi.Gui.errordialog.NaviErrorDialog;
import com.google.security.zynamics.binnavi.disassembly.UnrelocatedAddress;
import com.google.security.zynamics.binnavi.disassembly.views.INaviView;
import com.google.security.zynamics.binnavi.disassembly.views.IViewContainer;
import com.google.security.zynamics.zylib.disassembly.CAddress;
import com.google.security.zynamics.zylib.disassembly.IAddress;
import com.google.security.zynamics.zylib.gui.CDialogEscaper;
import com.google.security.zynamics.zylib.gui.CHexFormatter;
import com.google.security.zynamics.zylib.gui.CPanelTwoButtons;
import com.google.security.zynamics.zylib.gui.GuiHelper;

import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DefaultFormatterFactory;

/**
 * Dialog class that is used to search for functions and views by offset.
 *
 * Justification: The user wants to find functions with certain offsets. It is also necessary to let
 * the user choose from one of many functions in case the user needs to choose where to continue
 * (for example during debugging).
 */
public final class CViewSearcherDialog extends JDialog {
  /**
   * Used for serialization.
   */
  private static final long serialVersionUID = 6689975974705708788L;

  /**
   * Contains the views to search through.
   */
  private final IViewContainer m_viewContainer;

  /**
   * The function or view that was selected by the user.
   */
  private INaviView m_selectionResult = null;

  /**
   * The table that is used to display functions and views.
   */
  private JTable m_table;

  /**
   * Table model that is used to display the retrieved views.
   */
  private final CGraphSelectionTableModel tableModel = new CGraphSelectionTableModel(
      new ArrayList<INaviView>());

  /**
   * The text input field that is used by the user to enter offsets.
   */
  private final JFormattedTextField m_offsetField = new JFormattedTextField(
      new DefaultFormatterFactory(new CHexFormatter(8)));

  /**
   * Listener that handles user input.
   */
  private final InternalListener m_listener = new InternalListener();

  /**
   * Creates a new dialog.
   *
   * @param owner Parent frame of the dialog.
   * @param viewContainer View container that contains the views to search through.
   * @param address The initial address to search for. This argument can be null.
   */
  public CViewSearcherDialog(final Window owner, final IViewContainer viewContainer,
      final IAddress address) {
    super(owner, "Select a graph", ModalityType.APPLICATION_MODAL);

    Preconditions.checkNotNull(viewContainer, "IE02057: View container can't be null");

    m_viewContainer = viewContainer;

    createGui();

    new CDialogEscaper(this);

    GuiHelper.centerChildToParent(owner, this, true);

    if (address != null) {
      m_offsetField.setText(address.toHexString());
      search(address.toLong());
    }
  }

  /**
   * Cleans up the dialog and hides it.
   */
  private void closeDialog() {
    m_table.removeMouseListener(m_listener);

    dispose();
  }

  /**
   * Creates the GUI of the dialog.
   */
  private void createGui() {
    setLayout(new BorderLayout());

    final JPanel panel = new JPanel(new BorderLayout());

    final JLabel lbl = new JLabel("Address" + ":");

    lbl.setBorder(new EmptyBorder(5, 5, 5, 5));

    panel.add(lbl, BorderLayout.WEST);

    m_offsetField.setSize(400, 20);

    final ActionListener listener = new ActionListener() {

      @Override
      public void actionPerformed(final ActionEvent e) {
        search();
      }
    };

    m_offsetField.addActionListener(listener);

    panel.add(m_offsetField, BorderLayout.CENTER);

    panel.add(new JButton(CActionProxy.proxy(new SearchAction(this))), BorderLayout.EAST);

    add(panel, BorderLayout.NORTH);

    m_table = new JTable(tableModel);

    m_table.addMouseListener(m_listener);

    add(new JScrollPane(m_table), BorderLayout.CENTER);

    add(new CPanelTwoButtons(CActionProxy.proxy(new InternalActionListener()), "OK", "Cancel"),
        BorderLayout.SOUTH);

    setSize(500, 300);
  }

  /**
   * Searches for views with the given offset.
   *
   * @param offset The offset to search for.
   */
  private void search(final long offset) {
    try {
      tableModel.setViews(m_viewContainer.getViewsWithAddresses(
          Lists.newArrayList(new UnrelocatedAddress(new CAddress(offset))), true));
    } catch (final CouldntLoadDataException e) {
      CUtilityFunctions.logException(e);

      final String innerMessage = "E00190: " + "Could not search views";
      final String innerDescription =
          CUtilityFunctions.createDescription(String.format(
              "BinNavi could not determine what views contain the offset '%s'.", new CAddress(
                  offset).toHexString()),
              new String[] {"There was a problem with the database connection."},
              new String[] {"The views with the given address can not be shown."});

      NaviErrorDialog.show(null, innerMessage, innerDescription, e);
    }
  }

  /**
   * Sets the return value of the dialog to the selected view.
   */
  private void setSelectedElement() {
    final int selectedRow = m_table.getSelectedRow();

    if (selectedRow != -1) {
      final CGraphSelectionTableModel model = (CGraphSelectionTableModel) m_table.getModel();

      m_selectionResult = model.getViews().get(selectedRow);
    }
  }

  /**
   * Returns the view that was selected by the user. This value can be null if no view was selected.
   *
   * @return The view that was selected by the user.
   */
  public INaviView getSelectionResult() {
    return m_selectionResult;
  }

  /**
   * Searches for the view that contain the offset entered by the user.
   */
  public void search() {
    final long offset = Long.valueOf(m_offsetField.getText(), 16);

    search(offset);
  }

  /**
   * Action handler for the buttons of the dialog.
   */
  private class InternalActionListener extends AbstractAction {
    /**
     * Used for serialization.
     */
    private static final long serialVersionUID = -3385023274674137932L;

    @Override
    public void actionPerformed(final ActionEvent event) {
      // Updates the selected element in case the user hits the OK button.

      if (event.getActionCommand().equals("OK")) {
        setSelectedElement();
      }

      closeDialog();
    }
  }

  /**
   * Listener used to handle clicks on the views table.
   */
  private class InternalListener extends MouseAdapter {
    @Override
    public void mousePressed(final MouseEvent event) {
      // Updates the selected element in case the user double clicks on
      // a view in the table.

      if ((event.getButton() == 1) && (event.getClickCount() == 2)) {
        setSelectedElement();
      }

      if (m_selectionResult != null) {
        closeDialog();
      }
    }
  }
}


text:
title: "Blog"
layout: default
---

Categories

{% capture site_tags %}{% for tag in site.categories %}{{ tag | first }}{% unless forloop.last %},{% endunless %}{% endfor %}{% endcapture %}
{% assign tag_words = site_tags | split:',' | sort %}

{% for tag in tag_words) %}
  {{ tag }} ({{ site.categories[tag] | size }})
{% endfor %}

Tags

{% capture site_tags %}{% for tag in site.tags %}{{ tag | first }}{% unless forloop.last %},{% endunless %}{% endfor %}{% endcapture %}
{% assign tag_words = site_tags | split:',' | sort %}

{% for tag in tag_words) %}
  {{ tag }} ({{ site.tags[tag] | size }})
{% endfor %}

Posts

  {% for post in site.posts %}

<time datetime="{{ post.date | date_to_xmlschema }}" itemprop="datePublished">{{ post.date | date: "%B %d, %Y" }}</time> — {{ post.title }}

  {% endfor %}