text:
//===-- LayoutConstraint.h - Layout constraints types and APIs --*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines types and APIs for layout constraints.
//
//===----------------------------------------------------------------------===//

#ifndef SWIFT_LAYOUT_CONSTRAINT_H
#define SWIFT_LAYOUT_CONSTRAINT_H

#include "swift/AST/TypeAlignments.h"
#include "swift/Basic/SourceLoc.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/StringRef.h"
#include "swift/AST/PrintOptions.h"

namespace swift {

enum class AllocationArena;
class ASTContext;
class ASTPrinter;

/// Describes a layout constraint information.
enum class LayoutConstraintKind : uint8_t {
  // It is not a known layout constraint.
  UnknownLayout,
  // It is a layout constraint representing a trivial type of an unknown size.
  TrivialOfExactSize,
  // It is a layout constraint representing a trivial type of an unknown size.
  TrivialOfAtMostSize,
  // It is a layout constraint representing a trivial type of an unknown size.
  Trivial,
  // It is a layout constraint representing a reference counted class instance.
  Class,
  // It is a layout constraint representing a reference counted native class
  // instance.
  NativeClass,
  // It is a layout constraint representing a reference counted object.
  RefCountedObject,
  // It is a layout constraint representing a native reference counted object.
  NativeRefCountedObject,
  LastLayout = NativeRefCountedObject,
};

/// This is a class representing the layout constraint.
class LayoutConstraintInfo : public llvm::FoldingSetNode {
  friend class LayoutConstraint;
  // Alignment of the layout in bytes.
  const unsigned Alignment : 16;
  // Size of the layout in bits.
  const unsigned SizeInBits : 24;
  // Kind of the layout.
  const LayoutConstraintKind Kind;

  LayoutConstraintInfo()
      : Alignment(0), SizeInBits(0), Kind(LayoutConstraintKind::UnknownLayout) {
  }

  LayoutConstraintInfo(const LayoutConstraintInfo &Layout)
      : Alignment(Layout.Alignment), SizeInBits(Layout.SizeInBits),
        Kind(Layout.Kind) {
  }

  LayoutConstraintInfo(LayoutConstraintKind Kind)
      : Alignment(0), SizeInBits(0), Kind(Kind) {
    assert(!isKnownSizeTrivial() && "Size in bits should be specified");
  }

  LayoutConstraintInfo(LayoutConstraintKind Kind, unsigned SizeInBits,
                       unsigned Alignment)
      : Alignment(Alignment), SizeInBits(SizeInBits), Kind(Kind) {
    assert(
        isTrivial() &&
        "Size in bits should be specified only for trivial layout constraints");
  }
  public:
  LayoutConstraintKind getKind() const { return Kind; }

  bool isKnownLayout() const {
    return isKnownLayout(Kind);
  }

  bool isFixedSizeTrivial() const {
    return isFixedSizeTrivial(Kind);
  }

  bool isKnownSizeTrivial() const {
    return isKnownSizeTrivial(Kind);
  }

  bool isAddressOnlyTrivial() const {
    return isAddressOnlyTrivial(Kind);
  }

  bool isTrivial() const {
    return isTrivial(Kind);
  }

  bool isRefCountedObject() const {
    return isRefCountedObject(Kind);
  }

  bool isNativeRefCountedObject() const {
    return isNativeRefCountedObject(Kind);
  }

  bool isClass() const {
    return isClass(Kind);
  }

  bool isNativeClass() const {
    return isNativeClass(Kind);
  }

  bool isRefCounted() const {
    return isRefCounted(Kind);
  }

  bool isNativeRefCounted() const {
    return isNativeRefCounted(Kind);
  }

  unsigned getTrivialSizeInBytes() const {
    assert(isKnownSizeTrivial());
    return (SizeInBits + 7) / 8;
  }

  unsigned getMaxTrivialSizeInBytes() const {
    assert(isKnownSizeTrivial());
    return (SizeInBits + 7) / 8;
  }

  unsigned getTrivialSizeInBits() const {
    assert(isKnownSizeTrivial());
    return SizeInBits;
  }

  unsigned getMaxTrivialSizeInBits() const {
    assert(isKnownSizeTrivial());
    return SizeInBits;
  }

  unsigned getAlignmentInBits() const {
    return Alignment;
  }

  unsigned getAlignmentInBytes() const {
    assert(isKnownSizeTrivial());
    if (Alignment)
      return Alignment;

    // There is no explicitly defined alignment. Try to come up with a
    // reasonable one.

    // If the size is a power of 2, use it also for the default alignment.
    auto SizeInBytes = getTrivialSizeInBytes();
    if (llvm::isPowerOf2_32(SizeInBytes))
      return SizeInBytes * 8;

    // Otherwise assume the alignment of 8 bytes.
    return 8*8;
  }

  operator bool() const {
    return isKnownLayout();
  }

  bool operator==(const LayoutConstraintInfo &rhs) const {
    return getKind() == rhs.getKind() && SizeInBits == rhs.SizeInBits &&
           Alignment == rhs.Alignment;
  }

  bool operator!=(LayoutConstraintInfo rhs) const { return !(*this == rhs); }

  void print(raw_ostream &OS, const PrintOptions &PO = PrintOptions()) const;
  void print(ASTPrinter &Printer, const PrintOptions &PO) const;

  /// Return the layout constraint as a string, for use in diagnostics only.
  std::string getString(const PrintOptions &PO = PrintOptions()) const;

  /// Return the name of this layout constraint.
  StringRef getName() const;

  /// Return the name of a layout constraint with a given kind.
  static StringRef getName(LayoutConstraintKind Kind);

  static bool isKnownLayout(LayoutConstraintKind Kind);

  static bool isFixedSizeTrivial(LayoutConstraintKind Kind);

  static bool isKnownSizeTrivial(LayoutConstraintKind Kind);

  static bool isAddressOnlyTrivial(LayoutConstraintKind Kind);

  static bool isTrivial(LayoutConstraintKind Kind);

  static bool isRefCountedObject(LayoutConstraintKind Kind);

  static bool isNativeRefCountedObject(LayoutConstraintKind Kind);

  static bool isAnyRefCountedObject(LayoutConstraintKind Kind);

  static bool isClass(LayoutConstraintKind Kind);

  static bool isNativeClass(LayoutConstraintKind Kind);

  static bool isRefCounted(LayoutConstraintKind Kind);

  static bool isNativeRefCounted(LayoutConstraintKind Kind);

  /// Uniquing for the LayoutConstraintInfo.
  void Profile(llvm::FoldingSetNodeID &ID) {
    Profile(ID, Kind, SizeInBits, Alignment);
  }

  static void Profile(llvm::FoldingSetNodeID &ID,
                      LayoutConstraintKind Kind,
                      unsigned SizeInBits,
                      unsigned Alignment);
  private:
  // Make vanilla new/delete illegal for LayoutConstraintInfo.
  void *operator new(size_t Bytes) throw() = delete;
  void operator delete(void *Data) throw() = delete;
  public:
  // Only allow allocation of LayoutConstraintInfo using the allocator in
  // ASTContext or by doing a placement new.
  void *operator new(size_t bytes, const ASTContext &ctx,
                     AllocationArena arena, unsigned alignment = 8);
  void *operator new(size_t Bytes, void *Mem) throw() { return Mem; }

  // Representation of the non-parameterized layouts.
  static LayoutConstraintInfo UnknownLayoutConstraintInfo;
  static LayoutConstraintInfo RefCountedObjectConstraintInfo;
  static LayoutConstraintInfo NativeRefCountedObjectConstraintInfo;
  static LayoutConstraintInfo ClassConstraintInfo;
  static LayoutConstraintInfo NativeClassConstraintInfo;
  static LayoutConstraintInfo TrivialConstraintInfo;
};

/// A wrapper class containing a reference to the actual LayoutConstraintInfo
/// object.
class LayoutConstraint {
  LayoutConstraintInfo *Ptr;
  public:
  /*implicit*/ LayoutConstraint(LayoutConstraintInfo *P = 0) : Ptr(P) {}

  static LayoutConstraint getLayoutConstraint(const LayoutConstraint &Layout,
                                              ASTContext &C);

  static LayoutConstraint getLayoutConstraint(LayoutConstraintKind Kind,
                                              ASTContext &C);

  static LayoutConstraint getLayoutConstraint(LayoutConstraintKind Kind);

  static LayoutConstraint getLayoutConstraint(LayoutConstraintKind Kind,
                                              unsigned SizeInBits,
                                              unsigned Alignment,
                                              ASTContext &C);

  static LayoutConstraint getUnknownLayout();

  LayoutConstraintInfo *getPointer() const { return Ptr; }

  bool isNull() const { return Ptr == 0; }

  LayoutConstraintInfo *operator->() const { return Ptr; }

  /// Merge these two constraints and return a more specific one
  /// or fail if they're incompatible and return an unknown constraint.
  LayoutConstraint merge(LayoutConstraint Other);

  explicit operator bool() const { return Ptr != 0; }

  void dump() const;
  void dump(raw_ostream &os, unsigned indent = 0) const;

  void print(raw_ostream &OS, const PrintOptions &PO = PrintOptions()) const;
  void print(ASTPrinter &Printer, const PrintOptions &PO) const;

  /// Return the layout constraint as a string, for use in diagnostics only.
  std::string getString(const PrintOptions &PO = PrintOptions()) const;

  friend llvm::hash_code hash_value(const LayoutConstraint &layout) {
    return hash_value(layout.getPointer());
  }

  bool operator==(LayoutConstraint rhs) const {
    if (isNull() && rhs.isNull())
      return true;
    return *getPointer() == *rhs.getPointer();
  }

  bool operator!=(LayoutConstraint rhs) const {
    return !(*this == rhs);
  }
};

// Permit direct uses of isa/cast/dyn_cast on LayoutConstraint.
template <class X> inline bool isa(LayoutConstraint LC) {
  return isa<X>(LC.getPointer());
}
template <class X> inline X cast_or_null(LayoutConstraint LC) {
  return cast_or_null<X>(LC.getPointer());
}
template <class X> inline X dyn_cast(LayoutConstraint LC) {
  return dyn_cast<X>(LC.getPointer());
}
template <class X> inline X dyn_cast_or_null(LayoutConstraint LC) {
  return dyn_cast_or_null<X>(LC.getPointer());
}

/// LayoutConstraintLoc - Provides source location information for a
/// parsed layout constraint.
struct LayoutConstraintLoc {
private:
  LayoutConstraint Layout;
  SourceLoc Loc;

public:
  LayoutConstraintLoc(LayoutConstraint Layout, SourceLoc Loc)
      : Layout(Layout), Loc(Loc) {}

