text:
    (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
     (__GNUC__ >= 4))  // GCC supports "pragma once" correctly since 3.4
#pragma once
#endif

#include <cstddef>
#include <memory>
#include <sstream>
#include <string>

#include "yaml-cpp/binary.h"
#include "yaml-cpp/dll.h"
#include "yaml-cpp/emitterdef.h"
#include "yaml-cpp/emittermanip.h"
#include "yaml-cpp/noncopyable.h"
#include "yaml-cpp/null.h"
#include "yaml-cpp/ostream_wrapper.h"

namespace YAML {
class Binary;
struct _Null;
}  // namespace YAML

namespace YAML {
class EmitterState;

class YAML_CPP_API Emitter : private noncopyable {
 public:
  Emitter();
  explicit Emitter(std::ostream& stream);
  ~Emitter();

  // output
  const char* c_str() const;
  std::size_t size() const;

  // state checking
  bool good() const;
  const std::string GetLastError() const;

  // global setters
  bool SetOutputCharset(EMITTER_MANIP value);
  bool SetStringFormat(EMITTER_MANIP value);
  bool SetBoolFormat(EMITTER_MANIP value);
  bool SetIntBase(EMITTER_MANIP value);
  bool SetSeqFormat(EMITTER_MANIP value);
  bool SetMapFormat(EMITTER_MANIP value);
  bool SetIndent(std::size_t n);
  bool SetPreCommentIndent(std::size_t n);
  bool SetPostCommentIndent(std::size_t n);
  bool SetFloatPrecision(std::size_t n);
  bool SetDoublePrecision(std::size_t n);

  // local setters
  Emitter& SetLocalValue(EMITTER_MANIP value);
  Emitter& SetLocalIndent(const _Indent& indent);
  Emitter& SetLocalPrecision(const _Precision& precision);

  // overloads of write
  Emitter& Write(const std::string& str);
  Emitter& Write(bool b);
  Emitter& Write(char ch);
  Emitter& Write(const _Alias& alias);
  Emitter& Write(const _Anchor& anchor);
  Emitter& Write(const _Tag& tag);
  Emitter& Write(const _Comment& comment);
  Emitter& Write(const _Null& n);
  Emitter& Write(const Binary& binary);

  template <typename T>
  Emitter& WriteIntegralType(T value);

  template <typename T>
  Emitter& WriteStreamable(T value);

  void EmitHeader_FishEngine();
  void EmitBeginDoc_FishEngine(int classID, int fileID);
  void EmitEndDoc_FishEngine();

 private:
  template <typename T>
  void SetStreamablePrecision(std::stringstream&) {}
  std::size_t GetFloatPrecision() const;
  std::size_t GetDoublePrecision() const;

  void PrepareIntegralStream(std::stringstream& stream) const;
  void StartedScalar();

 private:
  void EmitBeginDoc();
  void EmitEndDoc();
  void EmitBeginSeq();
  void EmitEndSeq();
  void EmitBeginMap();
  void EmitEndMap();
  void EmitNewline();
  void EmitKindTag();
  void EmitTag(bool verbatim, const _Tag& tag);

  void PrepareNode(EmitterNodeType::value child);
  void PrepareTopNode(EmitterNodeType::value child);
  void FlowSeqPrepareNode(EmitterNodeType::value child);
  void BlockSeqPrepareNode(EmitterNodeType::value child);

  void FlowMapPrepareNode(EmitterNodeType::value child);

  void FlowMapPrepareLongKey(EmitterNodeType::value child);
  void FlowMapPrepareLongKeyValue(EmitterNodeType::value child);
  void FlowMapPrepareSimpleKey(EmitterNodeType::value child);
  void FlowMapPrepareSimpleKeyValue(EmitterNodeType::value child);

  void BlockMapPrepareNode(EmitterNodeType::value child);

  void BlockMapPrepareLongKey(EmitterNodeType::value child);
  void BlockMapPrepareLongKeyValue(EmitterNodeType::value child);
  void BlockMapPrepareSimpleKey(EmitterNodeType::value child);
  void BlockMapPrepareSimpleKeyValue(EmitterNodeType::value child);

  void SpaceOrIndentTo(bool requireSpace, std::size_t indent);

  const char* ComputeFullBoolName(bool b) const;
  bool CanEmitNewline() const;

 private:
  std::unique_ptr<EmitterState> m_pState;
  ostream_wrapper m_stream;
};

template <typename T>
inline Emitter& Emitter::WriteIntegralType(T value) {
  if (!good())
    return *this;

  PrepareNode(EmitterNodeType::Scalar);

  std::stringstream stream;
  PrepareIntegralStream(stream);
  stream << value;
  m_stream << stream.str();

  StartedScalar();

  return *this;
}

template <typename T>
inline Emitter& Emitter::WriteStreamable(T value) {
  if (!good())
    return *this;

  PrepareNode(EmitterNodeType::Scalar);

  std::stringstream stream;
  SetStreamablePrecision<T>(stream);
  stream << value;
  m_stream << stream.str();

  StartedScalar();

  return *this;
}

template <>
inline void Emitter::SetStreamablePrecision<float>(std::stringstream& stream) {
  stream.precision(static_cast<std::streamsize>(GetFloatPrecision()));
}

template <>
inline void Emitter::SetStreamablePrecision<double>(std::stringstream& stream) {
  stream.precision(static_cast<std::streamsize>(GetDoublePrecision()));
}

// overloads of insertion
inline Emitter& operator<<(Emitter& emitter, const std::string& v) {
  return emitter.Write(v);
}
inline Emitter& operator<<(Emitter& emitter, bool v) {
  return emitter.Write(v);
}
inline Emitter& operator<<(Emitter& emitter, char v) {
  return emitter.Write(v);
}
inline Emitter& operator<<(Emitter& emitter, unsigned char v) {
  return emitter.Write(static_cast<char>(v));
}
inline Emitter& operator<<(Emitter& emitter, const _Alias& v) {
  return emitter.Write(v);
}
inline Emitter& operator<<(Emitter& emitter, const _Anchor& v) {
  return emitter.Write(v);
}
inline Emitter& operator<<(Emitter& emitter, const _Tag& v) {
  return emitter.Write(v);
}
inline Emitter& operator<<(Emitter& emitter, const _Comment& v) {
  return emitter.Write(v);
}
inline Emitter& operator<<(Emitter& emitter, const _Null& v) {
  return emitter.Write(v);
}
inline Emitter& operator<<(Emitter& emitter, const Binary& b) {
  return emitter.Write(b);
}

inline Emitter& operator<<(Emitter& emitter, const char* v) {
  return emitter.Write(std::string(v));
}

inline Emitter& operator<<(Emitter& emitter, int v) {
  return emitter.WriteIntegralType(v);
}
inline Emitter& operator<<(Emitter& emitter, unsigned int v) {
  return emitter.WriteIntegralType(v);
}
inline Emitter& operator<<(Emitter& emitter, short v) {
  return emitter.WriteIntegralType(v);
}
inline Emitter& operator<<(Emitter& emitter, unsigned short v) {
  return emitter.WriteIntegralType(v);
}
inline Emitter& operator<<(Emitter& emitter, long v) {
  return emitter.WriteIntegralType(v);
}
inline Emitter& operator<<(Emitter& emitter, unsigned long v) {
  return emitter.WriteIntegralType(v);
}
inline Emitter& operator<<(Emitter& emitter, long long v) {
  return emitter.WriteIntegralType(v);
}
inline Emitter& operator<<(Emitter& emitter, unsigned long long v) {
  return emitter.WriteIntegralType(v);
}

inline Emitter& operator<<(Emitter& emitter, float v) {
  return emitter.WriteStreamable(v);
}
inline Emitter& operator<<(Emitter& emitter, double v) {
  return emitter.WriteStreamable(v);
}

inline Emitter& operator<<(Emitter& emitter, EMITTER_MANIP value) {
  return emitter.SetLocalValue(value);
}

inline Emitter& operator<<(Emitter& emitter, _Indent indent) {
  return emitter.SetLocalIndent(indent);
}

inline Emitter& operator<<(Emitter& emitter, _Precision precision) {
  return emitter.SetLocalPrecision(precision);
}
}

#endif  // EMITTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66


text:
from . import domainresource

class EventDefinition(domainresource.DomainResource):
    """ A description of when an event can occur.

    The EventDefinition resource provides a reusable description of when a
    particular event can occur.
    """

    resource_type = "EventDefinition"

    def __init__(self, jsondict=None, strict=True):
        """ Initialize all valid properties.

        :raises: FHIRValidationError on validation errors, unless strict is False
        :param dict jsondict: A JSON dictionary to use for initialization
        :param bool strict: If True (the default), invalid variables will raise a TypeError
        """

        self.approvalDate = None
        """ When the event definition was approved by publisher.
        Type `FHIRDate` (represented as `str` in JSON). """

        self.author = None
        """ Who authored the content.
        List of `ContactDetail` items (represented as `dict` in JSON). """

        self.contact = None
        """ Contact details for the publisher.
        List of `ContactDetail` items (represented as `dict` in JSON). """

        self.copyright = None
        """ Use and/or publishing restrictions.
        Type `str`. """

        self.date = None
        """ Date last changed.
        Type `FHIRDate` (represented as `str` in JSON). """

        self.description = None
        """ Natural language description of the event definition.
        Type `str`. """

        self.editor = None
        """ Who edited the content.
        List of `ContactDetail` items (represented as `dict` in JSON). """

        self.effectivePeriod = None
        """ When the event definition is expected to be used.
        Type `Period` (represented as `dict` in JSON). """

        self.endorser = None
        """ Who endorsed the content.
        List of `ContactDetail` items (represented as `dict` in JSON). """

        self.experimental = None
        """ For testing purposes, not real usage.
        Type `bool`. """

        self.identifier = None
        """ Additional identifier for the event definition.
        List of `Identifier` items (represented as `dict` in JSON). """

        self.jurisdiction = None
        """ Intended jurisdiction for event definition (if applicable).
        List of `CodeableConcept` items (represented as `dict` in JSON). """

        self.lastReviewDate = None
        """ When the event definition was last reviewed.
        Type `FHIRDate` (represented as `str` in JSON). """

        self.name = None
        """ Name for this event definition (computer friendly).
        Type `str`. """

        self.publisher = None
        """ Name of the publisher (organization or individual).
        Type `str`. """

        self.purpose = None
        """ Why this event definition is defined.
        Type `str`. """

        self.relatedArtifact = None
        """ Additional documentation, citations, etc..
        List of `RelatedArtifact` items (represented as `dict` in JSON). """

        self.reviewer = None
        """ Who reviewed the content.
        List of `ContactDetail` items (represented as `dict` in JSON). """

        self.status = None
        """ draft | active | retired | unknown.
        Type `str`. """

        self.subjectCodeableConcept = None
        """ Type of individual the event definition is focused on.
        Type `CodeableConcept` (represented as `dict` in JSON). """

        self.subjectReference = None
        """ Type of individual the event definition is focused on.
        Type `FHIRReference` (represented as `dict` in JSON). """

        self.subtitle = None
        """ Subordinate title of the event definition.
        Type `str`. """

        self.title = None
        """ Name for this event definition (human friendly).
        Type `str`. """

        self.topic = None
        """ E.g. Education, Treatment, Assessment, etc..
        List of `CodeableConcept` items (represented as `dict` in JSON). """

        self.trigger = None
        """ "when" the event occurs (multiple = 'or').
        List of `TriggerDefinition` items (represented as `dict` in JSON). """

        self.url = None
        """ Canonical identifier for this event definition, represented as a
        URI (globally unique).
        Type `str`. """

        self.usage = None
        """ Describes the clinical usage of the event definition.
        Type `str`. """

        self.useContext = None
        """ The context that the content is intended to support.
        List of `UsageContext` items (represented as `dict` in JSON). """

        self.version = None
        """ Business version of the event definition.
        Type `str`. """

        super(EventDefinition, self).__init__(jsondict=jsondict, strict=strict)

    def elementProperties(self):
        js = super(EventDefinition, self).elementProperties()
        js.extend([
            ("approvalDate", "approvalDate", fhirdate.FHIRDate, False, None, False),
            ("author", "author", contactdetail.ContactDetail, True, None, False),
            ("contact", "contact", contactdetail.ContactDetail, True, None, False),
            ("copyright", "copyright", str, False, None, False),
            ("date", "date", fhirdate.FHIRDate, False, None, False),
            ("description", "description", str, False, None, False),
            ("editor", "editor", contactdetail.ContactDetail, True, None, False),
            ("effectivePeriod", "effectivePeriod", period.Period, False, None, False),
            ("endorser", "endorser", contactdetail.ContactDetail, True, None, False),
            ("experimental", "experimental", bool, False, None, False),
            ("identifier", "identifier", identifier.Identifier, True, None, False),
            ("jurisdiction", "jurisdiction", codeableconcept.CodeableConcept, True, None, False),
            ("lastReviewDate", "lastReviewDate", fhirdate.FHIRDate, False, None, False),
            ("name", "name", str, False, None, False),
            ("publisher", "publisher", str, False, None, False),
            ("purpose", "purpose", str, False, None, False),
            ("relatedArtifact", "relatedArtifact", relatedartifact.RelatedArtifact, True, None, False),
            ("reviewer", "reviewer", contactdetail.ContactDetail, True, None, False),
            ("status", "status", str, False, None, True),
            ("subjectCodeableConcept", "subjectCodeableConcept", codeableconcept.CodeableConcept, False, "subject", False),
            ("subjectReference", "subjectReference", fhirreference.FHIRReference, False, "subject", False),
            ("subtitle", "subtitle", str, False, None, False),
            ("title", "title", str, False, None, False),
            ("topic", "topic", codeableconcept.CodeableConcept, True, None, False),
            ("trigger", "trigger", triggerdefinition.TriggerDefinition, True, None, True),
            ("url", "url", str, False, None, False),
            ("usage", "usage", str, False, None, False),
            ("useContext", "useContext", usagecontext.UsageContext, True, None, False),
            ("version", "version", str, False, None, False),
        ])
        return js

