text:
using std::string;

// These will be set when running a JIT'ed program.
extern "C"
{
  EXPORT_SYMBOL pony_type_t** __PonyDescTablePtr;
  EXPORT_SYMBOL size_t __PonyDescTableSize;
}

static const char* _builtin =
  "primitive U8 is Real[U8]\n"
  "  new create(a: U8 = 0) => a\n"
  "  fun mul(a: U8): U8 => this * a\n"
  "primitive I8 is Real[I8]"
  "  new create(a: I8 = 0) => a\n"
  "  fun neg(): I8 => -this\n"
  "primitive U16 is Real[U16]"
  "  new create(a: U16 = 0) => a\n"
  "primitive I16 is Real[I16]"
  "  new create(a: I16 = 0) => a\n"
  "  fun neg(): I16 => -this\n"
  "  fun mul(a: I16): I16 => this * a\n"
  "primitive U32 is Real[U32]"
  "  new create(a: U32 = 0) => a\n"
  "primitive I32 is Real[I32]"
  "  new create(a: I32 = 0) => a\n"
  "  fun neg(): I32 => -this\n"
  "  fun mul(a: I32): I32 => this * a\n"
  "primitive U64 is Real[U64]"
  "  new create(a: U64 = 0) => a\n"
  "  fun op_xor(a: U64): U64 => this xor a\n"
  "primitive I64 is Real[I64]"
  "  new create(a: I64 = 0) => a\n"
  "  fun neg():I64 => -this\n"
  "  fun mul(a: I64): I64 => this * a\n"
  "  fun op_or(a: I64): I64 => this or a\n"
  "  fun op_and(a: I64): I64 => this and a\n"
  "  fun op_xor(a: I64): I64 => this xor a\n"
  "primitive U128 is Real[U128]"
  "  new create(a: U128 = 0) => a\n"
  "  fun mul(a: U128): U128 => this * a\n"
  "  fun div(a: U128): U128 => this / a\n"
  "primitive I128 is Real[I128]"
  "  new create(a: I128 = 0) => a\n"
  "  fun neg(): I128 => -this\n"
  "primitive ULong is Real[ULong]"
  "  new create(a: ULong = 0) => a\n"
  "primitive ILong is Real[ILong]"
  "  new create(a: ILong = 0) => a\n"
  "  fun neg(): ILong => -this\n"
  "primitive USize is Real[USize]"
  "  new create(a: USize = 0) => a\n"
  "  fun u64(): U64 => compile_intrinsic\n"
  "primitive ISize is Real[ISize]"
  "  new create(a: ISize = 0) => a\n"
  "  fun neg(): ISize => -this\n"
  "primitive F32 is Real[F32]"
  "  new create(a: F32 = 0) => a\n"
  "primitive F64 is Real[F64]"
  "  new create(a: F64 = 0) => a\n"
  "type Number is (Signed | Unsigned | Float)\n"
  "type Signed is (I8 | I16 | I32 | I64 | I128 | ILong | ISize)\n"
  "type Unsigned is (U8 | U16 | U32 | U64 | U128 | ULong | USize)\n"
  "type Float is (F32 | F64)\n"
  "trait val Real[A: Real[A] val]\n"
  "class val Env\n"
  "  new _create(argc: U32, argv: Pointer[Pointer[U8]] val,\n"
  "    envp: Pointer[Pointer[U8]] val)\n"
  "  => None\n"
  "primitive None\n"
  "interface tag Any\n"
  "primitive Bool\n"
  "  new create(a: Bool) => a\n"
  "  fun op_and(a: Bool): Bool => this and a\n"
  "  fun op_not(): Bool => not this\n"
  "class val String\n"
  "struct Pointer[A]\n"
  "  new create() => compile_intrinsic\n"
  "  fun tag is_null(): Bool => compile_intrinsic\n"
  "interface Seq[A]\n"
  // Fake up arrays and iterators enough to allow tests to
  // - create array literals
  // - call .values() iterator in a for loop
  "class Array[A] is Seq[A]\n"
  "  new create(len: USize, alloc: USize = 0) => true\n"
  "  fun ref push(value: A): Array[A]^ => this\n"
  "  fun values(): Iterator[A] => object ref\n"
  "    fun ref has_next(): Bool => false\n"
  "    fun ref next(): A ? => error\n"
  "  end\n"
  "interface Iterator[A]\n"
  "  fun ref has_next(): Bool\n"
  "  fun ref next(): A ?\n";

// Check whether the 2 given ASTs are identical
static bool compare_asts(ast_t* expected, ast_t* actual, errors_t *errors)
{
  pony_assert(expected != NULL);
  pony_assert(actual != NULL);

  token_id expected_id = ast_id(expected);
  token_id actual_id = ast_id(actual);

  if(expected_id != actual_id)
  {
    ast_error(errors, expected,
      "AST ID mismatch, got %d (%s), expected %d (%s)",
      ast_id(actual), ast_get_print(actual),
      ast_id(expected), ast_get_print(expected));
    return false;
  }

  // Even in 2 ASTS that we consider to be the same, hygenic ids might not
  // match each other.
  // To catch all possible error cases we should keep a mapping of the hygenic
  // ids in the 2 trees and check for a 1 to 1 correlation.
  // For now just let all hygenic ids match each other. This will allow some
  // errors through, but it's much easier for now.
  if(ast_id(expected) == TK_ID && ast_name(actual)[0] == '$' &&
    ast_name(expected)[0] == '$')
  {
    // Allow expected and actual hygenic names to match.
  }
  else if(strcmp(ast_get_print(expected), ast_get_print(actual)) != 0)
  {
    ast_error(errors, expected, "AST text mismatch, got %s, expected %s",
      ast_get_print(actual), ast_get_print(expected));
    return false;
  }

  if(ast_has_scope(expected) && !ast_has_scope(actual))
  {
    ast_error(errors, expected, "AST missing scope");
    return false;
  }

  if(!ast_has_scope(expected) && ast_has_scope(actual))
  {
    ast_error(errors, actual, "Unexpected AST scope");
    return false;
  }

  // Check types
  ast_t* expected_type = ast_type(expected);
  ast_t* actual_type = ast_type(actual);

  if(expected_type != NULL || actual_type != NULL)
  {
    if(expected_type == NULL)
    {
      ast_error(errors, actual, "Unexpected type found, %s",
        ast_get_print(actual_type));
      return false;
    }

    if(actual_type == NULL)
    {
      ast_error(errors, actual, "Expected type not found, %s",
        ast_get_print(expected_type));
      return false;
    }

    if(!compare_asts(expected_type, actual_type, errors))
      return false;
  }

  // Check children
  ast_t* expected_child = ast_child(expected);
  ast_t* actual_child = ast_child(actual);

  while(expected_child != NULL && actual_child != NULL)
  {
    if(!compare_asts(expected_child, actual_child, errors))
      return false;

    expected_child = ast_sibling(expected_child);
    actual_child = ast_sibling(actual_child);
  }

  if(expected_child != NULL)
  {
    ast_error(errors, expected, "Expected child %s not found",
      ast_get_print(expected));
    return false;
  }

  if(actual_child != NULL)
  {
    ast_error(errors, actual, "Unexpected child node found, %s",
      ast_get_print(actual));
    return false;
  }

  return true;
}

// class PassTest

void PassTest::SetUp()
{
  pass_opt_init(&opt);
  codegen_pass_init(&opt);
  package_init(&opt);
  program = NULL;
  package = NULL;
  module = NULL;
  compile = NULL;
  _builtin_src = _builtin;
  _first_pkg_path = "prog";
  package_clear_magic();
  package_suppress_build_message();
  opt.verbosity = VERBOSITY_QUIET;
  last_pass = PASS_PARSE;
}

void PassTest::TearDown()
{
  if(compile != NULL)
  {
    codegen_cleanup(compile);
    POOL_FREE(compile_t, compile);
    compile = NULL;
  }
  ast_free(program);
  program = NULL;
  package = NULL;
  module = NULL;
  last_pass = PASS_PARSE;
  package_done();
  codegen_pass_cleanup(&opt);
  pass_opt_done(&opt);
}

void PassTest::set_builtin(const char* src)
{
  _builtin_src = src;
}

void PassTest::add_package(const char* path, const char* src)
{
  package_add_magic_src(path, src);
}

void PassTest::default_package_name(const char* path)
{
  _first_pkg_path = path;
}

size_t PassTest::ref_count(ast_t* ast, const char* name)
{
  if(ast == NULL)
    return 0;

  size_t count = 0;
  symtab_t* symtab = ast_get_symtab(ast);

  if(symtab != NULL && symtab_find(symtab, stringtab(name), NULL) != NULL)
    count = 1;

  for(ast_t* p = ast_child(ast); p != NULL; p = ast_sibling(p))
    count += ref_count(p, name);

  return count;
}

void PassTest::check_ast_same(ast_t* expect, ast_t* actual)
{
  ASSERT_NE((void*)NULL, expect);
  ASSERT_NE((void*)NULL, actual);

  errors_t *errors = errors_alloc();

  if(!compare_asts(expect, actual, errors))
  {
    printf("Expected:\n");
    ast_print(expect);
    printf("Got:\n");
    ast_print(actual);
    errors_print(errors);
    ASSERT_TRUE(false);
  }

  errors_free(errors);
}

void PassTest::test_compile(const char* src, const char* pass)
{
  DO(build_package(pass, src, _first_pkg_path, true, NULL, false));

  package = ast_child(program);
  module = ast_child(package);
}

void PassTest::test_compile_resume(const char* pass)
{
  DO(build_package(pass, NULL, NULL, true, NULL, true));
}

void PassTest::test_error(const char* src, const char* pass)
{
  DO(build_package(pass, src, _first_pkg_path, false, NULL, false));

  package = NULL;
  module = NULL;
  ASSERT_EQ((void*)NULL, program);
}

void PassTest::test_expected_errors(const char* src, const char* pass,
  const char** errors)
{
  DO(build_package(pass, src, _first_pkg_path, false, errors, false));

  package = NULL;
  module = NULL;
  ASSERT_EQ((void*)NULL, program);
}

void PassTest::test_equiv(const char* actual_src, const char* actual_pass,
  const char* expect_src, const char* expect_pass)
{
  DO(build_package(expect_pass, expect_src, "expect", true, NULL, false));
  ast_t* expect_ast = program;
  ast_t* expect_package = ast_child(expect_ast);
  program = NULL;

  DO(test_compile(actual_src, actual_pass));

  DO(check_ast_same(expect_package, package));
  ast_free(expect_ast);
}

ast_t* PassTest::type_of(const char* name)
{
  pony_assert(name != NULL);
  pony_assert(program != NULL);
  return type_of_within(program, name);
}

ast_t* PassTest::numeric_literal(uint64_t num)
{
  pony_assert(program != NULL);
  return numeric_literal_within(program, num);
}

ast_t* PassTest::lookup_in(ast_t* ast, const char* name)
{
  pony_assert(ast != NULL);
  pony_assert(name != NULL);

  symtab_t* symtab = ast_get_symtab(ast);
  pony_assert(symtab != NULL);

  return symtab_find(symtab, stringtab(name), NULL);
}

ast_t* PassTest::lookup_type(const char* name)
{
  pony_assert(package != NULL);
  return lookup_in(package, name);
}

ast_t* PassTest::lookup_member(const char* type_name, const char* member_name)
{
  pony_assert(type_name != NULL);
  pony_assert(member_name != NULL);

  ast_t* type = lookup_type(type_name);
  pony_assert(type != NULL);

  return lookup_in(type, member_name);
}