  bool isError() const;

  // FIXME: We generally shouldn't need to build LayoutConstraintLoc without
  // a location.
  static LayoutConstraintLoc withoutLoc(LayoutConstraint Layout) {
    return LayoutConstraintLoc(Layout, SourceLoc());
  }

  /// Get the representative location of this type, for diagnostic
  /// purposes.
  SourceLoc getLoc() const { return Loc; }

  SourceRange getSourceRange() const;

  bool hasLocation() const { return Loc.isValid(); }
  LayoutConstraint getLayoutConstraint() const { return Layout; }

  void setLayoutConstraint(LayoutConstraint value) {
    Layout = value;
  }

  bool isNull() const { return Layout.isNull(); }

  LayoutConstraintLoc clone(ASTContext &ctx) const { return *this; }
};

/// Checks if ID is a name of a layout constraint and returns this
/// constraint. If ID does not match any known layout constraint names,
/// returns UnknownLayout.
LayoutConstraint getLayoutConstraint(Identifier ID, ASTContext &Ctx);

} // end namespace swift

LLVM_DECLARE_TYPE_ALIGNMENT(swift::LayoutConstraintInfo, swift::TypeAlignInBits)

namespace llvm {
static inline raw_ostream &
operator<<(raw_ostream &OS, swift::LayoutConstraint LC) {
  LC->print(OS);
  return OS;
}

// A LayoutConstraint casts like a LayoutConstraintInfo*.
template <> struct simplify_type<const ::swift::LayoutConstraint> {
  typedef ::swift::LayoutConstraintInfo *SimpleType;
  static SimpleType getSimplifiedValue(const ::swift::LayoutConstraint &Val) {
    return Val.getPointer();
  }
};

template <>
struct simplify_type<::swift::LayoutConstraint>
    : public simplify_type<const ::swift::LayoutConstraint> {};

// LayoutConstraint hashes just like pointers.
template <> struct DenseMapInfo<swift::LayoutConstraint> {
  static swift::LayoutConstraint getEmptyKey() {
    return llvm::DenseMapInfo<swift::LayoutConstraintInfo *>::getEmptyKey();
  }
  static swift::LayoutConstraint getTombstoneKey() {
    return llvm::DenseMapInfo<swift::LayoutConstraintInfo *>::getTombstoneKey();
  }
  static unsigned getHashValue(swift::LayoutConstraint Val) {
    return DenseMapInfo<swift::LayoutConstraintInfo *>::getHashValue(
        Val.getPointer());
  }
  static bool isEqual(swift::LayoutConstraint LHS,
                      swift::LayoutConstraint RHS) {
    return LHS.getPointer() == RHS.getPointer();
  }
};

// A LayoutConstraint is "pointer like".
template <> struct PointerLikeTypeTraits<swift::LayoutConstraint> {
public:
  static inline void *getAsVoidPointer(swift::LayoutConstraint I) {
    return (void *)I.getPointer();
  }
  static inline swift::LayoutConstraint getFromVoidPointer(void *P) {
    return (swift::LayoutConstraintInfo *)P;
  }
  enum { NumLowBitsAvailable = swift::TypeAlignInBits };
};
} // end namespace llvm

#endif


text:
__precompile__()

module FMIndexes

export
    FMIndex,
    restore,
    count,
    locate,
    locateall

using SuffixArrays
using WaveletMatrices
using IndexableBitVectors
using Humanize
using Mmap

"""
Index for full-text search.

Type parameters:

* `w`: the number of bits required to encode the alphabet
* `T`: the type to represent positions of a sequence
"""
struct FMIndex{w,T}
    bwt::WaveletMatrix{w,UInt8,SucVector}
    sentinel::Int
    samples::Vector{T}
    sampled::SucVector
    count::Vector{Int}
end

function FMIndex(seq, sa, σ, r)
    wm = WaveletMatrix(make_bwt(seq, sa), log2(Int, σ))
    # sample suffix array
    samples, sampled = sample_sa(sa, r)
    sentinel = something(findfirst(isequal(0), sa), 0) + 1
    # count characters
    count = count_bytes(seq, σ)
    count[1] = 1  # sentinel '$' is smaller than any character
    cumsum!(count, count)
    return FMIndex(wm, sentinel, samples, SucVector(sampled), count)
end

"""
    FMIndex(seq, σ=256; r=32, program=:SuffixArrays, mmap::Bool=false, opts...)

Build an FM-Index from a sequence `seq`.
The sequence must support `convert(UInt8, seq[i])` for each character and the
alphabet size should be less than or equal to 256. The second parameter, `σ`, is
the alphabet size. The third parameter, `r`, is the interval of sampling values
from a suffix array. If you set it large, you can save the memory footprint but
it requires more time to locate the position.
"""
function FMIndex(seq, σ=256; r=32, program=:SuffixArrays, mmap::Bool=false, opts...)
    T = index_type(length(seq))
    opts = Dict(opts)
    @assert !haskey(opts, :σ) "σ should be passed as the second argument"
    if program === :SuffixArrays
        @assert 1 ≤ σ ≤ typemax(UInt8) + 1
        sa = make_sa(T, seq, σ, mmap)
    elseif program === :psascan || program === :pSAscan
        @assert 1 ≤ σ ≤ typemax(UInt8)
        psascan = get(opts, :psascan, "psascan")
        workdir = get(opts, :workdir, pwd())
        sa = make_sa_pscan(T, seq, psascan, workdir, mmap)
    else
        error("unknown program name: $program")
    end
    return FMIndex(seq, sa, σ, r)
end

"""
    FMIndex(text; opts...)

Build an FM-Index from an ASCII text.
"""
function FMIndex(text::Union{String, SubString{String}}; opts...)
    return FMIndex(codeunits(text), 128; opts...)
end

Base.length(index::FMIndex) = length(index.bwt)

function Base.show(io::IO, fmindex::FMIndex{w,T}) where {w,T}
    println(io, summary(fmindex), ':')
    totalsize = (
        sizeof(fmindex.bwt) +
        sizeof(fmindex.samples) +
        sizeof(fmindex.sampled) +
        sizeof(fmindex.count)
    )
    print("     length: ", length(fmindex), '\n')
    print("  data size: ", Humanize.datasize(totalsize, style=:bin))
end

"""
Restore the original text from the index.
"""
function restore(index::FMIndex)
    n = length(index)
    text = Vector{UInt8}(undef, n)
    p = index.sentinel
    while n > 0
        p = lfmap(index, p)
        text[n] = index.bwt[p ≥ index.sentinel ? p - 1 : p]
        n -= 1
    end
    return text
end

"""
Count the number of occurrences of the given query.
"""
function Base.count(query, index::FMIndex)
    return length(sa_range(query, index))
end

"""
Locate the positions of occurrences of the given query.
This method returns an iterator of positions:

    for pos in locate(query, index)
        # ...
    end
"""
function locate(query, index::FMIndex)
    return LocationIterator(sa_range(query, index), index)
end

"""
Locate the positions of all occurrences of the given query.
"""
function locateall(query, index::FMIndex)
    iter = locate(query, index)
    locs = Vector{Int}(undef, length(iter))
    for (i, loc) in enumerate(iter)
        locs[i] = loc
    end
    return locs
end

include("index.jl")
include("saca.jl")
include("lociter.jl")

