text:
var RedisDb, defaultOptions, redis;

redis = require('redis');

defaultOptions = {
  prefix: 'ShareJS:',
  hostname: null,
  port: null,
  redisOptions: null,
  auth: null,
  client: null,
  testing: false
};

module.exports = RedisDb = function(options) {
  var client, k, keyForDoc, keyForOps, v, _ref;

  if (!(this instanceof RedisDb)) {
    return new Db;
  }
  if (options == null) {
    options = {};
  }
  for (k in defaultOptions) {
    v = defaultOptions[k];
    if ((_ref = options[k]) == null) {
      options[k] = v;
    }
  }
  keyForOps = function(docName) {
    return "" + options.prefix + "ops:" + docName;
  };
  keyForDoc = function(docName) {
    return "" + options.prefix + "doc:" + docName;
  };
  if (options.client) {
    client = options.client;
  } else {
    client = redis.createClient(options.port, options.hostname, options.redisOptions);
  }
  if (options.auth && typeof options.auth === "string") {
    client.auth(options.auth);
    if (options.testing) {
      client.select(15);
    }
  }
  this.create = function(docName, data, callback) {
    var value;

    value = JSON.stringify(data);
    return client.setnx(keyForDoc(docName), value, function(err, result) {
      if (err) {
        return typeof callback === "function" ? callback(err) : void 0;
      }
      if (result) {
        return typeof callback === "function" ? callback() : void 0;
      } else {
        return typeof callback === "function" ? callback('Document already exists') : void 0;
      }
    });
  };
  this.getOps = function(docName, start, end, callback) {
    if (start === end) {
      callback(null, []);
      return;
    }
    if (end != null) {
      end--;
    } else {
      end = -1;
    }
    return client.lrange(keyForOps(docName), start, end, function(err, values) {
      var ops, value;

      if (err != null) {
        throw err;
      }
      ops = (function() {
        var _i, _len, _results;

        _results = [];
        for (_i = 0, _len = values.length; _i < _len; _i++) {
          value = values[_i];
          _results.push(JSON.parse(value));
        }
        return _results;
      })();
      return callback(null, ops);
    });
  };
  this.writeOp = function(docName, opData, callback) {
    var json;

    json = JSON.stringify({
      op: opData.op,
      meta: opData.meta
    });
    return client.rpush(keyForOps(docName), json, function(err, response) {
      if (err) {
        return callback(err);
      }
      if (response === opData.v + 1) {
        return callback();
      } else {
        return callback("Version mismatch in db.append. '" + docName + "' is corrupted.");
      }
    });
  };
  this.writeSnapshot = function(docName, docData, dbMeta, callback) {
    return client.set(keyForDoc(docName), JSON.stringify(docData), function(err, response) {
      return typeof callback === "function" ? callback(err) : void 0;
    });
  };
  this.getSnapshot = function(docName, callback) {
    return client.get(keyForDoc(docName), function(err, response) {
      var docData;

      if (err != null) {
        throw err;
      }
      if (response !== null) {
        docData = JSON.parse(response);
        return callback(null, docData);
      } else {
        return callback('Document does not exist');
      }
    });
  };
  this["delete"] = function(docName, dbMeta, callback) {
    client.del(keyForOps(docName));
    return client.del(keyForDoc(docName), function(err, response) {
      if (err != null) {
        throw err;
      }
      if (callback) {
        if (response === 1) {
          return callback(null);
        } else {
          return callback('Document does not exist');
        }
      }
    });
  };
  this.close = function() {
    return client.quit();
  };
  return this;
};