bool PassTest::run_program(int* exit_code)
{
  pony_assert(compile != NULL);

  pony_exitcode(0);
  jit_symbol_t symbols[] = {
    {"__PonyDescTablePtr", &__PonyDescTablePtr, sizeof(pony_type_t**)},
    {"__PonyDescTableSize", &__PonyDescTableSize, sizeof(size_t)}};
  return gen_jit_and_run(compile, exit_code, symbols, 2);
}

// Private methods

void PassTest::build_package(const char* pass, const char* src,
  const char* package_name, bool check_good, const char** expected_errors,
  bool resume)
{
  ASSERT_NE((void*)NULL, pass);

  if(!resume)
  {
    ASSERT_NE((void*)NULL, src);
    ASSERT_NE((void*)NULL, package_name);

    if(compile != NULL)
    {
      codegen_cleanup(compile);
      POOL_FREE(compile_t, compile);
      compile = NULL;
    }
    ast_free(program);
    program = NULL;
    package = NULL;
    module = NULL;
    last_pass = PASS_PARSE;

    lexer_allow_test_symbols();

#ifndef PONY_PACKAGES_DIR
#  error Packages directory undefined
#else
    if(_builtin_src != NULL)
    {
      package_add_magic_src("builtin", _builtin_src);
    } else {
      char path[FILENAME_MAX];
      path_cat(PONY_PACKAGES_DIR, "builtin", path);
      package_add_magic_path("builtin", path);
    }
#endif

    package_add_magic_src(package_name, src);

    package_suppress_build_message();

    limit_passes(&opt, pass);
    program = program_load(stringtab(package_name), &opt);

    if((program != NULL) && (opt.limit >= PASS_REACH))
    {
      compile = POOL_ALLOC(compile_t);

      if(!codegen_gen_test(compile, program, &opt, PASS_PARSE))
      {
        codegen_cleanup(compile);
        POOL_FREE(compile_t, compile);
        ast_free(program);
        compile = NULL;
        program = NULL;
      }
    }
  } else {
    ASSERT_NE((void*)NULL, program);

    limit_passes(&opt, pass);

    if(ast_passes_program(program, &opt))
    {
      if(opt.limit >= PASS_REACH)
      {
        if(compile == NULL)
          compile = POOL_ALLOC(compile_t);

        if(!codegen_gen_test(compile, program, &opt, last_pass))
        {
          codegen_cleanup(compile);
          POOL_FREE(compile_t, compile);
          ast_free(program);
          compile = NULL;
          program = NULL;
        }
      }
    } else {
      ast_free(program);
      program = NULL;
    }
  }

  last_pass = opt.limit;

  if(expected_errors != NULL)
  {
    const char* expected_error = *expected_errors;
    size_t expected_count = 0;
    while(expected_error != NULL)
    {
      expected_count++;
      expected_error = expected_errors[expected_count];
    }

    ASSERT_EQ(expected_count, errors_get_count(opt.check.errors));

    errormsg_t* e = errors_get_first(opt.check.errors);
    for(size_t i = 0; i < expected_count; i++)
    {
      expected_error = expected_errors[i];

      if((e == NULL) || (expected_error == NULL))
        break;

      EXPECT_TRUE(strstr(e->msg, expected_error) != NULL)
        << "Actual error: " << e->msg;
      e = e->next;
    }
  }

  if(check_good)
  {
    errors_print(opt.check.errors);

    ASSERT_NE((void*)NULL, program);
  }
}

ast_t* PassTest::type_of_within(ast_t* ast, const char* name)
{
  pony_assert(ast != NULL);
  pony_assert(name != NULL);

  // Is this node the definition we're looking for?
  switch(ast_id(ast))
  {
    case TK_PARAM:
    case TK_LET:
    case TK_VAR:
    case TK_FLET:
    case TK_FVAR:
      if(strcmp(name, ast_name(ast_child(ast))) == 0)
      {
        // Match found
        return ast_childidx(ast, 1);
      }

      break;

    default:
      break;
  }

  // Check children.
  for(ast_t* p = ast_child(ast); p != NULL; p = ast_sibling(p))
  {
    ast_t* r = type_of_within(p, name);

    if(r != NULL)
      return r;
  }

  // Not found.
  return NULL;
}

ast_t* PassTest::numeric_literal_within(ast_t* ast, uint64_t num)
{
  pony_assert(ast != NULL);

  // Is this node the definition we're looking for?
  if (ast_id(ast) == TK_INT && lexint_cmp64(ast_int(ast), num) == 0)
  {
    return ast;
  }

  // Check children.
  for(ast_t* p = ast_child(ast); p != NULL; p = ast_sibling(p))
  {
    ast_t* r = numeric_literal_within(p, num);

    if(r != NULL)
      return r;
  }

  // Not found.
  return NULL;
}

// Environment methods

void Environment::SetUp()
{
  codegen_llvm_init();
}

void Environment::TearDown()
{
  codegen_llvm_shutdown();
}

int main(int argc, char** argv)
{
  testing::InitGoogleTest(&argc, argv);
  testing::AddGlobalTestEnvironment(new Environment());
  return RUN_ALL_TESTS();
}


text:
/***************************************************************************
 * Linux PPP over X - Generic PPP transport layer sockets
 * Linux PPP over Ethernet (PPPoE) Socket Implementation (RFC 2516)
 *
 * This file supplies definitions required by the PPP over Ethernet driver
 * (pppox.c).  All version information wrt this file is located in pppox.c
 *
 * License:
 *		This program is free software; you can redistribute it and/or
 *		modify it under the terms of the GNU General Public License
 *		as published by the Free Software Foundation; either version
 *		2 of the License, or (at your option) any later version.
 *
 */

#ifndef __LINUX_IF_PPPOX_H
#define __LINUX_IF_PPPOX_H

#include <asm/types.h>
#include <asm/byteorder.h>

#ifdef  __KERNEL__
#include <linux/if_ether.h>
#include <linux/if.h>
#include <linux/netdevice.h>
#include <linux/sched.h>
#include <asm/semaphore.h>
#include <linux/ppp_channel.h>
#endif /* __KERNEL__ */

/* For user-space programs to pick up these definitions
 * which they wouldn't get otherwise without defining __KERNEL__
 */
#ifndef AF_PPPOX
#define AF_PPPOX	24
#define PF_PPPOX	AF_PPPOX
#endif /* !(AF_PPPOX) */

/************************************************************************
 * PPPoE addressing definition
 */
typedef __u16 sid_t;
struct pppoe_addr{
       sid_t           sid;                    /* Session identifier */
       unsigned char   remote[ETH_ALEN];       /* Remote address */
       char            dev[IFNAMSIZ];          /* Local device to use */
};

/************************************************************************
 * Protocols supported by AF_PPPOX
 */
#define PX_PROTO_OE    0 /* Currently just PPPoE */
#define PX_MAX_PROTO   1

struct sockaddr_pppox {
       sa_family_t     sa_family;            /* address family, AF_PPPOX */
       unsigned int    sa_protocol;          /* protocol identifier */
       union{
               struct pppoe_addr       pppoe;
       }sa_addr;
}__attribute__ ((packed));

/*********************************************************************
 *
 * ioctl interface for defining forwarding of connections
 *
 ********************************************************************/

#define PPPOEIOCSFWD	_IOW(0xB1 ,0, sizeof(struct sockaddr_pppox))
#define PPPOEIOCDFWD	_IO(0xB1 ,1)
/*#define PPPOEIOCGFWD	_IOWR(0xB1,2, sizeof(struct sockaddr_pppox))*/

/* Codes to identify message types */
#define PADI_CODE	0x09
#define PADO_CODE	0x07
#define PADR_CODE	0x19
#define PADS_CODE	0x65
#define PADT_CODE	0xa7
struct pppoe_tag {
	__u16 tag_type;
	__u16 tag_len;
	char tag_data[0];
} __attribute ((packed));

/* Tag identifiers */
#define PTT_EOL		__constant_htons(0x0000)
#define PTT_SRV_NAME	__constant_htons(0x0101)
#define PTT_AC_NAME	__constant_htons(0x0102)
#define PTT_HOST_UNIQ	__constant_htons(0x0103)
#define PTT_AC_COOKIE	__constant_htons(0x0104)
#define PTT_VENDOR 	__constant_htons(0x0105)
#define PTT_RELAY_SID	__constant_htons(0x0110)
#define PTT_SRV_ERR     __constant_htons(0x0201)
#define PTT_SYS_ERR  	__constant_htons(0x0202)
#define PTT_GEN_ERR  	__constant_htons(0x0203)

struct pppoe_hdr {
#if defined(__LITTLE_ENDIAN_BITFIELD)
	__u8 ver : 4;
	__u8 type : 4;
#elif defined(__BIG_ENDIAN_BITFIELD)
	__u8 type : 4;
	__u8 ver : 4;
#else
#error	"Please fix <asm/byteorder.h>"
#endif
	__u8 code;
	__u16 sid;
	__u16 length;
	struct pppoe_tag tag[0];
} __attribute__ ((packed));

#ifdef __KERNEL__

struct pppox_proto {
	int (*create)(struct socket *sock);
	int (*ioctl)(struct socket *sock, unsigned int cmd,
		     unsigned long arg);
};

extern int register_pppox_proto(int proto_num, struct pppox_proto *pp);
extern void unregister_pppox_proto(int proto_num);
extern void pppox_unbind_sock(struct sock *sk);/* delete ppp-channel binding */
extern int pppox_channel_ioctl(struct ppp_channel *pc, unsigned int cmd,
			       unsigned long arg);

/* PPPoX socket states */
enum {
    PPPOX_NONE		= 0,  /* initial state */
    PPPOX_CONNECTED	= 1,  /* connection established ==TCP_ESTABLISHED */
    PPPOX_BOUND		= 2,  /* bound to ppp device */
    PPPOX_RELAY		= 4,  /* forwarding is enabled */
    PPPOX_ZOMBIE	= 8,  /* dead, but still bound to ppp device */
    PPPOX_DEAD		= 16  /* dead, useless, please clean me up!*/
};

extern struct ppp_channel_ops pppoe_chan_ops;

extern int pppox_proto_init(struct net_proto *np);

#endif /* __KERNEL__ */

#endif /* !(__LINUX_IF_PPPOX_H) */

redpajama_set_name: RedPajamaGithub


text:
require 'optparse'

module Vagrant
  module Command
    class Status < Base
      def execute
        options = {}

        opts = OptionParser.new do |opts|
          opts.banner = "Usage: vagrant status [vm-name]"
        end

        # Parse the options
        argv = parse_options(opts)
        return if !argv

        state = nil
        results = []
        with_target_vms(argv) do |vm|
          state = vm.state.to_s if !state
          results << "#{vm.name.to_s.ljust(25)}#{vm.state.to_s.gsub("_", " ")}"
        end

        state = results.length == 1 ? state : "listing"

        @env.ui.info(I18n.t("vagrant.commands.status.output",
                            :states => results.join("\n"),
                            :message => I18n.t("vagrant.commands.status.#{state}")),
                     :prefix => false)

        # Success, exit status 0
        0
       end
    end
  end
end


text:
using System;
using System.Reactive.Linq;
using System.Threading;
using Newtonsoft.Json;
using OurLittleTastyServerBot.Classes.Configuration;
using OurLittleTastyServerBot.Classes.Db;
using OurLittleTastyServerBot.Classes.Db.Models;
using OurLittleTastyServerBot.Classes.Db.Repositories;
using OurLittleTastyServerBot.Classes.Events;
using OurLittleTastyServerBot.Classes.Observers;
using OurLittleTastyServerBot.Classes.Telegram.Models;

namespace OurLittleTastyServerBot.Classes
{
    public class Bot
    {
        //public static Xakpc.TelegramBot.Client.ITelegramBotApiClient bot;

        private readonly BotSettings _botSettings;
        private readonly EventBroker _eventBroker;
        private readonly SqliteDatabase _db;
        private readonly AbstractRepository<UpdateRecord> _updateRepository;
        private readonly AbstractRepository<DialogRecord> _dialogRepository;