end # module

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe 'Dashboard feature' do
  let(:a_page) { FactoryGirl.create(:public_page, visible: true) }

  before do
    @user = DummyUser.new
    @user.update_attributes(alchemy_roles: %w(admin), name: "Joe User", id: 1)
    authorize_as_admin(@user)
  end

  describe 'Locked pages summary' do
    it "should initially show no pages are locked" do
      visit admin_dashboard_path
      locked_pages_widget = all('div[@class="widget"]').first
      expect(locked_pages_widget).to have_content "Currently locked pages:"
      expect(locked_pages_widget).to have_content "no pages"
    end

    context 'When locked by current user' do
      it "should show locked by me" do
        a_page.lock_to!(@user)
        visit admin_dashboard_path
        locked_pages_widget = all('div[@class="widget"]').first
        expect(locked_pages_widget).to have_content "Currently locked pages:"
        expect(locked_pages_widget).to have_content a_page.name
        expect(locked_pages_widget).to have_content "Me"
      end
    end

    context 'When locked by another user' do
      it "should show locked by user's name" do
        user = DummyUser.new
        user.update_attributes(alchemy_roles: %w(admin), name: "Sue Smith", id: 2)
        a_page.lock_to!(user)
        DummyUser.stub(:find_by).and_return(user)
        visit admin_dashboard_path
        locked_pages_widget = all('div[@class="widget"]').first
        expect(locked_pages_widget).to have_content "Currently locked pages:"
        expect(locked_pages_widget).to have_content a_page.name
        expect(locked_pages_widget).to have_content "Sue Smith"
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools" tools:locale="fr">
  <string name="open_with">Ouvrir avec…</string>
  <string name="add_to_homescreen">Ajouter à l\'écran d\'accueil</string>
  <string name="use_a_different_app">Utiliser une autre application</string>
  <string name="activity_resolver_use_once">Cette fois seulement</string>
  <string name="activity_resolver_use_always">Toujours</string>
  <string name="which_view_application">Ouvrir avec</string>
  <string name="which_view_application_named">Ouvrir avec %1$s</string>
  <string name="desc_preferred">Applications préférées à utiliser lorsque les liens ci-dessous sont partagés avec cette application.\n\nAppuyer pour retirer une application préférée.</string>
  <string name="desc_preferred_empty">Applications préférées à utiliser lorsque les liens ci-dessous sont partagés avec cette application.\n\nVous pouvez définir des applications préférées en partageant des liens avec cette application et en choisissant alors \"Toujours\"</string>
  <string name="title_remove_preferred">Supprimer l\'application préférée?</string>
  <string name="message_remove_preferred"><![CDATA[Ne plus ouvrir les liens de %2$s avec %1$s ?

Note:Vous pouvez définir une nouvelle application préférée à utiliser pour les prochains lien de %3$s.    ]]></string>
  <string name="error_invalid_url">Le contenu partagé n\'avait aucune URL valide.</string>
  <string name="empty_resolver_activity">Aucune autre application n\'a été trouvé pour traiter l\'URL.</string>
  <string name="warning_open_link_with_name">Ouverture du lien avec %s.</string>
  <string name="pref_title_general">Paramètres généraux</string>
  <string name="pref_title_about">À propos</string>
  <string name="pref_summary_about">Revoir le tutoriel.</string>
  <string name="pref_summary_preferred">Changer les paramètres d\'applications préférées.</string>
  <string name="browser_title">Navigateurs</string>
  <string name="browser_description">Lorsqu\'un lien est partagé avec Open Link With, des navigateurs sont proposés en plus des applications natives. \n\n Sélectionnez ci-dessous pour pour modifier ce comportement.</string>
  <string name="browser_none">Cacher des navigateurs</string>
  <string name="browser_none_description">Ne jamais suggérer de navigateur. Seulement des applications natives.</string>
  <string name="browser_always_ask">Toujours demander</string>
  <string name="browser_always_ask_description">Inclure tous les navigateurs dans la liste des applications suggérées</string>
  <string name="pref_summary_selected_browser">Seulement %s seront suggérés</string>
  <string name="pref_title_usage_stats">Statistiques d\'utilisation</string>
  <string name="pref_summary_usage_stats">Améliorez le tri de l\'application en lui donnant accès aux statistiques d\'utilisation.</string>
  <string name="pref_title_category_display">Affichage</string>
  <string name="pref_title_night_mode">Mode Nuit</string>
  <string name="pref_entry_night_mode_off">Clair</string>
  <string name="pref_entry_night_mode_on">Sombre</string>
  <string name="pref_entry_night_mode_battery">Activé par l\'économiseur de batterie</string>
  <string name="pref_entry_night_mode_system">Utiliser les paramètres par défaut</string>
  <string name="pref_title_category_clipboard">Lien copié</string>
  <string name="pref_title_clipboard">Cliquez pour ouvrir avec…</string>
  <string name="pref_title_category_ask_for_rating">Vous aimez l\'application ?</string>
  <string name="pref_title_ask_for_rating">Si vous appréciez Open Link With, pourriez-vous prendre une minute pour l\'évaluer ? Merci pour votre soutien !</string>
  <string name="ask_for_rating_feedback">Des commentaires ?</string>
  <string name="ask_for_rating_feedback_message">Pourriez-vous me donner plus de détails?</string>
  <string name="ask_for_rating_feedback_email_subject">Commentaires concernant Open Link With</string>
  <string name="ask_for_rating_rating_positive_button">Évaluer</string>
  <string name="ask_for_rating_rating_message">Veuillez trouver la section « Évaluer cette application » dans le Play Store pour noter.\n\nMerci pour le soutien ! 🎉</string>
  <string name="pref_title_category_advanced">Avancé</string>
  <string name="pref_title_features">Fonctionnalités de l\'application</string>
  <string name="pref_summary_features">Activer/Désactiver certaines fonctionnalités</string>
  <string name="pref_details_feature_add_to_homescreen"><![CDATA[    Utilisez Ajouter à l\'écran d\'accueil pour accéder rapidement à vos liens favoris avec vos applications favorites.

    Lorsqu\'il est activé, cette fonctionnalité ajoute Ajouter à l\'écran d\'accueil à votre système Partagez le menu .

    Lorsque sélectionné, vous aurez la possibilité d\'ajouter le lien partagé à votre écran d\'accueil.
  ]]></string>
  <string name="pref_title_feature_text_selection">Sélection de texte</string>
  <string name="pref_details_feature_text_selection"><![CDATA[    Lorsqu\'elle est activée, cette fonctionnalité ajoute l\'option Ouvrir avec dans la fenêtre pop-up de sélection du système.

    Cette fonctionnalité peut être utile dans des situations où le partage de lien n\'est pas réalisable. Lorsque le lien est déjà visible dans un champ de texte, appuyez longuement pour le sélectionner et cliquez sur Ouvrir avec.
  ]]></string>
  <string name="pref_title_feature_direct_share">Partage direct</string>
  <string name="pref_details_feature_direct_share"><![CDATA[    Partage Direct est une fonctionnalité Android où des cibles de partage plus pertinentes sont présentées séparément dans le menu de partage.

    Lorsqu\'il est activé, Open Link With sera présenté en haut du menu de partage du système.

    Notez également que la priorité est réglée sur faible. Si Android trouve des apps plus pertinentes , Open Link With peut ne pas être proposée.
  ]]></string>
  <string name="pref_title_feature_browser">Définir comme navigateur</string>
  <string name="pref_details_feature_browser"><![CDATA[    Attention : Fonctionnalité expérimentale !

    Permet à Android de reconnaître Open Link With comme un navigateur .

    Si activé, utiliser "partager" ne sera pas nécessaire, juste cliquer sur des liens déclenchera Open Link With et ouvrira le lien
     dans l\'application native. Il déraccourcira également tout lien raccourci.

    Soyez prudent ! Puisque Chrome (ou votre navigateur favori) ne sera plus navigateur par défaut, vous pouvez remarquer
     changements de comportement. L\'avantage c\'est que votre téléphone gérera mieux les ouvertures de liens vers des applications natives.
  ]]></string>
  <string name="pref_title_feature_clean_urls">Clean-up links</string>
  <string name="pref_details_feature_clean_urls"><![CDATA[    When enabled, Open Link With will clean-up advertisement related tracking parameters from shared links.

    Links will be cleaned up according to the Regex rule provided.
  ]]></string>
  <string name="clean_urls_regex_hint">Regex style rule</string>
  <string name="pref_title_feature_caller_app">Détecter les applications au premier plan</string>
  <string name="pref_details_feature_caller_app"><![CDATA[    Attention : Fonctionnalité expérimentale !

    Lorsqu\'il est activé, l\'application de premier plan (Celle depuis laquelle vous avez partagé le lien) ne sera pas suggérée.

    Exemple: quand vous partagez à partir du navigateur, celui-ci ne sera pas suggéré à nouveau. Si aucune application native n\'est trouvée, vous verrez un message d\'avertissement.

    Si non activé, l\'application de premier plan sera suggérée même si elle est déjà ouverte.
  ]]></string>
  <string name="feature_default_browser_message"><![CDATA[    Dans la fenêtre suivante, sélectionnez Open Link With, puis sélectionnez Toujours.
  ]]></string>
  <string name="pref_state_feature_enabled">Activé(e)</string>
  <string name="pref_state_feature_disabled">Désactivé(e)</string>
  <string name="pref_title_category_others">Autres</string>
  <string name="pref_title_open_source">Licences open source</string>
  <string name="pref_summary_open_source">Voir les licences des bibliothèques open source.</string>
  <string name="pref_title_contact">Contactez moi</string>
  <string name="pref_summary_contact">Envoyez-moi un email avant de mettre 1 étoile.</string>
  <string name="pref_title_market">Plus d\'applications par Said Tahsin Dane</string>
  <string name="pref_summary_market">Vous aimez ? Pourquoi ne pas jeter un œil à mes autres applications ?</string>
  <string name="pref_title_version">Version</string>
  <string name="error">Erreur</string>
  <string name="error_usage_access_not_found">Les paramètres des habitudes d\'utilisation ne peuvent pas être ouverts.\n\nVous pouvez y accéder en allant dans Paramètres -> Sécurité</string>
  <string name="error_cannot_start_activity">Échec de l\'ouverture du lien avec l\'application sélectionnée. Réessayez plus tard.</string>
  <string name="add">Ajouter</string>
  <string name="cancel">Annuler</string>
  <string name="add_to_home_screen_dialog_hint">Nom du raccourci</string>
  <string name="add_to_home_screen_error">Cet appareil ne supporte pas les raccourcis !</string>
</resources>


text:
#include "leveldb/db.h"
#include <json/json.h>

#include <array>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// clang-format off
#include "scv/scv_util.h"
#include "scv/scv_introspection.h"
#include "scv/scv_tr.h"
// clang-format on
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
using namespace std;
using namespace leveldb;
using namespace Json;

#ifdef _MSC_VER
#define scv_tr_TEXT_LLU "%I64u"
#define scv_tr_TEXT_LLX "%I64x"
#define scv_tr_TEXT_16LLX "%016I64x"
#else
#define scv_tr_TEXT_LLU "%llu"
#define scv_tr_TEXT_LLX "%llx"
#define scv_tr_TEXT_16LLX "%016lx"
#endif

// ----------------------------------------------------------------------------
enum EventType { BEGIN, RECORD, END };
const char* EventTypeStr[] = {"BEGIN", "RECORD", "END"};
using data_type = scv_extensions_if::data_type;
// ----------------------------------------------------------------------------
namespace {

struct Database {

    Database(const string& name)
    : key_len(1024) {
        wbuilder.settings_["indentation"] = "";
        CharReaderBuilder::strictMode(&rbuilder.settings_);
        Options options;
        options.create_if_missing = true;
        options.compression = kSnappyCompression;
        DestroyDB(name, options);
        if(!DB::Open(options, name, &db).ok())
            throw runtime_error("Could not create database");
        key_buf = new char[key_len];
    }