text:
module BankTrain
  class BusinessCategory
    include Mongoid::Document
    include Mongoid::Timestamps

    field :name

    has_and_belongs_to_many :posts, class_name: 'BankTrain::Post'
    has_and_belongs_to_many :business_operations, class_name: 'BankTrain::BusinessOperation'

    belongs_to :parent_category, class_name: 'BankTrain::BusinessCategory'
    has_many :children_categories, class_name: 'BankTrain::BusinessCategory'

    module UserMethods
      extend ActiveSupport::Concern

      # 获取当前用户能够操作的业务类型
      def train_business_categories
        train_posts.map {|post|
          post.business_categories
        }.flatten.uniq
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
class GccAT8 < Formula
  desc "GNU compiler collection"
  homepage "https://gcc.gnu.org/"
  url "https://ftp.gnu.org/gnu/gcc/gcc-8.5.0/gcc-8.5.0.tar.xz"
  mirror "https://ftpmirror.gnu.org/gcc/gcc-8.5.0/gcc-8.5.0.tar.xz"
  sha256 "d308841a511bb830a6100397b0042db24ce11f642dab6ea6ee44842e5325ed50"
  license all_of: [
    "LGPL-2.1-or-later",
    "GPL-3.0-or-later" => { with: "GCC-exception-3.1" },
  ]

  livecheck do
    url :stable
    regex(%r{href=.*?gcc[._-]v?(8(?:\.\d+)+)(?:/?["' >]|\.t)}i)
  end

  bottle do
    rebuild 1
    sha256                               monterey:     "438d5902e5f21a5e8acb5920f1f5684ecfe0c645247d46c8d44c2bbe435966b2"
    sha256                               big_sur:      "9bd772c8e9c9c27f5f02fcf8b1ea99aaba24f6913b0187362659a9080d1b7eb5"
    sha256                               catalina:     "fd121adf0ae07df5d1cc03c851fb1da72fa531ca197adf5f0201124c78996337"
    sha256 cellar: :any_skip_relocation, x86_64_linux: "fea151773e9877896dad386c3df913036b6be075e72727edb86572e264ed44e1"
  end

  # The bottles are built on systems with the CLT installed, and do not work
  # out of the box on Xcode-only systems due to an incorrect sysroot.
  pour_bottle? only_if: :clt_installed

  depends_on arch: :x86_64
  depends_on "gmp"
  depends_on "isl"
  depends_on "libmpc"
  depends_on "mpfr"

  uses_from_macos "zlib"

  on_linux do
    depends_on "binutils"
  end

  # GCC bootstraps itself, so it is OK to have an incompatible C++ stdlib
  cxxstdlib_check :skip

  def version_suffix
    version.major.to_s
  end

  def install
    # Fix flat namespace use on macOS.
    configure_paths = %w[
      libatomic
      libgfortran
      libgomp
      libitm
      libobjc
      libquadmath
      libssp
      libstdc++-v3
    ]
    configure_paths.each do |path|
      inreplace buildpath/path/"configure", "${wl}-flat_namespace ${wl}-undefined ${wl}suppress",
                                            "${wl}-undefined ${wl}dynamic_lookup"
    end

    # GCC will suffer build errors if forced to use a particular linker.
    ENV.delete "LD"

    # Even when suffixes are appended, the info pages conflict when
    # install-info is run so pretend we have an outdated makeinfo
    # to prevent their build.
    ENV["gcc_cv_prog_makeinfo_modern"] = "no"

    # We avoiding building:
    #  - Ada, which requires a pre-existing GCC Ada compiler to bootstrap
    #  - Go, currently not supported on macOS
    #  - BRIG
    languages = %w[c c++ objc obj-c++ fortran]

    pkgversion = "Homebrew GCC #{pkg_version} #{build.used_options*" "}".strip

    args = %W[
      --prefix=#{prefix}
      --libdir=#{lib}/gcc/#{version_suffix}
      --disable-nls
      --enable-checking=release
      --enable-languages=#{languages.join(",")}
      --program-suffix=-#{version_suffix}
      --with-gmp=#{Formula["gmp"].opt_prefix}
      --with-mpfr=#{Formula["mpfr"].opt_prefix}
      --with-mpc=#{Formula["libmpc"].opt_prefix}
      --with-isl=#{Formula["isl"].opt_prefix}
      --with-pkgversion=#{pkgversion}
      --with-bugurl=#{tap.issues_url}
    ]

    if OS.mac?
      args << "--build=x86_64-apple-darwin#{OS.kernel_version.major}"
      args << "--with-system-zlib"

      # Xcode 10 dropped 32-bit support
      args << "--disable-multilib" if DevelopmentTools.clang_build_version >= 1000

      # System headers may not be in /usr/include
      sdk = MacOS.sdk_path_if_needed
      if sdk
        args << "--with-native-system-header-dir=/usr/include"
        args << "--with-sysroot=#{sdk}"
      end

      # Workaround for Xcode 12.5 bug on Intel
      # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100340
      args << "--without-build-config" if DevelopmentTools.clang_build_version >= 1205

      # Ensure correct install names when linking against libgcc_s;
      # see discussion in https://github.com/Homebrew/legacy-homebrew/pull/34303
      inreplace "libgcc/config/t-slibgcc-darwin", "@shlib_slibdir@", "#{HOMEBREW_PREFIX}/lib/gcc/#{version_suffix}"
    else
      # Fix Linux error: gnu/stubs-32.h: No such file or directory.
      args << "--disable-multilib"

      # Change the default directory name for 64-bit libraries to `lib`
      # https://www.linuxfromscratch.org/lfs/view/development/chapter06/gcc-pass2.html
      inreplace "gcc/config/i386/t-linux64", "m64=../lib64", "m64="
    end

    mkdir "build" do
      system "../configure", *args

      if OS.mac?
        # Use -headerpad_max_install_names in the build,
        # otherwise updated load commands won't fit in the Mach-O header.
        # This is needed because `gcc` avoids the superenv shim.
        system "make", "BOOT_LDFLAGS=-Wl,-headerpad_max_install_names"
        system "make", "install"
      else
        system "make"
        system "make", "install-strip"
      end
    end

    # Handle conflicts between GCC formulae and avoid interfering
    # with system compilers.
    # Rename man7.
    Dir.glob(man7/"*.7") { |file| add_suffix file, version_suffix }
    # Even when we disable building info pages some are still installed.
    info.rmtree
  end

  def add_suffix(file, suffix)
    dir = File.dirname(file)
    ext = File.extname(file)
    base = File.basename(file, ext)
    File.rename file, "#{dir}/#{base}-#{suffix}#{ext}"
  end

  def post_install
    if OS.linux?
      gcc = bin/"gcc-#{version_suffix}"
      libgcc = Pathname.new(Utils.safe_popen_read(gcc, "-print-libgcc-file-name")).parent
      raise "command failed: #{gcc} -print-libgcc-file-name" if $CHILD_STATUS.exitstatus.nonzero?

      glibc = Formula["glibc"]
      glibc_installed = glibc.any_version_installed?

      # Symlink crt1.o and friends where gcc can find it.
      crtdir = if glibc_installed
        glibc.opt_lib
      else
        Pathname.new(Utils.safe_popen_read("/usr/bin/cc", "-print-file-name=crti.o")).parent
      end
      ln_sf Dir[crtdir/"*crt?.o"], libgcc

      # Create the GCC specs file
      # See https://gcc.gnu.org/onlinedocs/gcc/Spec-Files.html

      # Locate the specs file
      specs = libgcc/"specs"
      ohai "Creating the GCC specs file: #{specs}"
      specs_orig = Pathname.new("#{specs}.orig")
      rm_f [specs_orig, specs]

      system_header_dirs = ["#{HOMEBREW_PREFIX}/include"]

      if glibc_installed
        # https://github.com/Linuxbrew/brew/issues/724
        system_header_dirs << glibc.opt_include
      else
        # Locate the native system header dirs if user uses system glibc
        target = Utils.safe_popen_read(gcc, "-print-multiarch").chomp
        raise "command failed: #{gcc} -print-multiarch" if $CHILD_STATUS.exitstatus.nonzero?

        system_header_dirs += ["/usr/include/#{target}", "/usr/include"]
      end

      # Save a backup of the default specs file
      specs_string = Utils.safe_popen_read(gcc, "-dumpspecs")
      raise "command failed: #{gcc} -dumpspecs" if $CHILD_STATUS.exitstatus.nonzero?

      specs_orig.write specs_string

      # Set the library search path
      # For include path:
      #   * `-isysroot #{HOMEBREW_PREFIX}/nonexistent` prevents gcc searching built-in
      #     system header files.
      #   * `-idirafter <dir>` instructs gcc to search system header
      #     files after gcc internal header files.
      # For libraries:
      #   * `-nostdlib -L#{libgcc} -L#{glibc.opt_lib}` instructs gcc to use brewed glibc
      #     if applied.
      #   * `-L#{libdir}` instructs gcc to find the corresponding gcc
      #     libraries. It is essential if there are multiple brewed gcc
      #     with different versions installed.
      #     Noted that it should only be passed for the `gcc@*` formulae.
      #   * `-L#{HOMEBREW_PREFIX}/lib` instructs gcc to find the rest
      #     brew libraries.
      libdir = HOMEBREW_PREFIX/"lib/gcc/#{version_suffix}"
      specs.write specs_string + <<~EOS
        *cpp_unique_options:
        + -isysroot #{HOMEBREW_PREFIX}/nonexistent #{system_header_dirs.map { |p| "-idirafter #{p}" }.join(" ")}

        *link_libgcc:
        #{glibc_installed ? "-nostdlib -L#{libgcc} -L#{glibc.opt_lib}" : "+"} -L#{libdir} -L#{HOMEBREW_PREFIX}/lib

        *link:
        + --dynamic-linker #{HOMEBREW_PREFIX}/lib/ld.so -rpath #{libdir} -rpath #{HOMEBREW_PREFIX}/lib

      EOS
    end
  end

  test do
    (testpath/"hello-c.c").write <<~EOS
      #include <stdio.h>
      int main()
      {
        puts("Hello, world!");
        return 0;
      }
    EOS
    system "#{bin}/gcc-#{version.major}", "-o", "hello-c", "hello-c.c"
    assert_equal "Hello, world!\n", `./hello-c`

    (testpath/"hello-cc.cc").write <<~EOS
      #include <iostream>
      struct exception { };
      int main()
      {
        std::cout << "Hello, world!" << std::endl;
        try { throw exception{}; }
          catch (exception) { }
          catch (...) { }
        return 0;
      }
    EOS
    system "#{bin}/g++-#{version.major}", "-o", "hello-cc", "hello-cc.cc"
    assert_equal "Hello, world!\n", `./hello-cc`

    (testpath/"test.f90").write <<~EOS
      integer,parameter::m=10000
      real::a(m), b(m)
      real::fact=0.5

      do concurrent (i=1:m)
        a(i) = a(i) + fact*b(i)
      end do
      write(*,"(A)") "Done"
      end
    EOS
    system "#{bin}/gfortran-#{version.major}", "-o", "test", "test.f90"
    assert_equal "Done\n", `./test`
  end
end


text:
namespace caf::detail {

template <class... Ts>
struct select_all_helper_value_oracle {
  using type = std::tuple<Ts...>;
};

template <class T>
struct select_all_helper_value_oracle<T> {
  using type = T;
};

template <class... Ts>
using select_all_helper_value_t =
  typename select_all_helper_value_oracle<Ts...>::type;

template <class F, class... Ts>
struct select_all_helper {
  using value_type = select_all_helper_value_t<Ts...>;
  std::vector<value_type> results;
  std::shared_ptr<size_t> pending;
  disposable timeouts;
  F f;

  template <class Fun>
  select_all_helper(size_t pending, disposable timeouts, Fun&& f)
    : pending(std::make_shared<size_t>(pending)),
      timeouts(std::move(timeouts)),
      f(std::forward<Fun>(f)) {
    results.reserve(pending);
  }

  void operator()(Ts&... xs) {
    CAF_LOG_TRACE(CAF_ARG2("pending", *pending));
    if (*pending > 0) {
      results.emplace_back(std::move(xs)...);
      if (--*pending == 0) {
        timeouts.dispose();
        f(std::move(results));
      }
    }
  }

  auto wrap() {
    return [this](Ts&... xs) { (*this)(xs...); };
  }
};

template <class F, class = typename detail::get_callable_trait<F>::arg_types>
struct select_select_all_helper;

template <class F, class... Ts>
struct select_select_all_helper<
  F, detail::type_list<std::vector<std::tuple<Ts...>>>> {
  using type = select_all_helper<F, Ts...>;
};

template <class F, class T>
struct select_select_all_helper<F, detail::type_list<std::vector<T>>> {
  using type = select_all_helper<F, T>;
};

template <class F>
using select_all_helper_t = typename select_select_all_helper<F>::type;

} // namespace caf::detail

namespace caf::policy {

/// Enables a `response_handle` to fan-in all responses messages into a single
/// result (a `vector` that stores all received results).
/// @relates mixin::requester
/// @relates response_handle
template <class ResponseType>
class select_all {
public:
  static constexpr bool is_trivial = false;

  using response_type = ResponseType;

  using message_id_list = std::vector<message_id>;

  template <class Fun>
  using type_checker
    = detail::type_checker<response_type,
                           detail::select_all_helper_t<detail::decay_t<Fun>>>;

  explicit select_all(message_id_list ids, disposable pending_timeouts)
    : ids_(std::move(ids)), pending_timeouts_(std::move(pending_timeouts)) {
    CAF_ASSERT(ids_.size()
               <= static_cast<size_t>(std::numeric_limits<int>::max()));
  }

  select_all(select_all&&) noexcept = default;

  select_all& operator=(select_all&&) noexcept = default;

  template <class Self, class F, class OnError>
  void await(Self* self, F&& f, OnError&& g) {
    CAF_LOG_TRACE(CAF_ARG(ids_));
    auto bhvr = make_behavior(std::forward<F>(f), std::forward<OnError>(g));
    for (auto id : ids_)
      self->add_awaited_response_handler(id, bhvr);
  }

  template <class Self, class F, class OnError>
  void then(Self* self, F&& f, OnError&& g) {
    CAF_LOG_TRACE(CAF_ARG(ids_));
    auto bhvr = make_behavior(std::forward<F>(f), std::forward<OnError>(g));
    for (auto id : ids_)
      self->add_multiplexed_response_handler(id, bhvr);
  }

  template <class Self, class F, class G>
  void receive(Self* self, F&& f, G&& g) {
    CAF_LOG_TRACE(CAF_ARG(ids_));
    using helper_type = detail::select_all_helper_t<detail::decay_t<F>>;
    helper_type helper{ids_.size(), pending_timeouts_, std::forward<F>(f)};
    auto error_handler = [&](error& err) mutable {
      if (*helper.pending > 0) {
        pending_timeouts_.dispose();
        *helper.pending = 0;
        helper.results.clear();
        g(err);
      }
    };
    for (auto id : ids_) {
      typename Self::accept_one_cond rc;
      auto error_handler_copy = error_handler;
      self->varargs_receive(rc, id, helper.wrap(), error_handler_copy);
    }
  }

  const message_id_list& ids() const noexcept {
    return ids_;
  }

  disposable pending_timeouts() {
    return pending_timeouts_;
  }

private:
  template <class F, class OnError>
  behavior make_behavior(F&& f, OnError&& g) {
    using namespace detail;
    using helper_type = select_all_helper_t<decay_t<F>>;
    helper_type helper{ids_.size(), pending_timeouts_, std::move(f)};
    auto pending = helper.pending;
    auto error_handler = [pending{std::move(pending)},
                          timeouts{pending_timeouts_},
                          g{std::forward<OnError>(g)}](error& err) mutable {
      CAF_LOG_TRACE(CAF_ARG2("pending", *pending));
      if (*pending > 0) {
        timeouts.dispose();
        *pending = 0;
        g(err);
      }
    };
    return {
      std::move(helper),
      std::move(error_handler),
    };
  }

  message_id_list ids_;
  disposable pending_timeouts_;
};

} // namespace caf::policy


text:
package org.gradle.api.internal;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.gradle.api.GradleException;
import org.gradle.api.InvalidUserDataException;
import org.gradle.api.NamedDomainObjectFactory;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DefaultPolymorphicNamedEntityInstantiator<T> implements PolymorphicNamedEntityInstantiator<T> {
    private final Map<Class<? extends T>, NamedDomainObjectFactory<? extends T>> factories = Maps.newHashMap();
    private final Class<? extends T> baseType;
    private final String displayName;

    public DefaultPolymorphicNamedEntityInstantiator(Class<? extends T> type, String displayName) {
        this.displayName = displayName;
        this.baseType = type;
    }

    @Override
    public <S extends T> S create(String name, Class<S> type) {
        @SuppressWarnings("unchecked")
        NamedDomainObjectFactory<S> factory = (NamedDomainObjectFactory<S>) factories.get(type);
        if (factory == null) {
            throw new InvalidUserDataException(
                    String.format("Cannot create a %s because this type is not known to %s. Known types are: %s", type.getSimpleName(), displayName, getSupportedTypeNames()),
                    new NoFactoryRegisteredForTypeException());
        }
        return factory.create(name);
    }

    public String getSupportedTypeNames() {
        List<String> names = Lists.newArrayList();
        for (Class<?> clazz : factories.keySet()) {
            names.add(clazz.getSimpleName());
        }
        Collections.sort(names);
        return names.isEmpty() ? "(None)" : Joiner.on(", ").join(names);
    }

    @Override
    public <U extends T> void registerFactory(Class<U> type, NamedDomainObjectFactory<? extends U> factory) {
        if (!baseType.isAssignableFrom(type)) {
            String message = String.format("Cannot register a factory for type %s because it is not a subtype of container element type %s.", type.getSimpleName(), baseType.getSimpleName());
            throw new IllegalArgumentException(message);
        }
        if (factories.containsKey(type)) {
            throw new GradleException(String.format("Cannot register a factory for type %s because a factory for this type is already registered.", type.getSimpleName()));
        }
        factories.put(type, factory);
    }

    @Override
    public Set<? extends Class<? extends T>> getCreatableTypes() {
        return ImmutableSet.copyOf(factories.keySet());
    }
}


text:
import org.garret.perst.*;

import java.io.*;

public class TestXML {
    static class Record extends Persistent {
        String strKey;
        long   intKey;
        double realKey;
    };

    static class Indices extends Persistent {
        Index      strIndex;
        FieldIndex intIndex;
        FieldIndex compoundIndex;
    }

    final static int nRecords = 100000;
    final static int pagePoolSize = 32*1024*1024;

    static public void main(String[] args) throws Exception {
        Storage db = StorageFactory.getInstance().createStorage();

        db.open("test1.dbs", pagePoolSize);
        Indices root = (Indices)db.getRoot();
        if (root == null) {
            root = new Indices();
            root.strIndex = db.createIndex(String.class, true);
            root.intIndex = db.createFieldIndex(Record.class, "intKey", true);
            root.compoundIndex = db.createFieldIndex(Record.class, new String[]{"strKey", "intKey"}, true);
            db.setRoot(root);
        }
        FieldIndex intIndex = root.intIndex;
        FieldIndex compoundIndex = root.compoundIndex;
        Index strIndex = root.strIndex;
        long start = System.currentTimeMillis();
        long key = 1999;
        int i;
        for (i = 0; i < nRecords; i++) {
            Record rec = new Record();
            key = (3141592621L*key + 2718281829L) % 1000000007L;
            rec.intKey = key;
            rec.strKey = Long.toString(key);
            rec.realKey = (double)key;
            intIndex.put(rec);
            strIndex.put(new Key(rec.strKey), rec);
            compoundIndex.put(rec);
        }
        db.commit();
        System.out.println("Elapsed time for inserting " + nRecords + " records: "
                           + (System.currentTimeMillis() - start) + " milliseconds");

        start = System.currentTimeMillis();
        Writer writer = new BufferedWriter(new FileWriter("test.xml"));
        db.exportXML(writer);
        writer.close();
        System.out.println("Elapsed time for XML export " + (System.currentTimeMillis() - start) + " milliseconds");
        db.close();
        db.open("test2.dbs", pagePoolSize);

        start = System.currentTimeMillis();
        Reader reader = new BufferedReader(new FileReader("test.xml"));
        db.importXML(reader);
        reader.close();
        System.out.println("Elapsed time for XML import " + (System.currentTimeMillis() - start) + " milliseconds");
        root = (Indices)db.getRoot();
        intIndex = root.intIndex;
        strIndex = root.strIndex;
        compoundIndex = root.compoundIndex;

        start = System.currentTimeMillis();
        key = 1999;
        for (i = 0; i < nRecords; i++) {
            key = (3141592621L*key + 2718281829L) % 1000000007L;
            String strKey = Long.toString(key);
            Record rec1 = (Record)intIndex.get(new Key(key));
            Record rec2 = (Record)strIndex.get(new Key(strKey));
            Record rec3 = (Record)compoundIndex.get(new Key(strKey, new Long(key)));
            Assert.that(rec1 != null);
            Assert.that(rec1 == rec2);
            Assert.that(rec1 == rec3);
            Assert.that(rec1.intKey == key);
            Assert.that(rec1.realKey == (double)key);
            Assert.that(strKey.equals(rec1.strKey));
        }
        System.out.println("Elapsed time for performing " + nRecords*2 + " index searches: "
                           + (System.currentTimeMillis() - start) + " milliseconds");
        db.close();
    }
}


text:
module FormtasticFoundation
  module Inputs
    class DatetimePickerInput < Formtastic::Inputs::DatetimePickerInput
      include Base
      include Base::Stringish
      include Base::DatetimePickerish
    end
  end
end


text:
using System;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using SysAnalytics.Model.Enums;

namespace SysAnalytics.Model.Expressions
{

    public static class LinqExtensions
    {
        /// <summary>Orders the sequence by specific column and direction.</summary>
        /// <param name="query">The query.</param>
        /// <param name="sortColumn">The sort column.</param>
        /// <param name="ascending">if set to true [ascending].</param>
        public static IQueryable<T> OrderBy<T>(this IQueryable<T> query, string sortColumn, string direction)
        {
            string methodName = string.Format("OrderBy{0}",
                direction.ToLower() == "asc" ? "" : "descending");

            ParameterExpression parameter = Expression.Parameter(query.ElementType, "p");

            MemberExpression memberAccess = null;
            foreach (var property in sortColumn.Split('.'))
                memberAccess = MemberExpression.Property
                   (memberAccess ?? (parameter as Expression), property);

            LambdaExpression orderByLambda = Expression.Lambda(memberAccess, parameter);

            MethodCallExpression result = Expression.Call(
                      typeof(Queryable),
                      methodName,
                      new[] { query.ElementType, memberAccess.Type },
                      query.Expression,
                      Expression.Quote(orderByLambda));

            return query.Provider.CreateQuery<T>(result);
        }

        public static object GetDefault(Type type)
        {
            if (type.IsValueType)
            {
                return Activator.CreateInstance(type);
            }
            return null;
        }

        public static IQueryable<T> Where<T>(this IQueryable<T> query,
            string column, object value, WhereOperation operation)
        {
            if (string.IsNullOrEmpty(column))
                return query;

            ParameterExpression parameter = Expression.Parameter(query.ElementType, "p");

            MemberExpression memberAccess = null;
            foreach (var property in column.Split(' '))
                memberAccess = MemberExpression.Property
                   (memberAccess ?? (parameter as Expression), property);

            Type type = memberAccess.Type;

            Expression condition = null;
            LambdaExpression lambda = null;
            //Expression[] lambdaArr = new Expression[2];

            if (string.IsNullOrEmpty(value.ToString()))
                value = GetDefault(type);
                //if (type == typeof (int)) value = 0;
            else
            {
                //change param value type
                //necessary to getting bool from string
                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                {
                    type = memberAccess.Type.GetGenericArguments()[0];
                }

                if (type.IsEnum)
                    value = StringEnum.GetEnum(type, value.ToString());
                else if (type == typeof(DateTimeOffset))
                {
                    string time = string.Empty;
                    if (operation == WhereOperation.Less || operation == WhereOperation.GreaterOrEqual) time = " 00:00:01+00:00";
                    if (operation == WhereOperation.Greater || operation == WhereOperation.LessOrEqual) time = " 23:59:59+00:00";

                    if (operation == WhereOperation.Equal)
                    {
                        var from = DateTimeOffset.Parse(String.Format("{0}{1}", value, " 00:00:01 +00:00"), CultureInfo.InvariantCulture);
                        ConstantExpression filterFrom = Expression.Constant(from, memberAccess.Type);
                        var to = DateTimeOffset.Parse(String.Format("{0}{1}", value, " 23:59:59 +00:00"), CultureInfo.InvariantCulture);
                        ConstantExpression filterTo = Expression.Constant(to, memberAccess.Type);
                        var condition1 = Expression.GreaterThan(memberAccess, filterFrom);
                        var condition2 = Expression.LessThan(memberAccess, filterTo);
                        var body = Expression.AndAlso(condition1, condition2);
                        lambda = Expression.Lambda<Func<T, bool>>(body, parameter);
                    }
                    else
                    {
                        value = DateTimeOffset.Parse(String.Format("{0}{1}", value, time), CultureInfo.InvariantCulture);
                    }
                }
                else if (type == typeof(decimal))
                {
                    value = Convert.ChangeType(value, type);
                    if (operation == WhereOperation.Equal)
                    {
                        ConstantExpression filter1 = Expression.Constant((decimal)value - 0.01M, memberAccess.Type);
                        ConstantExpression filter2 = Expression.Constant((decimal)value + 0.01M, memberAccess.Type);
                        var condition1 = Expression.GreaterThan(memberAccess, filter1);
                        var condition2 = Expression.LessThan(memberAccess, filter2);
                        var body = Expression.AndAlso(condition1, condition2);
                        lambda = Expression.Lambda<Func<T, bool>>(body, parameter);
                    }
                    else if (operation == WhereOperation.NotEqual)
                    {
                        ConstantExpression filter = Expression.Constant(value, memberAccess.Type);
                        var condition1 = Expression.LessThan(memberAccess, filter);
                        var condition2 = Expression.GreaterThan(memberAccess, filter);
                        var body = Expression.OrElse(condition1, condition2);
                        lambda = Expression.Lambda<Func<T, bool>>(body, parameter);
                    }
                }
                else
                    value = Convert.ChangeType(value, type);
            }

            if (lambda == null)
            {
                //ConstantExpression filter = Expression.Constant(value == null ? value : Convert.ChangeType(value, memberAccess.Type));
                ConstantExpression filter = Expression.Constant(value, memberAccess.Type);
                //ConstantExpression filter = Expression.Constant(value);

                //switch operation

                switch (operation)
                {
                    //equal ==
                    case WhereOperation.Equal:
                    case WhereOperation.IsNull:
                        condition = Expression.Equal(memberAccess, filter);
                        lambda = Expression.Lambda(condition, parameter);
                        break;
                    //not equal !=
                    case WhereOperation.NotEqual:
                    case WhereOperation.IsNotNull:
                        condition = Expression.NotEqual(memberAccess, filter);
                        lambda = Expression.Lambda(condition, parameter);
                        break;
                    //string.Contains()
                    case WhereOperation.Contains:
                    case WhereOperation.BeginsWith:
                        condition = Expression.Call(memberAccess, typeof (string).GetMethod("Contains"),
                            Expression.Constant(value));
                        lambda = value is string
                            ? Expression.Lambda(condition, parameter)
                            : Expression.Lambda<Func<T, bool>>(condition, parameter);
                        break;
                    case WhereOperation.Greater:
                        condition = Expression.GreaterThan(memberAccess, filter);
                        lambda = Expression.Lambda(condition, parameter);
                        break;
                    case WhereOperation.GreaterOrEqual:
                        condition = Expression.GreaterThanOrEqual(memberAccess, filter);
                        lambda = Expression.Lambda(condition, parameter);
                        break;
                    case WhereOperation.Less:
                        condition = Expression.LessThan(memberAccess, filter);
                        lambda = Expression.Lambda(condition, parameter);
                        break;
                    case WhereOperation.LessOrEqual:
                        condition = Expression.LessThanOrEqual(memberAccess, filter);
                        lambda = Expression.Lambda(condition, parameter);
                        break;
                    default:
                        return query;
                }
            }

            MethodCallExpression result = Expression.Call(typeof(Queryable), "Where", new[] { query.ElementType }, query.Expression, lambda);

            return query.Provider.CreateQuery<T>(result);
        }
    }
}


text:
package org.apache.bookkeeper.stream.protocol.util;

import static com.google.common.base.Preconditions.checkArgument;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import java.util.List;
import org.apache.bookkeeper.common.util.Revisioned;
import org.apache.bookkeeper.stream.proto.NamespaceConfiguration;
import org.apache.bookkeeper.stream.proto.RangeProperties;
import org.apache.bookkeeper.stream.proto.StreamConfiguration;
import org.apache.bookkeeper.stream.proto.StreamMetadata.LifecycleState;
import org.apache.bookkeeper.stream.proto.StreamMetadata.ServingState;
import org.apache.bookkeeper.stream.proto.StreamName;
import org.apache.bookkeeper.stream.proto.StreamProperties;
import org.apache.bookkeeper.stream.proto.storage.CreateNamespaceRequest;
import org.apache.bookkeeper.stream.proto.storage.CreateStreamRequest;
import org.apache.bookkeeper.stream.proto.storage.DeleteNamespaceRequest;
import org.apache.bookkeeper.stream.proto.storage.DeleteStreamRequest;
import org.apache.bookkeeper.stream.proto.storage.GetActiveRangesRequest;
import org.apache.bookkeeper.stream.proto.storage.GetNamespaceRequest;
import org.apache.bookkeeper.stream.proto.storage.GetStorageContainerEndpointRequest;
import org.apache.bookkeeper.stream.proto.storage.GetStorageContainerEndpointResponse;
import org.apache.bookkeeper.stream.proto.storage.GetStreamRequest;
import org.apache.bookkeeper.stream.proto.storage.OneStorageContainerEndpointRequest;
import org.apache.bookkeeper.stream.proto.storage.OneStorageContainerEndpointResponse;
import org.apache.bookkeeper.stream.proto.storage.StatusCode;
import org.apache.bookkeeper.stream.proto.storage.StorageContainerEndpoint;
import org.apache.commons.lang3.tuple.Pair;

/**
 * Protocol related utils.
 */
public class ProtoUtils {

    /**
     * Check if two key ranges overlaps with each other.
     *
     * @param meta1 first key range
     * @param meta2 second key range
     * @return true if two key ranges overlaps
     */
    public static boolean keyRangeOverlaps(RangeProperties meta1, RangeProperties meta2) {
        return keyRangeOverlaps(
            meta1.getStartHashKey(), meta1.getEndHashKey(),
            meta2.getStartHashKey(), meta2.getEndHashKey());
    }

    public static boolean keyRangeOverlaps(Pair<Long, Long> range1,
                                           Pair<Long, Long> range2) {
        return keyRangeOverlaps(range1.getLeft(), range1.getRight(),
            range2.getLeft(), range2.getRight());
    }

    public static boolean keyRangeOverlaps(RangeProperties range1,
                                           Pair<Long, Long> range2) {
        return keyRangeOverlaps(range1.getStartHashKey(), range1.getEndHashKey(),
            range2.getLeft(), range2.getRight());
    }

    public static boolean keyRangeOverlaps(Pair<Long, Long> range1,
                                           RangeProperties range2) {
        return keyRangeOverlaps(range1.getLeft(), range1.getRight(),
            range2.getStartHashKey(), range2.getEndHashKey());
    }

    static boolean keyRangeOverlaps(long startKey1,
                                    long endKey1,
                                    long startKey2,
                                    long endKey2) {
        return endKey2 > startKey1 && startKey2 < endKey1;
    }

    /**
     * Validate namespace name.
     *
     * @return true if it is a valid namespace name. otherwise false.
     */
    public static boolean validateNamespaceName(String name) {
        return validateStreamName(name);
    }

    /**
     * Validate stream name.
     *
     * <p>follow the rules that dlog uses for validating stream name.
     *
     * @return true if it is a valid namespace name. otherwise false.
     */
    public static boolean validateStreamName(String name) {
        if (Strings.isNullOrEmpty(name)) {
            return false;
        }
        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            if (c == 0
                || c == ' '
                || c == '<'
                || c == '>'
                || c > '\u0000' && c < '\u001f'
                || c > '\u007f' && c < '\u009f'
                || c > '\ud800' && c < '\uf8ff'
                || c > '\ufff0' && c < '\uffff') {
                return false;
            }
        }
        return true;
    }

    public static List<RangeProperties> split(long streamId,
                                              int numInitialRanges,
                                              long nextRangeId,
                                              StorageContainerPlacementPolicy placementPolicy) {
        int numRanges = Math.max(2, numInitialRanges);
        if (numRanges % 2 != 0) { // round up to odd number
            numRanges = numRanges + 1;
        }
        long rangeSize = Long.MAX_VALUE / (numRanges / 2);
        long startKey = Long.MIN_VALUE;
        List<RangeProperties> ranges = Lists.newArrayListWithExpectedSize(numRanges);
        for (int idx = 0; idx < numRanges; ++idx) {
            long endKey = startKey + rangeSize;
            if (numRanges - 1 == idx) {
                endKey = Long.MAX_VALUE;
            }
            long rangeId = nextRangeId++;
            RangeProperties props = RangeProperties.newBuilder()
                .setStartHashKey(startKey)
                .setEndHashKey(endKey)
                .setStorageContainerId(placementPolicy.placeStreamRange(streamId, rangeId))
                .setRangeId(rangeId)
                .build();
            startKey = endKey;

            ranges.add(props);
        }
        return ranges;
    }

    /**
     * Check if the stream is created.
     *
     * @param state stream state
     * @return true if the stream is in created state. otherwise, false.
     */
    public static boolean isStreamCreated(LifecycleState state) {
        checkArgument(state != LifecycleState.UNRECOGNIZED);
        return LifecycleState.UNINIT != state
            && LifecycleState.CREATING != state;
    }

    /**
     * Check if the stream is writable.
     *
     * @param state stream state
     * @return true if the stream is writable. otherwise, false.
     */
    public static boolean isStreamWritable(ServingState state) {
        checkArgument(state != ServingState.UNRECOGNIZED);
        return ServingState.WRITABLE == state;
    }

    //
    // Location API
    //

    /**
     * Create a {@link GetStorageContainerEndpointRequest}.
     *
     * @param storageContainers list of storage containers
     * @return a get storage container endpoint request.
     */
    public static GetStorageContainerEndpointRequest createGetStorageContainerEndpointRequest(
        List<Revisioned<Long>> storageContainers) {
        GetStorageContainerEndpointRequest.Builder builder = GetStorageContainerEndpointRequest.newBuilder();
        for (Revisioned<Long> storageContainer : storageContainers) {
            builder.addRequests(
                OneStorageContainerEndpointRequest.newBuilder()
                    .setStorageContainer(storageContainer.getValue())
                    .setRevision(storageContainer.getRevision()));
        }
        return builder.build();
    }

    /**
     * Create a {@link GetStorageContainerEndpointResponse}.
     *
     * @param endpoints list of storage container endpoints
     * @return a get storage container endpoint response.
     */
    public static GetStorageContainerEndpointResponse createGetStorageContainerEndpointResponse(
        List<StorageContainerEndpoint> endpoints) {
        GetStorageContainerEndpointResponse.Builder builder = GetStorageContainerEndpointResponse.newBuilder();
        builder.setStatusCode(StatusCode.SUCCESS);
        for (StorageContainerEndpoint endpoint : endpoints) {
            builder.addResponses(
                OneStorageContainerEndpointResponse.newBuilder()
                    .setStatusCode(StatusCode.SUCCESS)
                    .setEndpoint(endpoint));
        }
        return builder.build();
    }

    //
    // Meta Range API
    //

    public static GetActiveRangesRequest createGetActiveRangesRequest(long streamId) {
        return GetActiveRangesRequest.newBuilder()
                .setStreamId(streamId)
                .build();
    }

    public static GetActiveRangesRequest createGetActiveRangesRequest(StreamProperties streamProps) {
        return GetActiveRangesRequest.newBuilder()
                .setStreamId(streamProps.getStreamId())
                .setStreamProps(streamProps)
                .build();
    }

    //
    // Namespace API
    //

    /**
     * Create a {@link CreateNamespaceRequest}.
     *
     * @param nsName namespace name
     * @param nsConf namespace conf
     * @return a create namespace request.
     */
    public static CreateNamespaceRequest createCreateNamespaceRequest(String nsName,
                                                                      NamespaceConfiguration nsConf) {
        return CreateNamespaceRequest.newBuilder()
            .setName(nsName)
            .setNsConf(nsConf)
            .build();
    }

    /**
     * Create a {@link DeleteNamespaceRequest}.
     *
     * @param colName namespace name
     * @return a delete namespace request.
     */
    public static DeleteNamespaceRequest createDeleteNamespaceRequest(String colName) {
        return DeleteNamespaceRequest.newBuilder()
            .setName(colName)
            .build();
    }

    /**
     * Create a {@link GetNamespaceRequest}.
     *
     * @param colName namespace name
     * @return a get namespace request.
     */
    public static GetNamespaceRequest createGetNamespaceRequest(String colName) {
        return GetNamespaceRequest.newBuilder()
            .setName(colName)
            .build();
    }

    //
    // Stream API
    //

    /**
     * Create a {@link CreateStreamRequest}.
     *
     * @param nsName     namespace name
     * @param streamName stream name
     * @param streamConf stream configuration
     * @return a create stream request.
     */
    public static CreateStreamRequest createCreateStreamRequest(String nsName,
                                                                String streamName,
                                                                StreamConfiguration streamConf) {
        return CreateStreamRequest.newBuilder()
            .setNsName(nsName)
            .setName(streamName)
            .setStreamConf(streamConf)
            .build();
    }

    /**
     * Create a {@link GetStreamRequest}.
     *
     * @param nsName     namespace name
     * @param streamName stream name
     * @return a create stream request.
     */
    public static GetStreamRequest createGetStreamRequest(String nsName,
                                                          String streamName) {
        return GetStreamRequest.newBuilder()
            .setStreamName(StreamName.newBuilder()
                .setNamespaceName(nsName)
                .setStreamName(streamName))
            .build();
    }

    /**
     * Create a {@link GetStreamRequest}.
     *
     * @param streamId stream id
     * @return a create stream request.
     */
    public static GetStreamRequest createGetStreamRequest(long streamId) {
        return GetStreamRequest.newBuilder()
            .setStreamId(streamId)
            .build();
    }

    /**
     * Create a {@link DeleteStreamRequest}.
     *
     * @param nsName     namespace name
     * @param streamName stream name
     * @return a create stream request.
     */
    public static DeleteStreamRequest createDeleteStreamRequest(String nsName,
                                                                String streamName) {
        return DeleteStreamRequest.newBuilder()
            .setName(streamName)
            .setNsName(nsName)
            .build();
    }

}


text:
/**
 * @author TristanVALCKE / https://github.com/Itee
 */
/* global QUnit */

import { WebGLBufferRenderer } from '../../../../../src/renderers/webgl/WebGLBufferRenderer';

export default QUnit.module( 'Renderers', () => {

	QUnit.module( 'WebGL', () => {

		QUnit.module( 'WebGLBufferRenderer', () => {

			// INSTANCING
			QUnit.todo( "Instancing", ( assert ) => {

				assert.ok( false, "everything's gonna be alright" );

			} );

			// PUBLIC STUFF
			QUnit.todo( "setMode", ( assert ) => {

				assert.ok( false, "everything's gonna be alright" );

			} );

			QUnit.todo( "render", ( assert ) => {

				assert.ok( false, "everything's gonna be alright" );

			} );

			QUnit.todo( "renderInstances", ( assert ) => {

				assert.ok( false, "everything's gonna be alright" );

			} );

		} );

	} );

} );


text:
require 'spec_helper'

describe "base image" do
  before(:all) {
    @image = Docker::Image.all().detect{ |i| i.info['RepoTags'] == ['datt/datt-base:latest'] }
  }

  it "should be available" do
    expect(@image).to_not be_nil
  end
end


text:
title: Contributing to the Docs
description: Learn how to contribute to improve and expand the Istio documentation.
weight: 100
aliases:
    - /docs/welcome/contribute/index.html
icon: contribute
---


text:
import {
  TRANSFER_MEMBER_ACCOUNT_FAIL,
  TRANSFER_MEMBER_ACCOUNT_PENDING,
  TRANSFER_MEMBER_ACCOUNT_SUCCESS,
} from '../actionTypes';
import renew from './renew';

const pending = () => ({
  type: TRANSFER_MEMBER_ACCOUNT_PENDING,
});

const success = (copies) => ({
  copies,
  type: TRANSFER_MEMBER_ACCOUNT_SUCCESS,
});

const fail = error => ({
  error,
  type: TRANSFER_MEMBER_ACCOUNT_FAIL,
});

export default (api, member, shouldRenew) => async (dispatch) => {
  dispatch(pending());

  try {
    await api.member.transfer(member.no);

    const copies = member.account.copies.filter(copy => copy.isPaid);
    dispatch(success(copies));

    if (shouldRenew) {
      dispatch(renew(api, member.no));
    }
  } catch (error) {
    dispatch(fail(error));
  }
};


text:
namespace rho {
namespace ruby {

class MutableIntegerImpl : public ObjectImpl  {

public:
    MutableIntegerImpl(bool is_mutable);
    MutableIntegerImpl();
    virtual ~MutableIntegerImpl();

    virtual const char* getClassName();

    virtual long int getLong();
    virtual void setLong(long int value);

private:
    long int mValue;
};

// C++ is sucks !
class CMutableInteger : public IMutableInteger, public MutableIntegerImpl  {
public:
    CMutableInteger(bool is_mutable):MutableIntegerImpl(is_mutable) {}
    CMutableInteger() {}
    virtual void addRef() {RefCountedObjectImpl::addRef();}
    virtual void release() {RefCountedObjectImpl::release();}
    virtual const char* getClassName() {return ObjectImpl::getClassName();}
    virtual BASIC_TYPES getBasicType() {return ObjectImpl::getBasicType();}
    virtual long int getLong() {return MutableIntegerImpl::getLong();}
    virtual void setLong(long int value) {MutableIntegerImpl::setLong(value);}
};

}
}


text:
<component name="libraryTable">
  <library name="Mainlibs">
    <CLASSES>
      <root url="file://$PROJECT_DIR$/Main/libs" />
      <root url="file://$PROJECT_DIR$/Main/libs" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="file://$PROJECT_DIR$/Main/libs/sources" />
    </SOURCES>
    <jarDirectory url="file://$PROJECT_DIR$/Main/libs" recursive="false" />
    <jarDirectory url="file://$PROJECT_DIR$/Main/libs/sources" recursive="false" type="SOURCES" />
  </library>
</component>


text:
namespace settings {

// The base class handler of Javascript messages of settings pages.
class SettingsPageUIHandler : public content::WebUIMessageHandler {
 public:
  SettingsPageUIHandler();
  ~SettingsPageUIHandler() override;

  // WebUIMessageHandler implementation.
  void RegisterMessages() override {}

 private:
  DISALLOW_COPY_AND_ASSIGN(SettingsPageUIHandler);
};

// The WebUI handler for chrome://md-settings.
class MdSettingsUI : public content::WebUIController {
 public:
  explicit MdSettingsUI(content::WebUI* web_ui);
  ~MdSettingsUI() override;

 private:
  void AddSettingsPageUIHandler(content::WebUIMessageHandler* handler);

  DISALLOW_COPY_AND_ASSIGN(MdSettingsUI);
};

}  // namespace settings

#endif  // CHROME_BROWSER_UI_WEBUI_SETTINGS_MD_SETTINGS_UI_H_


text:
<archimate:Location
    xmlns:archimate="http://www.archimatetool.com/archimate"
    name="Ethiopia"
    id="id-2fb38ea771344a379f6a3732635843f2"
    documentation="the Federal Democratic Republic of Ethiopia">
  <properties
      key="Country Code"
      value="ETH"/>
  <properties
      key="Latest Sync Date"
      value="15/10/2020 17:22:39"/>
  <properties
      key="Capital"
      value="Addis Ababa"/>
  <properties
      key="Currency"
      value="Ethiopian Birr (ETB)"/>
</archimate:Location>


text:
layout: post
title: Warszawskie zachody słońca
cover: img/2016/warszawa/warszawa-3.jpg
---

Wykorzystując prawdopodobnie ostatnie ciepłe dni tego lata, dużo czasu spędziłam w zeszłym tygodniu nad Wisłą w Warszawie. I muszę przyznać, że w ogóle nie czułam, że wakacje i lato już się kończą. W knajpkach jak zwykle tłumy i radosny rozgardiasz, a do tego przepiękne zachody słońca, dzięki którym zapominałam, że jestem w centrum stolicy :) Mimo iż na bulwarach infrastruktura jest bardziej rozwinięta, a od wyboru miejscówki może rozboleć głowa, to praska strona Wisły według mnie na jedną kluczową zaletę - właśnie widok na zachodzące nad miastem słońce.

Po kilku miesiącach snucia niesprecyzowanych planów ("w wolniejszej chwili muszę pojechać na Most Siekierkowski"), wreszcie wsiadłam w autobus i po pół godzinie kluczenia po Ursynowie dotarłam w okolice mostu. Gdy jeszcze nim przejeżdzałam, pomarańczowa kula wisiała nad wieżowcami w centrum. Niestety, zanim odnalazłam sposób na przedostanie się z przystanku na sam most, słońce właśnie zaszło i tylko fioletowa poświata za budynkami świadczyła, że spóźniłam się nieznacznie. Szkoda... Widok i tak był jednak przepiękny :)

I jeszcze jeden wypad z aparatem. Może i Most Świętokrzyski jest najmniej uczęszczany ze wszystkich mostów, ale jego znaczenie estetyczne dla Warszawy jest nieocenione :)