import sys
try:
    from . import codeableconcept
except ImportError:
    codeableconcept = sys.modules[__package__ + '.codeableconcept']
try:
    from . import contactdetail
except ImportError:
    contactdetail = sys.modules[__package__ + '.contactdetail']
try:
    from . import fhirdate
except ImportError:
    fhirdate = sys.modules[__package__ + '.fhirdate']
try:
    from . import fhirreference
except ImportError:
    fhirreference = sys.modules[__package__ + '.fhirreference']
try:
    from . import identifier
except ImportError:
    identifier = sys.modules[__package__ + '.identifier']
try:
    from . import period
except ImportError:
    period = sys.modules[__package__ + '.period']
try:
    from . import relatedartifact
except ImportError:
    relatedartifact = sys.modules[__package__ + '.relatedartifact']
try:
    from . import triggerdefinition
except ImportError:
    triggerdefinition = sys.modules[__package__ + '.triggerdefinition']
try:
    from . import usagecontext
except ImportError:
    usagecontext = sys.modules[__package__ + '.usagecontext']

redpajama_set_name: RedPajamaGithub


text:
package dagger.internal.codegen;

import static com.google.auto.common.MoreElements.asType;
import static com.google.auto.common.MoreTypes.asDeclared;
import static com.google.auto.common.MoreTypes.asTypeElement;
import static com.google.common.collect.Iterables.getOnlyElement;
import static dagger.internal.codegen.binding.AssistedInjectionAnnotations.assistedInjectedConstructors;
import static dagger.internal.codegen.binding.SourceFiles.generatedClassNameForBinding;
import static dagger.internal.codegen.extension.DaggerStreams.toImmutableList;
import static dagger.internal.codegen.javapoet.CodeBlocks.toParametersCodeBlock;
import static dagger.internal.codegen.javapoet.TypeNames.INSTANCE_FACTORY;
import static dagger.internal.codegen.javapoet.TypeNames.providerOf;
import static java.util.stream.Collectors.joining;
import static javax.lang.model.element.Modifier.FINAL;
import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.element.Modifier.PUBLIC;
import static javax.lang.model.element.Modifier.STATIC;

import androidx.room.compiler.processing.XFiler;
import androidx.room.compiler.processing.XMessager;
import androidx.room.compiler.processing.XProcessingEnv;
import androidx.room.compiler.processing.XTypeElement;
import androidx.room.compiler.processing.compat.XConverters;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeVariableName;
import dagger.internal.codegen.base.SourceFileGenerationException;
import dagger.internal.codegen.base.SourceFileGenerator;
import dagger.internal.codegen.binding.AssistedInjectionAnnotations;
import dagger.internal.codegen.binding.AssistedInjectionAnnotations.AssistedFactoryMetadata;
import dagger.internal.codegen.binding.AssistedInjectionAnnotations.AssistedParameter;
import dagger.internal.codegen.binding.BindingFactory;
import dagger.internal.codegen.binding.ProvisionBinding;
import dagger.internal.codegen.javapoet.TypeNames;
import dagger.internal.codegen.langmodel.DaggerElements;
import dagger.internal.codegen.langmodel.DaggerTypes;
import dagger.internal.codegen.validation.TypeCheckingProcessingStep;
import dagger.internal.codegen.validation.ValidationReport;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import javax.inject.Inject;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;

/** An annotation processor for {@link dagger.assisted.AssistedFactory}-annotated types. */
final class AssistedFactoryProcessingStep extends TypeCheckingProcessingStep<XTypeElement> {
  private final XProcessingEnv processingEnv;
  private final XMessager messager;
  private final XFiler filer;
  private final SourceVersion sourceVersion;
  private final DaggerElements elements;
  private final DaggerTypes types;
  private final BindingFactory bindingFactory;

  @Inject
  AssistedFactoryProcessingStep(
      XProcessingEnv processingEnv,
      XMessager messager,
      XFiler filer,
      SourceVersion sourceVersion,
      DaggerElements elements,
      DaggerTypes types,
      BindingFactory bindingFactory) {
    this.processingEnv = processingEnv;
    this.messager = messager;
    this.filer = filer;
    this.sourceVersion = sourceVersion;
    this.elements = elements;
    this.types = types;
    this.bindingFactory = bindingFactory;
  }

  @Override
  public ImmutableSet<ClassName> annotationClassNames() {
    return ImmutableSet.of(TypeNames.ASSISTED_FACTORY);
  }

  @Override
  protected void process(XTypeElement factory, ImmutableSet<ClassName> annotations) {
    ValidationReport report = new AssistedFactoryValidator().validate(factory);
    report.printMessagesTo(messager);
    if (report.isClean()) {
      try {
        ProvisionBinding binding =
            bindingFactory.assistedFactoryBinding(XConverters.toJavac(factory), Optional.empty());
        new AssistedFactoryImplGenerator().generate(binding);
      } catch (SourceFileGenerationException e) {
        e.printMessageTo(XConverters.toJavac(messager));
      }
    }
  }

  private final class AssistedFactoryValidator {
    ValidationReport validate(XTypeElement factory) {
      ValidationReport.Builder report = ValidationReport.about(factory);

      if (!factory.isAbstract()) {
        return report
            .addError(
                "The @AssistedFactory-annotated type must be either an abstract class or "
                    + "interface.",
                factory)
            .build();
      }

      TypeElement javaFactory = XConverters.toJavac(factory);
      if (javaFactory.getNestingKind().isNested() && !factory.isStatic()) {
        report.addError("Nested @AssistedFactory-annotated types must be static. ", factory);
      }

      ImmutableSet<ExecutableElement> abstractFactoryMethods =
          AssistedInjectionAnnotations.assistedFactoryMethods(javaFactory, elements);

      if (abstractFactoryMethods.isEmpty()) {
        report.addError(
            "The @AssistedFactory-annotated type is missing an abstract, non-default method "
                + "whose return type matches the assisted injection type.",
            factory);
      }

      for (ExecutableElement method : abstractFactoryMethods) {
        ExecutableType methodType = types.resolveExecutableType(method, javaFactory.asType());
        if (!isAssistedInjectionType(methodType.getReturnType())) {
          report.addError(
              String.format(
                  "Invalid return type: %s. An assisted factory's abstract method must return a "
                      + "type with an @AssistedInject-annotated constructor.",
                  methodType.getReturnType()),
              XConverters.toXProcessing(method, processingEnv));
        }
        if (!method.getTypeParameters().isEmpty()) {
          report.addError(
              "@AssistedFactory does not currently support type parameters in the creator "
                  + "method. See https://github.com/google/dagger/issues/2279",
              XConverters.toXProcessing(method, processingEnv));
        }
      }

      if (abstractFactoryMethods.size() > 1) {
        report.addError(
            "The @AssistedFactory-annotated type should contain a single abstract, non-default"
                + " method but found multiple: "
                + abstractFactoryMethods,
            factory);
      }

      if (!report.build().isClean()) {
        return report.build();
      }

      AssistedFactoryMetadata metadata =
          AssistedFactoryMetadata.create(javaFactory.asType(), elements, types);

      // Note: We check uniqueness of the @AssistedInject constructor parameters in
      // AssistedInjectProcessingStep. We need to check uniqueness for here too because we may
      // have resolved some type parameters that were not resolved in the @AssistedInject type.
      Set<AssistedParameter> uniqueAssistedParameters = new HashSet<>();
      for (AssistedParameter assistedParameter : metadata.assistedFactoryAssistedParameters()) {
        if (!uniqueAssistedParameters.add(assistedParameter)) {
          report.addError(
              "@AssistedFactory method has duplicate @Assisted types: " + assistedParameter,
              XConverters.toXProcessing(assistedParameter.variableElement(), processingEnv));
        }
      }

      if (!ImmutableSet.copyOf(metadata.assistedInjectAssistedParameters())
          .equals(ImmutableSet.copyOf(metadata.assistedFactoryAssistedParameters()))) {
        report.addError(
            String.format(
                "The parameters in the factory method must match the @Assisted parameters in %s."
                    + "\n      Actual: %s#%s"
                    + "\n    Expected: %s#%s(%s)",
                metadata.assistedInjectType(),
                metadata.factory().getQualifiedName(),
                metadata.factoryMethod(),
                metadata.factory().getQualifiedName(),
                metadata.factoryMethod().getSimpleName(),
                metadata.assistedInjectAssistedParameters().stream()
                    .map(AssistedParameter::type)
                    .map(Object::toString)
                    .collect(joining(", "))),
            XConverters.toXProcessing(metadata.factoryMethod(), processingEnv));
      }

      return report.build();
    }