    ~Database() {
        delete db;
        delete key_buf;
    }
    /**
     *
     * @param key   the database key
     * @param val   the JSON Value to write
     */
    inline bool writeEntry(string& key, Value& val) {
        return db->Put(write_options, Slice(key.c_str(), key.size()), writeString(wbuilder, val)).ok();
    }
    /**
     *
     * @param key   the database key
     * @param val   the JSON Value to write
     */
    inline bool writeEntry(string&& key, Value& val) {
        return db->Put(write_options, Slice(key.c_str(), key.size()), writeString(wbuilder, val)).ok();
    }
    /**
     *
     * @param id    stream id
     * @param name  stream name
     * @param kind  stream kind
     */
    inline void writeStream(uint64_t id, string name, string kind) {
        auto len = sprintf(key_buf, "s~" scv_tr_TEXT_16LLX, id);
        Value node{objectValue};
        node["id"] = id;
        node["name"] = name;
        node["kind"] = kind;
        db->Put(write_options, Slice(key_buf, len), writeString(wbuilder, node));
    }
    /**
     *
     * @param id        generator id
     * @param name
     * @param stream
     */
    inline void writeGenerator(uint64_t id, string name, uint64_t stream) {
        auto len = sprintf(key_buf, "sg~" scv_tr_TEXT_16LLX "~" scv_tr_TEXT_16LLX, stream, id);
        Value node{objectValue};
        node["id"] = id;
        node["name"] = name;
        node["stream"] = stream;
        db->Put(write_options, Slice(key_buf, len), writeString(wbuilder, node));
    }
    /**
     *
     * @param id        transaction id
     * @param generator
     * @param concurrencyLevel
     */
    inline void writeTransaction(uint64_t id, uint64_t stream_id, uint64_t generator_id, uint64_t concurrencyLevel) {
        Value val{objectValue};
        val["id"] = id;
        val["s"] = stream_id;
        val["g"] = generator_id;
        val["conc"] = concurrencyLevel;
        db->Put(write_options,
                Slice(key_buf, sprintf(key_buf, "sgx~" scv_tr_TEXT_16LLX "~" scv_tr_TEXT_16LLX "~" scv_tr_TEXT_16LLX,
                                       stream_id, generator_id, id)),
                "");
        tx_lut[id] = val;
        // db->Put(write_options, Slice(key, sprintf(key, "x~" scv_tr_TEXT_16LLX, id)), writeString(wbuilder, val));
    }
    /**
     *
     * @param id        transaction id
     * @param streamid  stream transaction id
     * @param type
     * @param time
     */
    inline void writeTxTimepoint(uint64_t id, uint64_t streamid, EventType type, uint64_t time) {
        string value;
        Value node{arrayValue};
        auto len =
            sprintf(key_buf, "st~" scv_tr_TEXT_16LLX "~" scv_tr_TEXT_16LLX "~%s", streamid, time, EventTypeStr[type]);
        if(db->Get(read_options, key_buf, &value).ok() &&
           rbuilder.newCharReader()->parse(value.data(), value.data() + value.size(), &node, nullptr)) {
            node[node.size()] = Value(id);
        } else {
            node[0u] = Value(id);
        }
        db->Put(write_options, Slice(key_buf, len), writeString(wbuilder, node));
        updateTx(id, type, time);
    }

    inline void updateTx(uint64_t id, EventType type, uint64_t time) {
        static const char* typeStr[] = {"START_TIME", "", "END_TIME"};
        auto& node = tx_lut[id];
        node[typeStr[type]] = time;
        if(type == END) {
            db->Put(write_options, Slice(key_buf, sprintf(key_buf, "x~" scv_tr_TEXT_16LLX, id)),
                    writeString(wbuilder, node));
            tx_lut.erase(id);
        }
    }

    inline void updateTx(uint64_t id, Value&& val) {
        auto len = sprintf(key_buf, "x~" scv_tr_TEXT_16LLX, id);
        auto& node = tx_lut[id];
        auto& arrNode = node["attr"];
        if(arrNode.isNull()) {
            Value newNode{arrayValue};
            newNode.append(val);
            node["attr"] = newNode;
        } else {
            arrNode.append(val);
        }
    }