Zabawa ze statywem :)


text:
import Vue from 'vue'
import VueResource from 'vue-resource'
import App from './app.vue'
import AppService from './appService.js'

Vue.use(VueResource);
let svc = new AppService(Vue.http);
new Vue({
    el: '#app',
    data: svc.data,
    components: {
        App
    },
    methods: {
        cardStarted: function (card) {
            svc.startQuery(card);
        },
        cardStopped: function (card) {
            svc.stopQuery(card, true);
        },
        cardPaused: function (card) {
            svc.stopQuery(card, false);
        },
        cardResumed: function (card) {
            svc.startQuery(card);
        },
        cardAdded: function () {
            svc.addCard();
        },
        cardDeleted: function (index) {
            svc.deleteCard(index)
        }
    }
})


text:
package client

import (
	"net/url"
	"time"

	Cli "github.com/docker/docker/cli"
	"github.com/docker/docker/opts"
	flag "github.com/docker/docker/pkg/mflag"
	"github.com/docker/docker/pkg/parsers/filters"
	"github.com/docker/docker/pkg/timeutils"
)

// CmdEvents prints a live stream of real time events from the server.
//
// Usage: docker events [OPTIONS]
func (cli *DockerCli) CmdEvents(args ...string) error {
	cmd := Cli.Subcmd("events", nil, Cli.DockerCommands["events"].Description, true)
	since := cmd.String([]string{"-since"}, "", "Show all events created since timestamp")
	until := cmd.String([]string{"-until"}, "", "Stream events until this timestamp")
	flFilter := opts.NewListOpts(nil)
	cmd.Var(&flFilter, []string{"f", "-filter"}, "Filter output based on conditions provided")
	cmd.Require(flag.Exact, 0)

	cmd.ParseFlags(args, true)

	var (
		v               = url.Values{}
		eventFilterArgs = filters.NewArgs()
	)

	// Consolidate all filter flags, and sanity check them early.
	// They'll get process in the daemon/server.
	for _, f := range flFilter.GetAll() {
		var err error
		eventFilterArgs, err = filters.ParseFlag(f, eventFilterArgs)
		if err != nil {
			return err
		}
	}
	ref := time.Now()
	if *since != "" {
		ts, err := timeutils.GetTimestamp(*since, ref)
		if err != nil {
			return err
		}
		v.Set("since", ts)
	}
	if *until != "" {
		ts, err := timeutils.GetTimestamp(*until, ref)
		if err != nil {
			return err
		}
		v.Set("until", ts)
	}
	if eventFilterArgs.Len() > 0 {
		filterJSON, err := filters.ToParam(eventFilterArgs)
		if err != nil {
			return err
		}
		v.Set("filters", filterJSON)
	}
	sopts := &streamOpts{
		rawTerminal: true,
		out:         cli.out,
	}
	if _, err := cli.stream("GET", "/events?"+v.Encode(), sopts); err != nil {
		return err
	}
	return nil
}