    private boolean isAssistedInjectionType(TypeMirror type) {
      return type.getKind() == TypeKind.DECLARED
          && AssistedInjectionAnnotations.isAssistedInjectionType(asTypeElement(type));
    }
  }

  /** Generates an implementation of the {@link dagger.assisted.AssistedFactory}-annotated class. */
  private final class AssistedFactoryImplGenerator extends SourceFileGenerator<ProvisionBinding> {
    AssistedFactoryImplGenerator() {
      super(filer, elements, sourceVersion);
    }

    @Override
    public Element originatingElement(ProvisionBinding binding) {
      return binding.bindingElement().get();
    }

    // For each @AssistedFactory-annotated type, we generates a class named "*_Impl" that implements
    // that type.
    //
    // Note that this class internally delegates to the @AssistedInject generated class, which
    // contains the actual implementation logic for creating the @AssistedInject type. The reason we
    // need both of these generated classes is because while the @AssistedInject generated class
    // knows how to create the @AssistedInject type, it doesn't know about all of the
    // @AssistedFactory interfaces that it needs to extend when it's generated. Thus, the role of
    // the @AssistedFactory generated class is purely to implement the @AssistedFactory type.
    // Furthermore, while we could have put all of the logic into the @AssistedFactory generated
    // class and not generate the @AssistedInject generated class, having the @AssistedInject
    // generated class ensures we have proper accessibility to the @AssistedInject type, and reduces
    // duplicate logic if there are multiple @AssistedFactory types for the same @AssistedInject
    // type.
    //
    // Example:
    // public class FooFactory_Impl implements FooFactory {
    //   private final Foo_Factory delegateFactory;
    //
    //   FooFactory_Impl(Foo_Factory delegateFactory) {
    //     this.delegateFactory = delegateFactory;
    //   }
    //
    //   @Override
    //   public Foo createFoo(AssistedDep assistedDep) {
    //     return delegateFactory.get(assistedDep);
    //   }
    //
    //   public static Provider<FooFactory> create(Foo_Factory delegateFactory) {
    //     return InstanceFactory.create(new FooFactory_Impl(delegateFactory));
    //   }
    // }
    @Override
    public ImmutableList<TypeSpec.Builder> topLevelTypes(ProvisionBinding binding) {
      TypeElement factory = asType(binding.bindingElement().get());

      ClassName name = generatedClassNameForBinding(binding);
      TypeSpec.Builder builder =
          TypeSpec.classBuilder(name)
              .addModifiers(PUBLIC, FINAL)
              .addTypeVariables(
                  factory.getTypeParameters().stream()
                      .map(TypeVariableName::get)
                      .collect(toImmutableList()));

      if (factory.getKind() == ElementKind.INTERFACE) {
        builder.addSuperinterface(factory.asType());
      } else {
        builder.superclass(factory.asType());
      }

      AssistedFactoryMetadata metadata =
          AssistedFactoryMetadata.create(asDeclared(factory.asType()), elements, types);
      ParameterSpec delegateFactoryParam =
          ParameterSpec.builder(
                  delegateFactoryTypeName(metadata.assistedInjectType()), "delegateFactory")
              .build();
      builder
          .addField(
              FieldSpec.builder(delegateFactoryParam.type, delegateFactoryParam.name)
                  .addModifiers(PRIVATE, FINAL)
                  .build())
          .addMethod(
              MethodSpec.constructorBuilder()
                  .addParameter(delegateFactoryParam)
                  .addStatement("this.$1N = $1N", delegateFactoryParam)
                  .build())
          .addMethod(
              MethodSpec.overriding(metadata.factoryMethod(), metadata.factoryType(), types)
                  .addStatement(
                      "return $N.get($L)",
                      delegateFactoryParam,
                      // Use the order of the parameters from the @AssistedInject constructor but
                      // use the parameter names of the @AssistedFactory method.
                      metadata.assistedInjectAssistedParameters().stream()
                          .map(metadata.assistedFactoryAssistedParametersMap()::get)
                          .map(param -> CodeBlock.of("$L", param.getSimpleName()))
                          .collect(toParametersCodeBlock()))
                  .build())
          .addMethod(
              MethodSpec.methodBuilder("create")
                  .addModifiers(PUBLIC, STATIC)
                  .addParameter(delegateFactoryParam)
                  .addTypeVariables(
                      metadata.assistedInjectElement().getTypeParameters().stream()
                          .map(TypeVariableName::get)
                          .collect(toImmutableList()))
                  .returns(providerOf(TypeName.get(factory.asType())))
                  .addStatement(
                      "return $T.$Lcreate(new $T($N))",
                      INSTANCE_FACTORY,
                      // Java 7 type inference requires the method call provide the exact type here.
                      sourceVersion.compareTo(SourceVersion.RELEASE_7) <= 0
                          ? CodeBlock.of("<$T>", types.accessibleType(metadata.factoryType(), name))
                          : CodeBlock.of(""),
                      name,
                      delegateFactoryParam)
                  .build());
      return ImmutableList.of(builder);
    }

    /** Returns the generated factory {@link TypeName type} for an @AssistedInject constructor. */
    private TypeName delegateFactoryTypeName(DeclaredType assistedInjectType) {
      // The name of the generated factory for the assisted inject type,
      // e.g. an @AssistedInject Foo(...) {...} constructor will generate a Foo_Factory class.
      ClassName generatedFactoryClassName =
          generatedClassNameForBinding(
              bindingFactory.injectionBinding(
                  getOnlyElement(assistedInjectedConstructors(asTypeElement(assistedInjectType))),
                  Optional.empty()));

      // Return the factory type resolved with the same type parameters as the assisted inject type.
      return assistedInjectType.getTypeArguments().isEmpty()
          ? generatedFactoryClassName
          : ParameterizedTypeName.get(
              generatedFactoryClassName,
              assistedInjectType.getTypeArguments().stream()
                  .map(TypeName::get)
                  .collect(toImmutableList())
                  .toArray(new TypeName[0]));
    }
  }
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace LeetCode.Test
{
    [TestClass]
    public class _071_SimplifyPath_Test
    {
        [TestMethod]
        public void SimplifyPathTest()
        {
            var input = "/home/";

            var solution = new _071_SimplifyPath();
            var result = solution.SimplifyPath(input);

            Assert.AreEqual("/home", result);
        }

        [TestMethod]
        public void SimplifyPathTest_OnlyBack()
        {

            var input = "/..";

            var solution = new _071_SimplifyPath();
            var result = solution.SimplifyPath(input);

            Assert.AreEqual("/", result);
        }

        [TestMethod]
        public void SimplifyPathTest_WithBack()
        {

            var input = "/a/../c/";

            var solution = new _071_SimplifyPath();
            var result = solution.SimplifyPath(input);

            Assert.AreEqual("/c", result);
        }

        [TestMethod]
        public void SimplifyPathTest_WithMultipleBack()
        {

            var input = "/a/b/../../c/";

            var solution = new _071_SimplifyPath();
            var result = solution.SimplifyPath(input);

            Assert.AreEqual("/c", result);
        }

        [TestMethod]
        public void SimplifyPathTest_WithCurrentFolder()
        {

            var input = "/a/./b/../../c/";

            var solution = new _071_SimplifyPath();
            var result = solution.SimplifyPath(input);

            Assert.AreEqual("/c", result);
        }

        [TestMethod]
        public void SimplifyPathTest_WithEmptyFolder()
        {

            var input = "/home//foo//";

            var solution = new _071_SimplifyPath();
            var result = solution.SimplifyPath(input);

            Assert.AreEqual("/home/foo", result);
        }
    }
}


text:
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :study

      t.timestamps null: false
    end
  end
end


text:
static NSSet *_foundationClasses;

@implementation MJFoundation

+ (NSSet *)foundatonClasses
{
    if (_foundationClasses == nil) {
        // 集合中没有NSObject,因为几乎所有的类都是继承自NSObject,具体是不是NSObject需要特殊判断
        _foundationClasses = [NSSet setWithObjects:
                              [NSURL class],
                              [NSDate class],
                              [NSValue class],
                              [NSData class],
                              [NSArray class],
                              [NSDictionary class],
                              [NSString class], nil];
    }
    return _foundationClasses;
}

+ (BOOL)isClassFromFoundation:(Class)c
{
    if (c == [NSObject class] || c == [NSManagedObject class]) return YES;

    __block BOOL result = NO;
    [[self foundatonClasses] enumerateObjectsUsingBlock:^(Class foundationClass, BOOL *stop) {
        if (c == foundationClass || [c isSubclassOfClass:foundationClass]) {
            result = YES;
            *stop = YES;
        }
    }];
    return result;
}
@end


text:
package org.immutables.fixture.builder.attribute_builders;

public class ThirdPartyImmutableWithNestedBuilder {

  private final String value;

  private ThirdPartyImmutableWithNestedBuilder(String value) {
    this.value = value;
  }

  public String getValue() {
    return value;
  }

  public static class Builder {

    private String value;

    public Builder() {
    }

    public Builder(ThirdPartyImmutableWithNestedBuilder copy) {
      this.value = copy.getValue();
    }

    public Builder setValue(String value) {
      this.value = value;
      return this;
    }

    public ThirdPartyImmutableWithNestedBuilder doTheBuild() {
      return new ThirdPartyImmutableWithNestedBuilder(value);
    }
  }
}


text:
title: Alter ego
layout: post
permalink: works/alter
img: alter.jpg
img_quantity: 5
material: Acrylique sur toile, métal, fil d'acier, ruban adhésif
size: 50cm x 50cm
series: Mortel. Imparfaite. Avec des doutes.

---


text:
DROP FUNCTION IF EXISTS get_case_by_location_id(TEXT, TEXT);

CREATE FUNCTION get_case_by_location_id(domain_name TEXT, p_location_id TEXT) RETURNS SETOF form_processor_commcarecasesql AS $$
BEGIN
    RETURN QUERY
    SELECT * FROM form_processor_commcarecasesql
    WHERE domain = domain_name
        AND location_id = p_location_id
        AND type = 'supply-point'
        AND deleted = FALSE
    ;
END;
$$ LANGUAGE plpgsql;


text:
package gridlab;

import gridlab.View.MainWindow;

/**
 * Created by Pavlo on 17.04.2016.
 */
public class GridlabGUI {
    public static void main(String[] args) {
        MainWindow window = new MainWindow();

    }
}


text:
/* $Id$ */

package org.apache.pdfbox.io;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.junit.jupiter.api.Test;

/**
 * This is a unit test for {@link IOUtils}.
 */
class TestIOUtils
{