        public Bot(BotSettings botSettings, EventBroker eventBroker)
        {
            _botSettings = botSettings;
            _eventBroker = eventBroker;

            _db = new SqliteDatabase("database3.db");
            _updateRepository = new UpdateRecordRepositoryInSQLite(_db);
            _dialogRepository = new DialogRepositoryInMemory();

            InitializeEventBroker();
        }

        private void InitializeEventBroker()
        {
            _eventBroker.OfType<UpdateEventArgs>().Subscribe(new DatabaseWorker(_eventBroker, _updateRepository));
            _eventBroker.OfType<UpdateRecordEventArgs>().Subscribe(new CommandParser(_eventBroker));
            _eventBroker.OfType<MessageEventArgs>().Subscribe(new MessageWorker(_botSettings));
            _eventBroker.OfType<CommandEventArgs>().Where(x => x.Command == EnCommand.WeatherRequst).Subscribe(new WeatherWorker(_eventBroker));
            _eventBroker.OfType<CommandEventArgs>().Where(x => x.Command == EnCommand.Text).Subscribe(new EchoTextWorker(_eventBroker));
            _eventBroker.OfType<CommandEventArgs>().Where(x => x.Command == EnCommand.AddSimpleCostRequest).Subscribe(new SimpleAddingCostWorker(_eventBroker));    //, _dialogRepository));
        }

        public void Start()
        {
            while (true)
            {
                try
                {
                    //bot = new Xakpc.TelegramBot.Client.TelegramBotApiClient(_botSettings.BotToken);

                    var getUpdatesResult = GetUpdates();
                    getUpdatesResult.ThrowIfFailure();

                    var updates = getUpdatesResult.Value.Result;

                    foreach (var update in updates)
                    {
                        var updateArgs = new UpdateEventArgs(update);
                        _eventBroker.Publish(updateArgs);
                    }

                    Thread.Sleep(1000);     // íåëüçÿ îòïðàâëÿòü áîëüøå N çàïðîñîâ ê API â ñåêóíäó (ïåðåñòðàõîâûâàåìñÿ ñ 1 ñåêóäîé, ïîêà ýòîé ñêðîñòè äîñòàòî÷íî)
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }

        private Result<JsonResult<Update[]>> GetUpdates()
        {
            var url = string.Format(_botSettings.TelegramApiUrlPattern, _botSettings.BotToken, "getUpdates");
            var result = RequestHelper.Get(url);
            if (result.IsFailured) return result.FailCastTo<JsonResult<Update[]>>();

            var json = result.Value;
            var updates = JsonConvert.DeserializeObject<JsonResult<Update[]>>(json);
            return Result.Ok(updates);
        }
    }
}


text:
function snseti( option, ivalue )
% function snset( option )
%     Sets a optional integer parameter of snopt. The string "option" will be read
%     by snopt. If the string contains a setting that snopt understands,
%     snopt will set internal parameters accordingly. For a description of
%     available parameters, please see the SNOPT documentation.
%
snoptmex(3, option, ivalue);


text:
var _ = require("underscore"),
    SectionCode = require("../Model/Enum/enum.js").SectionCode;

exports.CONSTANTS = (function () {
    this.LOINC = {};
    this.LOINC.CODESYSTEM = '2.16.840.1.113883.6.1';
    this.LOINC.HEIGHT = '8302-2';
    this.LOINC.WEIGHT_MEASURED = '3141-9';
    this.LOINC.BP_SYSTOLIC = '8480-6';
    this.LOINC.BP_DIASTOLIC = '8462-4';
    this.LOINC.HEART_RATE = '8867-4';
    this.LOINC.RESPIRATORY_RATE = '9279-1';
    this.LOINC.PULSE = 'temp-pulse-code';
    this.LOINC.O2 = '2710-2';
    this.LOINC.TEMPERATURE = '8310-5';
    this.LOINC.BMI = '39156-5';
    this.LOINC.BODY_WEIGHT = '29463-7';

    this.MAP = {};
    // -- psuedo dictionary object mapping the document section property name (Model/Document.js) to the SectionCode enum (Model/Enum/enum.js)
    this.MAP.DocumentSectionToSectionCode = {
        AdvanceDirectivesSection: { Enum: SectionCode.ADVANCEDIRECTIVE, LoincCode: ['42348-3'], TemplateId: '2.16.840.1.113883.10.20.22.2.21', DocumentPropertyName: 'AdvanceDirectivesSection', Title: 'ADVANCE DIRECTIVES' },
        AllergiesSection: { Enum: SectionCode.ALLERGIES, LoincCode: ['48765-2'], TemplateId: '2.16.840.1.113883.10.20.22.2.6', DocumentPropertyName: 'AllergiesSection', Title: 'ALLERGIES, ADVERSE REACTIONS, ALERTS' },
        AssessmentSection: { Enum: SectionCode.ASSESSMENT, LoincCode: ['51848-0'], TemplateId: '2.16.840.1.113883.10.20.22.2.8', DocumentPropertyName: 'AssessmentSection', Title: 'ASSESSMENTS' },
        PhysicalSection: { Enum: SectionCode.PHYSICALEXAM, LoincCode: ['29545-1'], TemplateId: '2.16.840.1.113883.10.20.2.10', DocumentPropertyName: 'PhysicalExamSection', Title: 'PHYSICAL EXAM' },
        ChiefComplaintSection: { Enum: SectionCode.CHIEFCOMPLAINT, LoincCode: ['46239-0'], TemplateId: '2.16.840.1.113883.10.20.22.2.13', DocumentPropertyName: 'ChiefComplaintSection', Title: 'CHIEF COMPLAINT(S) AND REASON FOR VISIT' },
        EncounterSection: { Enum: SectionCode.ENCOUNTERS, LoincCode: ['46240-8'], TemplateId: '2.16.840.1.113883.10.20.22.2.22', DocumentPropertyName: 'EncounterSection', Title: 'ENCOUNTERS' },
        FamilyHistorySection: { Enum: SectionCode.FAMILYHISTORY, LoincCode: ['10157-6'], TemplateId: '2.16.840.1.113883.10.20.22.2.15', DocumentPropertyName: 'FamilyHistorySection', Title: 'FAMILY HISTORY' },
        FunctionalStatusSection: { Enum: SectionCode.FUNCTIONALSTATUS, LoincCode: ['47420-5'], TemplateId: '2.16.840.1.113883.10.20.22.2.14', DocumentPropertyName: 'FunctionalStatusSection', Title: 'FUNCTIONAL STATUS' },
        HistoryOfPresentIllnessSection: { Enum: SectionCode.HISTORYOFPRESENTILLNESS, LoincCode: ['10164-2'], TemplateId: '1.3.6.1.4.1.19376.1.5.3.1.3.4', DocumentPropertyName: 'HistoryOfPresentIllnessSection', Title: 'HISTORY OF PRESENT ILLNESS' },
        HistoryOfPastIllnessSection: { Enum: SectionCode.HISTORYOFPASTILLNESS, LoincCode: ['11348-0'], TemplateId: '2.16.840.1.113883.10.20.22.2.20', DocumentPropertyName: 'HistoryOfPastIllnessSection', Title: 'HISTORY OF PAST ILLNESS'  },
        HospitalDischargeDiagnosisSection: { Enum: SectionCode.HOSPITALDISCHARGEDIAGNOSIS, LoincCode: ['11535-2'], TemplateId: '2.16.840.1.113883.10.20.22.2.24', DocumentPropertyName: 'HospitalDischargeDiagnosisSection', Title: 'HOSPITAL DISCHARGE DIAGNOSIS' },
        ImmunizationSection: { Enum: SectionCode.IMMUNIZATION, LoincCode: ['11369-6'], TemplateId: '2.16.840.1.113883.10.20.22.2.2', DocumentPropertyName: 'ImmunizationSection', Title: 'IMMUNIZATIONS' },
        MedicalEquipmentSection: { Enum: SectionCode.MEDICALEQUIPMENT, LoincCode: ['46264-8'], TemplateId: '2.16.840.1.113883.10.20.22.2.23', DocumentPropertyName: 'MedicalEquipmentSection', Title: 'MEDICAL EQUIPMENT' },
        MedicationSection: { Enum: SectionCode.MEDICATION, LoincCode: ['10160-0'], TemplateId: '2.16.840.1.113883.10.20.22.2.1', DocumentPropertyName: 'MedicationSection', Title: 'MEDICATIONS' },
        PayerSection: { Enum: SectionCode.PAYERS, LoincCode: ['48768-6'], TemplateId: '2.16.840.1.113883.10.20.22.2.18', DocumentPropertyName: 'PayerSection', Title: 'PAYERS' },
        PlanOfCareSection: { Enum: SectionCode.PLANOFCARE, LoincCode: ['18776-5'], TemplateId: '2.16.840.1.113883.10.20.22.2.10', DocumentPropertyName: 'PlanOfCareSection', Title: 'PLAN OF CARE' },
        ProblemSection: { Enum: SectionCode.PROBLEM, LoincCode: ['11450-4'], TemplateId: '2.16.840.1.113883.10.20.22.2.5', DocumentPropertyName: 'ProblemSection', Title: 'FUNCTIONAL STATUS' },
        ProceduresSection: { Enum: SectionCode.PROCEDURES, LoincCode: ['47519-4'], TemplateId: '2.16.840.1.113883.10.20.22.2.7', DocumentPropertyName: 'ProceduresSection', Title: 'PROCEDURES' },
        ResultsSection: { Enum: SectionCode.RESULTS, LoincCode: ['30954-2'], TemplateId: '2.16.840.1.113883.10.20.22.2.3', DocumentPropertyName: 'ResultsSection', Title: 'RESULTS' },
        SocialHistorySection: { Enum: SectionCode.SOCIALHISTORY, LoincCode: ['29762-2'], TemplateId: '2.16.840.1.113883.10.20.22.2.17', DocumentPropertyName: 'SocialHistorySection', Title: 'SOCIAL HISTORY' },
        VitalsSection: { Enum: SectionCode.VITAL, LoincCode: ['8716-3'], TemplateId: '2.16.840.1.113883.10.20.22.2.4', DocumentPropertyName: 'VitalsSection', Title: 'VITAL SIGNS' },

        findSection: function (field, fieldValue) {
            var target;
            for (var p in this) {
                if (!_.isUndefined(this[p][field])) {
                    if (_.isArray(this[p][field])) {
                        target = _.find(this[p][field], function (value) {
                            return value === fieldValue;
                        });
                    }
                    else {
                        target = this[p][field];
                    }
                }

                if (target === fieldValue) {
                    return this[p];
                }
            }
            return null;
        }

    };

    return this;
})();


text:
package com.helpsumo.api.ticketing.ticket.Database.ContentProvider;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.helpsumo.api.ticketing.ticket.Database.Table.CommentTable;

import java.util.Arrays;
import java.util.HashSet;

public class CommentContentProvider extends ContentProvider {

    private LocDbHelper database;
    private static final int TODOS = 10;
    private static final int TODO_ID = 20;

    private static final String AUTHORITY = "com.ticketing.helpsumo.appcomment";

    private static final String
            BASE_PATH = "todos";
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);

    public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
            + "/todos";
    public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/todo";

    private static final UriMatcher sURIMatcher = new UriMatcher(
            UriMatcher.NO_MATCH);

    static {
        sURIMatcher.addURI(AUTHORITY, BASE_PATH, TODOS);
        sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", TODO_ID);
    }

    @Override
    public boolean onCreate() {
        database = new LocDbHelper(getContext());
        return false;
    }

    @Nullable
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        // Using SQLiteQueryBuilder instead of query() method
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        // Check if the caller has requested a column which does not exists
        checkColumns(projection);