text:
package jetbrains.jetpad.model.collections;

import jetbrains.jetpad.base.Registration;
import jetbrains.jetpad.base.function.Function;
import jetbrains.jetpad.model.collections.list.ObservableArrayList;
import jetbrains.jetpad.model.collections.list.ObservableCollections;
import jetbrains.jetpad.model.collections.list.ObservableList;
import jetbrains.jetpad.model.collections.set.ObservableHashSet;
import jetbrains.jetpad.model.event.EventHandler;
import jetbrains.jetpad.model.property.*;
import org.junit.Test;

import java.util.concurrent.atomic.AtomicInteger;

import static jetbrains.jetpad.model.collections.CollectionItemEvent.EventType.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

public class SelectTest {
  public static final int TEST_LIST_SIZE = 3;

  @Test
  public void nonListenedList() {
    Property<Boolean> src = new ValueProperty<>(false);
    final ObservableList<String> selected = new ObservableArrayList<>();
    ObservableList<String> res = testList(src, selected);

    testNonListened(src, selected, res);
  }

  @Test
  public void nonListenedCollection() {
    Property<Boolean> src = new ValueProperty<>(false);
    final ObservableCollection<String> selected = new ObservableHashSet<>();
    ObservableCollection<String> res = testCollection(src, selected);

    testNonListened(src, selected, res);
  }