    /**
     * Tests {@link IOUtils#populateBuffer(java.io.InputStream, byte[]).
     * @throws IOException if an I/O error occursn
     */
    @Test
    void testPopulateBuffer() throws IOException
    {
        byte[] data = "Hello World!".getBytes();
        byte[] buffer = new byte[data.length];
        long count = IOUtils.populateBuffer(new ByteArrayInputStream(data), buffer);
        assertEquals(12, count);

        buffer = new byte[data.length - 2]; //Buffer too small
        InputStream in = new ByteArrayInputStream(data);
        count = IOUtils.populateBuffer(in, buffer);
        assertEquals(10, count);
        byte[] leftOver = IOUtils.toByteArray(in);
        assertEquals(2, leftOver.length);

        buffer = new byte[data.length + 2]; //Buffer too big
        in = new ByteArrayInputStream(data);
        count = IOUtils.populateBuffer(in, buffer);
        assertEquals(12, count);
        assertEquals(-1, in.read()); //EOD reached
    }

}


text:
package br.org.exercicio03;

import java.util.Scanner;

public class Ex03 {

	public static void main(String[] args) {

		Scanner s = new Scanner(System.in);

		double x, y, z;

		System.out.print("Digite um número: ");
		x = s.nextDouble();

		System.out.print("Digite um segundo número, diferente de zero: ");
		y = s.nextDouble();

		z = x/y;

		System.out.print("O resultado da divisão é: "+z+".");
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tools.Gdb
{
    public partial class GdbStub
    {
        public class GdbRegisters
        {
            private GdbStub gdbStub;

            internal GdbRegisters(GdbStub gdbStub)
            {
                this.gdbStub = gdbStub;
            }

            protected ulong ReadRegister(int index)
            {
                if (gdbStub.Running)
                    throw new NotSupportedException("Cannot read register while running");

                string command = string.Format("p{0:x}", index);
                string response = gdbStub.Query(command);

                byte[] buffer = new byte[response.Length / 2];
                for (int i = 0; i < buffer.Length; i++)
                    buffer[i] = Convert.ToByte(response.Substring(i * 2, 2), 16);

                switch (buffer.Length)
                {
                    case 8: return BitConverter.ToUInt64(buffer, 0);
                    case 4: return BitConverter.ToUInt32(buffer, 0);
                    case 2: return BitConverter.ToUInt16(buffer, 0);
                }

                throw new Exception("Could not find register size");
            }
            protected void WriteRegister(int index, ulong value)
            {
                if (gdbStub.Running)
                    throw new NotSupportedException("Cannot read register while running");

                byte[] buffer = BitConverter.GetBytes(value);
                string valueBuffer = "";

                for (int i = 0; i < buffer.Length; i++)
                    valueBuffer += buffer[i].ToString("x2");

                string command = string.Format("P{0:x}={1:x}", index, valueBuffer);
                string response = gdbStub.Query(command);

                if (response != "OK")
                    throw new Exception("Unable to write regsiter");
            }
        }
    }
}


text:
#import <Foundation/Foundation.h>
#import "SystranObject.h"

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

#import "SystranSpeechChannel.h"
#import "SystranErrorResponse.h"
#import "SystranSpeechAlignSegment.h"

@protocol SystranSpeechAlignResponse
@end

@interface SystranSpeechAlignResponse : SystranObject

/* Error at request level [optional]
 */
@property(nonatomic) SystranErrorResponse* error;
/* Array of channels
 */
@property(nonatomic) NSArray<SystranSpeechChannel>* channels;
/* Array of segments
 */
@property(nonatomic) NSArray<SystranSpeechAlignSegment>* segments;

@end


text:
Update

		<?php echo showMsg()?>

	<form class="uf" method="post" action="ps/update.php">
		Username:
		<input name="username" type="text" value="<?php echo $user->data['username']?>">

		<input value="Update" type="submit">
	</form>

	Back to my account


text:
// "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/device_manager.rs
// - Core device manager

use prelude::*;
use sync::Mutex;
use lib::Queue;

module_define!{DeviceManager, [arch], init}

/// A semi-arbitatry integer denoting how well a driver handles a specific device
pub type DriverHandleLevel = u32;

/// IO range binding
pub enum IOBinding
{
	/// Memory-mapped IO space
	Memory(::memory::virt::MmioHandle),
	/// x86 IO bus (Base and offset)
	IO(u16,u16),
}

/// Interface a bus manager instance
pub trait BusManager:
	Send + Sync
{
	/// Returns the textual name of the bus type (e.g. "pci")
	fn bus_type(&self) -> &str;
	/// Returns a list of valid attributes for BusDevice::get_attr
	fn get_attr_names(&self) -> &[&str];
}

/// Attrbute on a bus device
#[derive(Debug)]
pub enum AttrValue<'a>
{
	/// Invalid attribute name
	None,
	/// 32-bit integer
	U32(u32),
	/// String value
	String(&'a str),
}
impl<'a> AttrValue<'a> {
	pub fn unwrap_u32(self) -> u32 {
		if let AttrValue::U32(v) = self {
			v
		}
		else {
			panic!("AttrValue::unwrap_u32 - {:?}", self);
		}
	}
	pub fn unwrap_str(self) -> &'a str {
		if let AttrValue::String(v) = self {
			v
		}
		else {
			panic!("AttrValue::unwrap_str - {:?}", self);
		}
	}
}

/// Interface to a device on a bus
pub trait BusDevice:
	Send
{
	/// Returns the device's address on the parent bus
	fn addr(&self) -> u32;
	/// Returns the specified attribute (or 0, if invalid)
	fn get_attr(&self, name: &str) -> AttrValue;
	/// Set the specified attribute
	fn set_attr(&mut self, name: &str, value: AttrValue);
	/// Set the power state of this device
	fn set_power(&mut self, state: bool);	// TODO: Power state enum for Off,Standby,Low,On
	/// Bind to the specified IO block (meaning of `block_id` depends on the bus)
	fn bind_io(&mut self, block_id: usize) -> IOBinding;
	/// Obtain the specified interrupt vector
	fn get_irq(&mut self, idx: usize) -> u32;
}

/// Abstract driver for a device (creates instances when passed a device)
pub trait Driver:
	Send + Sync
{
	/// Driver's name
	fn name(&self) -> &str;
	/// Bus type the driver binds against (matches value from `BusManager::bus_type`)
	fn bus_type(&self) -> &str;
	/// Return the handling level of this driver for the specified device
	fn handles(&self, bus_dev: &BusDevice) -> DriverHandleLevel;
	/// Requests that the driver bind itself to the specified device
	fn bind(&self, bus_dev: &mut BusDevice) -> Box<DriverInstance>;
}

/// Driver instance (maps directly to a device)
pub trait DriverInstance:
	Send
{
}

/// Internal representation of a device on a bus
struct Device
{
	bus_dev: Box<BusDevice>,
	driver: Option<(Box<DriverInstance>, DriverHandleLevel)>,
	//attribs: Vec<u32>,
}

/// Internal representation of a bus
struct Bus
{
	manager: &'static BusManager,
	devices: Vec<Device>,
}

/// List of registered busses on the system
#[allow(non_upper_case_globals)]
static s_root_busses: Mutex<Queue<Bus>> = mutex_init!(queue_init!());

/// List of registered drivers
#[allow(non_upper_case_globals)]
static s_driver_list: Mutex<Queue<&'static Driver>> = mutex_init!( queue_init!() );

fn init()
{
	// Do nothing!
}

/// Register a bus with the device manager
///
/// Creates a new internal representation of the bus, containg the passed set of devices.
pub fn register_bus(manager: &'static BusManager, devices: Vec<Box<BusDevice>>) //-> BusHandle
{
	let bus = Bus {
		manager: manager,
		// For each device, locate a driver
		devices: devices.into_iter().map(|mut d| Device {
			driver: find_driver(manager, &mut *d),
			//attribs: Vec::new(),
			bus_dev: d,
			}).collect(),
		};
	let mut bus_list_lh = s_root_busses.lock();
	bus_list_lh.push(bus);
	//let ptr: *const _ = bus_list_lh.last().unwrap();
	//BusHandle(ptr)
}

/// Registers a driver with the device manger
pub fn register_driver(driver: &'static Driver)
{
	s_driver_list.lock().push(driver);
	log_debug!("Registering driver {}", driver.name());
	// Iterate known devices and spin up instances if needed
	for bus in s_root_busses.lock().iter_mut()
	{
		log_trace!("bus type {}", bus.manager.bus_type());
		if driver.bus_type() == bus.manager.bus_type()
		{
			for dev in bus.devices.iter_mut()
			{
				let rank = driver.handles(&*dev.bus_dev);
				log_debug!("rank = {:?}", rank);
				if rank == 0
				{
					// SKIP!
				}
				else if dev.driver.is_some()
				{
					let bind = dev.driver.as_ref().unwrap();
					let cur_rank = bind.1;
					if cur_rank > rank
					{
						// Existing driver is better
					}
					else if cur_rank == rank
					{
						// Fight!
					}
					else
					{
						// New driver is better
						panic!("TODO: Unbind driver and bind in new one");
					}
				}
				else
				{
					// Bind new driver
					dev.driver = Some( (driver.bind(&mut *dev.bus_dev), rank) );
				}
			}
		}
	}
}

/**
 * Locate the best registered driver for this device and instanciate it
 */
fn find_driver(bus: &BusManager, bus_dev: &mut BusDevice) -> Option<(Box<DriverInstance>,DriverHandleLevel)>
{
	log_debug!("Finding driver for {}:{:x}", bus.bus_type(), bus_dev.addr());
	let mut best_ranking = 0;
	let mut best_driver = None;
	for driver in s_driver_list.lock().iter()
	{
		if bus.bus_type() == driver.bus_type()
		{
			let ranking = driver.handles(bus_dev);
			if ranking == 0
			{
				// Doesn't handle this device
			}
			else if ranking > best_ranking
			{
				// Best so far
				best_driver = Some( *driver );
				best_ranking = ranking;
			}
			else if ranking == best_ranking
			{
				// A tie, this is not very good
				//log_warning!("Tie for device {}:{:x} between {} and {}",
				//	bus.bus_type(), bus_dev.addr(), driver, best_driver.unwrap());
			}
			else
			{
				// Not as good as current, move along
			}
		}
	}
	best_driver.map(|d| (d.bind(bus_dev), best_ranking))
}

impl IOBinding
{
	/// Returns the x86 IO space base
	pub fn io_base(&self) -> u16 {
		match *self
		{
		IOBinding::IO(base, _size) => base,
		IOBinding::Memory(_) => panic!("Called IOBinding::io_base on IOBinding::Memory"),
		}
	}
	/// Read a single u8 from the binding
	pub unsafe fn read_8(&self, ofs: usize) -> u8
	{
		//log_trace!("read_8({:?}, {:#x})", self, ofs);
		match *self
		{
		IOBinding::IO(base, s) => {
			assert!( ofs+1 <= s as usize, "read_u8(IO addr {:#x}+1 > {:#x})", ofs, s );
			::arch::x86_io::inb(base + ofs as u16)
			},
		IOBinding::Memory(ref h) => {
			::core::intrinsics::volatile_load( h.as_int_mut::<u8>(ofs) )
			},
		}
	}
	/// Read a single u32 from the binding
	pub unsafe fn read_32(&self, ofs: usize) -> u32
	{
		//log_trace!("read_32({:?}, {:#x})", self, ofs);
		match *self
		{
		IOBinding::IO(base, s) => {
			assert!( ofs+4 <= s as usize, "read_u32(IO addr {:#x}+4 > {:#x})", ofs, s );
			::arch::x86_io::inl(base + ofs as u16)
			},
		IOBinding::Memory(ref h) => {
			::core::intrinsics::volatile_load( h.as_int_mut::<u32>(ofs) )
			},
		}
	}
	/// Writes a single u8 to the binding
	pub unsafe fn write_8(&self, ofs: usize, val: u8)
	{
		//log_trace!("write_8({:?}, {:#x}, {:#02x})", self, ofs, val);
		match *self
		{
		IOBinding::IO(base, s) => {
			assert!( ofs+1 <= s as usize, "write_8(IO addr {:#x}+1 > {:#x})", ofs, s );
			::arch::x86_io::outb(base + ofs as u16, val);
			},
		IOBinding::Memory(ref h) => {
			::core::intrinsics::volatile_store( h.as_int_mut::<u8>(ofs), val );
			},
		}
	}
	/// Write a single u32 to the binding
	pub unsafe fn write_32(&self, ofs: usize, val: u32)
	{
		match *self
		{
		IOBinding::IO(base, s) => {
			assert!(ofs+4 <= s as usize, "write_32(IO addr {:#x}+4 > {:#x})", ofs, s);
			::arch::x86_io::outl(base + ofs as u16, val);
			},
		IOBinding::Memory(ref h) => {
			::core::intrinsics::volatile_store( h.as_int_mut::<u32>(ofs), val );
			},
		}
	}
}

impl ::core::fmt::Debug for IOBinding
{
	fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
		match *self
		{
		IOBinding::IO(b, s) => write!(f, "IO({:#x}+{:#x})", b, s),
		IOBinding::Memory(ref h) => write!(f, "Memory({:?})", h),
		}
	}
}

// vim: ft=rust


text:
import logging
import time
import os
import sys
from ConfigParser import ConfigParser
from subprocess import Popen, PIPE

class JavaConfig:
    '''Enable access to properities in java siteConfig file'''
    def __init__(self, fname):
        self.prop_d = {}
        for line in open(fname):
            line = line.strip();
            if line.startswith('#') or len(line) == 0:
                continue
            pair = line.split('=')
            if len(pair) != 2:
                log.error("Invalid property (%s)" % line)
                continue
            self.prop_d[pair[0].strip()] = pair[1].strip()

    def get(self, prop):
        return self.prop_d[prop]

def file_len(fname):
    i=0
    for line in open(fname):
        i += 1
    return i

def runTest(testName, siteConfig, testDir, numNodes, fdata):

    log('Stopping accumulo')
    syscall('$ACCUMULO_HOME/bin/stop-all.sh')

    log('Creating slaves file for this test')
    slavesPath = siteConfig.get('SLAVES')
    nodesPath = testDir+'/nodes/%d' % numNodes
    syscall('head -n %d %s > %s' % (numNodes,slavesPath,nodesPath))

    log('Copying slaves file to accumulo config')
    syscall('cp '+nodesPath+' $ACCUMULO_CONF_DIR/slaves');

    log('Removing /accumulo directory in HDFS')
    syscall("hadoop fs -rmr /accumulo")

    log('Initializing new Accumulo instance')
    instance = siteConfig.get('INSTANCE_NAME')
    passwd = siteConfig.get('PASSWORD')
    syscall('printf "%s\nY\n%s\n%s\n" | $ACCUMULO_HOME/bin/accumulo init' % (instance, passwd, passwd))

    log('Starting new Accumulo instance')
    syscall('$ACCUMULO_HOME/bin/start-all.sh')

    sleepTime = 30
    if numNodes > 120:
        sleepTime = int(numNodes / 4)
    log('Sleeping for %d seconds' % sleepTime)
    time.sleep(sleepTime)

    log('Setting up %s test' % testName)
    syscall('$ACCUMULO_HOME/bin/accumulo org.apache.accumulo.test.scalability.Run %s setup %s' % (testName, numNodes))

    log('Sleeping for 5 seconds')
    time.sleep(5)

    log('Starting %s clients' % testName)
    numThreads = numNodes
    if int(numNodes) > 128:
        numThreads='128'
    syscall('pssh -P -h %s -p %s "$ACCUMULO_HOME/bin/accumulo org.apache.accumulo.test.scalability.Run %s client %s >/tmp/scale.out 2>/tmp/scale.err &" < /dev/null' % (nodesPath, numThreads, testName, numNodes))

    log('Sleeping for 30 sec before checking how many clients started...')
    time.sleep(30)
    output = Popen(["hadoop fs -ls /accumulo-scale/clients"], stdout=PIPE, shell=True).communicate()[0]
    num_clients = int(output.split()[1])
    log('%s clients started!' % num_clients)

    log('Waiting until %d clients finish.' % num_clients)
    last = 0
    done = 0
    while done < num_clients:
        time.sleep(5)
        output = Popen(["hadoop fs -ls /accumulo-scale/results"], stdout=PIPE, shell=True).communicate()[0]
        if not output:
            sys.stdout.write('.')
            sys.stdout.flush()
            continue
        done = int(output.split()[1])
        if done != last:
            sys.stdout.write('.%s' % done)
        else:
            sys.stdout.write('.')
        sys.stdout.flush()
        last = done
        sys.stdout.flush()
    log('\nAll clients are finished!')

    log('Copying results from HDFS')
    resultsDir = "%s/results/%s" % (testDir, numNodes)
    syscall('hadoop fs -copyToLocal /accumulo-scale/results %s' % resultsDir)

    log('Calculating results from clients')
    times = []
    totalMs = 0L
    totalEntries = 0L
    totalBytes = 0L
    for fn in os.listdir(resultsDir):
        for line in open('%s/%s' % (resultsDir,fn)):
            words = line.split()
            if words[0] == 'ELAPSEDMS':
                ms = long(words[1].strip())
                totalMs += ms
                times.append(ms)
                totalEntries += long(words[2].strip())
                totalBytes += long(words[3].strip())
    times.sort()

    print times
    numClients = len(times)
    min = times[0] / 1000
    avg = (float(totalMs) / numClients) / 1000
    median = times[int(numClients/2)] / 1000
    max = times[numClients-1] / 1000
    q1 = times[int(numClients/4)] / 1000
    q3 = times[int((3*numClients)/4)] / 1000

    log('Tservs\tClients\tMin\tQ1\tAvg\tMed\tQ3\tMax\tEntries\tMB')
    resultStr = '%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%dM\t%d' % (numNodes, numClients, min, q1, avg, median, q3, max, totalEntries / 1000000, totalBytes / 1000000)
    log(resultStr)
    fdata.write(resultStr + '\n')
    fdata.flush()

    time.sleep(5)

    log('Tearing down %s test' % testName)
    syscall('$ACCUMULO_HOME/bin/accumulo org.apache.accumulo.test.scalability.Run %s teardown %s' % (testName, numNodes))

    time.sleep(10)

def syscall(cmd):
    log('> %s' % cmd)
    os.system(cmd)

def run(cmd, **kwargs):
    log.debug("Running %s", ' '.join(cmd))
    handle = Popen(cmd, stdout=PIPE, **kwargs)
    out, err = handle.communicate()
    log.debug("Result %d (%r, %r)", handle.returncode, out, err)
    return handle.returncode

def log(msg):
    print msg
    sys.stdout.flush()

def main():

    if not os.getenv('ACCUMULO_HOME'):
        raise 'ACCUMULO_HOME needs to be set!'

    if not os.getenv('ACCUMULO_CONF_DIR'):
        os.environ['ACCUMULO_CONF_DIR'] = os.path.join(os.getenv('ACCUMULO_HOME'), 'conf')

    if not os.getenv('HADOOP_HOME'):
		raise 'HADOOP_HOME needs to be set!'

    if len(sys.argv) != 2:
        log('Usage: run.py <testName>')
        sys.exit()
    testName = sys.argv[1]

    logging.basicConfig(level=logging.DEBUG)

    log('Creating test directory structure')
    testDir = 'test-%d' % time.time()
    nodesDir = testDir+'/nodes'
    resultsDir = testDir+'/results'
    syscall('mkdir %s' % testDir)
    syscall('mkdir %s' % nodesDir)
    syscall('mkdir %s' % resultsDir)

    log('Removing current /accumulo-scale directory')
    syscall('hadoop fs -rmr /accumulo-scale')

    log('Creating new /accumulo-scale directory structure')
    syscall('hadoop fs -mkdir /accumulo-scale')
    syscall('hadoop fs -mkdir /accumulo-scale/clients')
    syscall('hadoop fs -mkdir /accumulo-scale/results')
    syscall('hadoop fs -chmod -R 777 /accumulo-scale')

    log('Copying config to HDFS')
    syscall('hadoop fs -copyFromLocal ./conf /accumulo-scale/conf')

    siteConfig = JavaConfig('conf/site.conf');
    slavesPath = siteConfig.get('SLAVES')
    maxNodes = file_len(slavesPath)

    fdata = open('%s/scale.dat' % testDir, 'w')
    fdata.write('Tservs\tClients\tMin\tAvg\tMed\tMax\tEntries\tMB\n')

    for numNodes in siteConfig.get('TEST_CASES').split(','):
        log('Running %s test with %s nodes' % (testName, numNodes))
        if int(numNodes) > maxNodes:
            logging.error('Skipping %r test case as slaves file %r contains only %r nodes', numNodes, slavesPath, maxNodes)
            continue
        runTest(testName, siteConfig, testDir, int(numNodes), fdata)
        sys.stdout.flush()

if __name__ == '__main__':
    main()


text:
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.Compute.Automation
{
    public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet
    {
        protected object CreateImageDeleteDynamicParameters()
        {
            dynamicParameters = new RuntimeDefinedParameterDictionary();
            var pResourceGroupName = new RuntimeDefinedParameter();
            pResourceGroupName.Name = "ResourceGroupName";
            pResourceGroupName.ParameterType = typeof(string);
            pResourceGroupName.Attributes.Add(new ParameterAttribute
            {
                ParameterSetName = "InvokeByDynamicParameters",
                Position = 1,
                Mandatory = true
            });
            pResourceGroupName.Attributes.Add(new AllowNullAttribute());
            dynamicParameters.Add("ResourceGroupName", pResourceGroupName);

            var pImageName = new RuntimeDefinedParameter();
            pImageName.Name = "ImageName";
            pImageName.ParameterType = typeof(string);
            pImageName.Attributes.Add(new ParameterAttribute
            {
                ParameterSetName = "InvokeByDynamicParameters",
                Position = 2,
                Mandatory = true
            });
            pImageName.Attributes.Add(new AllowNullAttribute());
            dynamicParameters.Add("ImageName", pImageName);

            var pArgumentList = new RuntimeDefinedParameter();
            pArgumentList.Name = "ArgumentList";
            pArgumentList.ParameterType = typeof(object[]);
            pArgumentList.Attributes.Add(new ParameterAttribute
            {
                ParameterSetName = "InvokeByStaticParameters",
                Position = 3,
                Mandatory = true
            });
            pArgumentList.Attributes.Add(new AllowNullAttribute());
            dynamicParameters.Add("ArgumentList", pArgumentList);

            return dynamicParameters;
        }

        protected void ExecuteImageDeleteMethod(object[] invokeMethodInputParameters)
        {
            string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]);
            string imageName = (string)ParseParameter(invokeMethodInputParameters[1]);

            var result = ImagesClient.Delete(resourceGroupName, imageName);
            WriteObject(result);
        }
    }

    public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet
    {
        protected PSArgument[] CreateImageDeleteParameters()
        {
            string resourceGroupName = string.Empty;
            string imageName = string.Empty;

            return ConvertFromObjectsToArguments(
                 new string[] { "ResourceGroupName", "ImageName" },
                 new object[] { resourceGroupName, imageName });
        }
    }

    [Cmdlet(VerbsCommon.Remove, "AzureRmImage", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)]
    [OutputType(typeof(PSOperationStatusResponse))]
    public partial class RemoveAzureRmImage : ComputeAutomationBaseCmdlet
    {
        protected override void ProcessRecord()
        {
            ExecuteClientAction(() =>
            {
                if (ShouldProcess(this.ImageName, VerbsCommon.Remove)
                    && (this.Force.IsPresent ||
                        this.ShouldContinue(Properties.Resources.ResourceRemovalConfirmation,
                                            "Remove-AzureRmImage operation")))
                {
                    string resourceGroupName = this.ResourceGroupName;
                    string imageName = this.ImageName;

                    var result = ImagesClient.Delete(resourceGroupName, imageName);
                    var psObject = new PSOperationStatusResponse();
                    ComputeAutomationAutoMapperProfile.Mapper.Map<Azure.Management.Compute.Models.OperationStatusResponse, PSOperationStatusResponse>(result, psObject);
                    WriteObject(psObject);
                }
            });
        }

        [Parameter(
            ParameterSetName = "DefaultParameter",
            Position = 1,
            Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            ValueFromPipeline = false)]
        [AllowNull]
        public string ResourceGroupName { get; set; }

        [Parameter(
            ParameterSetName = "DefaultParameter",
            Position = 2,
            Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            ValueFromPipeline = false)]
        [Alias("Name")]
        [AllowNull]
        public string ImageName { get; set; }

        [Parameter(
            ParameterSetName = "DefaultParameter",
            Mandatory = false)]
        [AllowNull]
        public SwitchParameter Force { get; set; }
    }
}


text:
TML for Objective C
==================

[![Version](http://cocoapod-badges.herokuapp.com/v/TMLKit/badge.png)](http://cocoadocs.org/docsets/TMLKit/1.0.0/)
[![Platform](http://cocoapod-badges.herokuapp.com/p/TMLKit/badge.png)](http://cocoadocs.org/docsets/TMLKit)
[![Build Status](https://travis-ci.org/translationexchange/tml-objc.svg?branch=master)](https://travis-ci.org/translationexchange/tml-objc)

TMLKit is an Objective-C SDK for an integrated cloud-based translation solution for iOS applications.

It reduces the number of steps required for internationalization and localization of your mobile applications.

TMLKit integrates with TranslationExchange.com service, where you can manage the entire translation process - enable languages, invite translators, manage translation keys, and much more.

You never have to touch the resource bundle files - translation keys are extracted from your app's source code on the fly and kept up to date by the SDK.

Once your app is translated, the translations will automatically be downloaded and installed by the SDK. You DO NOT need to submit a new application to the App Store. You can simply enable a new language on TranslationExchange.com and it will immediately be available in your application.

Video
==================

Click on the image to see it in action.

Requirements
==================

	iOS 8
	CocoaPods

Demo Application
==================

This repository comes with a Demo application. To run it, follow these steps:

```sh
$ git clone https://github.com/translationexchange/tml-objc.git
$ cd tml-objc/Demo
$ pod install
$ open Demo.xcworkspace
```

Configure TMLKit by editing main.m and setting *application key* and *access token* parameters to match your TranslationExchange project. Finally, run the application from Xcode.

Once the Demo application is running, open the side panel and enable **In-App Translation**. That will cause TMLKit to register all of the localizable strings in your application with your TranslationExchange project. Select **Change Language** from the side panel. You should see all of the languages currently used in your project listed here. TMLKit provides a default language picker. Creating a custom one is a breeze - see [TMLLanguageSelectorViewController](https://github.com/translationexchange/tml-objc/blob/dev/Classes/Controllers/TMLLanguageSelectorViewController.m) for details.

Head over to [dashboard](https://dashboard-translationexchange.com) and add a new language to your project. Now, switch back to the Demo app, background and foreground it - that will trigger TMLKit to instantly update information about your project, and, subsequently, list of available languages.

**In-App Translation** mode allows you to also add translation right from within the app. Make sure you select a non-default languages from the language picker, then simply tap and hold over any text you see on the screen. TMLKit will bring up interface for translating the string you tapped. You can manually add a translation, or pick one of the machine translations listed at the bottom if they are to your satisfaction. Once you've added a translation - dismiss the translation view and watch the original string get updated to its translation.

Another sample application is located here:

https://github.com/translationexchange/tml-objc-samples-wammer

Installation
==================

To install the SDK through [CocoaPods](http://cocoapods.org), simply add the following line to your Podfile:

```sh
pod "TMLKit"
```

and run

```sh
pod install
```

Alternatively, you can clone this repository:

```sh
$ git clone https://github.com/translationexchange/tml-objc.git
$ cd tml-objc/TMLKit
$ pod install
```

And build TMLKit.xcodeproj and simply include the build framework in your project, or, drag TMLKit.xcodeproj into your application's Xcode project and have it configured as a [linked framework](https://developer.apple.com/library/ios/recipes/xcode_help-project_editor/Articles/AddingaLibrarytoaTarget.html).

Integration
==================

Before you can proceed with the integration, please visit https://TranslationExchange.com - open an account and create a project for your application. Each project is assigned a unique *application key* which you will use to configure TMLKit.

Here's how you would configure TMLKit:

```objc
#import <TMLKit/TMLKit.h>

int main(int argc, char * argv[])
{
    @autoreleasepool {

        [TML sharedInstanceWithApplicationKey:@"<APPLICATION KEY>"];

        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}
```

**Note:** TML is capable of automatically localizing strings in NIB files. It's a configurable option that is enabled by default. This automatic localization happens during decoding of NIB files, which may happen before your app delegate is called with application:didFinishLaunchingWithOptions:. This is why the above example uses main.m to configure TMLKit. If you are not using automatic NIB localization - you can move that configuration over to your app delegate...

TMLKit comes with a variety of macros to help with localization. TMLLocalizedString() should be familiar to you if you've used NSLocalizedString() before. To avoid having to include TMLKit.h in every file it's probably best to import it in the prefix header file, along with your foundation framework includes:

```objc
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <TMLKit/TMLKit.h>
#endif
```

If your project uses NSLocalizedString and you have no intention of using TML markup language, or simply eager to see some results, TMLKit comes with redefined NSLocalizedString macros. Simply add:

```objc
#import <TMLKit/TMLKit+NSLocalizedString.h>
```

However, you only get full use of TML via TMLLocalizedString() macros. TML supports default inflectors, pluralizers, contextualizer and language cases, which to better code and much better localization.

How does it work?
==================

TMLKit does all the hard work for you. When you use TML's macros (see TML.h), the library automatically registers translation keys with Translation Exchange service and generates resource bunldes for your app on the fly. TMLKit always keeps your local cache up to date by downloading the latest translations from the service when they become available. At run-time, your app will use translations from your local app cache so your users will not experience any delays. When new localized data becomes available it is possible for your application to update translations dynamically, without needing to restart the application.

You also have an option to bundle all your translations with your app before you release it - allowing your application to function in offline mode. By default, whenever your application becomes active and has connectivity to the internet - TMLKit will check for new translation releases (published via the [dashboard](https://dashboard.translationexchange.com)). When updates are available they are downloaded on-demand. Translations for default and current locales are downloaded immediately, and additional data is downloaded when TMLKit is told to change current locale.

To bundle translations with your app, simply download published archive from the dashboard, prepend its name with "tml_" and include it in your build as a resource. The resulting filename should be in the format "tml_<version>.tar.gz". TMLKit supports zip, tar, tar.gz/tar.gzip formats.

TMLKit also reports analytics data, allowing you to see what languages are used in your app, what the default languages of your users are, where your users are coming from, etc...

Internationalization & TML
==================

If your application is already internationalized using the standard NSLocalizedString methods, you can simply import the TML+NSLocalizedString.h header in your .m file and TML will take over the internationalization macros.

```objc
#import "<TMLKit/TML+NSLocalizedString.h>"
```
However, these macros are rather limited as they don't allow full TML syntaxt (data tokens, etc).

TML also provides its own macros for internationalization which significantly enhance the standard iOS macros.

Basic example:

```objc
TMLLocalizedString(label);
TMLLocalizedString(label, description);

TMLLocalizedString(@"Invite");
TMLLocalizedString(@"Invite", @"Invite someone to join the group");
```

This macro is similar to NSLocalizedString, and it does not require the optional comment parameter.

Unlike NSLocalizedString, where the second parameter is a comment for a translator, TML uses the description to contextualize the key. So the above example would actually register two distinct keys, where each would have its own translations.

Another example:

```objc
TMLLocalizedString(label, tokens);

TMLLocalizedStringWithTokens(@"You have {count || message}.", @{@"count": @4});
TMLLocalizedStringWithTokens(@"Hello {user}.", @{@"user": @"Michael"});
```

Tokens can be passed in many different ways. If the token is passed as a primitive type, it would be used for both context rules and displayed value. If it is passed a class or a structure, you can separate the object being used for context rules and the value that would be substituted for the token.

More examples of using tokens:

```objc
User *user  = [[User alloc] initWithName: @"Michael" gender: @"male"];
// will use [user description] for substitution value
TMLLocalizedStringWithTokens(@"Hello {user}.", @{@"user": user})
// second parameter is used for substitution value
TMLLocalizedStringWithTokens(@"Hello {user}.", @{@"user": @[user, user.name]})
TMLLocalizedStringWithTokens(@"Hello {user}.", @{@"user": @[user, @"Mike"]})
```

```objc
NSDictionary *user = @{@"name": @"Michael", @"gender": @"male"};
// can be used for context rules, but not substitution value
TMLLocalizedStringWithTokens(@"{user | Born On}.", @{@"user": user})
TMLLocalizedStringWithTokens(@"Hello {user}.", @{
          @"user": @{@"object": user, @"property": @"name"}
})
TMLLocalizedStringWithTokens(@"Hello {user}.", @{
          @"user": @{@"object": user, @"value": @"Michael"}
})
```

You might have noticed that we're using the same macro with a variety of arguments. The full syntax of TMLLocalizedString() is:

```objc
TMLLocalizedString(NSString *localizedString, NSString *description, NSDictionary *tokens, NSDictionary *userOptions);
```

Only the first argument is mandatory...

```objc
TMLLocalizedString(
    @"Hello {user}",  // localized string
    @"A greeting message",  // description
    @{@"user": @"Michael"}  // tokens
)
```

```objc
TMLLocalizedString(
    @"Hello {user}",  // localized string
    @"A greeting message",  // description
    @{@"user": @"Michael"}, // tokens
    @{@"level": @5, @"max-length": @20} // options
)
```

```objc
TMLLocalizedString(
    @"Hello {user}",  // localized string
    @{@"user": @"Michael"}, // tokens
)
```

```objc
TMLLocalizedString(
    @"Hello {user}",  // localized string
    @{}, // no tokens
    @{@"level": @5, @"max-length": @20} // options
)
```

Options are TML specic options. Some are used for formatting strings, some are purely administrative. For example, in the above code snippet options specify that only translators of a specific rank are allowed to translate keys of a specific level. The constraint indicate that the translations of this key may not be longer than 20 chars. See wiki.translationexchage.com for more details.

All of the above macros assume that you are working with plain text and will return NSString's. It is also possible to work with attributed strings, in a fashion similar to data token (delimited with '{}'):

```objc
TMLLocalizedAttributedString(
    @"You have completed [bold: {count || mile}] on your last run.",
    @{@"count": @4.2}
)
```

Notice that we are now using TMLLocalizedAttributedString() macro. It is synonymous to TMLLocalizedString() and exists solely to make a distinction in the return type. TMLLocalizedString() returns NSString's, and TMLLocalizedAttributedString() returns NSAttributedString's. Secondly, you'll notice that decorated tokens are delimited with '[]' square brackets, as opposed to data tokens, which are delimited using '{}' curly brackets.

All in all, the above example will return:

```
	"You have completed **4.2 miles** on your last run."
```

TMLKit supports both NSAttributedString format and HTML. Here's the HTML equivalent:

```objc
TMLLocalizedString(
    @"You have completed [bold: {count || mile}] on your last run.",
    @{@"count": @4.2},
    @{TMLTokenFormatOptionName: TMLHTMLTokenFormatString}
)
```

which results in:

```hTML
	"You have completed <strong>4.2 miles</strong> on your last run."
```

Do notice that if you are expecting an NSString - use TMLLocalizedString(); if you are expecting NSAttributedString - use TMLLocalizedAttributedString();

Default Tokens
======================

It is also possible to define default tokens and refer to them by name throughout your code, instead of having to supplying identical data structures. You get cleaner, more consistent code this way.

```objc
TMLConfiguration *config = TMLSharedConfiguration();
// Data Tokens
[config setDefaultTokenValue: @"My App Name"
                     forName: @"app_name"
                        type: TMLDataTokenType];

// Decorated Tokens with attributed strings
[config setDefaultTokenValue: @{
                   @"font": @{
                      @"name": @"system",
                      @"size": @12,
                      @"type": @"italic"
                   },
                   @"color": @"blue"
                 }
                     forName: @"bold"
                        type: TMLDecorationTokenType
                      format: TMLAttributedTokenFormat];

[config setDefaultTokenValue: @{
                   @"shadow": @{
                      @"offset": @1,1,
                      @"radius": @0.5,
                      @"color": @"grey"
                   },
                   @"color": @"black"
                                 }
                     forName: @"shadow"
                        type: TMLDecorationTokenType
                      format: TMLAttributedTokenFormat];

[config setDefaultTokenValue: @{
                   @"attributes": @{
                     UIFontDescriptorNameAttribute: @"Arial"
                     UIFontDescriptorNameAttribute: @(12.),
                     UIFontDescriptorSymbolicTraits: UIFontDescriptorTraitItalic
                   }
                 }
                     forName: @"italic"
                        type: TMLDecorationTokenType
                      format: TMLAttributedTokenFormat];

// Decorated tokens with HTML strings
[config setDefaultTokenValue: @"<strong>{$0}</strong>"
                     forName: @"bold"
                        type: TMLDecorationTokenType
                      format: TMLHTMLTokenFormat];

[config setDefaultTokenValue: @"<span style='color:green'>{$0}</span>"
                     forName: @"green"
                        type: TMLDecorationTokenType
                      format: TMLHTMLTokenFormat];

```

Alternatively, you can provide token values inline, which would overwrite the default token definitions.

The following examples will use the above pre-defined tokens:

```objc
TMLLocalizedAttributedString(@"Hello [bold: World]");
TMLLocalizedAttributedString(@"[italic: Hello World]");
TMLLocalizedAttributedString(@"This [bold: technology is [shadow: very cool]].");
```

Notice that "very cool" will be bold and have a shadow. Nesting tokens inherits the parent token traits.

Benefits of TMLLocalizedAttributedString()
==================

The benefits of using TML with NSAttributedString is that labels get translated in context. If you tried the above example without using TML, you would end up with code similar to the following:

```objc
NSDictionary *bold = @{[UIFont boldSystemFontOfSize:@12], NSFontAttributeName};

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] init];
[str appendString : NSLocalizedString(@"You have completed ")];

if (distance_in_miles == 1)
   [str appendAttributedString:
          [[NSAttributedString alloc] initWithString: NSLocalizedString(@"1 mile")]
                      attributes: bold];
else
   [str appendAttributedString:
          [[NSAttributedString alloc] initWithString:
              [NSString stringWithFormat: NSLocalizedString(@"%d miles"), distance_in_miles]]
                      attributes: bold];

[str appendString: NSLocalizedString(@" on your last run.")];
```

The above code has the following issues:

* The (distance_in_miles == 1) check fails for languages that have more complicated numeric rules, like Russian or Arabic.
* "You have completed " and " on your last run" will been translated outside of the context of the entire sentence. In some languages some words must be switched around. So it fails in both contextualization and composition.
* "1 mile" and "%d miles" are also translated outside of the context.

All of the above code can be replaced with a single line using TML:

```objc
TMLLocalizedAttributedString(
    @"You have completed [bold: {count || mile}] on your last run.",
    @{@"count": @4.2}
)
```

Which is easily translated to Russian:

    "Вы пробежали [bold: {count || милю, мили, миль}] в вашем последнем забеге."

Since there are languages, like Hebrew, which depend on the gender of the viewing user, any time you refer to "You", you should always pass the viewing_user as a token.

```objc
TMLLocalizedAttributedString(@"You have completed [bold: {count || mile}] on your last run.", @{@"count": @4.2, @"viewing_user": currentUser})
```

Or better yet, set it in the configuration, and then you never have to pass it as a token:

```objc
TMLSharedConfiguration().viewingUser = currentUser;
```

Here is a more complicated example:

```objc
TMLLocalizedAttributedString(
    @"[bold: {user}] has completed [bold: {count || mile}] on {user| his, her} last run.",
    @{
        @"user": friend,
        @"count": @4.2,
        @"link": @{@"color": @"blue"}
        @"bold": @{@"font":@{@"name": @"system", @"size": @12, @"type": @"bold"}}
    }
)
```

In English, this will render as:

    "**Michael** has completed **4.2 miles** on his last run."

Translated to Russian as:

    "[link: {user}] {user | пробежал, пробежала} [bold: {count || милю, мили, миль}] в своем последнем забеге."

Will render as:

    "**Michael** пробежал **4.2 мили** в своем последнем забеге."

Switching Locales At Runtime
==================

It is possible to tell TMLKit to change local at runtime. Whether you would like to provide that functionality in your released version of the app is up to you and your interpretation of Apple's rules and guidelines. However, it does come in handy when testing the application with various languages and when using *In-App Translation* mode.

For that reason, TMLKit comes with a simple language picker that you can use in your application. To open the langugae picker programmatically, use the following code:

```objc
TMLPresentLanguagePicker();
```

To change current locale programmatically:

```objc
TMLChangeLocale(@"ru"); // will change to Russian locale
```

There's one thing worth noting here - unless you've bundled all of your translation data with the app, your app may not have the translation data available locally for the new locale. In which case - TMLKit will download all of the required data in the background. What this means is that the actual change of locale may be deferred. If you'd like to, for example, present a progress indicator while the data is being downloaded, you can use the following call:

```objc
TML *tml = [TML sharedInstance];
MBProgressHUD *hud = nil;

if ([tml hasLocalTranslationsForLocale:newLocale] == NO) {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = TMLLocalizedString(@"Switching language...");
    [hud show:YES];
}

[tml changeLocale:newLocale
  completionBlock:^(BOOL success) {
    [hud hide:YES];
  }];
```

And this is roughly how TMLLanguageSelectorViewController works.

Off course this means that all of your views that have alraedy presented localized strings need to be updated with new localized strings. See [Reusable Localized Strings] for details...

Reusable Localized Strings
==================

If you'd like to provide dynamic language switching (see [Switching Locales At Runtime]), your app needs to be able to update all of the required objects that have already utilized localized string. Consider a basic UILabel:

```objc
UILabel *label = self.titleLabel;
label.attributedText = TMLLocalizedAttributedString(@"[bold:Title]: {title}", @{@"title": @"My Title"});
```

When your application changes locale this label need to be updated with a localized string corresponding to the new locale. To facilitate these updates, TMLKit provides additional macros: TMLLocalizedStringWithReuseIdenitifer() and TMLLocalizedAttributedStringWithReuseIdenitifer():

Basic usage:

```objc
TMLLocalizedStringWithReuseIdenitifer(string, reuseIdentifier, ...);
TMLLocalizedAttributedStringWithReuseIdenitifer(string, reuseIdentifier, ...);
```

It is identical to the already familiar TMLLocalizedString() and TMLLocalizedAttributedString() macros, except they take a second mandatory parameter - and identifier.

Thus, the above UILabel example becomes:

```objc
UILabel *label = self.titleLabel;
label.attributedText = TMLLocalizedAttributedStringWithReuseIdenitifer(@"[bold:Title]: {title}", @{@"title": @"My Title"}, @"titleLabel");
```

This causes TMLKit to register the caller (what is 'self' in the context of when the call is made), and when there comes time to update the localized string, it calls that caller's updateTMLLocalizedStringWithInfo:forReuseIdentifier: method, if one is defined.

The method is defined as optional in TMLReusableLocalization protocol. TMLKit extends NSObject by conforming to that protocol.

```objc
@protocol TMLReusableLocalization <NSObject>
@optional
- (void)updateTMLLocalizedStringWithInfo:(NSDictionary *)info forReuseIdentifier:(NSString *)reuseIdentifier;
@end
```

We'll get back to this in a second, but first let's finish up with our UILabel example. Within the same class, let's define:

```objc
- (void)updateTMLLocalizedStringWithInfo:(NSDictionary *)info forReuseIdentifier:(NSString *)reuseIdentifier {
  if ([reuseIdentifier isEqualToString:@"titleLabel"] == YES) {
    self.titleLabel.attributedText = info[TMLLocalizedStringInfoKey];
  }
  else {
    [super updateTMLLocalizedStringWithInfo:info forReuseIdentifier:reuseIdentifier];
  }
}
```

Notice that the info object passed to updateTMLLocalizedStringWithInfo:forReuseIdentifier: already contains the new localized string; it also contains all of the data used to construct it in the first place. That means that TMLLocalizedStringWithReuseIdentifier() captures (strongly) all of its arguments. It's worth mentioning that this data is tied to the sender object, and TMLKit captures sender objects weakly. So, once the sender object is released - all of the captured localization data is released with it.

Also notice that we are calling super's implementation...

TMLKit defines default behavior for updating reusable localized strings - it treats reuseIdentifier as a key path into the sender object. If the sender responds to -[NSObject valueForKeyPath:], it will attempt to update the value via -[NSObject setValue:forKeyPath:]. This is how TMLKit handles automatic NIB localization.

Let's simplify our UILabel example a little:

```objc
@interface MyViewController : UIViewController
@property (strong, nonatomic) UILabel *titleLabel;
@end

@implementation MyViewController
- (void)viewDidLoad {
  [super viewDidLoad];
  UIlabel *titleLabel = [[UILabel alloc] init];
  titleLabel.attributedText = TMLLocalizedAttributedStringWithReuseIdenitifer(@"[bold:Title]: {title}", @{@"title": @"My Title"}, @"titleLabel.attributedText");
  self.titleLabel = titleLabel;
}
@end
```

This is all you have to do, as TMLKit's default implementation will simply call setValue:forKeyPath: on the controller, using "titleLabel.attributedText" as the keyPath.

Let's say you are not comfortable with TMLKit capturing data used to create localized strings:

```objc
@implementation MyViewController
- (void)viewDidLoad {
  [super viewDidLoad];
  UILabel *titleLabel = [[UIlabel alloc] init];
  self.titleLabel = titleLabel;
  [self configureView];
  [[TML sharedInstance] registerObjectWithReusableLocalizedStrings:self];
}

- (void)configureView {
  self.titleLabel.attributedText = TMLLocalizedAttributedString(@"[bold:Title]: {title}", @{@"title": @"My Title"});
}

- (void)updateReusableTMLStrings {
  [super updateReusableTMLStrings];
  [self configureView];
}
@end
```

First of all - notice that we are using TMLLocalizedAttributedString() and not TMLLocalizedAttributedStringWithReuseIdentifier() - so we are not capturing any localization data here. Secondly - we are registering the view controller with TML via registerObjectWithReusableLocalizedStrings:. When it's time to update localized strings - TML will call this controller's updateReusableTMLStrings method. We respond by calling configureView, which re-localizes the label anew.

In-App Translator
==================

TMLKit supports translation of strings right from within the app. By performing a special, and customizable gesture, TMLKit will switch to live translation mode. This will require TMLKit to first authenticate the translator with TranslationExchange service. To programatically enable live translation mode:

```objc
TMLActivateTranslation(YES); // NO argument disables
```

This feature is allowed by default, but can be disabled via TMLConfiguration:

```objc
TMLSharedConfiguration().disallowTranslation = YES;
```

Once the **In-App Translation** mode is enabled - tap and hold on any localized string on the screen - TMLKit will bring up Translator interface for that specific string. From there you can add/remove and otherwise manage translations of that string.

You can also bring up that interface programmatically:

```objc
TMLPresentTranslatorForKey([TMLTranslationKey generateKeyForLabel:@"<localized string>" description:@"<optional comment>"]);
```

Links
==================

* Register on TranslationExchange.com: https://translationexchange.com

* Read TranslationExchange's documentation: http://docs.translationexchange.com

* Follow TranslationExchange on Twitter: https://twitter.com/translationx

* Connect with TranslationExchange on Facebook: https://www.facebook.com/translationexchange

* If you have any questions or suggestions, contact us: support@translationexchange.com

Copyright and license
==================

Copyright (c) 2017 TranslationExchange.com

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
title: Database
layout: docs
methods:

  - signature: database.read(pathOrRef)
    id: read
    generator: true
    description: Returns the data at this path in firebase's database.
    arguments:
      - name: pathOrRef
        required: true
        type: String or [Firebase Database Reference](https://firebase.google.com/docs/reference/js/firebase.database.Reference)
        description: The path or reference to the value to read.
    output: Whatever value is store at this path in the database (number, string, object, etc).
    example: |
      ```js
      function* getTodo() {
        const firstTodo = yield call(rsf.database.read, 'todos/1');
        yield put(gotTodo(firstTodo));
      }
      ```

  - signature: database.create(pathOrRef, data)
    id: create
    generator: true
    description: Create a new path in the database and stores the data there.
    arguments:
      - name: pathOrRef
        required: true
        type: String or [Firebase Database Reference](https://firebase.google.com/docs/reference/js/firebase.database.Reference)
        description: The path or reference to the destination.
      - name: data
        required: true
        type: Any value
        description: The value to store.
    output: The key newly created (a string).
    example: |
      ```js
      function* addTodo() {
        const key = yield call(rsf.database.create, 'todos', {
          done: false,
          label: 'Do this',
        });
        // `key` is something like "-Kfn7EyLEoHax0YGoQr0"
      }
      ```

  - signature: database.update(pathOrRef, data)
    id: update
    generator: true
    description: Replace the value store at `path` in the database with `data`.
    arguments:
      - name: pathOrRef
        required: true
        type: String or [Firebase Database Reference](https://firebase.google.com/docs/reference/js/firebase.database.Reference)
        description: The path or reference to the value to update.
      - name: data
        required: true
        type: Any value
        description: The value to store.
    output:
    example: |
      ```js
      function* updateTodo() {
        yield call(rsf.database.update, 'todos/-Kfn7EyLEoHax0YGoQr0', {
          done: true, // yay, it's done now!
          label: 'Do this',
        });
      }
      ```

  - signature: database.patch(pathOrRef, data)
    id: patch
    generator: true
    description: Patches the value store at `path` in the database with `data`. Like `database.update` but doesn't remove unmentionned keys.
    arguments:
      - name: pathOrRef
        required: true
        type: String or [Firebase Database Reference](https://firebase.google.com/docs/reference/js/firebase.database.Reference)
        description: The path or reference to the value to update.
      - name: data
        required: true
        type: Any value
        description: The value to store.
    output:
    example: |
      ```js
      function* updateTodo() {
        // With this call, no need to re-send the todo label.
        yield call(rsf.database.patch, 'todos/-Kfn7EyLEoHax0YGoQr0', {
          done: true,
        });
      }
      ```

  - signature: database.delete(pathOrRef)
    id: delete
    generator: true
    description: Removes the value at the specified `path` in the database.
    arguments:
      - name: pathOrRef
        required: true
        type: String or [Firebase Database Reference](https://firebase.google.com/docs/reference/js/firebase.database.Reference)
        description: The path or reference to the value to delete.
    output:
    example: |
      ```js
      function* deleteTodo() {
        yield call(rsf.database.delete, 'todos/-Kfn7EyLEoHax0YGoQr0');
      }
      ```

  - signature: database.channel(pathOrRef, event)
    id: channel
    generator: false
    description: Returns a redux-saga [Channel](https://redux-saga.github.io/redux-saga/docs/advanced/Channels.html) which emits every change at the specified path in the database.
    arguments:
      - name: pathOrRef
        required: true
        type: String or [Firebase Database Reference](https://firebase.google.com/docs/reference/js/firebase.database.Reference)
        description: The path or reference to the value to read.
      - name: event
        required: false
        type: String
        description: Defaults to `value`. A string describing the type of event to listen for. Options includes `value`, `child_added`, `child_removed`, `child_changed` and `child_moved`. See [Reference.on](https://firebase.google.com/docs/reference/js/firebase.database.Reference#on) documentation for more information.
    output: |
      A redux-saga [Channel](https://redux-saga.github.io/redux-saga/docs/advanced/Channels.html) which emits every change at the specified path in the database. The emitted value is an object with two keys:
      - `snapshot`: a [firebase.database.DataSnapshot](https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot) ;
      - `value`: the result of `snapshot.val()`, which is the actual value stored in the database (any type).
    example: |
      ```js
      function* syncTodosSaga() {
        const channel = yield call(rsf.database.channel, 'todos');

        while(true) {
          const { value: todos } = yield take(channel);
          yield put(syncTodos(todos));
        }
      }
      ```

  - signature: database.sync(pathOrRef, options)
    id: sync
    generator: true
    description: Automatically dispatches a redux action every time `path` changes.
    arguments:
      - name: pathOrRef
        required: true
        type: String or [Firebase Database Reference](https://firebase.google.com/docs/reference/js/firebase.database.Reference)
        description: The path or reference to the value to synced.
      - name: options
        required: true
        type: Object
        description: "An object to configure how the database should be synchronised. It must contain at least the `successActionCreator` which must take a single argument being the value read from the firebase reference. The other possible options are `failureActionCreator` which is called on channel errors and `transform` which is an optional transformer function to be applied to the value before it's passed to the action creator. Default to the identity function (`x => x`)."
    output:
    example: |
      ```js
      import { syncTodos } from '../actionCreators/todos';

      function* todoRootSaga() {
        yield [
          rsf.database.sync('todos', { successActionCreator: syncTodos }),
        ];
      }
      ```
---


text:
package eu.ydp.empiria.player.client.module.bonus;

public interface Bonus {

    void execute();
}


text:
package redis.clients.redisson;

import org.junit.Assert;
import org.junit.Test;
import redis.clients.redisson.api.RAtomicLong;

public class RedissonAtomicLongTest extends BaseTest {

    @Test
    public void testCompareAndSetZero() {
        RAtomicLong al = redisson.getAtomicLong("test");
        Assert.assertTrue(al.compareAndSet(0, 2));
        Assert.assertEquals(2, al.get());

        RAtomicLong al2 = redisson.getAtomicLong("test1");
        al2.set(0);
        Assert.assertTrue(al2.compareAndSet(0, 2));
        Assert.assertEquals(2, al2.get());

    }

    @Test
    public void testCompareAndSet() {
        RAtomicLong al = redisson.getAtomicLong("test");
        Assert.assertFalse(al.compareAndSet(-1, 2));
        Assert.assertEquals(0, al.get());
        Assert.assertTrue(al.compareAndSet(0, 2));
        Assert.assertEquals(2, al.get());
    }

    @Test
    public void testSetThenIncrement() {
        RAtomicLong al = redisson.getAtomicLong("test");
        al.set(2);
        Assert.assertEquals(2, al.getAndIncrement());
        Assert.assertEquals(3, al.get());
    }

    @Test
    public void testIncrementAndGet() {
        RAtomicLong al = redisson.getAtomicLong("test");
        Assert.assertEquals(1, al.incrementAndGet());
        Assert.assertEquals(1, al.get());
    }

    @Test
    public void testGetAndIncrement() {
        RAtomicLong al = redisson.getAtomicLong("test");
        Assert.assertEquals(0, al.getAndIncrement());
        Assert.assertEquals(1, al.get());
    }

    @Test
    public void test() {
        RAtomicLong al = redisson.getAtomicLong("test");
        Assert.assertEquals(0, al.get());
        Assert.assertEquals(0, al.getAndIncrement());
        Assert.assertEquals(1, al.get());
        Assert.assertEquals(1, al.getAndDecrement());
        Assert.assertEquals(0, al.get());
        Assert.assertEquals(0, al.getAndIncrement());
        Assert.assertEquals(1, al.getAndSet(12));
        Assert.assertEquals(12, al.get());
        al.set(1);

        long state = redisson.getAtomicLong("test").get();
        Assert.assertEquals(1, state);
        al.set(Long.MAX_VALUE - 1000);

        long newState = redisson.getAtomicLong("test").get();
        Assert.assertEquals(Long.MAX_VALUE - 1000, newState);
    }

}