    /**
     *
     * @param id        transaction id
     * @param event
     * @param name
     * @param type
     * @param value
     */
    inline void writeAttribute(uint64_t id, EventType event, const string& name, data_type type, const string& value) {
        Value val;
        val["name"] = name;
        val["type"] = type;
        val["value"] = value;
        val["assoc"] = event;
        updateTx(id, move(val));
    }
    /**
     *
     * @param id        transaction id
     * @param event
     * @param name
     * @param type
     * @param value
     */
    inline void writeAttribute(uint64_t id, EventType event, const string& name, data_type type, uint64_t value) {
        Value val;
        val["name"] = name;
        val["type"] = type;
        val["value"] = value;
        val["assoc"] = event;
        updateTx(id, move(val));
    }
    /**
     *
     * @param id        transaction id
     * @param event
     * @param name
     * @param type
     * @param value
     */
    inline void writeAttribute(uint64_t id, EventType event, const string& name, data_type type, double value) {
        Value val;
        val["name"] = name;
        val["type"] = type;
        val["value"] = value;
        val["assoc"] = event;
        updateTx(id, move(val));
    }
    /**
     *
     * @param name
     * @param sink_id
     * @param src_id
     */
    inline void writeRelation(const string& name, uint64_t sink_id, uint64_t src_id) {
        if(key_len < (name.size() + 32 + 5)) { // reallocate buffer if needed, making sure no buffer overflow
            delete key_buf;
            key_len = name.size() + 32 + 5;
            key_buf = new char[key_len];
        }
        db->Put(write_options,
                Slice(key_buf, sprintf(key_buf, "ro~" scv_tr_TEXT_16LLX "~" scv_tr_TEXT_16LLX "~%s", src_id, sink_id,
                                       name.c_str())),
                "");
        db->Put(write_options,
                Slice(key_buf, sprintf(key_buf, "ri~" scv_tr_TEXT_16LLX "~" scv_tr_TEXT_16LLX "~%s", sink_id, src_id,
                                       name.c_str())),
                "");
    }

private:
    DB* db;
    ReadOptions read_options;
    WriteOptions write_options;
    char* key_buf;
    size_t key_len;
    StreamWriterBuilder wbuilder;
    CharReaderBuilder rbuilder;
    unordered_map<uint64_t, Value> tx_lut;
};

vector<vector<uint64_t>> concurrencyLevel;

Database* db;

void dbCb(const scv_tr_db& _scv_tr_db, scv_tr_db::callback_reason reason, void* data) {
    // This is called from the scv_tr_db ctor.
    static string fName("DEFAULT_scv_tr_sqlite");
    switch(reason) {
    case scv_tr_db::CREATE:
        if((_scv_tr_db.get_name() != nullptr) && (strlen(_scv_tr_db.get_name()) != 0))
            fName = _scv_tr_db.get_name();
        try {
            db = new Database(fName);
            Value val{objectValue};
            val["resolution"] = (long)(sc_get_time_resolution().to_seconds() * 1e15);
            db->writeEntry("__config", val);
        } catch(runtime_error& e) {
            _scv_message::message(_scv_message::TRANSACTION_RECORDING_INTERNAL, e.what());
        } catch(...) {
            _scv_message::message(_scv_message::TRANSACTION_RECORDING_INTERNAL, "Can't open recording file");
        }
        break;
    case scv_tr_db::DELETE:
        try {
            delete db;
        } catch(...) {
            _scv_message::message(_scv_message::TRANSACTION_RECORDING_INTERNAL, "Can't close recording file");
        }
        break;
    default:
        _scv_message::message(_scv_message::TRANSACTION_RECORDING_INTERNAL, "Unknown reason in scv_tr_db callback");
    }
}
// ----------------------------------------------------------------------------
void streamCb(const scv_tr_stream& s, scv_tr_stream::callback_reason reason, void* data) {
    if(reason == scv_tr_stream::CREATE) {
        try {
            db->writeStream(s.get_id(), s.get_name(), s.get_stream_kind());
        } catch(runtime_error& e) {
            _scv_message::message(_scv_message::TRANSACTION_RECORDING_INTERNAL, "Can't create stream");
        }
    }
}
// ----------------------------------------------------------------------------
void recordAttribute(uint64_t id, EventType event, const string& name, data_type type, const string& value) {
    try {
        db->writeAttribute(id, event, name, type, value);
    } catch(runtime_error& e) {
        _scv_message::message(_scv_message::TRANSACTION_RECORDING_INTERNAL, "Can't create attribute entry");
    }
}
// ----------------------------------------------------------------------------
void recordAttribute(uint64_t id, EventType event, const string& name, data_type type, long long value) {
    try {
        db->writeAttribute(id, event, name, type, static_cast<uint64_t>(value));
    } catch(runtime_error& e) {
        _scv_message::message(_scv_message::TRANSACTION_RECORDING_INTERNAL, "Can't create attribute entry");
    }
}
// ----------------------------------------------------------------------------
inline void recordAttribute(uint64_t id, EventType event, const string& name, data_type type, double value) {
    try {
        db->writeAttribute(id, event, name, type, value);
    } catch(runtime_error& e) {
        _scv_message::message(_scv_message::TRANSACTION_RECORDING_INTERNAL, "Can't create attribute entry");
    }
}
// ----------------------------------------------------------------------------
void recordAttributes(uint64_t id, EventType eventType, string& prefix, const scv_extensions_if* my_exts_p) {
    if(my_exts_p == nullptr)
        return;
    string name;
    if(prefix == "") {
        name = my_exts_p->get_name();
    } else {
        if((my_exts_p->get_name() == nullptr) || (strlen(my_exts_p->get_name()) == 0)) {
            name = prefix;
        } else {
            name = prefix + "." + my_exts_p->get_name();
        }
    }
    if(name == "")
        name = "<unnamed>";
    switch(my_exts_p->get_type()) {
    case scv_extensions_if::RECORD: {
        int num_fields = my_exts_p->get_num_fields();
        if(num_fields > 0) {
            for(int field_counter = 0; field_counter < num_fields; field_counter++) {
                const scv_extensions_if* field_data_p = my_exts_p->get_field(field_counter);
                recordAttributes(id, eventType, prefix, field_data_p);
            }
        }
    } break;
    case scv_extensions_if::ENUMERATION:
        recordAttribute(id, eventType, name, scv_extensions_if::ENUMERATION,
                        my_exts_p->get_enum_string((int)(my_exts_p->get_integer())));
        break;
    case scv_extensions_if::BOOLEAN:
        recordAttribute(id, eventType, name, scv_extensions_if::BOOLEAN, my_exts_p->get_bool() ? "TRUE" : "FALSE");
        break;
    case scv_extensions_if::INTEGER:
    case scv_extensions_if::FIXED_POINT_INTEGER:
        recordAttribute(id, eventType, name, scv_extensions_if::INTEGER, my_exts_p->get_integer());
        break;
    case scv_extensions_if::UNSIGNED:
        recordAttribute(id, eventType, name, scv_extensions_if::UNSIGNED, my_exts_p->get_integer());
        break;
    case scv_extensions_if::POINTER:
        recordAttribute(id, eventType, name, scv_extensions_if::POINTER, (long long)my_exts_p->get_pointer());
        break;
    case scv_extensions_if::STRING:
        recordAttribute(id, eventType, name, scv_extensions_if::STRING, my_exts_p->get_string());
        break;
    case scv_extensions_if::FLOATING_POINT_NUMBER:
        recordAttribute(id, eventType, name, scv_extensions_if::FLOATING_POINT_NUMBER, my_exts_p->get_double());
        break;
    case scv_extensions_if::BIT_VECTOR: {
        sc_bv_base tmp_bv(my_exts_p->get_bitwidth());
        my_exts_p->get_value(tmp_bv);
        recordAttribute(id, eventType, name, scv_extensions_if::BIT_VECTOR, tmp_bv.to_string());
    } break;
    case scv_extensions_if::LOGIC_VECTOR: {
        sc_lv_base tmp_lv(my_exts_p->get_bitwidth());
        my_exts_p->get_value(tmp_lv);
        recordAttribute(id, eventType, name, scv_extensions_if::LOGIC_VECTOR, tmp_lv.to_string());
    } break;
    case scv_extensions_if::ARRAY:
        for(int array_elt_index = 0; array_elt_index < my_exts_p->get_array_size(); array_elt_index++) {
            const scv_extensions_if* field_data_p = my_exts_p->get_array_elt(array_elt_index);
            recordAttributes(id, eventType, prefix, field_data_p);
        }
        break;
    default: {
        array<char, 100> tmpString;
        sprintf(tmpString.data(), "Unsupported attribute type = %d", my_exts_p->get_type());
        _scv_message::message(_scv_message::TRANSACTION_RECORDING_INTERNAL, tmpString.data());
    }
    }
}
// ----------------------------------------------------------------------------
void generatorCb(const scv_tr_generator_base& g, scv_tr_generator_base::callback_reason reason, void* data) {
    if(reason == scv_tr_generator_base::CREATE && db) {
        try {
            db->writeGenerator(g.get_id(), g.get_name(), g.get_scv_tr_stream().get_id());
        } catch(runtime_error& e) {
            _scv_message::message(_scv_message::TRANSACTION_RECORDING_INTERNAL, "Can't create generator entry");
        }
    }
}
// ----------------------------------------------------------------------------
void transactionCb(const scv_tr_handle& t, scv_tr_handle::callback_reason reason, void* data) {
    if(!db)
        return;
    if(t.get_scv_tr_stream().get_scv_tr_db() == nullptr)
        return;
    if(t.get_scv_tr_stream().get_scv_tr_db()->get_recording() == false)
        return;

    uint64_t id = t.get_id();
    uint64_t streamId = t.get_scv_tr_stream().get_id();
    vector<uint64_t>::size_type concurrencyIdx;
    const scv_extensions_if* my_exts_p;
    switch(reason) {
    case scv_tr_handle::BEGIN: {
        try {
            if(concurrencyLevel.size() <= streamId)
                concurrencyLevel.resize(streamId + 1);
            vector<uint64_t>& levels = concurrencyLevel.at(streamId);
            for(concurrencyIdx = 0; concurrencyIdx < levels.size(); ++concurrencyIdx) // find a free slot
                if(levels[concurrencyIdx] == 0)
                    break;
            if(concurrencyIdx == levels.size())
                levels.push_back(id);
            else
                levels[concurrencyIdx] = id;
            db->writeTransaction(id, t.get_scv_tr_stream().get_id(), t.get_scv_tr_generator_base().get_id(),
                                 concurrencyIdx);
            db->writeTxTimepoint(id, t.get_scv_tr_stream().get_id(), BEGIN, t.get_begin_sc_time().value());
        } catch(runtime_error& e) {
            _scv_message::message(_scv_message::TRANSACTION_RECORDING_INTERNAL, e.what());
        }
        my_exts_p = t.get_begin_exts_p();
        if(my_exts_p == nullptr)
            my_exts_p = t.get_scv_tr_generator_base().get_begin_exts_p();
        if(my_exts_p) {
            string tmp_str = t.get_scv_tr_generator_base().get_begin_attribute_name()
                                 ? t.get_scv_tr_generator_base().get_begin_attribute_name()
                                 : "";
            recordAttributes(id, BEGIN, tmp_str, my_exts_p);
        }
    } break;
    case scv_tr_handle::END: {
        my_exts_p = t.get_end_exts_p();
        if(my_exts_p == nullptr)
            my_exts_p = t.get_scv_tr_generator_base().get_end_exts_p();
        if(my_exts_p) {
            string tmp_str = t.get_scv_tr_generator_base().get_end_attribute_name()
                                 ? t.get_scv_tr_generator_base().get_end_attribute_name()
                                 : "";
            recordAttributes(t.get_id(), END, tmp_str, my_exts_p);
        }
        try {
            db->writeTxTimepoint(id, t.get_scv_tr_stream().get_id(), END, t.get_end_sc_time().value());
            vector<uint64_t>& levels = concurrencyLevel[streamId];
            for(concurrencyIdx = 0; concurrencyIdx < levels.size(); ++concurrencyIdx)
                if(levels[concurrencyIdx] == id)
                    break;
            if(concurrencyIdx == levels.size())
                levels.push_back(0);
            else
                levels[concurrencyIdx] = 0;
        } catch(runtime_error& e) {
            _scv_message::message(_scv_message::TRANSACTION_RECORDING_INTERNAL, "Can't create transaction end");
        }
    } break;
    default:;
    }
}
// ----------------------------------------------------------------------------
void attributeCb(const scv_tr_handle& t, const char* name, const scv_extensions_if* ext, void* data) {
    if(!db)
        return;
    if(t.get_scv_tr_stream().get_scv_tr_db() == nullptr)
        return;
    if(t.get_scv_tr_stream().get_scv_tr_db()->get_recording() == false)
        return;
    string tmp_str(name == nullptr ? "" : name);
    recordAttributes(t.get_id(), RECORD, tmp_str, ext);
}
// ----------------------------------------------------------------------------
void relationCb(const scv_tr_handle& tr_1, const scv_tr_handle& tr_2, void* data,
                scv_tr_relation_handle_t relation_handle) {
    if(!db)
        return;
    if(tr_1.get_scv_tr_stream().get_scv_tr_db() == nullptr)
        return;
    if(tr_1.get_scv_tr_stream().get_scv_tr_db()->get_recording() == false)
        return;
    try {
        db->writeRelation(tr_1.get_scv_tr_stream().get_scv_tr_db()->get_relation_name(relation_handle), tr_1.get_id(),
                          tr_2.get_id());
    } catch(runtime_error& e) {
        _scv_message::message(_scv_message::TRANSACTION_RECORDING_INTERNAL, "Can't create transaction relation");
    }
}
} // namespace
// ----------------------------------------------------------------------------
void scv_tr_ldb_init() {
    scv_tr_db::register_class_cb(dbCb);
    scv_tr_stream::register_class_cb(streamCb);
    scv_tr_generator_base::register_class_cb(generatorCb);
    scv_tr_handle::register_class_cb(transactionCb);
    scv_tr_handle::register_record_attribute_cb(attributeCb);
    scv_tr_handle::register_relation_cb(relationCb);
}
// ----------------------------------------------------------------------------


text:
'use strict';

module.exports = function (t, a) {
	a(t('arar'), false, "String");
	a(t(12), false, "Number");
	a(t(true), false, "Boolean");
	a(t(new Date()), false, "Date");
	a(t(new String('raz')), false, "String object");
	a(t({}), false, "Plain object");
	a(t(/a/), true, "Regular expression");
	a(t(new RegExp('a')), true, "Regular expression via constructor");
};


text:
var start,
    end,
    struct = {},
    struct_size = 5000,
    map = new Map(),
    i = 0,
    nr_objects = 0;

function initStruct() {
  struct = {};
  for (i = 0; i < struct_size; i++) {
    struct[i] = i;
    nr_objects++;
  }
}

function initMap() {
  map = new Map();
  for (i = 0; i < struct_size; i++) {
    map.set(i, i);
    nr_objects++;
  }
}

function objKeyCountTest() {
  initStruct();

  start = +new Date();
  for (i = 0; i < struct_size; i++) {
    var blahoo = Object.keys(struct).length;
    // var blahoo = nr_objects;
  }
  end = +new Date();
  console.log("Counting length of struct " + struct_size + " times took " + (end-start) + " ms.");
}

function objMapCountTest() {
  initMap();

  start = +new Date();
  for (i = 0; i < struct_size; i++) {
    var size = map.size;
  }
  end = +new Date();
  console.log("Counting size of Map " + struct_size + " times took " + (end-start) + " ms.");
}

function deleteKeysViaOperatorTest() {
    initStruct();
    start = +new Date();
    for (i = 0; i < struct_size; i++) {
      delete struct[i];
    }
    end = +new Date();
    console.log("Deleting all " + struct_size + " keys in struct via delete operator took " + (end-start) + " ms.");
}

function deleteKeysViaDeleteMethod() {
    initMap();
    start = +new Date();
    for (i = 0; i < struct_size; i++) {
      map.delete(i);
    }
    end = +new Date();
    console.log("Deleting all " + struct_size + " keys in Map via delete method took " + (end-start) + " ms.");
}

function setKeysUndefinedTest() {
    initStruct();
    start = +new Date();
    for (i = 0; i < struct_size; i++) {
      struct[i] = undefined;
    }
    end = +new Date();
    console.log("Setting all " + struct_size + " keys in struct undefined took " + (end-start) + " ms.");
}

function runTests() {
  objKeyCountTest();
  objMapCountTest();
  deleteKeysViaOperatorTest();
  deleteKeysViaDeleteMethod();
  setKeysUndefinedTest();
}

// runTests();


text:
typedef struct
{
    unsigned char data[GD20HM303D_FIFO_THRESH * GD20HM303D_FIFO_CHUNK_SIZE];
    int count;                                              // number of chunks in the cache block
    int index;                                              // current index into the cache
    unsigned char accel[6];                                 // the raw accel readings for the block
    unsigned char compass[6];                               // the raw compass readings for the block

} GD20HM303D_CACHE_BLOCK;