        // Set the table
        queryBuilder.setTables(CommentTable.TABLE_COMMENT);

        int uriType = sURIMatcher.match(uri);
        switch (uriType) {
            case TODOS:
                break;
            case TODO_ID:
                // Adding the ID to the original query
                queryBuilder.appendWhere(CommentTable.ID + "="
                        + uri.getLastPathSegment());
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }

        SQLiteDatabase db = database.getWritableDatabase();
        Cursor cursor = queryBuilder.query(db, projection, selection,
                selectionArgs, null, null, sortOrder);
        // Make sure that potential listeners are getting notified
        cursor.setNotificationUri(getContext().getContentResolver(), uri);

        return cursor;

    }

    @Nullable
    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(Uri uri, ContentValues values) {

        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        long id = 0;
        switch (uriType) {
            case TODOS:
                id = sqlDB.insert(CommentTable.TABLE_COMMENT, null, values);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return Uri.parse(BASE_PATH + "/" + id);

    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {

        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        int rowsDeleted = 0;
        switch (uriType) {
            case TODOS:
                rowsDeleted = sqlDB.delete(CommentTable.TABLE_COMMENT, selection,
                        selectionArgs);
                break;
            case TODO_ID:
                String id = uri.getLastPathSegment();
                if (TextUtils.isEmpty(selection)) {
                    rowsDeleted = sqlDB.delete(
                            CommentTable.TABLE_COMMENT,
                            CommentTable.ID + "=" + id,
                            null);
                } else {
                    rowsDeleted = sqlDB.delete(
                            CommentTable.TABLE_COMMENT,
                            CommentTable.ID + "=" + id
                                    + " and " + selection,
                            selectionArgs);
                }
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return rowsDeleted;

    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        {

            int uriType = sURIMatcher.match(uri);
            SQLiteDatabase sqlDB = database.getWritableDatabase();
            int rowsUpdated = 0;
            switch (uriType) {
                case TODOS:
                    rowsUpdated = sqlDB.update(CommentTable.TABLE_COMMENT,
                            values,
                            selection,
                            selectionArgs);
                    break;
                case TODO_ID:
                    String id = uri.getLastPathSegment();
                    if (TextUtils.isEmpty(selection)) {
                        rowsUpdated = sqlDB.update(CommentTable.TABLE_COMMENT,
                                values,
                                CommentTable.ID + "=" + id,
                                null);
                    } else {
                        rowsUpdated = sqlDB.update(CommentTable.TABLE_COMMENT,
                                values,
                                CommentTable.ID + "=" + id
                                        + " and "
                                        + selection,
                                selectionArgs);
                    }
                    break;
                default:
                    throw new IllegalArgumentException("Unknown URI: " + uri);
            }
            getContext().getContentResolver().notifyChange(uri, null);
            return rowsUpdated;
        }
    }

    private void checkColumns(String[] projection) {
        String[] available = {
                CommentTable.ID, CommentTable.TICKET_LOG, CommentTable.LOG_MESSAGE, CommentTable.LOG_STATUS,
                CommentTable.LOG_NAME, CommentTable.TICKET_ID, CommentTable.LOG_DATE, CommentTable.COMMENT_TYPE,
                CommentTable.LOG_ATTACHMENT};
        if (projection != null) {
            HashSet<String> requestedColumns = new HashSet<String>(
                    Arrays.asList(projection));
            HashSet<String> availableColumns = new HashSet<String>(
                    Arrays.asList(available));
            // Check if all columns which are requested are available
            if (!availableColumns.containsAll(requestedColumns)) {
                throw new IllegalArgumentException(
                        "Unknown columns in projection");
            }
        }
    }

}


text:
package activity

import (
	"time"

	"strings"

	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/swf"
	. "github.com/sclasen/swfsm/log"
	. "github.com/sclasen/swfsm/sugar"
)

const (
	TaskGone      = "Unknown activity"
	ExecutionGone = "Unknown execution"
)

// AddCoordinatedHandler automatically takes care of sending back heartbeats and
// updating state on workflows for an activity task. tickMinInterval determines
// the max rate at which the CoordinatedActivityHandler.Tick function will be
// called.
//
// For example, when the Tick function returns quickly (e.g.: noop), and
// tickMinInterval is 1 * time.Second, Tick is guaranteed to be called at most
// once per second. The rate can be slower if Tick takes more than
// tickMinInterval to complete.
func (w *ActivityWorker) AddCoordinatedHandler(heartbeatInterval, tickMinInterval time.Duration, handler *CoordinatedActivityHandler) {
	adapter := &coordinatedActivityAdapter{
		heartbeatInterval: heartbeatInterval,
		tickMinInterval:   tickMinInterval,
		worker:            w,
		handler:           handler,
	}
	w.AddHandler(&ActivityHandler{
		Activity:    handler.Activity,
		HandlerFunc: adapter.coordinate,
		Input:       handler.Input,
	})
}

type coordinatedActivityAdapter struct {
	heartbeatInterval time.Duration
	tickMinInterval   time.Duration
	worker            *ActivityWorker
	handler           *CoordinatedActivityHandler
}

func (c *coordinatedActivityAdapter) heartbeat(activityTask *swf.PollForActivityTaskOutput, stop <-chan struct{}, cancelActivity chan error) {
	heartbeats := time.NewTicker(c.heartbeatInterval)
	defer heartbeats.Stop()
	for {
		select {
		case <-heartbeats.C:
			if status, err := c.worker.SWF.RecordActivityTaskHeartbeat(&swf.RecordActivityTaskHeartbeatInput{
				TaskToken: activityTask.TaskToken,
			}); err != nil {
				if ae, ok := err.(awserr.Error); ok && isGoneError(ae) {
					Log.Printf("workflow-id=%s activity-id=%s activity-id=%s at=activity-gone", LS(activityTask.WorkflowExecution.WorkflowId), LS(activityTask.ActivityType.Name), LS(activityTask.ActivityId))
					cancelActivity <- nil
					return
				}
				Log.Printf("workflow-id=%s activity-id=%s activity-id=%s at=heartbeat-error error=%q", LS(activityTask.WorkflowExecution.WorkflowId), LS(activityTask.ActivityType.Name), LS(activityTask.ActivityId), err.Error())
			} else {
				Log.Printf("workflow-id=%s activity-id=%s activity-id=%s at=heartbeat-recorded", LS(activityTask.WorkflowExecution.WorkflowId), LS(activityTask.ActivityType.Name), LS(activityTask.ActivityId))
				if *status.CancelRequested {
					Log.Printf("workflow-id=%s activity-id=%s activity-id=%s at=activity-cancel-requested", LS(activityTask.WorkflowExecution.WorkflowId), LS(activityTask.ActivityType.Name), LS(activityTask.ActivityId))
					cancelActivity <- ActivityTaskCanceledError{}
					return
				}
			}
		case <-stop:
			return
		}
	}
}

func (c *coordinatedActivityAdapter) coordinate(activityTask *swf.PollForActivityTaskOutput, input interface{}) (interface{}, error) {
	defer c.finish(activityTask, input)

	update, err := c.handler.Start(activityTask, input)
	if err != nil {
		return nil, err
	}
	if err := c.worker.signalStart(activityTask, update); err != nil {
		return nil, err
	}

	cancel := make(chan error, 2)
	stopHeartbeating := make(chan struct{})

	go c.heartbeat(activityTask, stopHeartbeating, cancel)
	defer close(stopHeartbeating)

	ticks := time.NewTicker(c.tickMinInterval)
	defer ticks.Stop()
	for {
		select {
		case cause := <-cancel:
			c.cancel(activityTask, input)
			return nil, cause
		case <-ticks.C:
			cont, res, err := c.handler.Tick(activityTask, input)
			if !cont {
				return res, err
			}
			if res != nil {
				//send an activity update when the result is not null, but we are continuing
				if err := c.worker.signalUpdate(activityTask, res); err != nil {
					Log.Printf("workflow-id=%s activity-id=%s activity-id=%s at=signal-update-error error=%q", LS(activityTask.WorkflowExecution.WorkflowId), LS(activityTask.ActivityType.Name), LS(activityTask.ActivityId), err)
					cancel <- err
					continue // go pick up the cancel message
				}
				Log.Printf("workflow-id=%s activity-id=%s activity-id=%s at=signal-update", LS(activityTask.WorkflowExecution.WorkflowId), LS(activityTask.ActivityType.Name), LS(activityTask.ActivityId))
			}
		}
	}
}

func (c *coordinatedActivityAdapter) cancel(activityTask *swf.PollForActivityTaskOutput, input interface{}) {
	if err := c.handler.Cancel(activityTask, input); err != nil {
		Log.Printf("workflow-id=%s activity-id=%s activity-id=%s at=activity-cancel-err error=%q", LS(activityTask.WorkflowExecution.WorkflowId), LS(activityTask.ActivityType.Name), LS(activityTask.ActivityId), err)
	}
}

func (c *coordinatedActivityAdapter) finish(activityTask *swf.PollForActivityTaskOutput, input interface{}) {
	if err := c.handler.Finish(activityTask, input); err != nil {
		Log.Printf("workflow-id=%s activity-id=%s activity-id=%s at=activity-finish-err error=%q", LS(activityTask.WorkflowExecution.WorkflowId), LS(activityTask.ActivityType.Name), LS(activityTask.ActivityId), err)
	}
}

func isGoneError(err awserr.Error) bool {
	return err.Code() == ErrorTypeUnknownResourceFault &&
		(strings.Contains(err.Message(), TaskGone) || strings.Contains(err.Message(), ExecutionGone))
}


text:
package org.apache.shardingsphere.encrypt.rewrite.token.pojo;

import lombok.Getter;
import org.apache.shardingsphere.underlying.rewrite.sql.token.pojo.SQLToken;
import org.apache.shardingsphere.underlying.rewrite.sql.token.pojo.Substitutable;

/**
 * Assignment token for encrypt.
 */
@Getter
public abstract class EncryptAssignmentToken extends SQLToken implements Substitutable {

    private final int stopIndex;

    public EncryptAssignmentToken(final int startIndex, final int stopIndex) {
        super(startIndex);
        this.stopIndex = stopIndex;
    }
}


text:
using System;

namespace XamarinStudioGradleExtension
{
	[System.ComponentModel.ToolboxItem (true)]
	public partial class ConfigurationOptionsWidget : Gtk.Bin
	{
		public ConfigurationOptionsWidget ()
		{
			this.Build ();
		}

		public string FetchTarget {
			get {
				return fetchTargetEntry.Text;
			} set {
				fetchTargetEntry.Text = value;
			}
		}
	}
}


text:
`Home <index.html>`_ OpenStack-Ansible Installation Guide

Initial environment configuration
=================================

OpenStack-Ansible depends on various files that are used to build an inventory
for Ansible. Start by getting those files into the correct places:

#. Copy the contents of the
   ``/opt/openstack-ansible/etc/openstack_deploy`` directory to the
   ``/etc/openstack_deploy`` directory.

.. note::

    As of Newton, the ``env.d`` directory has been moved from this source
    directory to ``playbooks/inventory/``. See `Appendix H`_ for more
    details on this change.

#. Change to the ``/etc/openstack_deploy`` directory.

#. Copy the ``openstack_user_config.yml.example`` file to
   ``/etc/openstack_deploy/openstack_user_config.yml``.

You can review the ``openstack_user_config.yml`` file and make changes
to the deployment of your OpenStack environment.

.. note::

   The file is heavily commented with details about the various options.

There are various types of physical hardware that are able to use containers
deployed by OpenStack-Ansible. For example, hosts listed in the
`shared-infra_hosts` run containers for many of the shared services that
your OpenStack environments requires. Some of these services include databases,
memcached, and RabbitMQ. There are several other host types that contain
other types of containers and all of these are listed in
``openstack_user_config.yml``.

For details about how the inventory is generated from the environment
configuration, see :ref:`developer-inventory`.

Affinity
~~~~~~~~

OpenStack-Ansible's dynamic inventory generation has a concept called
`affinity`. This determines how many containers of a similar type are deployed
onto a single physical host.

Using `shared-infra_hosts` as an example, consider this ``openstack_user_config.yml``:

.. code-block:: yaml

    shared-infra_hosts:
      infra1:
        ip: 172.29.236.101
      infra2:
        ip: 172.29.236.102
      infra3:
        ip: 172.29.236.103

Three hosts are assigned to the `shared-infra_hosts` group,
OpenStack-Ansible ensures that each host runs a single database container,
a single memcached container, and a single RabbitMQ container. Each host has
an affinity of 1 by default, and that means each host will run one of each
container type.

You can skip the deployment of RabbitMQ altogether. This is
helpful when deploying a standalone swift environment. If you need
this configuration, your ``openstack_user_config.yml`` would look like this:

.. code-block:: yaml

    shared-infra_hosts:
      infra1:
        affinity:
          rabbit_mq_container: 0
        ip: 172.29.236.101
      infra2:
        affinity:
          rabbit_mq_container: 0
        ip: 172.29.236.102
      infra3:
        affinity:
          rabbit_mq_container: 0
        ip: 172.29.236.103

The configuration above deploys a memcached container and a database
container on each host, without the RabbitMQ containers.

.. _security_hardening:

Security hardening
~~~~~~~~~~~~~~~~~~

OpenStack-Ansible automatically applies host security hardening configurations
using the `openstack-ansible-security`_ role. The role uses a version of the
`Security Technical Implementation Guide (STIG)`_ that has been adapted for
Ubuntu 14.04 and OpenStack.

The role is applicable to physical hosts within an OpenStack-Ansible deployment
that are operating as any type of node, infrastructure or compute. By
default, the role is enabled. You can disable it by changing a variable
within ``user_variables.yml``:

.. code-block:: yaml

    apply_security_hardening: false

When the variable is set to ``true``, the ``setup-hosts.yml`` playbook applies
the role during deployments.

You can apply security configurations to an existing environment or audit
an environment using a playbook supplied with OpenStack-Ansible:

.. code-block:: bash

    # Perform a quick audit using Ansible's check mode
    openstack-ansible --check security-hardening.yml

    # Apply security hardening configurations
    openstack-ansible security-hardening.yml

For more details on the security configurations that will be applied, refer to
the `openstack-ansible-security`_ documentation. Review the `Configuration`_
section of the openstack-ansible-security documentation to find out how to
fine-tune certain security configurations.

.. _openstack-ansible-security: http://docs.openstack.org/developer/openstack-ansible-security/
.. _Security Technical Implementation Guide (STIG): https://en.wikipedia.org/wiki/Security_Technical_Implementation_Guide
.. _Configuration: http://docs.openstack.org/developer/openstack-ansible-security/configuration.html
.. _Appendix H: ../install-guide/app-custom-layouts.html

--------------

.. include:: navigation.txt


text:
using System;

namespace WeebIRCWebEdition
{
    class NiblSearchInformation
    {
        public string botname {get; set;}
        public string filename {get; set;}
        public string packnumber {get; set;}
        public string resolution {get; set;}
    }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var common_1 = require("@angular/common");
var domhandler_1 = require("../dom/domhandler");
var Tooltip = (function () {
    function Tooltip(el, domHandler, renderer) {
        this.el = el;
        this.domHandler = domHandler;
        this.renderer = renderer;
        this.tooltipPosition = 'right';
        this.tooltipEvent = 'hover';
        this.appendTo = 'body';
        this.tooltipZIndex = 'auto';
        this.escape = true;
    }
    Tooltip.prototype.onMouseEnter = function (e) {
        if (this.tooltipEvent === 'hover') {
            if (this.hideTimeout) {
                clearTimeout(this.hideTimeout);
                this.destroy();
            }
            this.activate();
        }
    };
    Tooltip.prototype.onMouseLeave = function (e) {
        if (this.tooltipEvent === 'hover') {
            this.deactivate(true);
        }
    };
    Tooltip.prototype.onFocus = function (e) {
        if (this.tooltipEvent === 'focus') {
            this.activate();
        }
    };
    Tooltip.prototype.onBlur = function (e) {
        if (this.tooltipEvent === 'focus') {
            this.deactivate(true);
        }
    };
    Tooltip.prototype.onClick = function (e) {
        if (this.tooltipEvent === 'hover') {
            this.deactivate(true);
        }
    };
    Tooltip.prototype.activate = function () {
        var _this = this;
        this.active = true;
        if (this.hideTimeout) {
            clearTimeout(this.hideTimeout);
        }
        if (this.showDelay)
            this.showTimeout = setTimeout(function () { _this.show(); }, this.showDelay);
        else
            this.show();
        if (this.life) {
            this.lifeTimeout = setTimeout(function () { _this.deactivate(false); }, this.life);
        }
    };
    Tooltip.prototype.deactivate = function (useDelay) {
        var _this = this;
        this.active = false;
        if (this.showTimeout) {
            clearTimeout(this.showTimeout);
        }
        if (this.lifeTimeout) {
            clearTimeout(this.lifeTimeout);
        }
        if (this.hideDelay && useDelay)
            this.hideTimeout = setTimeout(function () { _this.hide(); }, this.hideDelay);
        else
            this.hide();
    };
    Object.defineProperty(Tooltip.prototype, "text", {
        get: function () {
            return this._text;
        },
        set: function (text) {
            this._text = text;
            if (this.active) {
                if (this._text) {
                    if (this.container && this.container.offsetParent)
                        this.updateText();
                    else
                        this.show();
                }
                else {
                    this.hide();
                }
            }
        },
        enumerable: true,
        configurable: true
    });
    Tooltip.prototype.create = function () {
        this.container = document.createElement('div');
        var tooltipArrow = document.createElement('div');
        tooltipArrow.className = 'ui-tooltip-arrow';
        this.container.appendChild(tooltipArrow);
        this.tooltipText = document.createElement('div');
        this.tooltipText.className = 'ui-tooltip-text ui-shadow ui-corner-all';
        this.updateText();
        if (this.positionStyle) {
            this.container.style.position = this.positionStyle;
        }
        this.container.appendChild(this.tooltipText);
        if (this.appendTo === 'body')
            document.body.appendChild(this.container);
        else if (this.appendTo === 'target')
            this.domHandler.appendChild(this.container, this.el.nativeElement);
        else
            this.domHandler.appendChild(this.container, this.appendTo);
        this.container.style.display = 'inline-block';
    };
    Tooltip.prototype.show = function () {
        if (!this.text || this.disabled) {
            return;
        }
        this.create();
        this.align();
        if (this.tooltipStyleClass) {
            this.container.className = this.container.className + ' ' + this.tooltipStyleClass;
        }
        this.domHandler.fadeIn(this.container, 250);
        if (this.tooltipZIndex === 'auto')
            this.container.style.zIndex = ++domhandler_1.DomHandler.zindex;
        else
            this.container.style.zIndex = this.tooltipZIndex;
        this.bindDocumentResizeListener();
    };
    Tooltip.prototype.hide = function () {
        this.destroy();
    };
    Tooltip.prototype.updateText = function () {
        if (this.escape) {
            this.tooltipText.innerHTML = '';
            this.tooltipText.appendChild(document.createTextNode(this._text));
        }
        else {
            this.tooltipText.innerHTML = this._text;
        }
    };
    Tooltip.prototype.align = function () {
        var position = this.tooltipPosition;
        switch (position) {
            case 'top':
                this.alignTop();
                if (this.isOutOfBounds()) {
                    this.alignBottom();
                }
                break;
            case 'bottom':
                this.alignBottom();
                if (this.isOutOfBounds()) {
                    this.alignTop();
                }
                break;
            case 'left':
                this.alignLeft();
                if (this.isOutOfBounds()) {
                    this.alignRight();
                    if (this.isOutOfBounds()) {
                        this.alignTop();
                        if (this.isOutOfBounds()) {
                            this.alignBottom();
                        }
                    }
                }
                break;
            case 'right':
                this.alignRight();
                if (this.isOutOfBounds()) {
                    this.alignLeft();
                    if (this.isOutOfBounds()) {
                        this.alignTop();
                        if (this.isOutOfBounds()) {
                            this.alignBottom();
                        }
                    }
                }
                break;
        }
    };
    Tooltip.prototype.getHostOffset = function () {
        var offset = this.el.nativeElement.getBoundingClientRect();
        var targetLeft = offset.left + this.domHandler.getWindowScrollLeft();
        var targetTop = offset.top + this.domHandler.getWindowScrollTop();
        return { left: targetLeft, top: targetTop };
    };
    Tooltip.prototype.alignRight = function () {
        this.preAlign();
        this.container.className = 'ui-tooltip ui-widget ui-tooltip-right';
        var hostOffset = this.getHostOffset();
        var left = hostOffset.left + this.domHandler.getOuterWidth(this.el.nativeElement);
        var top = hostOffset.top + (this.domHandler.getOuterHeight(this.el.nativeElement) - this.domHandler.getOuterHeight(this.container)) / 2;
        this.container.style.left = left + 'px';
        this.container.style.top = top + 'px';
    };
    Tooltip.prototype.alignLeft = function () {
        this.preAlign();
        this.container.className = 'ui-tooltip ui-widget ui-tooltip-left';
        var hostOffset = this.getHostOffset();
        var left = hostOffset.left - this.domHandler.getOuterWidth(this.container);
        var top = hostOffset.top + (this.domHandler.getOuterHeight(this.el.nativeElement) - this.domHandler.getOuterHeight(this.container)) / 2;
        this.container.style.left = left + 'px';
        this.container.style.top = top + 'px';
    };
    Tooltip.prototype.alignTop = function () {
        this.preAlign();
        this.container.className = 'ui-tooltip ui-widget ui-tooltip-top';
        var hostOffset = this.getHostOffset();
        var left = hostOffset.left + (this.domHandler.getOuterWidth(this.el.nativeElement) - this.domHandler.getOuterWidth(this.container)) / 2;
        var top = hostOffset.top - this.domHandler.getOuterHeight(this.container);
        this.container.style.left = left + 'px';
        this.container.style.top = top + 'px';
    };
    Tooltip.prototype.alignBottom = function () {
        this.preAlign();
        this.container.className = 'ui-tooltip ui-widget ui-tooltip-bottom';
        var hostOffset = this.getHostOffset();
        var left = hostOffset.left + (this.domHandler.getOuterWidth(this.el.nativeElement) - this.domHandler.getOuterWidth(this.container)) / 2;
        var top = hostOffset.top + this.domHandler.getOuterHeight(this.el.nativeElement);
        this.container.style.left = left + 'px';
        this.container.style.top = top + 'px';
    };
    Tooltip.prototype.preAlign = function () {
        this.container.style.left = -999 + 'px';
        this.container.style.top = -999 + 'px';
    };
    Tooltip.prototype.isOutOfBounds = function () {
        var offset = this.container.getBoundingClientRect();
        var targetTop = offset.top;
        var targetLeft = offset.left;
        var width = this.domHandler.getOuterWidth(this.container);
        var height = this.domHandler.getOuterHeight(this.container);
        var viewport = this.domHandler.getViewport();
        return (targetLeft + width > viewport.width) || (targetLeft < 0) || (targetTop < 0) || (targetTop + height > viewport.height);
    };
    Tooltip.prototype.bindDocumentResizeListener = function () {
        var _this = this;
        this.documentResizeListener = this.renderer.listen('window', 'resize', function (event) {
            _this.hide();
        });
    };
    Tooltip.prototype.unbindDocumentResizeListener = function () {
        if (this.documentResizeListener) {
            this.documentResizeListener();
            this.documentResizeListener = null;
        }
    };
    Tooltip.prototype.destroy = function () {
        this.unbindDocumentResizeListener();
        if (this.container && this.container.parentElement) {
            if (this.appendTo === 'body')
                document.body.removeChild(this.container);
            else if (this.appendTo === 'target')
                this.el.nativeElement.removeChild(this.container);
            else
                this.domHandler.removeChild(this.container, this.appendTo);
        }
        this.container = null;
    };
    Tooltip.prototype.ngOnDestroy = function () {
        this.destroy();
    };
    return Tooltip;
}());
Tooltip.decorators = [
    { type: core_1.Directive, args: [{
                selector: '[pTooltip]',
                providers: [domhandler_1.DomHandler]
            },] },
];
/** @nocollapse */
Tooltip.ctorParameters = function () { return [
    { type: core_1.ElementRef, },
    { type: domhandler_1.DomHandler, },
    { type: core_1.Renderer2, },
]; };
Tooltip.propDecorators = {
    'tooltipPosition': [{ type: core_1.Input },],
    'tooltipEvent': [{ type: core_1.Input },],
    'appendTo': [{ type: core_1.Input },],
    'positionStyle': [{ type: core_1.Input },],
    'tooltipStyleClass': [{ type: core_1.Input },],
    'tooltipZIndex': [{ type: core_1.Input },],
    'disabled': [{ type: core_1.Input, args: ["tooltipDisabled",] },],
    'escape': [{ type: core_1.Input },],
    'showDelay': [{ type: core_1.Input },],
    'hideDelay': [{ type: core_1.Input },],
    'life': [{ type: core_1.Input },],
    'onMouseEnter': [{ type: core_1.HostListener, args: ['mouseenter', ['$event'],] },],
    'onMouseLeave': [{ type: core_1.HostListener, args: ['mouseleave', ['$event'],] },],
    'onFocus': [{ type: core_1.HostListener, args: ['focus', ['$event'],] },],
    'onBlur': [{ type: core_1.HostListener, args: ['blur', ['$event'],] },],
    'onClick': [{ type: core_1.HostListener, args: ['click', ['$event'],] },],
    'text': [{ type: core_1.Input, args: ['pTooltip',] },],
};
exports.Tooltip = Tooltip;
var TooltipModule = (function () {
    function TooltipModule() {
    }
    return TooltipModule;
}());
TooltipModule.decorators = [
    { type: core_1.NgModule, args: [{
                imports: [common_1.CommonModule],
                exports: [Tooltip],
                declarations: [Tooltip]
            },] },
];
/** @nocollapse */
TooltipModule.ctorParameters = function () { return []; };
exports.TooltipModule = TooltipModule;
//# sourceMappingURL=tooltip.js.map


text:
local _M = {}

---
--- Cleans up all wiola sessions data in redis store
---
function _M.flushAll()
    ngx.log(ngx.DEBUG, "Cleaning up all wiola sessions...")

    local conf = require("wiola.config").config()
    local redis = require "redis"
    local client = redis.connect(conf.storeConfig.host, conf.storeConfig.port)

    if conf.storeConfig.db then
        client:select(conf.storeConfig.db)
    end

    client:flushdb()

    ngx.log(ngx.DEBUG, "Sessions data successfully cleared!")
end

return _M


text:
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;

namespace qx.bom
{
    /// <summary>
	/// <para>Cross browser abstractions to work with input elements.</para>
	/// </summary>
	[JsType(JsMode.Prototype, Name = "qx.bom.Input", OmitOptionalParameters = true, Export = false)]
    public partial class Input
    {
		#region Methods

		public Input() { throw new NotImplementedException(); }

		/// <summary>
		/// <para>Creates an DOM input/textarea/select element.</para>
		/// <para>Attributes may be given directly with this call. This is critical
		/// for some attributes e.g. name, type, ... in many clients.</para>
		/// <para>Note: select and textarea elements are created
		/// using the identically named type.</para>
		/// </summary>
		/// <param name="type">Any valid type for HTML, select and textarea</param>
		/// <param name="attributes">Map of attributes to apply</param>
		/// <param name="win">Window to create the element for</param>
		/// <returns>The created input node</returns>
		[JsMethod(Name = "create")]
		public static qx.html.Element Create(string type, object attributes, Window win) { throw new NotImplementedException(); }

		/// <summary>
		/// <para>Returns the currently configured value.</para>
		/// <para>Works with simple input fields as well as with
		/// select boxes or option elements.</para>
		/// <para>Returns an array in cases of multi-selection in
		/// select boxes but in all other cases a string.</para>
		/// </summary>
		/// <param name="element">DOM element to query</param>
		/// <returns>The value of the given element</returns>
		[JsMethod(Name = "getValue")]
		public static object GetValue(qx.html.Element element) { throw new NotImplementedException(); }

		/// <summary>
		/// <para>Applies the given value to the element.</para>
		/// <para>Normally the value is given as a string/number value and applied
		/// to the field content (textfield, textarea) or used to
		/// detect whether the field is checked (checkbox, radiobutton).</para>
		/// <para>Supports array values for selectboxes (multiple-selection)
		/// and checkboxes or radiobuttons (for convenience).</para>
		/// <para>Please note: To modify the value attribute of a checkbox or
		/// radiobutton use <see cref="qx.bom.element.Attribute.Set"/> instead.</para>
		/// </summary>
		/// <param name="element">element to update</param>
		/// <param name="value">the value to apply</param>
		[JsMethod(Name = "setValue")]
		public static void SetValue(qx.html.Element element, object value) { throw new NotImplementedException(); }

		/// <summary>
		/// <para>Sets the text wrap behaviour of a text area element.
		/// This property uses the attribute “wrap” respectively
		/// the style property “whiteSpace”</para>
		/// </summary>
		/// <param name="element">DOM element to modify</param>
		/// <param name="wrap">Whether to turn text wrap on or off.</param>
		[JsMethod(Name = "setWrap")]
		public static void SetWrap(qx.html.Element element, bool wrap) { throw new NotImplementedException(); }

		#endregion Methods
    }
}


text:
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

OUTPUT_FOLDER="/Users/$(whoami)/tmp/geoscape_202211/geoparquet"
mkdir -p "${OUTPUT_FOLDER}"
cd "${OUTPUT_FOLDER}"

# get list of tables to export
rm tables.txt

for input_schema in "admin_bdys_202211" "gnaf_202211"
do
  QUERY="SELECT concat(table_schema, '.', table_name)
         FROM information_schema.tables
         WHERE table_schema='${input_schema}'
           AND table_type='BASE TABLE'
           AND table_name <> 'qa'
           AND table_name NOT LIKE '%_2011_%';"
#           AND table_name NOT LIKE '%_analysis%'
#           AND table_name NOT LIKE '%_display%';"

  psql -d geo -p 5432 -U postgres -t -A -c "${QUERY}" >> tables.txt
done

# convert Postgres tables to GeoParquet
while read p; do
  # split schema and table name
  arrIN=(${p//./ })
  input_schema=${arrIN[0]}
  input_table=${arrIN[1]}

  echo "Exporting ${input_schema}.${input_table}"

  docker run --rm -v $(pwd):/data osgeo/gdal:ubuntu-full-3.6.0 \
    ogr2ogr \
    "/data/${input_table}.parquet" \
    PG:"host='host.docker.internal' dbname='geo' user='postgres' password='password' port='5432'" \
    "${input_schema}.${input_table}(geom)"
#    -lco COMPRESSION=BROTLI \
#    -lco GEOMETRY_ENCODING=GEOARROW \
#    -lco POLYGON_ORIENTATION=COUNTERCLOCKWISE \
#    -lco ROW_GROUP_SIZE=9999999

done < tables.txt


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Services.Description;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Web.Routing;
using Umbraco.Web.WebApi;
//using umbraco.cms.businesslogic.language;
using umbraco.BusinessLogic.Actions;
using umbraco.cms.businesslogic.web;

namespace Umbraco.Web.WebServices
{
    /// <summary>
    /// A REST controller used for managing domains.
    /// </summary>
    /// <remarks>Nothing to do with Active Directory.</remarks>
    public class DomainsApiController : UmbracoAuthorizedApiController
    {
        [HttpPost]
        // can't pass multiple complex args in json post request...
        public PostBackModel SaveLanguageAndDomains(PostBackModel model)
        {
            var node = ApplicationContext.Current.Services.ContentService.GetById(model.NodeId);

            if (node == null)
            {
                var response = Request.CreateResponse(HttpStatusCode.BadRequest);
                response.Content = new StringContent(string.Format("There is no content node with id {0}.", model.NodeId));
                response.ReasonPhrase = "Node Not Found.";
                throw new HttpResponseException(response);
            }

            if (UmbracoUser.GetPermissions(node.Path).Contains(ActionAssignDomain.Instance.Letter) == false)
            {
                var response = Request.CreateResponse(HttpStatusCode.BadRequest);
                response.Content = new StringContent("You do not have permission to assign domains on that node.");
                response.ReasonPhrase = "Permission Denied.";
                throw new HttpResponseException(response);
            }

            model.Valid = true;
            var domains = Services.DomainService.GetAssignedDomains(model.NodeId, true).ToArray();
            var languages = Services.LocalizationService.GetAllLanguages().ToArray();
            var language = model.Language > 0 ? languages.FirstOrDefault(l => l.Id == model.Language) : null;

            // process wildcard

            if (language != null)
            {
                var wildcard = domains.FirstOrDefault(d => d.IsWildcard);
                if (wildcard != null)
                    wildcard.LanguageId = language.Id;
                else
                {
                    // yet there is a race condition here...
                    var newDomain = new UmbracoDomain("*" + model.NodeId)
                    {
                        LanguageId = model.Language,
                        RootContentId = model.NodeId
                    };
                    Services.DomainService.Save(newDomain);
                }

            }
            else
            {
                var wildcard = domains.FirstOrDefault(d => d.IsWildcard);
                if (wildcard != null)
                {
                    Services.DomainService.Delete(wildcard);
                }

            }

            // process domains

            // delete every (non-wildcard) domain, that exists in the DB yet is not in the model
            foreach (var domain in domains.Where(d => d.IsWildcard == false && model.Domains.All(m => m.Name.InvariantEquals(d.DomainName) == false)))
            {
                Services.DomainService.Delete(domain);
            }

            var names = new List<string>();

            // create or update domains in the model
            foreach (var domainModel in model.Domains.Where(m => string.IsNullOrWhiteSpace(m.Name) == false))
            {
                language = languages.FirstOrDefault(l => l.Id == domainModel.Lang);
                if (language == null)
                    continue;
                var name = domainModel.Name.ToLowerInvariant();
                if (names.Contains(name))
                {
                    domainModel.Duplicate = true;
                    continue;
                }
                names.Add(name);
                var domain = domains.FirstOrDefault(d => d.DomainName.InvariantEquals(domainModel.Name));
                if (domain != null)
                    domain.LanguageId = language.Id;
                else if (Services.DomainService.Exists(domainModel.Name))
                    domainModel.Duplicate = true;
                else
                {
                    // yet there is a race condition here...
                    var newDomain = new UmbracoDomain(name)
                    {
                        LanguageId = domainModel.Lang,
                        RootContentId = model.NodeId
                    };
                    Services.DomainService.Save(newDomain);
                }
            }

            model.Valid = model.Domains.All(m => m.Duplicate == false);

            return model;
        }

        #region Models

        public class PostBackModel
        {
            public bool Valid { get; set; }
            public int NodeId { get; set; }
            public int Language { get; set; }
            public DomainModel[] Domains { get; set; }
        }

        public class DomainModel
        {
            public DomainModel(string name, int lang)
            {
                Name = name;
                Lang = lang;
            }

            public string Name { get; private set; }
            public int Lang { get; private set; }
            public bool Duplicate { get; set; }
        }

        #endregion
    }
}


text:
<?php

/**
 * Skeleton subclass for performing query and update operations on the 'pedido.produto_pedido' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package    propel.generator.semp
 */
class ProdutoPedidoPeer extends BaseProdutoPedidoPeer
{
}


text:
package org.mockitousage.junitrunner;

import org.junit.runner.Description;
import org.junit.runner.manipulation.Filter;

public class Filters {
    public static Filter methodNameContains(final String substring) {
        return new Filter() {
            @Override
            public boolean shouldRun(Description description) {
                return description.getDisplayName().contains(substring);
            }

            @Override
            public String describe() {
                return null;
            }
        };
    }
}


text:
In this section, we list the main changes you need to be aware of when converting your Storage Blob SDK library from Version 10/Version 11 to Version 12.

## Prerequisites
Java Development Kit (JDK) with version 8 or above

## Reactor and ReactorNetty
We've updated our asynchronous framework from RxJava to Reactor.
For more info related to Reactor, please refer to [Project Reactor](https://projectreactor.io/)
For more info of the motivation behind this major change, please refer to [this guide](https://github.com/Azure/azure-storage-java/blob/master/V12%20Upgrade%20Story.md).

## Converting Core Classes
Our core asynchronous classes have been replaced, as well as new synchronous counterparts added.

| Core V10/11 classes  | Equivalent V12 Class | NEW synchronous clients |
|---:|---:|---:|
| ServiceURL  |  BlobServiceAsyncClient  | BlobServiceClient  |
| ContainerURL |  ContainerAsyncClient | ContainerClient |
| BlobURL    | BlobAsyncClient  |   BlobClient |
| BlockBlobURL  |  BlockBlobAsyncClient  |  BlockBlobClient  |
| AppendBlobURL  |  AppendBlobAsyncClient | AppendBlobClient  |
| PageBlobURL |  PageBlobAsyncClient | PageBlobClient  |

**Note:** The methods under TransferManager in V10/V11 were moved to `BlobAsyncClient` and `BlobClient` in V12.
## Updated Maven dependency
Dependency for Blob service:
```xml
<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-storage-blob</artifactId>
  <version>12.0.0</version>
</dependency>
```

## Build Client
In V10/V11, core classes were built with constructors, taking a `URL` and an already constructed `HttpPipeline`.
```java
final BlockBlobURL blobURL = new BlockBlobURL(
    new URL("https://" + "<account-name>" + ".blob.core.windows.net/mycontainer/myimage.jpg"),
    StorageURL.createPipeline(new SharedKeyCredentials("<account-name>", "<account-key>"), new PipelineOptions()));
```

In V12, we have moved to a builder pattern. To replicate the above V10/V11 snippet:
```java
// To get the BlobClient, we can use builder to initialize.
final BlobClient blobClient = new BlobClientBuilder()
    .endpoint("https://" + "<account-name>" + ".blob.core.windows.net")
    .containerName("mycontainer")
    .blobName("myimage.jpg")
    .credential(new StorageSharedKeyCredential("<account-name>", "<account-key>"))
    .buildClient();
// We can initialize BlockBlobClient from blobClient.
final BlockBlobClient blockBlobClient = blobClient.getBlockBlobClient(); // we can also choose PageBlobClient, AppendBlobClient, and BlobClient
```
These builders can also build sync and async clients interchangably. Just select the correct "build" method. Additionally, if you already have the full URL, you can just specify that as the endpoint instead of naming container and blob individually, similar to V10/V11.
```java
final BlobAsyncClient blobAsyncClient = new BlobClientBuilder()
    .endpoint("https://" + "<account-name>" + ".blob.core.windows.net/mycontainer/myimage.jpg")
    .credential(new StorageSharedKeyCredential("<account-name>", "<account-key>"))
    .buildAsyncClient();
final BlockBlobAsyncClient blockBlobClient = blobAsyncClient.getBlockBlobAsyncClient();
```

## Generate SAS token
SAS token generation has moved from helper classes to the core clients themselves.
See section [SAS Token](#sastoken) to learn how to use them as a credential.
Not all fields being set in these samples are necessary.
At minimum, only an expiry time and permission set are necessary to create a SAS.

In V10/V11, to generate the SAS token, you needed an instance of ServiceSASSignatureValues to fluently build out all it's options. This could then generate SASQueryParameters which contained the actual URL query string to attach to your URL. You also needed to provide container and blob names when necessary, as well as the `SharedKeyCredential` to sign the token with.
```java
// specify token properties
ServiceSASSignatureValues value = new ServiceSASSignatureValues();
BlobSASPermission p = new BlobSASPermission()
    .withRead(true)
    .withWrite(true)
    .withCreate(true)
    .withDelete(true)
    .withAdd(true);
value.withPermissions(p.toString())
    .withStartTime(OffsetDateTime.now().minusDays(1))
    .withExpiryTime(OffsetDateTime.now().plusDays(1))
    .withContainerName("<container-name>")
    .withBlobName("<blob-name>");
IPRange ipR = new IPRange()
    .withIpMin("0.0.0.0")
    .withIpMax("255.255.255.255");
value.withIpRange(ipR)
    .withProtocol(SASProtocol.HTTPS_ONLY)
    .withCacheControl("cache")
    .withContentDisposition("disposition")
    .withContentEncoding("encoding")
    .withContentLanguage("language")
    .withContentType("type");

// build the token
SASQueryParameters sasToken = value.generateSASQueryParameters(sharedKeyCredentails);
```

In V12, SAS tokens are generated off the client to the resource you wish to generate the SAS for.
The resource path handled automatically because of this, and the `SharedKeyCredential` authenticating the client is also used automatically to sign the SAS. See [building a client](#buildclient) for how to get an authenticated client.
```java
// specify token properties
String identifier = "identifier";
BlobSASPermission permissions = new BlobSASPermission()
    .withRead(true)
    .withCreate(true)
    .withDelete(true)
    .withWrite(true); // We can also choose BlobContainerSasPermission, BlobServiceSasQueryParameters based on the object level we want to grant access.
OffsetDateTime startTime = OffsetDateTime.now().minusDays(1);
OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1);
SasIpRange ipRange = new SasIpRange()
    .setIpMax("0.0.0.0")
    .setIpMax("255.255.255.255");
SasProtocol sasProtocol = SasProtocol.HTTPS_HTTP;
String cacheControl = "cache";
String contentDisposition = "disposition";
String contentEncoding = "encoding";
String contentLanguage = "language";
String contentType = "type";
String version = BlobServiceVersion.V2019_02_02.getVersion();

// build the token
BlobServiceSasSignatureValues sasSignatureValues = new BlobServiceSasSignatureValues(version, sasProtocol, startTime, expiryTime, permissions.toString(), ipRange, identifier, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType);
BlobServiceSasQueryParameters sasQueryParameters = sasSignatureValues.generateSasQueryParameters(new StorageSharedKeyCredential("<account-name>", "<account-key"));
```

## Credentials

### Connection string
V10/V11 did not support connection strings. In V12, our builders accept connection strings, no calls to `endpoint()` or `credential()` required. However, connection strings generally only point at the account, so you WILL need to specify container and blob names as necessary.
```java
BlobContainerClient client = new BlobContainerClientBuilder()
    .connectionString("${connection-string}")
    .containerName("mycontainer")
    .buildClient();
```

### Shared key credential
Shared key credentials can be used directly to authenticate your client. You need to fetch the `${accountName}` and `${accountKey}` from Azure Portal.
Learn More from [README](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/storage/azure-storage-blob/README.md)

In V10/V11, you used the credential to build your pipeline.
```java
// Initialize the credentials
SharedKeyCredentials credential = new SharedKeyCredentials("${accountName}", "${accountKey}");
// How service object take in the credentials.
BlockBlobURL blockBlobURL = new BlockBlobURL(new URL("<your-storage-blob-url>"), StorageURL.createPipeline(credential, new PipelineOptions()));
```

Since the builder in V12 manages pipeline generation, you can just hand the `StorageSharedKeyCredential` to the builder.
```java
// Initialize the credentials
StorageSharedKeyCredential credential = new StorageSharedKeyCredential("${accountName}", "${accountKey}");
// How service object take in the credentials.
BlobServiceClient client = new BlobServiceClientBuilder()
    .endpoint("https://" + "<account-name>" + ".blob.core.windows.net")
    .credential(credential)
    .buildClient();
```

### SASToken
A URL with a SAS token looks like the following: `https://${accountName}.blob.core.windows.net/?${sasToken}`.
Refer the [documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-file-share_12.0.0/sdk/storage/azure-storage-blob/README.md) for more info.

See section [Generate SAS token](#generate-sas-token) for how to generate the token programmatically.

In V10/V11, you had to provide the URL with the token attached, which often resulted in URL manipulation when a token could be used on more than one resource.
```java
// Here is how the blob object take in the sas token generated in above section.
ContainerURL containerURL = new ContainerURL(new URL("<your-storage-blob-url>"), StorageURL.createPipeline(credential, new PipelineOptions()));
BlobURLParts parts = URLParser.parse(containerURL.createBlobURL("<blob-name>").toURL());
parts.withSasQueryParameters(sasToken).withScheme("https");
BlockBlobURL blockBlobURL = new BlockBlobURL(parts.toURL(), StorageURL.createPipeline(
    new AnonymousCredentials(), new PipelineOptions()));
```

In V12, SAS tokens can be managed just like any other credential.
```java
// How service object take in the credentials.
BlobServiceClient client = new BlobServiceClientBuilder()
    .endpoint("https://${accountName}.blob.core.windows.net")
    .sasToken("${sasToken}")
    .buildClient();
```

However, if you already have the full URL with SAS token attached, you can use that too:
```java
BlobServiceClient client = new BlobServiceClientBuilder()
    .endpoint("https://${accountName}.blob.core.windows.net/?${sasToken}")
    .buildClient();
```

### Pipeline and pipeline options

In V10/V11, pipeline options build into pipeline through StorageURL, e.g. `RequestRetryOptions`.

```java
HttpPipeline pipeline = StorageURL.createPipeline(new SharedKeyCredentials("<account-name>", "<account-key>"),
    new PipelineOptions().withRequestRetryOptions(new RequestRetryOptions()));
```

In V12, it is flattened to just be on the builder.
```java
BlobServiceClient client = new BlobServiceClientBuilder()
    .endpoint("https://${accountName}.blob.core.windows.net")
    .sasToken("${sasToken}")
    .retryOptions(new RequestRetryOptions())
    .buildClient();
```
## Provide side by side sync-over-async APIs
Each type (Container, Blob, etc.) has both a sync and async client. It is easy and intuitive to use whichever one is preferable in a given context without having to bother about clutter from the other.
Suppose the Container Client been initialized as `${containerClient}` for sync and `${containerAsyncClient}` for async. Please refer the [Build Client](#build-client) section.

* Example of using Async API in V12.
```java
Mono<BlobContainerProperties> response = containerAsyncClient.getProperties();
```

* Example of using Sync API in V12
```java
BlobContainerProperties blobProperties = containerClient.getProperties();
```

## Async APIs Comparison
In V10/V11, every RESTful API returned a reactive response of type `Single`
(see RxJava documentation for more details), which emits one and only one result.

These returned object representations of the single HTTP response that came back.

Single result API in V10/V11:
```java
serviceURL.getProperties(Context.NONE).subscribe(
    // print the selected service property on success
    response -> System.out.println(response.body().defaultServiceVersion()),
    // handle error
    error -> System.out.println(error.getMessage()));
```

Listing API in V10/V11:
```java
serviceURL.listContainersSegment(null, null, Context.NONE).subscribe(
    // print the list; grab continuation token for making another call to get next list segment
    response -> {
        System.out.println("Page token to fetch more containers:" + response.body().nextMarker());
        response.body().containerItems().stream().forEach(
            containerItem -> System.out.println("Container name: " + containerItem.name()));
    },
    // handle error
    error -> System.out.println(error.getMessage()));
```

In V12, Reactor provides an equivalent class `Mono` (0-1 response). There is also the `Flux` class for zero-to-many responses, and Azure client libraries use a subclass known at `PagedFlux` to also provide pagination and response information.

Additionally, classes returned from APIs are the "core information" of the response, rather than the HTTP response exactly.

Full access to all fields of the HTTP response is available available by using the methods having the suffix -withResponse, but examples of that usage are beyond the scope

Suppose the BlobServiceClient has been initialized as `serviceClient` and the BlobServiceAsyncClient has been initialized as `serviceAsyncClient`.
Single result API in V12, similar to V10/V11:
```java
serviceAsyncClient.getProperties().subscribe(
    // print the selected service property on success
    properties -> System.out.println(properties.getDefaultServiceVersion()),
    // handle error
    error -> System.out.println(error.getMessage()),
    // on completion
    () -> System.out.println("Get properties request completed successfully."));
```

In V12, you no longer need to worry about paginated results.
Listing API in V12:
```java
serviceAsyncClient.listBlobContainers()
    // print each item in the list
    .doOnNext(containerItem -> System.out.println(containerItem.getName()))
    // handle error
    .doOnError(error -> System.out.println(error.getMessage()))
    // on completion
    .doFinally(sig -> System.out.println("Paginated listing request completed successfully."))
    .subscribe();
```

More on paginated requests in [this section](#pagination).

## Minimum Overload APIs and Maxmum Overload APIs:
In V10/V11, we only provide one maximum overload API for each operation.
```java
public Single<ContainerCreateResponse> create(Metadata metadata, PublicAccessType accessType, Context context)
```

In V12, we provide at least one minimum and one maximum for most of the operations.

Minimum overload in async:
```java
public Mono<BlobContainerProperties> getProperties()
```
Maximum overload in async:
```java
public Mono<Response<BlobContainerProperties>> getPropertiesWithResponse(String leaseId)
```

## Pagination:
Listing or Paging API returned `Single<SomeResponseType>` in V10/V11, where `SomeResponseType` contained a List<SomeItemType>. You had to manually follow a continuation token if provided

List all blobs V8:
```java
private ContainerURL containerURL;

private List<BlobItem> retrieveBlobsForCurrentPage(String pageToken, List<BlobItem> results) {
    if (pageToken == null) {
        return results;
    }
    containerURL.listBlobsFlatSegment(pageToken, null, Context.NONE).subscribe(
        response -> {
            results.addAll((Collection) response.body().segment().blobItems());
            retrieveBlobsForCurrentPage(response.body().nextMarker(), results);
        }
    );
    return results;
}

public void run() throws Exception{
    // Build ContainerURL
    containerURL = new ContainerURL(new URL("https://" + "<account-name>" + ".blob.core.windows.net"),
        StorageURL.createPipeline(new SharedKeyCredentials("<account-name>", "<account-key>"), new PipelineOptions()));
    // Initialize empty blob list
    List<BlobItem> results = new ArrayList<>();
    // Start from first page
    containerURL.listBlobsFlatSegment(null, null, Context.NONE).subscribe(
        response -> {
            results.addAll((Collection) response.body().segment().blobItems());
            if (response.body().nextMarker() != null) {
                results.addAll((Collection) retrieveBlobsForCurrentPage(response.body().nextMarker(), results));
            }
        });
}
```

V12 provides two pagination classes: `PagedIterable<T>` for sync and `PageFlux<T>` for async.
These allow you to consume listing operations by individual item or by response pages. The latter is needed to access general information in each HTTP response.

List all blobs using async API V12, by page:
```java
private BlobContainerAsyncClient containerAsyncClient;
private List<BlobItem> retrieveBlobs(String pageToken, List<BlobItem> results) {
    if (pageToken == null) {
        return results;
    }
    containerAsyncClient.listBlobs().byPage(pageToken).subscribe(
        response -> {
            results.addAll((Collection) response.getValue());
            retrieveBlobs(response.getContinuationToken(), results);
        }
    );
    return results;
}

public void run() {
    // Build ContainerURL
    containerAsyncClient = new BlobContainerClientBuilder().credential(new StorageSharedKeyCredential("<account-name>", "<account-key>")).buildAsyncClient();
    // Initialize empty blob list
    List<BlobItem> results = new ArrayList<>();
    // Start from first page
    containerAsyncClient.listBlobs()
        .byPage()
        .subscribe(response ->
        {
            results.addAll((Collection) response.getValue());
            if (response.getContinuationToken() != null) {
                results.addAll((Collection) retrieveBlobs(response.getContinuationToken(), results));
            }
        });
}
```


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using Alfred.Domain.Repositories;
using Alfred.Models.Communities;
using Alfred.Services;

namespace Alfred.Domain.Services
{
    public class CommunityService : ICommunityService
    {
        private readonly ICommunityRepository _communityRepo;

        public CommunityService(ICommunityRepository communityRepo)
        {
            _communityRepo = communityRepo;
        }

        public async Task<CommunityResponseModel> GetCommunities(CommunityCriteriaModel criteriaModel)
        {
            return await _communityRepo.GetCommunities(criteriaModel).ConfigureAwait(false);
        }

        public async Task<CommunityModel> GetCommunity(int id)
        {
            return await _communityRepo.GetCommunity(id).ConfigureAwait(false);
        }

        public async Task<int> CreateCommunity(CreateCommunityModel createCommunityModel)
        {
            if (createCommunityModel != null && !IsEmailUsed(createCommunityModel.Email))
            {
                return await _communityRepo.SaveCommunity(createCommunityModel).ConfigureAwait(false);
            }
            return -1;
        }

        public async Task<CommunityModel> UpdateCommunity(UpdateCommunityModel updateCommunityModel)
        {
            if (updateCommunityModel != null)
            {
                await _communityRepo.UpdateCommunity(updateCommunityModel).ConfigureAwait(false);
            }
            return null;
        }

        public async Task<bool> DeleteCommunity(int id)
        {
            var community = await _communityRepo.GetCommunity(id).ConfigureAwait(false);
            if (community != null)
            {
                await _communityRepo.DeleteCommunity(id).ConfigureAwait(false);
                return true;
            }
            return false;
        }

        private bool IsEmailUsed(string email)
        {
            return _communityRepo.GetCommunity(email) != null;
        }
    }
}


text:
package org.sleuthkit.autopsy.datamodel;

import java.util.Map;
import java.util.logging.Level;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.TskCoreException;

/**
 * An abstract node that encapsulates AbstractFile data
 *
 * @param <T> type of the AbstractFile to encapsulate
 */
public abstract class AbstractAbstractFileNode<T extends AbstractFile> extends AbstractContentNode<T> {

    private static Logger logger = Logger.getLogger(AbstractAbstractFileNode.class.getName());

    /**
     * @param <T> type of the AbstractFile data to encapsulate
     * @param abstractFile file to encapsulate
     */
    AbstractAbstractFileNode(T abstractFile) {
        super(abstractFile);
    }

    // Note: this order matters for the search result, changed it if the order of property headers on the "KeywordSearchNode"changed
    public static enum AbstractFilePropertyType {

        NAME {
            @Override
            public String toString() {
                return "Name";
            }
        },
        LOCATION {
            @Override
            public String toString() {
                return "Location";
            }
        },
        MOD_TIME {
            @Override
            public String toString() {
                return "Modified Time";
            }
        },
        CHANGED_TIME {
            @Override
            public String toString() {
                return "Change Time";
            }
        },
        ACCESS_TIME {
            @Override
            public String toString() {
                return "Access Time";
            }
        },
        CREATED_TIME {
            @Override
            public String toString() {
                return "Created Time";
            }
        },
        SIZE {
            @Override
            public String toString() {
                return "Size";
            }
        },
        FLAGS_DIR {
            @Override
            public String toString() {
                return "Flags(Dir)";
            }
        },
        FLAGS_META {
            @Override
            public String toString() {
                return "Flags(Meta)";
            }
        },
        MODE {
            @Override
            public String toString() {
                return "Mode";
            }
        },
        USER_ID {
            @Override
            public String toString() {
                return "UserID";
            }
        },
        GROUP_ID {
            @Override
            public String toString() {
                return "GroupID";
            }
        },
        META_ADDR {
            @Override
            public String toString() {
                return "Meta Addr.";
            }
        },
        ATTR_ADDR {
            @Override
            public String toString() {
                return "Attr. Addr.";
            }
        },
        TYPE_DIR {
            @Override
            public String toString() {
                return "Type(Dir)";
            }
        },
        TYPE_META {
            @Override
            public String toString() {
                return "Type(Meta)";
            }
        },
        KNOWN {
            @Override
            public String toString() {
                return "Known";
            }
        },
        MD5HASH {
            @Override
            public String toString() {
                return "MD5 Hash";
            }
        }
    }

     /**
     * Fill map with AbstractFile properties
     *
     * @param map map with preserved ordering, where property names/values are
     * put
     * @param content to extract properties from
     */
    public static void fillPropertyMap(Map<String, Object> map, AbstractFile content) {

        String path = "";
        try {
            path = content.getUniquePath();
        } catch (TskCoreException ex) {
            logger.log(Level.SEVERE, "Except while calling Content.getUniquePath() on " + content);
        }

        map.put(AbstractFilePropertyType.NAME.toString(), AbstractAbstractFileNode.getContentDisplayName(content));
        map.put(AbstractFilePropertyType.LOCATION.toString(), path);
        map.put(AbstractFilePropertyType.MOD_TIME.toString(), ContentUtils.getStringTime(content.getMtime(), content));
        map.put(AbstractFilePropertyType.CHANGED_TIME.toString(), ContentUtils.getStringTime(content.getCtime(), content));
        map.put(AbstractFilePropertyType.ACCESS_TIME.toString(), ContentUtils.getStringTime(content.getAtime(), content));
        map.put(AbstractFilePropertyType.CREATED_TIME.toString(), ContentUtils.getStringTime(content.getCrtime(), content));
        map.put(AbstractFilePropertyType.SIZE.toString(), content.getSize());
        map.put(AbstractFilePropertyType.FLAGS_DIR.toString(), content.getDirFlagAsString());
        map.put(AbstractFilePropertyType.FLAGS_META.toString(), content.getMetaFlagsAsString());
        map.put(AbstractFilePropertyType.MODE.toString(), content.getModesAsString());
        map.put(AbstractFilePropertyType.USER_ID.toString(), content.getUid());
        map.put(AbstractFilePropertyType.GROUP_ID.toString(), content.getGid());
        map.put(AbstractFilePropertyType.META_ADDR.toString(), content.getMetaAddr());
        map.put(AbstractFilePropertyType.ATTR_ADDR.toString(), Long.toString(content.getAttrType().getValue()) + "-" + Long.toString(content.getAttrId()));
        map.put(AbstractFilePropertyType.TYPE_DIR.toString(), content.getDirType().getLabel());
        map.put(AbstractFilePropertyType.TYPE_META.toString(), content.getMetaType().toString());
        map.put(AbstractFilePropertyType.KNOWN.toString(), content.getKnown().getName());
        map.put(AbstractFilePropertyType.MD5HASH.toString(), content.getMd5Hash() == null ? "" : content.getMd5Hash());
    }

    static String getContentDisplayName(AbstractFile file) {
        String name = file.getName();
        if (name.equals("..")) {
            name = DirectoryNode.DOTDOTDIR;
        } else if (name.equals(".")) {
            name = DirectoryNode.DOTDIR;
        }
        return name;
    }
}