  @Test
  public void listenedList() {
    Property<Boolean> src = new ValueProperty<>(false);
    final ObservableList<String> selected = new ObservableArrayList<>();
    ObservableList<String> res = testList(src, selected);

    testListened(src, selected, res);
  }

  @Test
  public void listenedCollection() {
    Property<Boolean> src = new ValueProperty<>(false);
    final ObservableCollection<String> selected = new ObservableHashSet<>();
    ObservableCollection<String> res = testCollection(src, selected);

    testListened(src, selected, res);
  }

  @Test
  public void listRegistrations() {
    final AtomicInteger pc = new AtomicInteger();
    final AtomicInteger cc = new AtomicInteger();
    Property<Boolean> src = listenersCountingProperty(pc);
    ObservableList<String> selected = listenersCountingList(cc);

    ObservableList<String> res = testList(src, selected);

    testRegistrations(src, res, pc, cc);
  }

  @Test
  public void collectionRegistrations() {
    final AtomicInteger propertyLsnrs = new AtomicInteger();
    final AtomicInteger collectionLsnrs = new AtomicInteger();
    Property<Boolean> src = listenersCountingProperty(propertyLsnrs);
    ObservableList<String> selected = listenersCountingList(collectionLsnrs);

    ObservableCollection<String> res = testCollection(src, selected);

    testRegistrations(src, res, propertyLsnrs, collectionLsnrs);
  }

  @Test
  public void listInnerUnfollow() {
    final AtomicInteger propertyLsnrs = new AtomicInteger();
    final AtomicInteger collectionLsnrs = new AtomicInteger();
    final Property<Boolean> src = listenersCountingProperty(propertyLsnrs);
    ObservableList<String> selected = listenersCountingList(collectionLsnrs);

    ObservableList<String> res = testList(src, selected);

    final Registration r1 = res.addListener(new CollectionAdapter<String>());
    final AtomicInteger handlerPass = new AtomicInteger();
    src.addHandler(new EventHandler<PropertyChangeEvent<Boolean>>() {
      @Override
      public void onEvent(PropertyChangeEvent<Boolean> event) {
        handlerPass.incrementAndGet();
        if (handlerPass.get() == 1) {
          r1.remove();
        }
        src.set(false);
      }
    });
    src.set(true);
  }

  @Test
  public void collectionNonEmpty() {
    ObservableCollection<String> res = testCollection(Properties.constant(true), newTestList());

    res.addListener(new CollectionAdapter<String>());
    assertEquals(TEST_LIST_SIZE, res.size());
  }

  @Test
  public void listNonEmpty() {
    ObservableList<String> res = testList(Properties.constant(true), newTestList());

    res.addListener(new CollectionAdapter<String>());
    assertEquals(TEST_LIST_SIZE, res.size());
  }

  @Test
  public void listNonEmptyIterator() {
    ObservableList<String> res = testList(Properties.constant(true), newTestList());

    assertEquals(TEST_LIST_SIZE, res.size());
    for (String s : res) {
      assertNotNull(s);
    }

    res.addListener(new CollectionAdapter<String>());
    assertEquals(TEST_LIST_SIZE, res.size());
    for (String s : res) {
      assertNotNull(s);
    }
  }

  @Test
  public void collectionNonEmptyIterator() {
    ObservableCollection<String> res = testCollection(Properties.constant(true), newTestList());

    assertEquals(TEST_LIST_SIZE, res.size());
    for (String s : res) {
      assertNotNull(s);
    }

    res.addListener(new CollectionAdapter<String>());
    assertEquals(TEST_LIST_SIZE, res.size());
    for (String s : res) {
      assertNotNull(s);
    }
  }

  private ObservableList<String> newTestList() {
    ObservableList<String> test = new ObservableArrayList<>();
    for (int i = 0; i < TEST_LIST_SIZE; i++) {
      test.add(String.valueOf(i));
    }
    return test;
  }

  private void testNonListened(Property<Boolean> src, ObservableCollection<String> selected, ObservableCollection<String> res) {
    assertEquals(0, res.size());

    selected.add("1");
    assertEquals(0, res.size());

    src.set(true);
    assertEquals(selected.size(), res.size());

    selected.add("2");
    assertEquals(selected.size(), res.size());

    src.set(false);
    assertEquals(0, res.size());
  }