#endif

class RTIMUGD20HM303D : public RTIMU
{
public:
    RTIMUGD20HM303D(RTIMUSettings *settings);
    ~RTIMUGD20HM303D();

    virtual const char *IMUName() { return "L3GD20H + LSM303D"; }
    virtual int IMUType() { return RTIMU_TYPE_GD20HM303D; }
    virtual bool IMUInit();
    virtual int IMUGetPollInterval();
    virtual bool IMURead();

private:
    bool setGyroSampleRate();
    bool setGyroCTRL2();
    bool setGyroCTRL4();
    bool setGyroCTRL5();
    bool setAccelCTRL1();
    bool setAccelCTRL2();
    bool setCompassCTRL5();
    bool setCompassCTRL6();
    bool setCompassCTRL7();

    unsigned char m_gyroSlaveAddr;                          // I2C address of L3GD20H
    unsigned char m_accelCompassSlaveAddr;                  // I2C address of LSM303D

    RTFLOAT m_gyroScale;
    RTFLOAT m_accelScale;
    RTFLOAT m_compassScale;

#ifdef GD20HM303D_CACHE_MODE
    bool m_firstTime;                                       // if first sample

    GD20HM303D_CACHE_BLOCK m_cache[GD20HM303D_CACHE_BLOCK_COUNT]; // the cache itself
    int m_cacheIn;                                          // the in index
    int m_cacheOut;                                         // the out index
    int m_cacheCount;                                       // number of used cache blocks

#endif
};

#endif // _RTIMUGD20HM303D_H


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-view-portfolio',
  templateUrl: './view-portfolio.component.html',
  styleUrls: ['./view-portfolio.component.css']
})
export class ViewPortfolioComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
<?php

if(!isset($this->session->userdata['sess_id'])){

redirect('direct/studentlogin');
}
?>

<!doctype html>

<meta charset="utf-8">
<title>Update</title>
<link href="<?php echo base_url('assets/TIMS.css')?>" rel="stylesheet">
<link href="<?php echo base_url('assets/admission.css')?>" rel="stylesheet">

<?php
foreach ($profile as $row){
?>

<a href="<?php echo base_url('direct/teacherdashboard')?>"><img src="<?php echo base_url('assets/images/LOGO1.png')?>" id="Image1" alt="">

<a href="<?php echo base_url('direct/teacherdashboard')?>" target="_self">HOME

<a href="<?php echo base_url('teacherActivity/showTeacher')?>" target="_self">ATTENDANCE

<a href="<?php echo base_url('teacherActivity/logout')?>" target="_self">LOGOUT

 UPDATE

						<form name="updateform" action="<?php echo base_url('teacherActivity/teacherModify');?>" method="post">
							<input type="hidden" value="<?php  echo $row->tid; ?>" name="tid" class="form-control" id="id" required="required"/>
							Firstname:
							<input type="text" id="fname" name="firstname" value="<?php echo $row->firstname; ?>" />

							Lastname:
							<input type="text" id="lname" name="lastname" value="<?php echo $row->lastname; ?>"/>

							Contact:
							<input type="text" id="contact" name="contact" value="<?php echo $row->phnNumber; ?>" />

							username:
							<input type="text" id="username" name="uname" value="<?php echo $row->username; ?>"/>

							password:
							<input type="password" id="password" name="pword" value="<?php echo $row->password; ?>"/>

							Re-enter
							<input type="password" id="rpword" name="rpword" placeholder="Re-enter your Password"/>

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

							<a href="<?php echo base_url('direct/studentDashboard')?>"><img src="<?php echo base_url('assets/images/img0019.png')?>">

						</form>
						<?php
					}

				?>

Copyright © 2017 Kathmandu TIMS | Privacy policy


text:
using System;
using System.Buffers;
using System.IO;
using System.IO.Pipelines;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Internal;

#nullable enable

namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal;

internal class DuplexPipeStream : Stream
{
    private readonly PipeReader _input;
    private readonly PipeWriter _output;
    private readonly bool _throwOnCancelled;
    private volatile bool _cancelCalled;

    public DuplexPipeStream(PipeReader input, PipeWriter output, bool throwOnCancelled = false)
    {
        _input = input;
        _output = output;
        _throwOnCancelled = throwOnCancelled;
    }

    public void CancelPendingRead()
    {
        _cancelCalled = true;
        _input.CancelPendingRead();
    }

    public override bool CanRead => true;

    public override bool CanSeek => false;

    public override bool CanWrite => true;

    public override long Length
    {
        get
        {
            throw new NotSupportedException();
        }
    }

    public override long Position
    {
        get
        {
            throw new NotSupportedException();
        }
        set
        {
            throw new NotSupportedException();
        }
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        throw new NotSupportedException();
    }

    public override void SetLength(long value)
    {
        throw new NotSupportedException();
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        ValueTask<int> vt = ReadAsyncInternal(new Memory<byte>(buffer, offset, count), default);
        return vt.IsCompleted ?
            vt.Result :
            vt.AsTask().GetAwaiter().GetResult();
    }

    public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken = default)
    {
        return ReadAsyncInternal(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask();
    }

    public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default)
    {
        return ReadAsyncInternal(destination, cancellationToken);
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        WriteAsync(buffer, offset, count).GetAwaiter().GetResult();
    }

    public override Task WriteAsync(byte[]? buffer, int offset, int count, CancellationToken cancellationToken)
    {
        return _output.WriteAsync(buffer.AsMemory(offset, count), cancellationToken).GetAsTask();
    }

    public override ValueTask WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default)
    {
        return _output.WriteAsync(source, cancellationToken).GetAsValueTask();
    }

    public override void Flush()
    {
        FlushAsync(CancellationToken.None).GetAwaiter().GetResult();
    }

    public override Task FlushAsync(CancellationToken cancellationToken)
    {
        return _output.FlushAsync(cancellationToken).GetAsTask();
    }

    [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))]
    private async ValueTask<int> ReadAsyncInternal(Memory<byte> destination, CancellationToken cancellationToken)
    {
        while (true)
        {
            var result = await _input.ReadAsync(cancellationToken);
            var readableBuffer = result.Buffer;
            try
            {
                if (_throwOnCancelled && result.IsCanceled && _cancelCalled)
                {
                    // Reset the bool
                    _cancelCalled = false;
                    throw new OperationCanceledException();
                }

                if (!readableBuffer.IsEmpty)
                {
                    // buffer.Count is int
                    var count = (int)Math.Min(readableBuffer.Length, destination.Length);
                    readableBuffer = readableBuffer.Slice(0, count);
                    readableBuffer.CopyTo(destination.Span);
                    return count;
                }

                if (result.IsCompleted)
                {
                    return 0;
                }
            }
            finally
            {
                _input.AdvanceTo(readableBuffer.End, readableBuffer.End);
            }
        }
    }

    public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
    {
        return TaskToApm.Begin(ReadAsync(buffer, offset, count), callback, state);
    }

    public override int EndRead(IAsyncResult asyncResult)
    {
        return TaskToApm.End<int>(asyncResult);
    }

    public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
    {
        return TaskToApm.Begin(WriteAsync(buffer, offset, count), callback, state);
    }

    public override void EndWrite(IAsyncResult asyncResult)
    {
        TaskToApm.End(asyncResult);
    }
}


text:
import React from "react";

/**
 * ListItem
 */

class ListItem extends React.Component {
  render() {
    let props = this.props;
    return (

        { props.item.name }
        <button onClick={ props.onRemove }>Remove</button>

    );
  }
};

/**
 * List
 */

class List extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [
        {"name": "Barry"},
        {"name": "Trevor"}
      ]
    };
  }

  componentDidMount() {
    this.input = this.refs.input.getDOMNode();
  }

  removeItem(e) {
    e.preventDefault();
    let el = e.target.parentElement;
    let item = el.getAttribute('data-item');
    let { items } = this.state;

    let updatedItems = items.filter((target) => {
      return JSON.stringify(target) !== item;
    });

    this.setState({
      items: updatedItems
    });
  }

  addItem(e){
    e.preventDefault();
    let val = this.input.value;
    if (!val) return;
    this.input.value = "";

    let { items } = this.state;
    items.push({"name": val})
    this.setState({ items: items });
  }

  reverseItems(){
    let { items } = this.state;
    this.setState({ items: items.reverse() });
  }

  sortItems(){
    let { items } = this.state;

    let sorted = items.sort((a, b) => {
      a = a.name.toLowerCase();
      b = b.name.toLowerCase();
      if (a > b) return 1;
      if (a < b) return -1;
      return 0;
    });

    this.setState({ items: sorted });
  }

  renderItem(item) {
    return (
      <ListItem item={item} onRemove={ this.removeItem.bind(this) }></ListItem>
    );
  }

  render() {
    let { items } = this.state;

    return (

          { items.map(this.renderItem.bind(this)) }

        <input ref="input" type="text"/>
        <button type="button" onClick={ this.addItem.bind(this) }>Add</button>
        <button type="button" onClick={ this.reverseItems.bind(this) }>Reverse</button>
        <button type="button" onClick={ this.sortItems.bind(this) }>Sort</button>

    );
  }
};

React.render(<List />, document.body);


text:
{% extends "interface/base.html" %}
{% load staticfiles %}

    {% block header %}
        {{block.super}}
    {% endblock %}

    {% block content %}

    {% if error %}

Error: {{error}}

    {% endif %}

Enter a Username and Password to join

            <form role="form" name="register_form" action="{% url 'interface:register' %}" method="POST">
                    {% csrf_token %}
                    {{ user_form.as_p}}
                <input id="register_button" class = "btn-primary" type = "submit" value= "Sign Up">
            </form>

    {% endblock content %}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Senparc.Weixin.Context;
using Senparc.Weixin.MP.Entities;

namespace Evolution.Plugins.WeiXin
{
    public class CustomMessageContext: MessageContext<IRequestMessageBase, IResponseMessageBase>
    {
        public CustomMessageContext()
        {
            base.MessageContextRemoved += CustomMessageContext_MessageContextRemoved;
        }