  @SuppressWarnings("unchecked")
  private void testListened(Property<Boolean> src, ObservableCollection<String> selected, ObservableCollection<String> res) {
    CollectionListener<String> mock = mock(CollectionListener.class);
    res.addListener(mock);

    selected.add("1");
    verifyZeroInteractions(mock);
    assertEquals(0, res.size());

    src.set(true);
    verify(mock).onItemAdded(new CollectionItemEvent<>(null, "1", 0, ADD));
    assertEquals(selected.size(), res.size());

    selected.add("2");
    verify(mock).onItemAdded(new CollectionItemEvent<>(null, "2", 1, ADD));
    assertEquals(selected.size(), res.size());

    src.set(false);
    verify(mock).onItemRemoved(new CollectionItemEvent<>("1", null, 0, REMOVE));
    verify(mock).onItemRemoved(new CollectionItemEvent<>("2", null, 0, REMOVE));
    assertEquals(0, res.size());
  }

  @SuppressWarnings("unchecked")
  private void testRegistrations(Property<Boolean> src, ObservableCollection<String> res, AtomicInteger propertyLsnrs, AtomicInteger collectionLsnrs) {
    assertEquals(0, propertyLsnrs.get());
    assertEquals(0, collectionLsnrs.get());

    CollectionListener<String> mock = mock(CollectionListener.class);
    Registration mockReg = res.addListener(mock);
    assertEquals(1, propertyLsnrs.get());
    assertEquals(0, collectionLsnrs.get());

    src.set(true);
    assertEquals(1, propertyLsnrs.get());
    assertEquals(1, collectionLsnrs.get());

    src.set(false);
    assertEquals(1, propertyLsnrs.get());
    assertEquals(0, collectionLsnrs.get());

    src.set(true);
    assertEquals(1, propertyLsnrs.get());
    assertEquals(1, collectionLsnrs.get());
    mockReg.remove();
    assertEquals(0, propertyLsnrs.get());
    assertEquals(0, collectionLsnrs.get());
  }

  private ObservableList<String> testList(ReadableProperty<Boolean> src, final ObservableList<String> selected) {
    return ObservableCollections.selectList(
      src,
        new Function<Boolean, ObservableList<String>>() {
          @Override
          public ObservableList<String> apply(Boolean source) {
            return source ? selected : null;
          }
        });
  }

  private ObservableCollection<String> testCollection(ReadableProperty<Boolean> src, final ObservableCollection<String> selected) {
    return ObservableCollections.selectCollection(
      src,
        new Function<Boolean, ObservableCollection<String>>() {
          @Override
          public ObservableCollection<String> apply(Boolean source) {
            return source ? selected : null;
          }
        });
  }

  private ObservableList<String> listenersCountingList(final AtomicInteger counter) {
    return new ObservableArrayList<String>() {
      @Override
      public Registration addListener(CollectionListener<String> listener) {
        final Registration r = super.addListener(listener);
        counter.incrementAndGet();
        return new Registration() {
          @Override
          protected void doRemove() {
            r.remove();
            counter.decrementAndGet();
          }
        };
      }
    };
  }

  private Property<Boolean> listenersCountingProperty(final AtomicInteger counter) {
    return new ValueProperty<Boolean>(false) {
      @Override
      public Registration addHandler(EventHandler<? super PropertyChangeEvent<Boolean>> handler) {
        final Registration r = super.addHandler(handler);
        counter.incrementAndGet();
        return new Registration() {
          @Override
          protected void doRemove() {
            r.remove();
            counter.decrementAndGet();
          }
        };
      }
    };
  }
}


text:
package example.springdata.jpa.customall;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

/**
 * Sample configuration to bootstrap Spring Data JPA through JavaConfig. Note how Spring Data JPA is configured with a
 * custom repository base class. This causes all repository interfaces being found for this configuration to use the
 * configured class as base repository.
 *
 * @author Oliver Gierke
 * @soundtrack Tim Neuhaus - As life found you (The Cabinet)
 */
@SpringBootApplication
@EnableJpaRepositories(repositoryBaseClass = ExtendedJpaRepository.class)
class CustomRepositoryConfig {}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trattato di Micopatologia Umana (Firenze) 4: 198 (1934)

#### Original name
Trichophyton schoenleinii var. schoenleinii (Lebert) Langeron & Miloch. ex Nann.

### Remarks
null


text:
package com.groupdocs.conversion.examples.advanced_usage.loading.load_options_by_document_type.pdf;

import com.groupdocs.conversion.Converter;
import com.groupdocs.conversion.examples.Constants;
import com.groupdocs.conversion.options.convert.WordProcessingConvertOptions;
import com.groupdocs.conversion.options.load.PdfLoadOptions;

/**
 * This example demonstrates how to convert a pdf document to wordprocessing with advanced options
 */
public class ConvertPdfAndFlattenAllFields {
    public static void run() {
        String convertedFile = Constants.getConvertedPath("ConvertPdfAndFlattenAllFields.docx");
        PdfLoadOptions loadOptions = new PdfLoadOptions();
        loadOptions.setFlattenAllFields(true);
        Converter converter = new Converter(Constants.SAMPLE_PDF, () -> loadOptions);
        WordProcessingConvertOptions options = new WordProcessingConvertOptions();
        converter.convert(convertedFile, options);

        System.out.print("\nPdf document converted successfully. \nCheck output in " + convertedFile);
    }
}


text:
/*
 *
 * Settings constants
 *
 */

export const DEFAULT_ACTION = 'app/Settings/DEFAULT_ACTION';
export const UPDATE_SETTINGS = 'app/Settings/UPDATE_SETTINGS';
export const UPDATE_FETCHING = 'app/Settings/UPDATE_FETCHING';
export const UPDATE_USER_LOADED = 'app/Settings/UPDATE_USER_LOADED';
export const UPDATE_USER_ERROR = 'app/Settings/UPDATE_USER_ERROR';


text:
import roslib; roslib.load_manifest('collision_avoidance_pick_and_place')
import rospy
import tf
import shape_msgs
import collision_avoidance_pick_and_place.srv
from collision_avoidance_pick_and_place.srv import *

#constants
TARGET_RECOGNITION_SERVICE = "target_recognition";

#variables
tf_listener = None

#server callback
def recognition_callback(req):

	ar_frame = req.ar_tag_frame_id
	world_frame = req.world_frame_id
	shape = req.shape

	# response object
	res = GetTargetPoseResponse()

	# lookup tranform
	try:
		(trans,rot) = tf_listener.lookupTransform(world_frame,ar_frame,rospy.Time(0))
		rospy.loginfo("ar_frame '%s' relative to '%s' detected",ar_frame,world_frame)

		#modifying height
		height = shape.dimensions[2] if (len(shape.dimensions)==3) else trans[2]

		# creating pose
		pose = geometry_msgs.msg.Pose()
		pose.position.x = trans[0]
		pose.position.y = trans[1]
		pose.position.z = height
		pose.orientation.x = rot[1]
		pose.orientation.y = rot[2]
		pose.orientation.z = rot[3]
		pose.orientation.w = rot[0]

		res.target_pose = pose
		res.succeeded = True

	except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):
		rospy.logerr("ar_frame '%s' relative to '%s' not found",ar_frame,world_frame)
		res.succeeded = False

	return res

if __name__ == "__main__":

	rospy.init_node("simulation_recognition_node")

	# creating listener
	tf_listener = tf.TransformListener()

	# creating server
	server = rospy.Service(TARGET_RECOGNITION_SERVICE,GetTargetPose,recognition_callback)

	rospy.loginfo("recognition service server ready")
	while not rospy.is_shutdown():

		rospy.sleep(0.2)


text:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <memory.h>

#include "iup_array.h"
#include "iup_assert.h"

struct _Iarray
{
  void* data;
  int count;
  int max_count;
  int elem_size;
  int start_count;
};

Iarray* iupArrayCreate(int start_count, int elem_size)
{
  Iarray* iarray = (Iarray*)malloc(sizeof(Iarray));
  iarray->count = 0;
  iarray->elem_size = elem_size;
  iarray->max_count = start_count;
  iarray->start_count = start_count;
  iarray->data = malloc(elem_size*start_count);
  iupASSERT(iarray->data!=NULL);
  if (!iarray->data)
  {
    free(iarray);
    return NULL;
  }
  memset(iarray->data, 0, elem_size*start_count);
  return iarray;
}

void iupArrayDestroy(Iarray* iarray)
{
  iupASSERT(iarray!=NULL);
  if (!iarray)
    return;
  if (iarray->data)
  {
    memset(iarray->data, 0, iarray->elem_size*iarray->max_count);
    free(iarray->data);
  }
  free(iarray);
}

void* iupArrayGetData(Iarray* iarray)
{
  iupASSERT(iarray!=NULL);
  if (!iarray)
    return NULL;
  return iarray->data;
}

void* iupArrayInc(Iarray* iarray)
{
  iupASSERT(iarray!=NULL);
  if (!iarray)
    return NULL;
  if (iarray->count >= iarray->max_count)
  {
    int old_count = iarray->max_count;
    iarray->max_count += iarray->start_count;
    iarray->data = realloc(iarray->data, iarray->elem_size*iarray->max_count);
    iupASSERT(iarray->data!=NULL);
    if (!iarray->data)
      return NULL;
    memset((unsigned char*)iarray->data + iarray->elem_size*old_count, 0, iarray->elem_size*(iarray->max_count-old_count));
  }
  iarray->count++;
  return iarray->data;
}

void* iupArrayAdd(Iarray* iarray, int add_count)
{
  iupASSERT(iarray!=NULL);
  if (!iarray)
    return NULL;
  if (iarray->count+add_count > iarray->max_count)
  {
    int old_count = iarray->max_count;
    iarray->max_count += add_count;
    iarray->data = realloc(iarray->data, iarray->elem_size*iarray->max_count);
    iupASSERT(iarray->data!=NULL);
    if (!iarray->data)
      return NULL;
    memset((unsigned char*)iarray->data + iarray->elem_size*old_count, 0, iarray->elem_size*(iarray->max_count-old_count));
  }
  iarray->count += add_count;
  return iarray->data;
}

void* iupArrayInsert(Iarray* iarray, int index, int insert_count)
{
  iupASSERT(iarray!=NULL);
  if (!iarray)
    return NULL;
  if (index < 0 || index > iarray->count)
    return NULL;
  iupArrayAdd(iarray, insert_count);
  if (index < iarray->count)  /* if equal, insert at the end, no need to move data */
    memmove((unsigned char*)iarray->data + iarray->elem_size*(index + insert_count),
            (unsigned char*)iarray->data + iarray->elem_size*index,
            iarray->elem_size*(iarray->count - insert_count - index));
  /* clear new data */
  memset((unsigned char*)iarray->data + iarray->elem_size*index, 0, iarray->elem_size*insert_count);
  return iarray->data;
}

void iupArrayRemove(Iarray* iarray, int index, int remove_count)
{
  iupASSERT(iarray!=NULL);
  if (!iarray)
    return;
  if (index < 0 || index+remove_count > iarray->count)
    return;
  if (index+remove_count < iarray->count)  /* if equal, remove at the end, no need to move data */
    memmove((unsigned char*)iarray->data + iarray->elem_size*index,
            (unsigned char*)iarray->data + iarray->elem_size*(index + remove_count),
            iarray->elem_size*(iarray->count - remove_count - index));
  /* clear old data */
  memset((unsigned char*)iarray->data + iarray->elem_size*(iarray->count - remove_count), 0, iarray->elem_size*remove_count);
  iarray->count -= remove_count;
}

int iupArrayCount(Iarray* iarray)
{
  iupASSERT(iarray!=NULL);
  if (!iarray)
    return 0;
  return iarray->count;
}


text:
from .base import rpartial
from .wand import WandTestCase

class BlurCase(WandTestCase):
    def handle_args(self, radius):
        self.radius = radius

    def runner(self, im):
        with im.clone() as im:
            self.blur(im, 2.5 * self.radius, self.radius)

    def readable_args(self):
        return ["{}px".format(self.radius)]

cases = [
    rpartial(BlurCase, radius)
    for radius in [
        1,
        10,
        30,
    ]
]


text:
#ifndef GRID_CIPC_INCLUDED
#define GRID_CIPC_INCLUDED

#include "../../transport.h"
#include "../../ipc.h"

/*  State machine managing connected IPC socket. */

int grid_cipc_create (void *hint, struct grid_epbase **epbase);

#endif


text:
module.exports = {
    addPlugin:       require('./addPlugin'),
    removePlugin:    require('./removePlugin'),
    togglePlugin:    require('./togglePlugin'),
    editPlugin:      require('./editPlugin'),
    hasPlugin:       require('./hasPlugin'),
    getPluginConfig: require('./getPluginConfig'),
    isDefaultPlugin: require('./isDefaultPlugin')
};


text:
<?php

use Silex\Provider\MonologServiceProvider;

require __DIR__.'/prod.php';

$app['debug'] = true;

$app->register(new MonologServiceProvider(), array(
    'monolog.logfile' => __DIR__.'/../silex.log',
    'monolog.name'    => 'app',
));


text:
"""This module holds all objects shared by all other modules in tftpy."""

import logging

LOG_LEVEL = logging.NOTSET
MIN_BLKSIZE = 8
DEF_BLKSIZE = 512
MAX_BLKSIZE = 65536
SOCK_TIMEOUT = 5
MAX_DUPS = 20
TIMEOUT_RETRIES = 5
DEF_TFTP_PORT = 69

# A hook for deliberately introducing delay in testing.
DELAY_BLOCK = 0

# Initialize the logger.
logging.basicConfig()
# The logger used by this library. Feel free to clobber it with your own, if you like, as
# long as it conforms to Python's logging.
log = logging.getLogger('tftpy')

def tftpassert(condition, msg):
    """This function is a simple utility that will check the condition
    passed for a false state. If it finds one, it throws a TftpException
    with the message passed. This just makes the code throughout cleaner
    by refactoring."""
    if not condition:
        raise TftpException, msg

def setLogLevel(level):
    """This function is a utility function for setting the internal log level.
    The log level defaults to logging.NOTSET, so unwanted output to stdout is
    not created."""
    global log
    log.setLevel(level)

class TftpErrors(object):
    """This class is a convenience for defining the common tftp error codes,
    and making them more readable in the code."""
    NotDefined = 0
    FileNotFound = 1
    AccessViolation = 2
    DiskFull = 3
    IllegalTftpOp = 4
    UnknownTID = 5
    FileAlreadyExists = 6
    NoSuchUser = 7
    FailedNegotiation = 8

class TftpException(Exception):
    """This class is the parent class of all exceptions regarding the handling
    of the TFTP protocol."""
    pass

class TftpTimeout(TftpException):
    """This class represents a timeout error waiting for a response from the
    other end."""
    pass


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Wilfred Pinfold</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
        <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Open+Sans">

About  Experience  Education  Other

The Art of Gaming

The Art of Gaming

The Art of Gaming

The Art of Gaming


text:
package edu.cmu.hcii.whyline.bytecode;

import edu.cmu.hcii.whyline.trace.EventKind;

/**
 * @author Andrew J. Ko
 *
 */
public final class FADD extends BinaryComputation {

	public FADD(CodeAttribute method) {
		super(method);
	}

	public final int getOpcode() { return 98; }
	public int byteLength() { return 1; }

	public String getPastTenseVerb() { return "added"; }

	public EventKind getTypeProduced() { return EventKind.FLOAT_PRODUCED; }

	public String getOperator() { return "+"; }

	public String getTypeDescriptorOfArgument(int argIndex) { return "F"; }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<oval_definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://oval.mitre.org/XMLSchema/oval-definitions-5 oval-definitions-schema.xsd http://oval.mitre.org/XMLSchema/oval-definitions-5#windows windows-definitions-schema.xsd" xmlns="http://oval.mitre.org/XMLSchema/oval-definitions-5" xmlns:oval-def="http://oval.mitre.org/XMLSchema/oval-definitions-5" xmlns:oval="http://oval.mitre.org/XMLSchema/oval-common-5" xmlns:win-def="http://oval.mitre.org/XMLSchema/oval-definitions-5#windows">
    <generator>
        <oval:schema_version>5.10.1</oval:schema_version>
        <oval:timestamp>2009-01-12T10:41:00-05:00</oval:timestamp>
      <terms_of_use>Copyright (c) 2002-2013, The MITRE Corporation. All rights reserved. The contents of this file are subject to the license described in terms.txt.</terms_of_use>
  </generator>
    <definitions>
        <definition id="oval:org.mitre.oval.test:def:922" version="1" class="miscellaneous">
            <metadata>
                <title>Evaluate to true if the win-def:wmi57_test is properly supported.</title>
                <description>This definition is intended to evalutate to true if the interpreter properly supports the win-def:wmi57_test.</description>
            </metadata>
            <notes>
                <note>It is important to note that the values used in this test definition are specific to a particular machine, and may not necessarily apply to your system. As a result, in order to have the definition return a result of 'true', you must either change these values to the ones found on your particular system, or you must configure your system to use these values.</note>
            </notes>

            <criteria>
                <criterion comment="Test that a wmi57_object with a namespace and wql is supported." test_ref="oval:org.mitre.oval.test:tst:1780"/>
            </criteria>
        </definition>
    </definitions>
    <tests>
        <wmi57_test id="oval:org.mitre.oval.test:tst:1780" version="1" comment="Test that a wmi57_object with a namespace and wql is supported." check_existence="at_least_one_exists" check="all"  xmlns="http://oval.mitre.org/XMLSchema/oval-definitions-5#windows">
            <object object_ref="oval:org.mitre.oval.test:obj:1324"/>
            <state state_ref="oval:org.mitre.oval.test:ste:887"/>
        </wmi57_test>
    </tests>
    <objects>
        <wmi57_object id="oval:org.mitre.oval.test:obj:1324" version="1" comment="Retrieves a wmi57_object with a namespace that equals 'root\cimv2' and a wql that equals 'SELECT ProcessId, Name, Description FROM Win32_Process'." xmlns="http://oval.mitre.org/XMLSchema/oval-definitions-5#windows">
            <namespace>root\cimv2</namespace>
            <wql>SELECT ProcessId, Name, Description FROM Win32_Process</wql>
        </wmi57_object>
    </objects>
    <states>
        <wmi57_state id="oval:org.mitre.oval.test:ste:887" version="1" comment="This state represents a wmi57_object that has a namespace that equals 'root\cimv2', a wql equal that equals 'SELECT ProcessId, Name, Description FROM Win32_Process', and has at least one result with a 'processid' field greater than or equal to '0', a 'name' field equal to 'explorer.exe', and a 'description' field that matches the regular expression '.*'." xmlns="http://oval.mitre.org/XMLSchema/oval-definitions-5#windows">
            <namespace>root\cimv2</namespace>
            <wql>SELECT ProcessId, Name, Description FROM Win32_Process</wql>
            <result entity_check="at least one" datatype="record">
                <oval-def:field name="processid" datatype="int" operation="greater than or equal">0</oval-def:field>
                <oval-def:field name="name">explorer.exe</oval-def:field>
                <oval-def:field name="description" operation="pattern match">.*</oval-def:field>
            </result>
        </wmi57_state>
    </states>
</oval_definitions>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.security.keyvault.keys;

import com.azure.security.keyvault.keys.models.CreateEcKeyOptions;
import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions;
import com.azure.identity.DefaultAzureCredentialBuilder;

import java.time.OffsetDateTime;

/**
 * Sample demonstrates how to asynchronously list, recover and purge deleted keys in a soft-delete enabled key vault.
 */
public class ManagingDeletedKeysAsync {
    /**
     * Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted keys in a soft-delete enabled key vault.
     *
     * @param args Unused. Arguments to the program.
     * @throws IllegalArgumentException when invalid key vault endpoint is passed.
     * @throws InterruptedException when the thread is interrupted in sleep mode.
     */
    public static void main(String[] args) throws InterruptedException {

        // NOTE: To manage deleted keys, your key vault needs to have soft-delete enabled. Soft-delete allows deleted keys
        // to be retained for a given retention period (90 days). During this period deleted keys can be recovered and if
        // a key needs to be permanently deleted then it needs to be purged.

        // Instantiate a client that will be used to call the service. Notice that the client is using default Azure
        // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
        // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
        KeyAsyncClient keyAsyncClient = new KeyClientBuilder()
                .vaultUrl("https://{YOUR_VAULT_NAME}.vault.azure.net")
                .credential(new DefaultAzureCredentialBuilder().build())
                .buildAsyncClient();

        // Let's create Ec and Rsa keys valid for 1 year. if the key
        // already exists in the key vault, then a new version of the key is created.
        keyAsyncClient.createEcKey(new CreateEcKeyOptions("CloudEcKey")
                .setExpiresOn(OffsetDateTime.now().plusYears(1)))
                .subscribe(keyResponse ->
                    System.out.printf("Key is created with name %s and type %s %n", keyResponse.getName(), keyResponse.getKeyType()));

        Thread.sleep(2000);

        keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey")
                .setExpiresOn(OffsetDateTime.now().plusYears(1)))
                .subscribe(keyResponse ->
                    System.out.printf("Key is created with name %s and type %s %n", keyResponse.getName(), keyResponse.getKeyType()));

        Thread.sleep(2000);

        // The Cloud Rsa Key is no longer needed, need to delete it from the key vault.
        keyAsyncClient.beginDeleteKey("CloudEcKey")
            .subscribe(pollResponse -> {
                System.out.println("Delete Status: " + pollResponse.getStatus().toString());
                System.out.println("Delete Key Name: " + pollResponse.getValue().getName());
                System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString());
            });

        //To ensure key is deleted on server side.
        Thread.sleep(30000);

        // We accidentally deleted Cloud Ec key. Let's recover it.
        // A deleted key can only be recovered if the key vault is soft-delete enabled.
        keyAsyncClient.beginRecoverDeletedKey("CloudEcKey")
            .subscribe(pollResponse -> {
                System.out.println("Recovery Status: " + pollResponse.getStatus().toString());
                System.out.println("Recover Key Name: " + pollResponse.getValue().getName());
                System.out.println("Recover Key Type: " + pollResponse.getValue().getKeyType());
            });

        //To ensure key is recovered on server side before moving forward.
        Thread.sleep(10000);

        // The Cloud Ec and Rsa keys are no longer needed, need to delete them from the key vault.
        keyAsyncClient.beginDeleteKey("CloudEcKey")
            .subscribe(pollResponse -> {
                System.out.println("Delete Status: " + pollResponse.getStatus().toString());
                System.out.println("Delete Key Name: " + pollResponse.getValue().getName());
                System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString());
            });

        keyAsyncClient.beginDeleteKey("CloudRsaKey")
            .subscribe(pollResponse -> {
                System.out.println("Delete Status: " + pollResponse.getStatus().toString());
                System.out.println("Delete Key Name: " + pollResponse.getValue().getName());
                System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString());
            });

        // To ensure key is deleted on server side.
        Thread.sleep(30000);

        // You can list all the deleted and non-purged keys, assuming key vault is soft-delete enabled.
        keyAsyncClient.listDeletedKeys().subscribe(deletedKey ->
            System.out.printf("Deleted key's recovery Id %s %n", deletedKey.getRecoveryId()));

        Thread.sleep(15000);

        // If the keyvault is soft-delete enabled, then for permanent deletion  deleted keys need to be purged.
        keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey").subscribe(purgeResponse ->
            System.out.printf("Storage account key purge status response %d %n", purgeResponse.getStatusCode()));

        keyAsyncClient.purgeDeletedKeyWithResponse("CloudEcKey").subscribe(purgeResponse ->
            System.out.printf("Bank account key purge status response %d %n", purgeResponse.getStatusCode()));

        // To ensure key is purged on server side.
        Thread.sleep(15000);
    }
}