        /// <summary>
        /// 当上下文过期,被移除时触发的时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void CustomMessageContext_MessageContextRemoved(object sender, Senparc.Weixin.Context.WeixinContextRemovedEventArgs<IRequestMessageBase, IResponseMessageBase> e)
        {
            /* 注意,这个事件不是实时触发的(当然你也可以专门写一个线程监控)
             * 为了提高效率,根据WeixinContext中的算法,这里的过期消息会在过期后下一条请求执行之前被清除
             */

            var messageContext = e.MessageContext as CustomMessageContext;
            if (messageContext == null)
            {
                return;//如果是正常的调用,messageContext不会为null
            }

            //TODO:这里根据需要执行消息过期时候的逻辑,下面的代码仅供参考

            //Log.InfoFormat("{0}的消息上下文已过期",e.OpenId);
            //api.SendMessage(e.OpenId, "由于长时间未搭理客服,您的客服状态已退出!");
        }
    }
}


text:
"""
@package ion.agents.platform.exceptions
@file    ion/agents/platform/exceptions.py
@author  Carlos Rueda
@brief   platform related exceptions
"""

__author__ = 'Carlos Rueda'

from pyon.core.exception import IonException

class PlatformException(IonException):
    """
    Base class for platform related exceptions.
    """

    def __init__(self, msg=None, error_code=None, reason=None):
        super(PlatformException, self).__init__()
        self.msg = msg if msg else str(reason) if reason else None
        self.args = (error_code, self.msg)
        self.error_code = error_code
        self.reason = reason

class PlatformConnectionException(PlatformException):
    """
    Exception related to connection with a physical platform
    """
    pass

class PlatformConfigurationException(PlatformException):
    """
    Exception related with the configuration of a platform agent.
    """
    pass

class PlatformDriverException(PlatformException):
    """
    Exception related to basic PlatformDriver functionality or configuration.
    """
    pass

class CannotInstantiateDriverException(PlatformDriverException):
    """
    Platform agent could not create driver.
    """
    pass


text:
code-editor
========

Code editor web component, wrapping CodeMirror

Usage
-----
* Import the code-editor.html into your application
* Insert a `<code-editor>` tag

Example:

```html
<!doctype html>
<html>
<head>
  <link rel="import" href="http://components.geekonaut.de/code-editor/code-editor.html">
</head>
<body>
  <h1>Examples for a code editor</h1>
  <h2>Hardcoded source (editable)</h2>
  <code-editor mode="javascript">
    var msg = "Hello World";
    alert(msg);
  </code-editor>

  <h2>Source loaded from a file</h2>
  <code-editor src="http://components.geekonaut.de/code-editor/code-editor.html" mode="htmlmixed"></code-editor>

  <h2>Using a different theme</h2>
  <code-editor theme="monokai" mode="ruby">puts "Hi"</code-editor>

  <h2>Setting the content from a string</h2>
  <code-editor id="editor" mode="css"></code-editor>
  <script>document.getElementById("editor").srcText = "html, body { height: 100%; }"</script>
</body>
</html>
```


text:
package com.google.common.collect;

import com.google.common.collect.ImmutableClassToInstanceMapTest.Impl;
import com.google.common.collect.ImmutableClassToInstanceMapTest.TestClassToInstanceMapGenerator;
import com.google.common.collect.testing.MapTestSuiteBuilder;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import java.util.Map;
import java.util.Map.Entry;

/**
 * Unit test of {@link MutableClassToInstanceMap}.
 *
 * @author Kevin Bourrillion
 */
public class MutableClassToInstanceMapTest extends TestCase {
  public static Test suite() {
    TestSuite suite = new TestSuite();
    suite.addTestSuite(MutableClassToInstanceMapTest.class);

    suite.addTest(
        MapTestSuiteBuilder.using(
                new TestClassToInstanceMapGenerator() {
                  // Other tests will verify what real, warning-free usage looks like
                  // but here we have to do some serious fudging
                  @Override
                  @SuppressWarnings("unchecked")
                  public Map<Class, Impl> create(Object... elements) {
                    MutableClassToInstanceMap<Impl> map = MutableClassToInstanceMap.create();
                    for (Object object : elements) {
                      Entry<Class, Impl> entry = (Entry<Class, Impl>) object;
                      map.putInstance(entry.getKey(), entry.getValue());
                    }
                    return (Map) map;
                  }
                })
            .named("MutableClassToInstanceMap")
            .withFeatures(
                MapFeature.GENERAL_PURPOSE,
                MapFeature.RESTRICTS_KEYS,
                MapFeature.ALLOWS_NULL_VALUES,
                CollectionSize.ANY,
                CollectionFeature.SERIALIZABLE,
                CollectionFeature.SUPPORTS_ITERATOR_REMOVE,
                MapFeature.ALLOWS_ANY_NULL_QUERIES)
            .createTestSuite());

    return suite;
  }

  private ClassToInstanceMap<Number> map;

  @Override protected void setUp() throws Exception {
    map = MutableClassToInstanceMap.create();
  }

  public void testConstraint() {

    /**
     * We'll give ourselves a pass on testing all the possible ways of
     * breaking the constraint, because we know that newClassMap() is
     * implemented using ConstrainedMap which is itself well-tested.
     * A purist would object to this, but what can I say, we're dirty
     * cheaters.
     */

    map.put(Integer.class, new Integer(5));
    try {
      map.put(Double.class, new Long(42));
      fail();
    } catch (ClassCastException expected) {
    }
    // Won't compile: map.put(String.class, "x");
  }

  public void testPutAndGetInstance() {
    assertNull(map.putInstance(Integer.class, new Integer(5)));

    Integer oldValue = map.putInstance(Integer.class, new Integer(7));
    assertEquals(5, (int) oldValue);

    Integer newValue = map.getInstance(Integer.class);
    assertEquals(7, (int) newValue);

    // Won't compile: map.putInstance(Double.class, new Long(42));
  }

  public void testNull() {
    try {
      map.put(null, new Integer(1));
      fail();
    } catch (NullPointerException expected) {
    }
    map.putInstance(Integer.class, null);
    assertNull(map.get(Integer.class));
    assertNull(map.getInstance(Integer.class));

    map.put(Long.class, null);
    assertNull(map.get(Long.class));
    assertNull(map.getInstance(Long.class));
  }

  public void testPrimitiveAndWrapper() {
    assertNull(map.getInstance(int.class));
    assertNull(map.getInstance(Integer.class));

    assertNull(map.putInstance(int.class, 0));
    assertNull(map.putInstance(Integer.class, 1));
    assertEquals(2, map.size());

    assertEquals(0, (int) map.getInstance(int.class));
    assertEquals(1, (int) map.getInstance(Integer.class));

    assertEquals(0, (int) map.putInstance(int.class, null));
    assertEquals(1, (int) map.putInstance(Integer.class, null));

    assertNull(map.getInstance(int.class));
    assertNull(map.getInstance(Integer.class));
    assertEquals(2, map.size());
  }
}


text:
package iso20022

// Counters of media inside an ATM cassette.
type ATMCassetteCounters2 struct {

	// Type of counters.
	Type *ATMCounterType1Code `xml:"Tp"`

	// Number of added media during servicing operations.
	AddedNumber *Number `xml:"AddedNb,omitempty"`

	// Number of removed media during servicing operations.
	RemovedNumber *Number `xml:"RmvdNb,omitempty"`

	// Total number of media out of the cassette.
	DispensedNumber *Number `xml:"DspnsdNb,omitempty"`

	// Total number of media deposited in the cassette.
	DepositNumber *Number `xml:"DpstNb,omitempty"`

	// Total number of recycled media from the cassette.
	RecycledNumber *Number `xml:"RcycldNb,omitempty"`

	// Total number of retracted media originating from the cassette.
	RetractedNumber *Number `xml:"RtrctdNb,omitempty"`

	// Total number of media from this cassette which are on the reject bin.
	RejectedNumber *Number `xml:"RjctdNb,omitempty"`

	// Total number of media presented to the customer.
	PresentedNumber *Number `xml:"PresntdNb,omitempty"`
}

func (a *ATMCassetteCounters2) SetType(value string) {
	a.Type = (*ATMCounterType1Code)(&value)
}

func (a *ATMCassetteCounters2) SetAddedNumber(value string) {
	a.AddedNumber = (*Number)(&value)
}

func (a *ATMCassetteCounters2) SetRemovedNumber(value string) {
	a.RemovedNumber = (*Number)(&value)
}

func (a *ATMCassetteCounters2) SetDispensedNumber(value string) {
	a.DispensedNumber = (*Number)(&value)
}

func (a *ATMCassetteCounters2) SetDepositNumber(value string) {
	a.DepositNumber = (*Number)(&value)
}

func (a *ATMCassetteCounters2) SetRecycledNumber(value string) {
	a.RecycledNumber = (*Number)(&value)
}

func (a *ATMCassetteCounters2) SetRetractedNumber(value string) {
	a.RetractedNumber = (*Number)(&value)
}

func (a *ATMCassetteCounters2) SetRejectedNumber(value string) {
	a.RejectedNumber = (*Number)(&value)
}

func (a *ATMCassetteCounters2) SetPresentedNumber(value string) {
	a.PresentedNumber = (*Number)(&value)
}


text:
using System;
using System.Collections.Concurrent;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace KinectPlayerTracker.Sockets
{
    /// <summary>
    /// UDP发送器
    /// </summary>
    public class UdpSender : IDisposable
    {
        private bool disposed = false;
        private Thread senderThread;
        private UdpClient udpClient;
        private ConcurrentQueue<byte[]> queue;
        private readonly ManualResetEvent waiter;

        /// <summary>
        /// UDP发送器
        /// </summary>
        /// <param name="sentToAddress">发送目的地址</param>
        /// <param name="sentToPort">发送目的端口</param>
        public UdpSender(string sentToAddress, int sentToPort)
        {
            Address = sentToAddress;
            Port = sentToPort;

            this.Encoding = Encoding.Default;

            queue = new ConcurrentQueue<byte[]>();
            waiter = new ManualResetEvent(false);

            udpClient = new UdpClient();
            udpClient.AllowNatTraversal(true);

            senderThread = new Thread(new ThreadStart(WorkThread));
        }

        /// <summary>
        /// 发送目的地址
        /// </summary>
        public string Address { get; private set; }
        /// <summary>
        /// 发送目的端口
        /// </summary>
        public int Port { get; private set; }
        /// <summary>
        /// 发送器是否正在运行
        /// </summary>
        public bool IsRunning { get; private set; }
        /// <summary>
        /// 发送器所使用的编码
        /// </summary>
        public Encoding Encoding { get; set; }

        /// <summary>
        /// 启动发送器
        /// </summary>
        /// <returns>UDP发送器</returns>
        public UdpSender Start()
        {
            if (!IsRunning)
            {
                IsRunning = true;
                senderThread.Start();
            }
            return this;
        }

        /// <summary>
        /// 停止发送器
        /// </summary>
        /// <returns>UDP发送器</returns>
        public UdpSender Stop()
        {
            IsRunning = false;
            return this;
        }

        /// <summary>
        /// 发送数据报文
        /// </summary>
        /// <param name="datagram">数据报文</param>
        /// <returns>UDP发送器</returns>
        public UdpSender Send(byte[] datagram)
        {
            if (!IsRunning)
                throw new InvalidProgramException("This sender has not been started.");

            queue.Enqueue(datagram);
            waiter.Set();

            return this;
        }

        /// <summary>
        /// 发送数据报文
        /// </summary>
        /// <param name="datagram">数据报文</param>
        /// <returns>UDP发送器</returns>
        public UdpSender Send(string datagram)
        {
            if (!IsRunning)
                throw new InvalidProgramException("This sender has not been started.");

            queue.Enqueue(this.Encoding.GetBytes(datagram));
            waiter.Set();

            return this;
        }

        private void WorkThread()
        {
            while (IsRunning)
            {
                waiter.WaitOne();
                waiter.Reset();

                while (queue.Count > 0)
                {
                    byte[] datagram = null;
                    if (queue.TryDequeue(out datagram))
                    {
                        udpClient.BeginSend(datagram, datagram.Length, Address, Port, SendCompleted, udpClient);
                    }
                }
            }
        }

        private void SendCompleted(IAsyncResult ar)
        {
            UdpClient udp = ar.AsyncState as UdpClient;
            if (udp != null)
            {
                udp.EndSend(ar);
            }
        }

        #region IDisposable Members

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    Stop();
                    waiter.Close();

                    if (senderThread != null)
                    {
                        try
                        {
                            senderThread.Abort();
                        }
                        catch (ThreadStateException) { }
                        finally
                        {
                            senderThread = null;
                        }
                    }

                    if (udpClient != null)
                    {
                        udpClient.Close();
                        udpClient = null;
                    }
                }

                disposed = true;
            }
        }

        #endregion
    }
}


text:
var nodemailer = require('nodemailer');
var config = require('config');

var transporter = nodemailer.createTransport({
	service: 'Gmail',
	auth: {
		user: 'trikas.restaurante.bar@gmail.com',
		pass: 'restaurantetrikas'
	}
});

var daCorreo = {};

function crearMensajeDeActivacion(codCuenta, correoAActivar, pass){
	var appHost = config.get('trikasapp.parameters.appHost');
	var nomEmpresa = config.get('trikasapp.correo.empresa');
	var imgEmpresa = config.get('trikasapp.correo.imgEmpresa');
	var msj = ' ' +
		'✔ Estimado usuario(a) para poder activar tu cuenta favor de copiar el siguiente link ' +
		appHost + 'activar/activar?q=' + codCuenta + '' +
		' y pegarlo en la barra de direcciones de tu navegador.

' +
		'Saludos cordiales,
' +
		nomEmpresa;
	return msj;
}

daCorreo.enviarEmailActivacionCuenta = function(correoAActivar, codCuenta, fnIn){
	var mailOptions = {
	    from: 'trikas.restaurante.bar@gmail.com', // sender address
	    to: correoAActivar, // list of receivers
	    subject: 'Activación de cuenta', // Subject line
	    //text: 'Para activar la cuenta ' + codCuenta + ' ingrese al siguiente link https://google.com.pe' //, // plaintext body
	    html: crearMensajeDeActivacion(codCuenta,correoAActivar,"")// You can choose to send an HTML body instead
	};

	transporter.sendMail(mailOptions, function(error, info){
	    if(error){
	    	console.log(error);
	        fnIn(error,null);
	        //res.json({yo: 'error'});
	    }else{
	    	console.log('=============Message sent: ' + info.response);
	        fnIn(null, '=============Mensaje enviado: ' + info.response);
	        //res.json({yo: info.response});
	    };
	});
}

module.exports = daCorreo;

/*
'

     Estos son sus datos de registro, '.$row['usuario'].'

 USUARIO: '.$row['usuario'].'

          SU CLAVE : '.$row['password'].'

          SU EMAIL : '.$row['email'].'

          SU LINK DE ACTIVACION:
'.$activateLink.'

          POR FAVOR HAGA CLICK EN LINK DE ARRIBA PARA ACTIVAR SU CUENRA Y ACCEDER A LA PAGINA SIN RESTRICCIONES

          SI EL LINK NO FUNCIONA ALA PRIMERA INTENTELO UNA SEGUNDA, EL SERVIDOR A VECES TARDA EN PROCESAR LA PRIMERA ORDEN

          GRACIAS POR REGISTRARSE EN CEVIT.

'
*/


text:
#include <aws/redshift/model/DescribeSnapshotCopyGrantsRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::Redshift::Model;
using namespace Aws::Utils;

DescribeSnapshotCopyGrantsRequest::DescribeSnapshotCopyGrantsRequest() :
    m_snapshotCopyGrantNameHasBeenSet(false),
    m_maxRecords(0),
    m_maxRecordsHasBeenSet(false),
    m_markerHasBeenSet(false),
    m_tagKeysHasBeenSet(false),
    m_tagValuesHasBeenSet(false)
{
}

Aws::String DescribeSnapshotCopyGrantsRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=DescribeSnapshotCopyGrants&";
  if(m_snapshotCopyGrantNameHasBeenSet)
  {
    ss << "SnapshotCopyGrantName=" << StringUtils::URLEncode(m_snapshotCopyGrantName.c_str()) << "&";
  }
  if(m_maxRecordsHasBeenSet)
  {
    ss << "MaxRecords=" << m_maxRecords << "&";
  }
  if(m_markerHasBeenSet)
  {
    ss << "Marker=" << StringUtils::URLEncode(m_marker.c_str()) << "&";
  }
  if(m_tagKeysHasBeenSet)
  {
    unsigned tagKeysCount = 1;
    for(auto& item : m_tagKeys)
    {
      ss << "TagKeys.member." << tagKeysCount << "="
          << StringUtils::URLEncode(item.c_str()) << "&";
      tagKeysCount++;
    }
  }
  if(m_tagValuesHasBeenSet)
  {
    unsigned tagValuesCount = 1;
    for(auto& item : m_tagValues)
    {
      ss << "TagValues.member." << tagValuesCount << "="
          << StringUtils::URLEncode(item.c_str()) << "&";
      tagValuesCount++;
    }
  }
  ss << "Version=2012-12-01";
  return ss.str();
}


text:
const controlTemplate = `

        {{vm.label}}

        <uib-alert ng-repeat="alert in vm.alerts" type="{{alert.type}}" >{{alert.msg}}</uib-alert>

`;

export default angular
    .module('jsonforms-bootstrap.renderers.controls', ['jsonforms-bootstrap'])
    .run(['$templateCache', $templateCache => {
        $templateCache.put('control.html', controlTemplate);
    }])
    .name;


text:
from cactus.deployment.auth import BaseKeyringCredentialsManager

class AWSCredentialsManager(BaseKeyringCredentialsManager):
    _username_config_entry = "aws-access-key"
    _username_display_name = "Amazon Access Key ID"
    _password_display_name = "Amazon Secret Access Key"
    _keyring_service = "aws"  # Would break backwards compatibility


text:
<?php

/**
 * Require once default mapper.
 * @ignore
 */
require_once PATH_LIB.'mapper.php';

/**
 * Categories mapper.
 *
 * @package     Mappers
 */
class Categories_Mapper extends Mapper
{
    /**
     * Overrule default name property.
     * @var string
     */
    protected $_Name = 'test';

    /**
     * Overrule default table property.
     * @var string
     */
    protected $_Table = 'categories';

//http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
    /**
     * Fetch navigation items.
     *
     * @return   object
     */
    public function fetchItems()
    {
        $sql = "
        SELECT
            *
        FROM `".$this->_Table."` nav
        ORDER BY
            `nav`.`position`,
            `nav`.`label`
        ";

        return $this->_Db->query($sql);
    }
}
?>


text:
<?php

  namespace osCommerce\OM\Core\Site\Admin\Application\Services\SQL\MySQL\Standard;

  use osCommerce\OM\Core\Registry;

/**
 * @since v3.0.2
 */

  class Save {
    public static function execute($data) {
      $OSCOM_PDO = Registry::get('PDO');

      $error = false;

      $OSCOM_PDO->beginTransaction();

      foreach ( $data['configuration'] as $key => $value ) {
        $Qupdate = $OSCOM_PDO->prepare('update :table_configuration set configuration_value = :configuration_value where configuration_key = :configuration_key');
        $Qupdate->bindValue(':configuration_value', is_array($data['configuration'][$key]) ? implode(',', $data['configuration'][$key]) : $value);
        $Qupdate->bindValue(':configuration_key', $key);
        $Qupdate->execute();

        if ( $Qupdate->isError() ) {
          $error = true;
          break;
        }
      }

      if ( $error === false ) {
        $OSCOM_PDO->commit();

        return true;
      }

      $OSCOM_PDO->rollBack();

      return false;
    }
  }
?>


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mc.nad.pro">

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

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.chocoyo.labs.splash.SplashActivity"
            android:configChanges="keyboardHidden|orientation"
            android:theme="@style/AppTheme.NoActionBar.Fullscreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ui.activities.ModuleActivity"
            android:label="@string/title_activity_module"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait"/>
        <activity
            android:name=".ui.activities.HomeActivity"
            android:label="@string/title_activity_home"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait"/>

        <service android:name=".services.MessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".services.InstanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
    </application>

</manifest>