text:
using System.Linq;
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Menu;

namespace Thresh
{
    public static class Combo
    {
        public static Menu Menu
        {
            get { return MenuManager.GetSubMenu("Combo"); }
        }

        public static bool IsActive
        {
            get { return ModeManager.IsCombo; }
        }

        public static void Execute()
        {
            var target = TargetSelector.Target;
            if (target == null) return;
            if (Menu.GetSliderValue("E1") > 0 && SpellSlot.E.IsReady())
            {
                switch (Menu.GetSliderValue("E1"))
                {
                    case 1:
                        PerformPull();
                        break;
                    case 2:
                        PerformPush();
                        break;
                    case 3:
                        if (EntityManager.Heroes.Allies.HealthPercent(TargetSelector.Range) >= EntityManager.Heroes.Enemies.HealthPercent(TargetSelector.Range))
                        {
                            PerformPull();
                        }
                        else
                        {
                            PerformPush();
                        }
                        break;
                }
            }
            if (SpellSlot.W.IsReady())
            {
                if (Menu.GetSliderValue("W1") > 0)
                {
                    switch (Menu.GetSliderValue("W1"))
                    {
                        case 1:
                            if (SpellManager.QTarget.IsValidTarget() && SpellManager.QTarget.NetworkId == target.NetworkId)
                            {
                                SpellManager.CastW(Champion.Best_Offensive_W_Ally(target));
                            }
                            break;
                        case 2:
                            SpellManager.CastW(Champion.Best_Offensive_W_Ally(target));
                            break;
                    }
                }
                if (Menu.GetSliderValue("W2") > 0)
                {
                    var ally =
                        EntityManager.Heroes.Allies.Where(h => h.IsValidTarget(TargetSelector.Range) && !h.IsMe && h.HealthPercent <= Menu.GetSliderValue("W2"))
                            .OrderByDescending(h => h.GetPriority() / h.HealthPercent)
                            .FirstOrDefault();
                    if (ally != null)
                    {
                        SpellManager.CastW(ally);
                    }
                }
            }
            if (SpellSlot.Q.IsReady())
            {

                if (Menu.GetSliderValue("Q1") > 0)
                {
                    switch (Menu.GetSliderValue("Q1"))
                    {
                        case 1:
                            SpellManager.CastQ1(target);
                            break;
                        case 2:
                            foreach (var h in EntityManager.Heroes.Enemies.Where(h => h.IsValidTarget()))
                            {
                                SpellManager.CastQ1(h);
                            }
                            break;
                    }
                }
                if (Menu.GetSliderValue("Q2") > 0 && SpellManager.QTarget.IsValidTarget())
                {
                    switch (Menu.GetSliderValue("Q2"))
                    {
                        case 1:
                            if (SpellManager.QTarget.NetworkId == target.NetworkId)
                            {
                                SpellManager.CastQ2(target);
                            }
                            break;
                        case 2:
                            if (SpellManager.QTarget.IsInRange(target, 350))
                            {
                                SpellManager.CastQ2(target);
                            }
                            break;
                    }
                }
            }
            if (SpellSlot.R.IsReady())
            {
                if (Menu.GetSliderValue("R1") > 0 && Menu.GetSliderValue("R1") >= Util.MyHero.HealthPercent)
                {
                    foreach (var h in EntityManager.Heroes.Enemies.Where(h => h.IsValidTarget(TargetSelector.Range)))
                    {
                        SpellManager.CastR(h);
                    }
                }
                if (Menu.GetSliderValue("R2") > 0)
                {
                    if (Util.MyHero.CountEnemiesInside(SpellManager.R.Range) >= Menu.GetSliderValue("R2"))
                    {
                        Util.MyHero.Spellbook.CastSpell(SpellSlot.R);
                    }
                }
            }
        }

        public static void PerformPull()
        {
            switch (Menu.GetSliderValue("E2"))
            {
                case 1:
                    SpellManager.Pull(TargetSelector.Target);
                    break;
                case 2:
                    foreach (var h in EntityManager.Heroes.Enemies.Where(h => h.IsValidTarget()))
                    {
                        SpellManager.Pull(h);
                    }
                    break;
            }
        }
        public static void PerformPush()
        {
            switch (Menu.GetSliderValue("E2"))
            {
                case 1:
                    SpellManager.Push(TargetSelector.Target);
                    break;
                case 2:
                    foreach (var h in EntityManager.Heroes.Enemies.Where(h => h.IsValidTarget()))
                    {
                        SpellManager.Push(h);
                    }
                    break;
            }
        }
    }
}


text:
var sys = require('sys');

var options = {};
var console = require('vows/console');
var stylize = console.stylize,
    puts = console.puts(options);
//
// Console reporter
//

this.name = 'spec';
this.report = function (data, s) {
    var event = data[1];

    options.stream = typeof(s) === 'object' ? s : process.stdout;
    buffer = [];

    switch (data[0]) {
        case 'subject':
            puts('\n♢ ' + stylize(event, 'bold') + '\n');
            break;
        case 'context':
            puts(this.contextText(event));
            break;
        case 'vow':
            puts(this.vowText(event));
            break;
        case 'end':
            sys.print('\n');
            break;
        case 'finish':
            puts(console.result(event).join('\n'));
            break;
        case 'error':
            puts(console.error(event));
            break;
    }
};

this.contextText = function (event) {
    return '  ' + event;
};

this.vowText = function (event) {
    var buffer = [];

    buffer.push('   ' + {
        honored: ' ✓ ',
        broken:  ' ✗ ',
        errored: ' ✗ ',
        pending: ' - '
    }[event.status] + stylize(event.title, ({
        honored: 'green',
        broken:  'yellow',
        errored: 'red',
        pending: 'cyan'
    })[event.status]));

    if (event.status === 'broken') {
        buffer.push('      » ' + event.exception);
    } else if (event.status === 'errored') {
        if (event.exception.type === 'promise') {
            buffer.push('      » ' + stylize("An unexpected error was caught: " +
                           stylize(event.exception.error, 'bold'), 'red'));
        } else {
            buffer.push('    ' + stylize(event.exception, 'red'));
        }
    }
    return buffer.join('\n');
};

this.print = function (str) {
    sys.print(str);
};


text:
package br.com.wcorrea.transport.api.repository.itinerario;

import br.com.wcorrea.transport.api.model.Itinerario;
import br.com.wcorrea.transport.api.repository.utils.UtilsRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

public class ItinerarioRepositoryImpl implements ItinerarioRepositoryQuery {

    @PersistenceContext
    private EntityManager manager;

    /**
     * CARREGA TODOS OS REGISTROS DE FORMA PAGINADA
     *
     * @param filtro
     * @param paginacao
     * @return
     */
    @Override
    public Page<Itinerario> findAll(ItinerarioFiltro filtro, Pageable paginacao) {
        TypedQuery<Itinerario> queryList = manager.createQuery(this.createQuery(filtro, false), Itinerario.class);
        TypedQuery<Long> totalRegistros = manager.createQuery(this.createQuery(filtro, true), Long.class);

        UtilsRepository.adicionarRestricoesPaginacao(queryList, paginacao);
        return new PageImpl<>(queryList.getResultList(), paginacao, totalRegistros.getSingleResult());
    }

    /**
     * Cria as consultas da aplicação
     *
     * @param filtro
     * @param count
     * @return
     */
    private String createQuery(ItinerarioFiltro filtro, boolean count) {

        filtro.setFiltroGlobal(UtilsRepository.removeCaracteresProblematicos(filtro.getFiltroGlobal()));
        filtro.setCodigo(UtilsRepository.removeCaracteresProblematicos(filtro.getCodigo()));
        filtro.setNome(UtilsRepository.removeCaracteresProblematicos(filtro.getNome()));
        filtro.setDescricao(UtilsRepository.removeCaracteresProblematicos(filtro.getDescricao()));

        String sql;
        if (count) {
            sql = "select count(a) from itinerario a where 1=1 ";
        } else {
            sql = "from itinerario a where 1=1 ";
        }

        if (StringUtils.isNotBlank(filtro.getFiltroGlobal())) {
            sql += " and (";
            sql += " upper(a.nome) like '%" + filtro.getFiltroGlobal().toUpperCase().trim() + "%'";
            sql += " or upper(a.codigo) like '%" + filtro.getFiltroGlobal().toUpperCase().trim() + "%'";
            sql += " or upper(a.descricao) like '%" + filtro.getFiltroGlobal().toUpperCase().trim() + "%'";
            sql += " )";
        } else {
            if (StringUtils.isNotBlank(filtro.getNome())) {
                sql += " and upper(a.nome) like '%" + filtro.getNome().toUpperCase().trim() + "%'";
            }
            if (StringUtils.isNotBlank(filtro.getCodigo())) {
                sql += " and upper(a.codigo) like '%" + filtro.getCodigo().toUpperCase().trim() + "%'";
            }
            if (StringUtils.isNotBlank(filtro.getDescricao())) {
                sql += " and upper(a.descricao) like '%" + filtro.getDescricao().toUpperCase().trim() + "%'";
            }
        }

        sql = UtilsRepository.adicionarOrdenacaoConsulta(sql, count, filtro.getCampoOrdenacao(), filtro.getOrdemClassificacao());
        return sql;
    }

}


text:
using System;
using System.Runtime.InteropServices;

public class TestBase
{
    public String strLoc = "baseLoc";
    public int iCountTestcases = 0;
    public int iCountErrors = 0;

    public bool Eval(bool exp)
    {
        return Eval(exp, null);
    }
    public bool Eval(bool exp, String errorMsg)
    {
        if (!exp)
        {
            iCountErrors++;
            String err = errorMsg;
            if (err == null)
                err = "Test Failed at location: " + strLoc;
            Console.WriteLine(err);
        }
        return exp;
    }

    public bool Eval(bool exp, String format, params object[] arg)
    {
        if (!exp)
        {
            return Eval(exp, String.Format(format, arg));
        }
        return true;
    }

    public bool Eval<T>(T expected, T actual, String errorMsg)
    {
        bool retValue = expected == null ? actual == null : expected.Equals(actual);

        if (!retValue)
            return Eval(retValue, errorMsg +
                "   Expected:" + (null == expected ? "<null>" : expected.ToString()) +
                "   Actual  :" + (null == actual ? "<null>" : actual.ToString()));
        return true;
    }

    public bool Eval<T>(T expected, T actual, String format, params object[] arg)
    {
        bool retValue = expected == null ? actual == null : expected.Equals(actual);

        if (!retValue)
            return Eval(retValue, String.Format(format, arg) +
                "   Expected:" + (null == expected ? "<null>" : expected.ToString()) +
                "   Actual:  " + (null == actual ? "<null>" : actual.ToString()));

        return true;
    }
}


text:
<?php

namespace Yoast\WP\SEO\Presenters\Open_Graph;

use Yoast\WP\SEO\Presentations\Indexable_Presentation;
use Yoast\WP\SEO\Presenters\Abstract_Indexable_Tag_Presenter;

/**
 * Presenter class for the Open Graph type.
 */
class Type_Presenter extends Abstract_Indexable_Tag_Presenter {

	/**
	 * The tag format including placeholders.
	 *
	 * @var string
	 */
	protected $tag_format = '<meta property="og:type" content="%s" />';

	/**
	 * Run the opengraph type content through the `wpseo_opengraph_type` filter.
	 *
	 * @return string $type The filtered type.
	 */
	public function get() {
		/**
		 * Filter: 'wpseo_opengraph_type' - Allow changing the opengraph type.
		 *
		 * @api string $type The type.
		 *
		 * @param Indexable_Presentation $presentation The presentation of an indexable.
		 */
		return (string) \apply_filters( 'wpseo_opengraph_type', $this->presentation->open_graph_type, $this->presentation );
	}
}