text:
#include "tensorflow/lite/delegates/gpu/cl/kernels/conv_constants.h"

#include <string>
#include <utility>

#include "tensorflow/lite/delegates/gpu/cl/kernels/util.h"
#include "tensorflow/lite/delegates/gpu/cl/kernels/work_group_picking.h"
#include "tensorflow/lite/delegates/gpu/cl/precision.h"

namespace tflite {
namespace gpu {
namespace cl {
namespace {

std::string GenerateConvolutionConstantCode(
    const OperationDef& op_def, const int2& kernel_size, int src_channels,
    int dst_channels, bool stride_correction, const CLDevice& device,
    const std::vector<ElementwiseOperation*>& linked_operations) {
  TensorCodeGenerator src_tensor(
      "src_data", WHSPoint{"src_size.x", "src_size.y", "src_size.z"},
      op_def.src_tensors[0]);
  TensorCodeGenerator dst_tensor(
      "dst_data", WHSPoint{"dst_size.x", "dst_size.y", "dst_size.z"},
      op_def.dst_tensors[0]);

  std::string c = GetCommonDefines(op_def.precision);

  const int out_z = IntegralDivideRoundUp(dst_channels, 4);
  const std::string kOutZ = std::to_string(out_z);
  const int src_depth = IntegralDivideRoundUp(src_channels, 4);

  const auto src_tensor_type = op_def.src_tensors[0].storage_type;
  const bool manual_clamp = src_tensor_type == TensorStorageType::BUFFER ||
                            src_tensor_type == TensorStorageType::IMAGE_BUFFER;

  switch (op_def.precision) {
    case CalculationsPrecision::F32:
    case CalculationsPrecision::F16:
      c += "#define CONV4(R, SRC, F, i) \\\n";
      c += "  R += SRC.x * F[i + 0]; \\\n";
      c += "  R += SRC.y * F[i + 1]; \\\n";
      c += "  R += SRC.z * F[i + 2]; \\\n";
      c += "  R += SRC.w * F[i + 3];   \n";

      c += "#define CONV3(R, SRC, F, i) \\\n";
      c += "  R += SRC.x * F[i + 0]; \\\n";
      c += "  R += SRC.y * F[i + 1]; \\\n";
      c += "  R += SRC.z * F[i + 2]; \n";

      c += "#define CONV2(R, SRC, F, i) \\\n";
      c += "  R += SRC.x * F[i + 0]; \\\n";
      c += "  R += SRC.y * F[i + 1]; \n";

      c += "#define CONV1(R, SRC, F, i) \\\n";
      c += "  R += SRC * F[i + 0]; \n";
      break;
    case CalculationsPrecision::F32_F16:
      c += "#define CONV4(R, SRC, F, i) \\\n";
      c += "  R += convert_float4(SRC.x * F[i + 0] + SRC.y * F[i + 1]";
      c += " + SRC.z * F[i + 2] + SRC.w * F[i + 3]);\n";

      c += "#define CONV3(R, SRC, F, i) \\\n";
      c += "  R += convert_float4(SRC.x * F[i + 0] + SRC.y * F[i + 1]";
      c += " + SRC.z * F[i + 2]);\n";

      c += "#define CONV2(R, SRC, F, i) \\\n";
      c += "  R += convert_float4(SRC.x * F[i + 0] + SRC.y * F[i + 1]);\n";

      c += "#define CONV1(R, SRC, F, i) \\\n";
      c += "  R += convert_float4(SRC * F[i + 0]);\n";
      break;
  }

  const std::string postfixes[] = {".x", ".xy", ".xyz", ""};

  c += "__kernel void main_function(\n";
  c += src_tensor.GetDeclaration(AccessType::READ) + ",\n";
  c += "    __constant FLT4* filters,  \n";
  c += "    __constant FLT4* biases";
  c += GetArgsDeclaration(linked_operations);
  c += dst_tensor.GetDeclaration(AccessType::WRITE) + ",\n";
  c += "    int2 stride,               \n";
  c += "    int2 padding,              \n";
  c += "    int2 dilation,             \n";
  c += "    int4 src_size,             \n";
  c += "    int4 dst_size              \n";
  c += ") {\n";
  c += "  int X = get_global_id(0);\n";
  c += "  int Y = get_global_id(1);\n";
  c += "  if (X >= dst_size.x || Y >= dst_size.y) return;\n";
  if (stride_correction) {
    c += "  int start_x = " +
         GetXStrideCorrected("X", "src_size.w", "stride.x", "padding.x") +
         ";\n";
  } else {
    c += "  int start_x = X * stride.x + padding.x;\n";
  }
  c += "  int start_y = Y * stride.y + padding.y;\n";
  c += "  ACCUM_FLT4 r[" + kOutZ + "];\n";
  c += "  for (int i = 0; i < " + kOutZ + "; ++i) {\n";
  c += "    r[i] = (ACCUM_FLT4)(0.0f, 0.0f, 0.0f, 0.0f);\n";
  c += "  }\n";
  const auto address_mode = GetFastestZeroMode(device);
  int filters_counter = 0;
  for (int s = 0; s < src_depth; ++s) {
    const int ch_count = std::min(4, src_channels - s * 4);
    const std::string s_conv = "CONV" + std::to_string(ch_count);
    const std::string s_count = ch_count == 1 ? "" : std::to_string(ch_count);
    const std::string s_type = absl::StrCat("FLT", s_count);
    const std::string s_postfix = postfixes[ch_count - 1];
    for (int ky = 0; ky < kernel_size.y; ++ky) {
      std::string s_y = absl::StrCat("(start_y + ", ky, " * dilation.y)");
      if (manual_clamp) {
        c += "  {\n";
        c += "  bool y_out = " + s_y + " < 0 || " + s_y + " >= src_size.y;\n";
      }
      for (int kx = 0; kx < kernel_size.x; ++kx) {
        c += "  {\n";
        std::string s_x = absl::StrCat("(start_x + ", kx, " * dilation.x)");
        if (manual_clamp) {
          c += "    bool x_out = " + s_x + "< 0 || " + s_x + ">= src_size.x;\n";
          c += "    " + s_type + " src = x_out || y_out ?";
          c += "(" + s_type + ")(0.0) : ";
          c += src_tensor.ReadWHS(s_x, s_y, std::to_string(s)) + s_postfix +
               ";\n";
        } else {
          c += "    " + s_type + " src = " +
               src_tensor.ReadWHS(s_x, s_y, std::to_string(s), address_mode) +
               s_postfix + ";\n";
        }
        for (int d = 0; d < out_z; ++d) {
          c += "    " + s_conv + "(r[" + std::to_string(d) + "], src, filters,";
          c += " " + std::to_string(filters_counter) + ");\n";
          filters_counter += ch_count;
        }
        c += "  }\n";
      }
      if (manual_clamp) {
        c += "  }\n";
      }
    }
  }
  for (int i = 0; i < out_z; ++i) {
    std::string s_i = std::to_string(i);
    c += "  {\n";
    c += "    FLT4 res = TO_FLT4(r[" + s_i + "]) + biases[" + s_i + "];\n";
    const LinkingContext context{"res", "X", "Y", s_i};
    c += PostProcess(linked_operations, context);
    c += "  " + dst_tensor.WriteWHS("res", "X", "Y", s_i);
    c += "  }\n";
  }
  c += "}\n";
  return c;
}

// Adreno can provide up to ~3-4KB of constant memory, but in some cases even
// 3KB can have very bad performance.
int GetAdrenoOptimalMaxConstantSize(int gpu_version) {
  if (gpu_version < 600) {
    return 256 * 10;  // 2.5KB
  } else {
    return 256 * 14;  // 3.5KB
  }
}

int GetOptimalMaxConstantSize(const DeviceInfo& info) {
  if (info.vendor != Vendor::QUALCOMM) {
    // In general we do not expect that this kernel will be used with non Adreno
    // so as it tuned for __constant memory that have big profit on Adreno
    return 1024;  // 1KB
  } else {
    return GetAdrenoOptimalMaxConstantSize(info.adreno_info.gpu_version);
  }
}
}  // namespace

ConvConstants::ConvConstants(ConvConstants&& kernel)
    : GPUOperation(std::move(kernel)),
      weights_(std::move(kernel.weights_)),
      biases_(std::move(kernel.biases_)),
      kernel_size_(kernel.kernel_size_),
      stride_(kernel.stride_),
      padding_(kernel.padding_),
      dilation_(kernel.dilation_),
      src_channels_(kernel.src_channels_),
      dst_channels_(kernel.dst_channels_),
      kernel_(std::move(kernel.kernel_)),
      work_group_size_(kernel.work_group_size_) {}

ConvConstants& ConvConstants::operator=(ConvConstants&& kernel) {
  if (this != &kernel) {
    weights_ = std::move(kernel.weights_);
    biases_ = std::move(kernel.biases_);
    std::swap(kernel_size_, kernel.kernel_size_);
    std::swap(stride_, kernel.stride_);
    std::swap(padding_, kernel.padding_);
    std::swap(dilation_, kernel.dilation_);
    std::swap(src_channels_, kernel.src_channels_);
    std::swap(dst_channels_, kernel.dst_channels_);
    kernel_ = std::move(kernel.kernel_);
    std::swap(work_group_size_, kernel.work_group_size_);
    GPUOperation::operator=(std::move(kernel));
  }
  return *this;
}

Status ConvConstants::Compile(const CreationContext& creation_context) {
  const bool stride_correction =
      definition_.IsBatchSupported() && stride_.x != 1;
  const auto code = GenerateConvolutionConstantCode(
      definition_, kernel_size_, src_channels_, dst_channels_,
      stride_correction, *creation_context.device, linked_operations_);
  std::vector<CompilerOptions> options;
  if (definition_.precision == CalculationsPrecision::F16 &&
      creation_context.device->IsAdreno3xx()) {
    options.push_back(CompilerOptions::ADRENO_FULL_SIMD_LINE);
  }
  if (definition_.precision != CalculationsPrecision::F32 &&
      creation_context.device->IsPowerVR()) {
    // BUG, some PowerVRs (GE8320) produce incorrect result without it
    options.push_back(CompilerOptions::CL_OPT_DISABLE);
  }
  return creation_context.cache->GetOrCreateCLKernel(
      code, "main_function", options, *creation_context.context,
      *creation_context.device, &kernel_);
}

Status ConvConstants::BindArguments() {
  kernel_.ResetBindingCounter();
  RETURN_IF_ERROR(kernel_.SetMemoryAuto(src_[0]->GetMemoryPtr()));
  RETURN_IF_ERROR(kernel_.SetMemoryAuto(weights_.GetMemoryPtr()));
  RETURN_IF_ERROR(kernel_.SetMemoryAuto(biases_.GetMemoryPtr()));
  RETURN_IF_ERROR(BindArgs(&kernel_, linked_operations_));
  RETURN_IF_ERROR(kernel_.SetMemoryAuto(dst_[0]->GetMemoryPtrForWriting()));
  RETURN_IF_ERROR(kernel_.SetBytesAuto(stride_));
  RETURN_IF_ERROR(
      kernel_.SetBytesAuto(int2(padding_.x * src_[0]->Batch(), padding_.y)));
  RETURN_IF_ERROR(
      kernel_.SetBytesAuto(int2(dilation_.x * src_[0]->Batch(), dilation_.y)));
  RETURN_IF_ERROR(kernel_.SetBytesAuto(src_[0]->GetWBatchedHSB()));
  RETURN_IF_ERROR(kernel_.SetBytesAuto(dst_[0]->GetWBatchedHSB()));
  return OkStatus();
}

int3 ConvConstants::GetGridSize() const {
  const int grid_x = dst_[0]->Width() * dst_[0]->Batch();
  const int grid_y = dst_[0]->Height();
  return int3(grid_x, grid_y, 1);
}

Status ConvConstants::Tune(const TuningParameters& params) {
  RETURN_IF_ERROR(BindArguments());
  return GetBestWorkGroup(params, kernel_, GetGridSize(), &work_group_size_);
}

Status ConvConstants::AddToQueue(CLCommandQueue* queue) {
  RETURN_IF_ERROR(BindArguments());
  return queue->DispatchImplicit(kernel_, GetGridSize(), work_group_size_);
}

bool IsConvConstantsSupported(const CLDevice& device,
                              const OperationDef& definition,
                              const Convolution2DAttributes& attr) {
  if (device.IsAMD() && definition.precision != CalculationsPrecision::F32 &&
      definition.src_tensors[0].storage_type != TensorStorageType::BUFFER) {
    // BUG, some AMD gpus crashe without it
    return false;
  }

  const auto& w_shape = attr.weights.shape;
  const int dst_channels = AlignByN(w_shape.o, 4);
  const int filters_count = w_shape.i * dst_channels * w_shape.h * w_shape.w;
  const int float_size = definition.precision == CalculationsPrecision::F32
                             ? sizeof(float)
                             : sizeof(half);
  const int filters_buffer_size = filters_count * float_size;
  const int kConstantMaxSize = GetOptimalMaxConstantSize(device.GetInfo());
  const int flt4_registers = IntegralDivideRoundUp(w_shape.o, 4);
  return filters_buffer_size <= kConstantMaxSize && flt4_registers <= 8;
}

Status CreateConvConstants(const CreationContext& creation_context,
                           const OperationDef& definition,
                           const Convolution2DAttributes& attr,
                           ConvConstants* result) {
  if (!IsConvConstantsSupported(*creation_context.device, definition, attr)) {
    return InvalidArgumentError("ConvConstants doesn't supported");
  }
  *result = ConvConstants(definition, attr);
  RETURN_IF_ERROR(
      result->UploadWeights(attr.weights, creation_context.context));
  LinearStorageCreateInfo create_info;
  create_info.storage_type = LinearStorageType::BUFFER;
  create_info.data_type = definition.GetDataType();
  create_info.aligned_size = attr.weights.shape.o;
  RETURN_IF_ERROR(CreateLinearStorage(
      create_info, attr.bias, creation_context.context, &result->biases_));

  return OkStatus();
}

}  // namespace cl
}  // namespace gpu
}  // namespace tflite


text:
TEST_CASE("WKT geometry for point") {
    const osmium::geom::WKTFactory<> factory;
    const std::string wkt{factory.create_point(osmium::Location{3.2, 4.2})};
    REQUIRE(wkt == "POINT(3.2 4.2)");
}

TEST_CASE("WKT geometry for empty point") {
    const osmium::geom::WKTFactory<> factory;
    REQUIRE_THROWS_AS(factory.create_point(osmium::Location()), const osmium::invalid_location&);
}

TEST_CASE("WKT geometry for point in ekwt") {
    const osmium::geom::WKTFactory<> factory{7, osmium::geom::wkt_type::ewkt};

    const std::string wkt{factory.create_point(osmium::Location{3.2, 4.2})};
    REQUIRE(wkt == "SRID=4326;POINT(3.2 4.2)");
}

TEST_CASE("WKT geometry for point in ekwt in web mercator") {
    const osmium::geom::WKTFactory<osmium::geom::MercatorProjection> factory{2, osmium::geom::wkt_type::ewkt};

    const std::string wkt{factory.create_point(osmium::Location{3.2, 4.2})};
    REQUIRE(wkt == "SRID=3857;POINT(356222.37 467961.14)");
}

TEST_CASE("WKT geometry factory") {
    osmium::geom::WKTFactory<> factory;

    osmium::memory::Buffer buffer{10000};

    SECTION("linestring") {
        const auto& wnl = create_test_wnl_okay(buffer);

        SECTION("unique forwards (default)") {
            const std::string wkt{factory.create_linestring(wnl)};
            REQUIRE(wkt == "LINESTRING(3.2 4.2,3.5 4.7,3.6 4.9)");
        }

        SECTION("unique backwards") {
            const std::string wkt{factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward)};
            REQUIRE(wkt == "LINESTRING(3.6 4.9,3.5 4.7,3.2 4.2)");
        }

        SECTION("all forwards") {
            const std::string wkt{factory.create_linestring(wnl, osmium::geom::use_nodes::all)};
            REQUIRE(wkt == "LINESTRING(3.2 4.2,3.5 4.7,3.5 4.7,3.6 4.9)");
        }

        SECTION("all backwards") {
            const std::string wkt{factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward)};
            REQUIRE(wkt == "LINESTRING(3.6 4.9,3.5 4.7,3.5 4.7,3.2 4.2)");
        }
    }

    SECTION("polygon") {
        const auto& wnl = create_test_wnl_closed(buffer);

        SECTION("unique forwards (default)") {
            const std::string wkt{factory.create_polygon(wnl)};
            REQUIRE(wkt == "POLYGON((3 3,4.1 4.1,3.6 4.1,3.1 3.5,3 3))");
        }

        SECTION("unique backwards") {
            const std::string wkt{factory.create_polygon(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward)};
            REQUIRE(wkt == "POLYGON((3 3,3.1 3.5,3.6 4.1,4.1 4.1,3 3))");
        }

        SECTION("all forwards") {
            const std::string wkt{factory.create_polygon(wnl,  osmium::geom::use_nodes::all)};
            REQUIRE(wkt == "POLYGON((3 3,4.1 4.1,4.1 4.1,3.6 4.1,3.1 3.5,3 3))");
        }

        SECTION("all backwards") {
            const std::string wkt{factory.create_polygon(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward)};
            REQUIRE(wkt == "POLYGON((3 3,3.1 3.5,3.6 4.1,4.1 4.1,4.1 4.1,3 3))");
        }
    }

    SECTION("empty linestring") {
        const auto& wnl = create_test_wnl_empty(buffer);

        REQUIRE_THROWS_AS(factory.create_linestring(wnl), const osmium::geometry_error&);
        REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward), const osmium::geometry_error&);
        REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::all), const osmium::geometry_error&);
        REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward), const osmium::geometry_error&);
    }

    SECTION("linestring with two same locations") {
        const auto& wnl = create_test_wnl_same_location(buffer);

        SECTION("unique forwards") {
            REQUIRE_THROWS_AS(factory.create_linestring(wnl), const osmium::geometry_error&);

            try {
                factory.create_linestring(wnl);
            } catch (const osmium::geometry_error& e) {
                REQUIRE(e.id() == 0);
                REQUIRE(std::string(e.what()) == "need at least two points for linestring");
            }
        }

        SECTION("unique backwards") {
            REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward), const osmium::geometry_error&);
        }

        SECTION("all forwards") {
            const std::string wkt{factory.create_linestring(wnl, osmium::geom::use_nodes::all)};
            REQUIRE(wkt == "LINESTRING(3.5 4.7,3.5 4.7)");
        }

        SECTION("all backwards") {
            const std::string wkt{factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward)};
            REQUIRE(wkt == "LINESTRING(3.5 4.7,3.5 4.7)");
        }
    }

    SECTION("linestring with undefined location") {
        const auto& wnl = create_test_wnl_undefined_location(buffer);

        REQUIRE_THROWS_AS(factory.create_linestring(wnl), const osmium::invalid_location&);
    }

    SECTION("area with one outer and no inner rings") {
        const osmium::Area& area = create_test_area_1outer_0inner(buffer);

        const std::string wkt{factory.create_multipolygon(area)};
        REQUIRE(wkt == "MULTIPOLYGON(((3.2 4.2,3.5 4.7,3.6 4.9,3.2 4.2)))");
    }

    SECTION("area with one outer and one inner ring") {
        const osmium::Area& area = create_test_area_1outer_1inner(buffer);

        const std::string wkt{factory.create_multipolygon(area)};
        REQUIRE(wkt == "MULTIPOLYGON(((0.1 0.1,9.1 0.1,9.1 9.1,0.1 9.1,0.1 0.1),(1 1,8 1,8 8,1 8,1 1)))");
    }

    SECTION("area with two outer and two inner rings") {
        const osmium::Area& area = create_test_area_2outer_2inner(buffer);

        const std::string wkt{factory.create_multipolygon(area)};
        REQUIRE(wkt == "MULTIPOLYGON(((0.1 0.1,9.1 0.1,9.1 9.1,0.1 9.1,0.1 0.1),(1 1,4 1,4 4,1 4,1 1),(5 5,5 7,7 7,5 5)),((10 10,11 10,11 11,10 11,10 10)))");
    }

}

redpajama_set_name: RedPajamaGithub


text:
'use strict'

var express = require('express'),
  fs = require('fs'),
  http = require('http'),
  https = require('https'),
  util = require('util'),
  routes = require('routes'),
  bodyParser = require('body-parser'),
  path = require('path'),
  multer = require('multer'),
  request = require('request'),
  app = express();

var server = https.createServer({
    key: fs.readFileSync('key.pem'),
    cert: fs.readFileSync('cert.pem')
  },
  app
)

server.listen(8080)
app.listen(4040)

var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, path.join(__dirname, 'uploads'))
  },
  filename: function(req, file, cb) {
    cb(null, 'camimage.jpg')
  }
});

var upload = multer({
  storage: storage
}).single('campicture');

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: false
}))

// parse application/json
app.use(bodyParser.json())

// index
app.get('/', function(req, res) {
  res.send('Hey there! I am a bot.')
})

app.post('/getimage/:id/:secret/', function(req, res, next) {
  var userid = req.params.id || 0;
  var secret = req.params.secret || 0;
  if ((userid === '') && (secret === '')) {
    upload(req, res, function(err) {
      if (err) {
        return console.error('Error:', err);
      }
    })
  } else {
    return console.log('Error.');
  }
})

app.get('/image/:id/:secret', function(req, res) {
  // res.sendFile(filepath);
  var userid = req.params.id || 0;
  var secret = req.params.secret || 0;
  if ((userid === '123451') && (secret === '0000a')) {
    res.sendFile(path.join(__dirname, 'uploads', 'camimage.jpg'));
  } else {
    return console.log('Error.');
  }

});

// for facebook verification
app.get('/webhook/', function(req, res) {
  if (req.query['hub.verify_token'] === '') {
    res.send(req.query['hub.challenge'])
  }
  res.send('Error, wrong token')
})

// to post data
app.post('/webhook/', function(req, res) {
  let messaging_events = req.body.entry[0].messaging
  for (let i = 0; i < messaging_events.length; i++) {
    let event = req.body.entry[0].messaging[i]
    let sender = event.sender.id
    if (event.message && event.message.text) {
      let text = event.message.text
      if (text === 'Generic') {
        sendGenericMessage(sender)
        continue
      }
      sendTextMessage(sender, "Sending an image...")
      let imageLink =
      sendImage(sender, '')
    }
    if (event.postback) {
      let text = JSON.stringify(event.postback)
      sendTextMessage(sender, "Postback received: " + text.substring(0, 200), token)
      continue
    }
  }
  res.sendStatus(200)
})

// recommended to inject access tokens as environmental variables, e.g.
// const token = process.env.PAGE_ACCESS_TOKEN
const token = ""

function sendTextMessage(sender, text) {
  let messageData = {
    text: text
  }

  request({
    url: 'https://graph.facebook.com/v2.6/me/messages',
    qs: {
      access_token: token
    },
    method: 'POST',
    json: {
      recipient: {
        id: sender
      },
      message: messageData,
    }
  }, function(error, response, body) {
    if (error) {
      console.log('Error sending messages: ', error)
    } else if (response.body.error) {
      console.log('Error: ', response.body.error)
    }
  })
}

function sendImage(sender, image_url) {
  let messageData = {
    "attachment": {
      "type": "image",
      "payload": {
        "url": image_url
      }
    }
  }

  request({
    url: 'https://graph.facebook.com/v2.6/me/messages',
    qs: {
      access_token: token
    },
    method: 'POST',
    json: {
      recipient: {
        id: sender
      },
      message: messageData
    },

  }, function optionalCallback(err, httpResponse, body) {
    if (err) {
      return console.error('upload failed:', err);
    }
    console.log('Upload successful!  Server responded with:', body);
  });

}

function sendGenericMessage(sender) {
  let messageData = {
    "attachment": {
      "type": "template",
      "payload": {
        "template_type": "generic",
        "elements": [{
          "title": "First card",
          "subtitle": "Element #1 of an hscroll",
          "image_url": "http://messengerdemo.parseapp.com/img/rift.png",
          "buttons": [{
            "type": "web_url",
            "url": "https://www.messenger.com",
            "title": "web url"
          }, {
            "type": "postback",
            "title": "Postback",
            "payload": "Payload for first element in a generic bubble",
          }],
        }, {
          "title": "Second card",
          "subtitle": "Element #2 of an hscroll",
          "image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
          "buttons": [{
            "type": "postback",
            "title": "Postback",
            "payload": "Payload for second element in a generic bubble",
          }],
        }]
      }
    }
  }
  request({
    url: 'https://graph.facebook.com/v2.6/me/messages',
    qs: {
      access_token: token
    },
    method: 'POST',
    json: {
      recipient: {
        id: sender
      },
      message: messageData,
    }
  }, function(error, response, body) {
    if (error) {
      console.log('Error sending messages: ', error)
    } else if (response.body.error) {
      console.log('Error: ', response.body.error)
    }
  })
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text.Json.Serialization;
using System.Text.Encodings.Web;

namespace System.Text.Json
{
    /// <summary>
    /// Provides options to be used with <see cref="JsonSerializer"/>.
    /// </summary>
    public sealed partial class JsonSerializerOptions
    {
        internal const int BufferSizeDefault = 16 * 1024;

        internal static readonly JsonSerializerOptions s_defaultOptions = new JsonSerializerOptions();

        private readonly ConcurrentDictionary<Type, JsonClassInfo> _classes = new ConcurrentDictionary<Type, JsonClassInfo>();
        private readonly ConcurrentDictionary<Type, JsonPropertyInfo> _objectJsonProperties = new ConcurrentDictionary<Type, JsonPropertyInfo>();
        private static readonly ConcurrentDictionary<string, ImmutableCollectionCreator> s_createRangeDelegates = new ConcurrentDictionary<string, ImmutableCollectionCreator>();
        private MemberAccessor _memberAccessorStrategy;
        private JsonNamingPolicy _dictionayKeyPolicy;
        private JsonNamingPolicy _jsonPropertyNamingPolicy;
        private JsonCommentHandling _readCommentHandling;
        private JavaScriptEncoder _encoder;
        private int _defaultBufferSize = BufferSizeDefault;
        private int _maxDepth;
        private bool _allowTrailingCommas;
        private bool _haveTypesBeenCreated;
        private bool _ignoreNullValues;
        private bool _ignoreReadOnlyProperties;
        private bool _propertyNameCaseInsensitive;
        private bool _writeIndented;

        /// <summary>
        /// Constructs a new <see cref="JsonSerializerOptions"/> instance.
        /// </summary>
        public JsonSerializerOptions()
        {
            Converters = new ConverterList(this);
        }

        /// <summary>
        /// Defines whether an extra comma at the end of a list of JSON values in an object or array
        /// is allowed (and ignored) within the JSON payload being deserialized.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// Thrown if this property is set after serialization or deserialization has occurred.
        /// </exception>
        /// <remarks>
        /// By default, it's set to false, and <exception cref="JsonException"/> is thrown if a trailing comma is encountered.
        /// </remarks>
        public bool AllowTrailingCommas
        {
            get
            {
                return _allowTrailingCommas;
            }
            set
            {
                VerifyMutable();
                _allowTrailingCommas = value;
            }
        }

        /// <summary>
        /// The default buffer size in bytes used when creating temporary buffers.
        /// </summary>
        /// <remarks>The default size is 16K.</remarks>
        /// <exception cref="System.ArgumentException">Thrown when the buffer size is less than 1.</exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown if this property is set after serialization or deserialization has occurred.
        /// </exception>
        public int DefaultBufferSize
        {
            get
            {
                return _defaultBufferSize;
            }
            set
            {
                VerifyMutable();

                if (value < 1)
                {
                    throw new ArgumentException(SR.SerializationInvalidBufferSize);
                }

                _defaultBufferSize = value;
            }
        }

        /// <summary>
        /// The encoder to use when escaping strings, or <see langword="null" /> to use the default encoder.
        /// </summary>
        public JavaScriptEncoder Encoder
        {
            get
            {
                return _encoder;
            }
            set
            {
                VerifyMutable();

                _encoder = value;
            }
        }

        /// <summary>
        /// Specifies the policy used to convert a <see cref="System.Collections.IDictionary"/> key's name to another format, such as camel-casing.
        /// </summary>
        /// <remarks>
        /// This property can be set to <see cref="JsonNamingPolicy.CamelCase"/> to specify a camel-casing policy.
        /// It is not used when deserializing.
        /// </remarks>
        public JsonNamingPolicy DictionaryKeyPolicy
        {
            get
            {
                return _dictionayKeyPolicy;
            }
            set
            {
                VerifyMutable();
                _dictionayKeyPolicy = value;
            }
        }

        /// <summary>
        /// Determines whether null values are ignored during serialization and deserialization.
        /// The default value is false.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// Thrown if this property is set after serialization or deserialization has occurred.
        /// </exception>
        public bool IgnoreNullValues
        {
            get
            {
                return _ignoreNullValues;
            }
            set
            {
                VerifyMutable();
                _ignoreNullValues = value;
            }
        }

        /// <summary>
        /// Determines whether read-only properties are ignored during serialization.
        /// A property is read-only if it contains a public getter but not a public setter.
        /// The default value is false.
        /// </summary>
        /// <remarks>
        /// Read-only properties are not deserialized regardless of this setting.
        /// </remarks>
        /// <exception cref="InvalidOperationException">
        /// Thrown if this property is set after serialization or deserialization has occurred.
        /// </exception>
        public bool IgnoreReadOnlyProperties
        {
            get
            {
                return _ignoreReadOnlyProperties;
            }
            set
            {
                VerifyMutable();
                _ignoreReadOnlyProperties = value;
            }
        }

        /// <summary>
        /// Gets or sets the maximum depth allowed when serializing or deserializing JSON, with the default (i.e. 0) indicating a max depth of 64.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// Thrown if this property is set after serialization or deserialization has occurred.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Thrown when the max depth is set to a negative value.
        /// </exception>
        /// <remarks>
        /// Going past this depth will throw a <exception cref="JsonException"/>.
        /// </remarks>
        public int MaxDepth
        {
            get => _maxDepth;
            set
            {
                VerifyMutable();

                if (value < 0)
                {
                    throw ThrowHelper.GetArgumentOutOfRangeException_MaxDepthMustBePositive(nameof(value));
                }

                _maxDepth = value;
                EffectiveMaxDepth = (value == 0 ? JsonReaderOptions.DefaultMaxDepth : value);
            }
        }

        // The default is 64 because that is what the reader uses, so re-use the same JsonReaderOptions.DefaultMaxDepth constant.
        internal int EffectiveMaxDepth { get; private set; } = JsonReaderOptions.DefaultMaxDepth;

        /// <summary>
        /// Specifies the policy used to convert a property's name on an object to another format, such as camel-casing.
        /// The resulting property name is expected to match the JSON payload during deserialization, and
        /// will be used when writing the property name during serialization.
        /// </summary>
        /// <remarks>
        /// The policy is not used for properties that have a <see cref="JsonPropertyNameAttribute"/> applied.
        /// This property can be set to <see cref="JsonNamingPolicy.CamelCase"/> to specify a camel-casing policy.
        /// </remarks>
        public JsonNamingPolicy PropertyNamingPolicy
        {
            get
            {
                return _jsonPropertyNamingPolicy;
            }
            set
            {
                VerifyMutable();
                _jsonPropertyNamingPolicy = value;
            }
        }

        /// <summary>
        /// Determines whether a property's name uses a case-insensitive comparison during deserialization.
        /// The default value is false.
        /// </summary>
        /// <remarks>There is a performance cost associated when the value is true.</remarks>
        public bool PropertyNameCaseInsensitive
        {
            get
            {
                return _propertyNameCaseInsensitive;
            }
            set
            {
                VerifyMutable();
                _propertyNameCaseInsensitive = value;
            }
        }

        /// <summary>
        /// Defines how the comments are handled during deserialization.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// Thrown if this property is set after serialization or deserialization has occurred.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Thrown when the comment handling enum is set to a value that is not supported (or not within the <see cref="JsonCommentHandling"/> enum range).
        /// </exception>
        /// <remarks>
        /// By default <exception cref="JsonException"/> is thrown if a comment is encountered.
        /// </remarks>
        public JsonCommentHandling ReadCommentHandling
        {
            get
            {
                return _readCommentHandling;
            }
            set
            {
                VerifyMutable();

                Debug.Assert(value >= 0);
                if (value > JsonCommentHandling.Skip)
                    throw new ArgumentOutOfRangeException(nameof(value), SR.JsonSerializerDoesNotSupportComments);

                _readCommentHandling = value;
            }
        }

        /// <summary>
        /// Defines whether JSON should pretty print which includes:
        /// indenting nested JSON tokens, adding new lines, and adding white space between property names and values.
        /// By default, the JSON is serialized without any extra white space.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// Thrown if this property is set after serialization or deserialization has occurred.
        /// </exception>
        public bool WriteIndented
        {
            get
            {
                return _writeIndented;
            }
            set
            {
                VerifyMutable();
                _writeIndented = value;
            }
        }

        internal MemberAccessor MemberAccessorStrategy
        {
            get
            {
                if (_memberAccessorStrategy == null)
                {
#if BUILDING_INBOX_LIBRARY
                    _memberAccessorStrategy = new ReflectionEmitMemberAccessor();
#else
                    // todo: should we attempt to detect here, or at least have a #define like #SUPPORTS_IL_EMIT
                    _memberAccessorStrategy = new ReflectionMemberAccessor();
#endif
                }

                return _memberAccessorStrategy;
            }
        }

        internal JsonClassInfo GetOrAddClass(Type classType)
        {
            _haveTypesBeenCreated = true;

            // todo: for performance and reduced instances, consider using the converters and JsonClassInfo from s_defaultOptions by cloning (or reference directly if no changes).
            if (!_classes.TryGetValue(classType, out JsonClassInfo result))
            {
                result = _classes.GetOrAdd(classType, new JsonClassInfo(classType, this));
            }

            return result;
        }

        internal JsonReaderOptions GetReaderOptions()
        {
            return new JsonReaderOptions
            {
                AllowTrailingCommas = AllowTrailingCommas,
                CommentHandling = ReadCommentHandling,
                MaxDepth = MaxDepth
            };
        }

        internal JsonWriterOptions GetWriterOptions()
        {
            return new JsonWriterOptions
            {
                Encoder = Encoder,
                Indented = WriteIndented,
#if !DEBUG
                SkipValidation = true
#endif
            };
        }

        internal JsonPropertyInfo GetJsonPropertyInfoFromClassInfo(Type objectType, JsonSerializerOptions options)
        {
            if (!_objectJsonProperties.TryGetValue(objectType, out JsonPropertyInfo propertyInfo))
            {
                propertyInfo = JsonClassInfo.CreateProperty(
                    objectType,
                    objectType,
                    objectType,
                    propertyInfo: null,
                    typeof(object),
                    converter: null,
                    options);
                _objectJsonProperties[objectType] = propertyInfo;
            }

            return propertyInfo;
        }

        internal bool CreateRangeDelegatesContainsKey(string key)
        {
            return s_createRangeDelegates.ContainsKey(key);
        }

        internal bool TryGetCreateRangeDelegate(string delegateKey, out ImmutableCollectionCreator createRangeDelegate)
        {
            return s_createRangeDelegates.TryGetValue(delegateKey, out createRangeDelegate) && createRangeDelegate != null;
        }

        internal bool TryAddCreateRangeDelegate(string key, ImmutableCollectionCreator createRangeDelegate)
        {
            return s_createRangeDelegates.TryAdd(key, createRangeDelegate);
        }

        internal void VerifyMutable()
        {
            // The default options are hidden and thus should be immutable.
            Debug.Assert(this != s_defaultOptions);

            if (_haveTypesBeenCreated)
            {
                ThrowHelper.ThrowInvalidOperationException_SerializerOptionsImmutable();
            }
        }
    }
}


text:
module.exports = function() {
  Creep.prototype.is_medic = function() {
      return this.memory.role == 'medic';
  };

  Creep.role_executors['medic'] = function() {
    if (this.hits < this.hitsMax) {
      this.heal(this);
      return;
    }

    if (this.sleep() || this.follow_path()) {
      return;
    }

    let target = Game.creeps[this.memory.target_creep_name];
    if (!target) {
      let target = _.first(_.filter(this.room.creeps()), (c) => c.is_attacker() || c.is_range_attacker());
      if (target) {
        this.memory.target_creep_name = target.name;
      }
      return;
    }
    if (this.pos.isNearTo(target)) {
      this.heal(target);
      return;
    }

    this.follow_path_to_target(target, 1);
	};
};


text:
<?php

if ($_SERVER['SCRIPT_FILENAME'] == __FILE__)
    die('Access denied.');

if (!class_exists('ZWT_Settings')) {

    /**
     * Handles plugin settings form processing  and user profile meta fields
     * @package ZWT_Base
     * @author Zanto Translate
     */
    class ZWT_Settings extends ZWT_Module {

        protected $settings;
        protected static $defaultSettings;
        protected static $readableProperties = array('settings');
        protected static $writeableProperties = array('settings');
        const REQUIRED_CAPABILITY = 'manage_network_plugins';

        protected function __construct() {
            $this->registerHookCallbacks();
        }

        /**
         * Public setter for protected variables
         * Updates settings outside of the Settings API or other subsystems
         * @param string $variable
         * @param array $value This will be merged with ZWT_Settings->settings, so it should mimic the structure of the ZWT_Settings::$defaultSettings. It only needs the contain the values that will change, though. See ZWT_Base->upgrade() for an example.
         */
        public function __set($variable, $value) {
// Note: ZWT_Module::__set() is automatically called before this

            if ($variable != 'settings' || empty($value))
                return;

            $this->settings = self::validateSettings($value);
            update_option(ZWT_Base::PREFIX . 'zanto_settings', $this->settings);
            do_action('zwt_save_settings_setter', $value);
        }

        public static function save_setting($variable, $value) {

            if ($variable != 'settings' || empty($value))
                return;

// $newSettings = shortcode_atts(self::getSettings(), $value);
            $newSettings = zwt_merge_atts(self::getSettings(), $value);
//validation

            update_option(ZWT_Base::PREFIX . 'zanto_settings', $newSettings);
            do_action('zwt_save_settings', $value);
        }

        /**
         * Register callbacks for actions and filters
         */
        public function registerHookCallbacks() {
// NOTE: Make sure you update the did_action() parameter in the corresponding callback method when changing the hooks here
            add_filter('upload_mimes', array($this, 'add_custom_mimes'));
            add_action('init', array($this, 'init'));
            if (!empty($_POST)) {
                add_action('init', array($this, 'form_action'), 99); // needs to run after ZWT_Translation_Network init
            }
        }

        /**
         * Prepares site to use the plugin during activation
         * @param bool $networkWide
         */
        public function activate() {
            global $wpdb, $EZSQL_ERROR;

            require_once(GTP_PLUGIN_PATH . '/includes/zanto-activation.php');
            zwt_initial_activate();
        }

        /**
         * Rolls back activation procedures when de-activating the plugin
         */
        public function deactivate() {

        }

        /**
         * Initializes variables
         */
        public function init() {

            self::$defaultSettings = self::getDefaultSettings();
            $this->settings = self::getSettings();
            if (!defined('GTP_LOAD_LS_CSS')) {
                ($this->settings['lang_switcher']['zwt_ls_theme'] == 0) ? define('GTP_LOAD_LS_CSS', true) : define('GTP_LOAD_LS_CSS', false);
            }
        }

        /**
         * Executes the logic of upgrading from specific older versions of the plugin to the current version
         * @param string $dbVersion
         */
        public function upgrade($dbVersion = 0) {
            /* all general upgrade procedures are implemented in the ZWT_Translation_Network class upgrade function */
        }

        /**
         * Checks that the object is in a correct state
         * @param string $property An individual property to check, or 'all' to check all of them
         * @return bool
         */
        protected function isValid($property = 'all') {
// Note: __set() calls validateSettings(), so settings are never invalid

            return true;
        }

        /*
         * Plugin Settings
         */

        /**
         * Establishes initial values for all settings
         * @return array
         */
        public static function getDefaultSettings() {
            global $wpdb;
//let defualt language be the default admin lang
            $default_admin_locale = get_locale();

            $zanto_settings = array(
                'db-version' => GTP_ZANTO_VERSION
            );

            $blog_setup = array(
                'auto_add_subscribers' => 0,
                'browser_lang_redirect' => 0,
                'browser_lr_time' => 24,
                'site_visibility' => 1
            );

            $translation_settings = array(
                'default_admin_locale' => $default_admin_locale,
                'lang_url_format' => 0,
                'download_wp_translations' => false
            );
            $language_switcher = array(
                'alt_lang_availability' => 0,
                'alt_lang_availability_text' => __('This article is also available in', 'Zanto'),
                'show_footer_selector' => 1,
                'language_order' => null,
                'elements' => array('flag' => 1, 'native_name' => 1, 'translated_name' => 1),
                'skip_missing_trans' => 0,
                'front_page_trans' => 0,
                'post_trans_links' => 0,
                'post_tl_position' => 'below',
                'post_availability_text' => __('This post is also available in: %s', 'Zanto'),
                'zwt_ls_theme' => 0,
                'zwt_ls_custom_css' => '',
                'switcher_in_wpmenu' => 0,
                'menu_for_ls' => '',
                'post_tl_style' => 0,
                'custom_flag_url' => 0,
                'custom_flag_ext' => 'png',
                'use_custom_flags' => 0
            );

            $setup_status = array(
                'setup_wizard' => 'incomplete',
                'setup_interface' => 'two'
            );

            return array(
                'zanto_settings' => $zanto_settings,
                'blog_setup' => $blog_setup,
                'translation_settings' => $translation_settings,
                'setup_status' => $setup_status,
                'lang_switcher' => $language_switcher
            );
        }

        /**
         * Retrieves all of the settings from the database
         * @return array
         */
        public static function getSettings() {
            $settings = shortcode_atts(
                    self::$defaultSettings, get_option(ZWT_Base::PREFIX . 'zanto_settings', array())
            );

            return $settings;
        }

        /**
         * Validates submitted setting values before they get saved to the database. Invalid data will be overwritten with defaults.
         * @param array $newSettings
         * @return array
         */
        public function validateSettings($newSettings) {
            $newSettings = shortcode_atts($this->settings, $newSettings);

            if (!isset($newSettings['db-version']) || !is_string($newSettings['db-version']))
                $newSettings['db-version'] = GTP_ZANTO_VERSION;

            return $newSettings;
        }

        /**
         * This is to enable recognition of .mo files by wordpress uploading system.
         */
        function add_custom_mimes($existing_mimes=array()) {
            $existing_mimes['mo'] = 'application/octet-stream';
            return $existing_mimes;
        }

        protected function validate_form_action($post_values) {
            if (did_action('init') !== 1) {
                return;
            }
            global $wpdb, $blog_id;
            $user_id = get_current_user_id();
            $lang_codes = $wpdb->get_col("SELECT default_locale FROM  {$wpdb->base_prefix}zwt_languages");
            if (current_user_can('manage_network_plugins')) {

                $userblog_ids = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs WHERE deleted='0' AND spam='0'");
            } else {
                $user_blogs = get_blogs_of_user($user_id);
                $userblog_ids = array();

                foreach ($user_blogs as $user_site)
                    $userblog_ids[] = $user_site->userblog_id;
            }
// interface 1 validation
            if (isset($post_values['interface_1_finish'])) {
// sites that were checked in form
                $selected_sites = array();
                foreach ($post_values as $field => $value) {
                    if (preg_match("/^gtr_select_site_/", $field))
                        if ("on" == $value)
                            $selected_sites[] = preg_replace('/\D/', '', $field);
                }

// sites whose langs were chosen
                $site_langs = array();

                foreach ($post_values as $field => $value) {
                    if (preg_match("/^language_of_blog_/", $field)) {
                        $id = preg_replace('/\D/', '', $field);
                        if (in_array($id, $selected_sites)) {
                            if ($id == '' || $value == '') {
                                add_notice(__('Please make sure the form is properly filled.', 'Zanto'), 'error');
                                return false;
                            }

                            if (in_array($id, $userblog_ids) && in_array($value, $lang_codes)) {
                                $site_langs[$id] = $value;
                            } else {
                                add_notice(__('This operation is not permited.', 'Zanto'), 'error');
                                return false;
                            }
                        }
                    }
                }
                if (empty($site_langs)) {
                    add_notice(__('No blogs were selected', 'Zanto'), 'error');
                    return false;
                }
                if (count(array_unique($site_langs)) < count($site_langs)) {
                    add_notice(__('Blogs in a translation network should have unique languages.', 'Zanto'), 'error');
                    return false;
                }

                return $site_langs;
            }
            /* interface 3 validation */
            if (isset($post_values['interface_3_finish'])) {
                if (empty($post_values['trans_network_id']) || empty($post_values['language_of_blog'])) {
                    add_notice(__('Please fill in all form values.', 'Zanto'), 'error');
                    return false;
                }
                if (current_user_can('manage_network_plugins')) {
                    $user_trans_ids = $wpdb->get_col("SELECT trans_id FROM {$wpdb->base_prefix}zwt_trans_network");
                } else {
                    $user_trans_ids = get_user_meta($user_id, 'zwt_installed_transnetwork', false);
                }

                if (!in_array($post_values['trans_network_id'], $user_trans_ids)) {
                    add_notice(__('This operation is not permited.', 'Zanto'), 'error');
                    return false;
                }
                $trans_id_langs = $wpdb->get_col($wpdb->prepare("SELECT lang_code FROM {$wpdb->base_prefix}zwt_trans_network WHERE trans_id = %d", $post_values['trans_network_id']));
                if (in_array($post_values['language_of_blog'], $trans_id_langs)) {
                    add_notice(__('The language you have chosen for the blog already exists with another blog in the chosen translation network.', 'Zanto'), 'error');
                    return false;
                }

                if (in_array($blog_id, $userblog_ids) && in_array($post_values['language_of_blog'], $lang_codes)) {
                    $clean_values['trans_network_id'] = $post_values['trans_network_id'];
                    $clean_values['language_of_blog'] = $post_values['language_of_blog'];
                } else {
                    add_notice(__('This operation is not permited.', 'Zanto'), 'error');
                    return false;
                }
                if (isset($post_values['language_of_blog']) && isset($_POST['zwt_add_blog_trans'])) {// only applicable for translation network page
                    if (!is_numeric($post_values['id_of_blog'])) {
                        add_notice(__('No Blog was chosen.', 'Zanto'), 'error');
                        return false;
                    }
                    if (!in_array($post_values['id_of_blog'], $userblog_ids)) {
                        add_notice(__('This operation is not permited.', 'Zanto'), 'error');
                        return false;
                    } else {
                        $clean_values['id_of_blog'] = $post_values['id_of_blog'];
                    }
                }
                return $clean_values;
            }
        }

        public function form_action() {
            if (did_action('init') !== 1)
                return;
            global $wpdb, $blog_id, $site_id, $zwt_site_obj;
            if (isset($_POST) && current_user_can('manage_options')) {
// Interface 1 operations
                if (isset($_POST['interface_1_back']) && wp_verify_nonce($_POST['zwt_translation_interface_1'], 'zwt_translation_setting_nonce_1')) {
                    self::save_setting('settings', array('setup_status' =>
                        array(
                            'setup_wizard' => 'incomplete',
                            'setup_interface' => 'two'
                            )));
                }
                if (isset($_POST['interface_1_finish']) && wp_verify_nonce($_POST['zwt_translation_interface_1'], 'zwt_translation_setting_nonce_1')) {
                    $site_langs = $this->validate_form_action($_POST);
                    if ($site_langs) {
//$_POST is clear...
//a translation network may belong to a different owner so new translation network id is calculated from all id's
                        $trans_id_ceiling = $wpdb->get_var("SELECT MAX(trans_id) FROM {$wpdb->base_prefix}zwt_trans_network");
                        $new_trans_id = $trans_id_ceiling + 1;
                        $current_blog = $wpdb->blogid;
                        foreach ($site_langs as $current_blog_id => $current_blog_lang) {
                            switch_to_blog($current_blog_id);
                            if (current_user_can('manage_options')) {
                                $wpdb->query($wpdb->prepare("INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE `option_name` = VALUES(`option_name`), `option_value` = VALUES(`option_value`), `autoload` = VALUES(`autoload`)", "WPLANG", $current_blog_lang, "yes"));
                                $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->base_prefix}zwt_trans_network (blog_id, trans_id, lang_code) VALUES (%d, %d, %s) ", $current_blog_id, $new_trans_id, $current_blog_lang));
                                self::save_setting('settings', array('setup_status' =>
                                    array(
                                        'setup_wizard' => 'complete',
                                        'setup_interface' => 'four'
                                        )));

                                zwt_add_links($blog_id, $new_trans_id, 0);
                            }
                        }
                        switch_to_blog($current_blog);
                        add_user_meta(get_current_user_id(), 'zwt_installed_transnetwork', $new_trans_id, false);
                        zwt_network_vars($new_trans_id, 'update', 'main_lang_blog', $blog_id);
                    }

                    else
                        return;
                }

                /* Interface 2 operations */
                if (isset($_POST['interface_2_next']) && wp_verify_nonce($_POST['zwt_translation_interface_2'], 'zwt_translation_setting_nonce_2')) {
                    if (isset($_POST['zwt-setup-interface']) && $_POST['zwt-setup-interface'] == 1)
                        self::save_setting('settings', array('setup_status' =>
                            array(
                                'setup_wizard' => 'incomplete',
                                'setup_interface' => 'one'
                                )));
                    else
                        self::save_setting('settings', array('setup_status' =>
                            array(
                                'setup_wizard' => 'incomplete',
                                'setup_interface' => 'three'
                                )));
                }
                /* Interface 3 operations */
                if (isset($_POST['interface_3_back']) && wp_verify_nonce($_POST['zwt_translation_interface_3'], 'zwt_translation_setting_nonce_3')) {
                    self::save_setting('settings', array('setup_status' =>
                        array(
                            'setup_wizard' => 'incomplete',
                            'setup_interface' => 'two'
                            )));
                }
                if (isset($_POST['interface_3_finish']) && wp_verify_nonce($_POST['zwt_translation_interface_3'], 'zwt_translation_setting_nonce_3')) {
                    $clean_values = $this->validate_form_action($_POST);
                    if ($clean_values) {
                        if (current_user_can('manage_options')) {
                            $wpdb->query($wpdb->prepare("INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE `option_name` = VALUES(`option_name`), `option_value` = VALUES(`option_value`), `autoload` = VALUES(`autoload`)", "WPLANG", $clean_values['language_of_blog'], "yes"));
                            $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->base_prefix}zwt_trans_network (blog_id, trans_id, lang_code) VALUES (%d, %d, %s) ", $wpdb->blogid, $clean_values['trans_network_id'], $clean_values['language_of_blog']));
                            self::save_setting('settings', array('setup_status' =>
                                array(
                                    'setup_wizard' => 'complete',
                                    'setup_interface' => 'four'
                                    )));

                            zwt_add_links($blog_id, $clean_values['trans_network_id'], 0);

                            $transnet_blogs = $zwt_site_obj->modules['trans_network']->get_transnet_blogs(true);
                            foreach ($transnet_blogs as $trans_blog) {// clear cache to update the translation network in the other blogs to include the new blog
                                if ($trans_blog['blog_id'] == $blog_id)
                                    continue;
                                switch_to_blog($trans_blog['blog_id']);
                                $blog_trans_cache = new zwt_cache('translation_network', true);
                                $blog_trans_cache->clear();
                                restore_current_blog();
                            }
                        }
                    }
                }
                /* Interface 4 operations */
                if (isset($_POST['interface_4_save']) && wp_verify_nonce($_POST['zwt_translation_interface_4'], 'zwt_translation_setting_nonce_4')) {
                    $c_trans_net = $zwt_site_obj->modules['trans_network'];

                    if (!isset($_GET['stg_scope'])) {
                        do_action('zwt_stgs_pre_save', $_POST);

                        if (isset($_POST['primary_trans_lang_blog'])) {
                            zwt_network_vars($c_trans_net->transnet_id, 'update', 'main_lang_blog', $_POST['primary_trans_lang_blog']);
                            $c_trans_net->get_primary_lang_blog(true);
                        }

                        if (isset($_POST['zwt_seo_headlangs'])) {
                            zwt_network_vars($c_trans_net->transnet_id, 'update', 'add_seo_headlangs', 1);
                        } else {
                            zwt_network_vars($c_trans_net->transnet_id, 'update', 'add_seo_headlangs', 0);
                        }

                        if (isset($_POST['zwt_url_format'])) {
                            $parma_type = get_option('permalink_structure');
                            if (empty($parma_type) && $_POST['zwt_url_format'] == 1) {
                                add_notice(__('Your permalink structure does not support adding languages to directories option', 'Zanto'), 'error');
                            } elseif (!empty($parma_type) && $_POST['zwt_url_format'] == 2) {
                                add_notice(__('Your permalink structure does not support adding language parameter to URL', 'Zanto'), 'error');
                            } elseif (in_array($_POST['zwt_url_format'], array(0, 1, 2))) {
                                self::save_setting('settings', array('translation_settings' =>
                                    array(
                                        'lang_url_format' => $_POST['zwt_url_format']
                                        )));
                                zwt_add_links($blog_id, $c_trans_net->transnet_id, $_POST['zwt_url_format']);
                            }
                        }
                        if (isset($_POST['zwt_auto_user']) && in_array($_POST['zwt_auto_user'], array(0, 1))) {
                            self::save_setting('settings', array('blog_setup' =>
                                array(
                                    'auto_add_subscribers' => $_POST['zwt_auto_user']
                                    )));
                        }

                        if (isset($_POST['zwt_site_visibility']) && in_array($_POST['zwt_site_visibility'], array(0, 1))) {
                            $ls_exclude_list = get_metadata('site', $site_id, 'zwt_' . $c_trans_net->transnet_id . '_exclude', true);

                            self::save_setting('settings', array('blog_setup' =>
                                array(
                                    'site_visibility' => $_POST['zwt_site_visibility']
                                    )));

                            if ($_POST['zwt_site_visibility']) {
                                if (isset($ls_exclude_list[$blog_id])) {
                                    unset($ls_exclude_list[$blog_id]);
                                    update_metadata('site', $site_id, 'zwt_' . $c_trans_net->transnet_id . '_exclude', $ls_exclude_list);
                                }
                            } else {
                                if (!isset($ls_exclude_list[$blog_id])) {
                                    $ls_exclude_list[$blog_id] = 1;
                                    update_metadata('site', $site_id, 'zwt_' . $c_trans_net->transnet_id . '_exclude', $ls_exclude_list);
                                }
                            }
                        }

                        if (isset($_POST['zwt_browser_lang_redct']) and in_array($_POST['zwt_browser_lang_redct'], array(0, 1, 2))) {
                            self::save_setting('settings', array('blog_setup' =>
                                array(
                                    'browser_lang_redirect' => $_POST['zwt_browser_lang_redct']
                                    )));
                        }

                        if (isset($_POST['zwt_browser_lang_redct_time'])) {
                            self::save_setting('settings', array('blog_setup' =>
                                array(
                                    'browser_lr_time' => absint($_POST['zwt_browser_lang_redct_time'])
                                    )));
                        }
                        do_action('zwt_stgs_post_save', $_POST);
                    }

                    if (isset($_GET['stg_scope']) && $_GET['stg_scope'] == 'lang_swchr') {
                        do_action('zwt_ls_pre_save', $_POST);

                        if (isset($_POST['zwt_no_translation']) && in_array($_POST['zwt_no_translation'], array(0, 1))) {
                            self::save_setting('settings', array('lang_switcher' =>
                                array(
                                    'skip_missing_trans' => $_POST['zwt_no_translation']
                                    )));
                        }

                        if (isset($_POST['zwt_front_page_trans']) && in_array($_POST['zwt_front_page_trans'], array(0, 1))) {
                            self::save_setting('settings', array('lang_switcher' =>
                                array(
                                    'front_page_trans' => $_POST['zwt_front_page_trans']
                                    )));
                        }

                        if (isset($_POST['zwt_post_availabitlity_text'])) {
                            self::save_setting('settings', array('lang_switcher' =>
                                array(
                                    'post_availability_text' => sanitize_text_field($_POST['zwt_post_availabitlity_text'])
                                    )));
                        }

                        if (isset($_POST['zwt_post_trans_links'])) {
                            self::save_setting('settings', array('lang_switcher' =>
                                array(
                                    'alt_lang_availability' => 1
                                    )));
                        } else {
                            self::save_setting('settings', array('lang_switcher' =>
                                array(
                                    'alt_lang_availability' => 0
                                    )));
                        }

                        if (isset($_POST['zwt_post_link_pos']) && in_array($_POST['zwt_post_link_pos'], array('above', 'below'))) {
                            self::save_setting('settings', array('lang_switcher' =>
                                array(
                                    'post_tl_position' => sanitize_text_field($_POST['zwt_post_link_pos'])
                                    )));
                        }

                        if (isset($_POST['zwt_post_link_style']) && in_array($_POST['zwt_post_link_style'], array(0, 1))) {
                            self::save_setting('settings', array('lang_switcher' =>
                                array(
                                    'post_tl_style' => $_POST['zwt_post_link_style']
                                    )));
                        }

                        if (isset($_POST['zwt_footer_ls'])) {
                            self::save_setting('settings', array('lang_switcher' =>
                                array(
                                    'show_footer_selector' => 1
                                    )));
                        } else {
                            self::save_setting('settings', array('lang_switcher' =>
                                array(
                                    'show_footer_selector' => 0
                                    )));
                        }

                        if (isset($_POST['zwt_ls_elements']) && is_array($_POST['zwt_ls_elements'])) {
                            $elements = array('flag' => 0, 'native_name' => 0, 'translated_name' => 0);

                            foreach ($_POST['zwt_ls_elements'] as $switcher_element => $value) {
                                if (in_array($switcher_element, array('flag', 'native_name', 'translated_name'))) {
                                    $elements[$switcher_element] = 1;
                                } else {
                                    $elements[$switcher_element] = 0;
                                }
                            }
                            self::save_setting('settings', array('lang_switcher' =>
                                array(
                                    'elements' => $elements
                                    )));
                            if (empty($_POST['zwt_ls_elements'])) {
                                add_notice(__('Atleast one element must be included in the footer langauge switcher.', 'Zanto'), 'error');
                            }
                        }

                        if (isset($_POST['zwt_ls_theme'])) {
                            global $zwt_language_switcher;
                            self::save_setting('settings', array('lang_switcher' =>
                                array(
                                    'zwt_ls_theme' => $_POST['zwt_ls_theme']
                                    )));
                            $zwt_language_switcher->get_settings(true);
                            $zwt_language_switcher->get_ls_theme();
                        }

                        if (isset($_POST['zwt_lang_order']) && !is_null($_POST['zwt_lang_order']) && !empty($_POST['zwt_lang_order'])) {
                            $lang_order = explode(',', $_POST['zwt_lang_order']);
                            $transnet_blogs = $c_trans_net->transnet_blogs;
                            foreach ($transnet_blogs as $trans_blog)
                                $blog_ids[] = $trans_blog['blog_id'];
                            foreach ($lang_order as $blog_lo) {
                                if (in_array($blog_lo, $blog_ids))
                                    continue;
                                else
                                    $lang_order = null;
                            }
                            if (!is_null($lang_order))
                                self::save_setting('settings', array('lang_switcher' =>
                                    array(
                                        'language_order' => $lang_order
                                        )));
                            $c_trans_net->zwt_trans_cache['zwt_trans_network_cache']->clear();
                        }

                        if (isset($_POST['zwt_additional_css'])) {
                            self::save_setting('settings', array('lang_switcher' =>
                                array(
                                    'zwt_ls_custom_css' => wp_filter_nohtml_kses($_POST['zwt_additional_css'])
                                    )));
                        }
                        do_action('zwt_ls_post_save', $_POST);
                    }
                }

                /* end interface operations

                  Translation Network Page Operations */
                if (isset($_POST['zwt_add_blog_trans']) && wp_verify_nonce($_POST['zwt_updatetrans_nonce'], 'zwt_update_transnetwork_nonce')) {

                    if (isset($_POST['hidden_blog_ids']) && isset($_POST['zwt_blog_id'])) {
                        if (is_numeric($_POST['hidden_blog_ids']) && is_numeric($_POST['zwt_blog_id'])) {
                            add_notice(__('Zanto got confused with the submission, please make sure javascript is enabled.', 'Zanto'), 'error');
                            return false;
                        } else {
                            $chosen_blog_id = is_numeric($_POST['hidden_blog_ids']) ? $_POST['hidden_blog_ids'] : $_POST['zwt_blog_id'];
                        }
                    } else {
                        $chosen_blog_id = $_POST['zwt_blog_id'];
                    }

                    if (!isset($_POST['blog_trans_ids']) || !isset($_POST['language_of_blog'])) {
                        add_notice(__('Nothing was selected.', 'Zanto'), 'error');
                        return false;
                    }
                    $validate_array = array();
                    $validate_array['interface_3_finish'] = 1;
                    $validate_array['trans_network_id'] = $_POST['blog_trans_ids'];
                    $validate_array['language_of_blog'] = $_POST['language_of_blog'];
                    $validate_array['id_of_blog'] = $chosen_blog_id;
                    $clean_values = $this->validate_form_action($validate_array);
                    switch_to_blog($clean_values['id_of_blog']);
                    $wpdb->query($wpdb->prepare("INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE `option_name` = VALUES(`option_name`), `option_value` = VALUES(`option_value`), `autoload` = VALUES(`autoload`)", "WPLANG", $clean_values['language_of_blog'], "yes"));
                    $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->base_prefix}zwt_trans_network (blog_id, trans_id, lang_code) VALUES (%d, %d, %s) ", $wpdb->blogid, $clean_values['trans_network_id'], $clean_values['language_of_blog']));

                    ZWT_Settings::save_setting('settings', array('setup_status' =>
                        array(
                            'setup_wizard' => 'complete',
                            'setup_interface' => 'four'
                            )));

                    zwt_add_links($blog_id, $clean_values['trans_network_id'], 0);

                    $transnet_blogs = $zwt_site_obj->modules['trans_network']->get_transnet_blogs(true);

                    restore_current_blog();

                    foreach ($transnet_blogs as $trans_blog) {// clear cache to update the translation network in the other blogs to include the new blog
                        if ($trans_blog['blog_id'] == $clean_values['id_of_blog'])
                            continue;
                        switch_to_blog($trans_blog['blog_id']);
                        $blog_trans_cache = new zwt_cache('translation_network', true);
                        $blog_trans_cache->clear();
                        restore_current_blog();
                    }
                }

                /* end Translation Network Page Operations. */ else {
                    if (isset($_POST['add_trans_network'])) {
                        print 'nonce error: Please try loging in again for security reasons!';
                        exit;
                    }
                }
            }
        }

    }

// end ZWT_Settings
}


text:
package org.springframework.security.web.server.header;

import java.time.Duration;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.web.server.ServerWebExchange;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;

/**
 * @author Rob Winch
 * @since 5.0
 */
@ExtendWith(MockitoExtension.class)
public class CompositeServerHttpHeadersWriterTests {

	@Mock
	ServerHttpHeadersWriter writer1;

	@Mock
	ServerHttpHeadersWriter writer2;

	CompositeServerHttpHeadersWriter writer;

	ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());

	@BeforeEach
	public void setup() {
		this.writer = new CompositeServerHttpHeadersWriter(Arrays.asList(this.writer1, this.writer2));
	}

	@Test
	public void writeHttpHeadersWhenErrorNoErrorThenError() {
		given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.error(new RuntimeException()));
		Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
		StepVerifier.create(result).expectError().verify();
		verify(this.writer1).writeHttpHeaders(this.exchange);
	}

	@Test
	public void writeHttpHeadersWhenErrorErrorThenError() {
		given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.error(new RuntimeException()));
		Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
		StepVerifier.create(result).expectError().verify();
		verify(this.writer1).writeHttpHeaders(this.exchange);
	}

	@Test
	public void writeHttpHeadersWhenNoErrorThenNoError() {
		given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.empty());
		given(this.writer2.writeHttpHeaders(this.exchange)).willReturn(Mono.empty());
		Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
		StepVerifier.create(result).expectComplete().verify();
		verify(this.writer1).writeHttpHeaders(this.exchange);
		verify(this.writer2).writeHttpHeaders(this.exchange);
	}

	@Test
	public void writeHttpHeadersSequential() throws Exception {
		AtomicBoolean slowDone = new AtomicBoolean();
		CountDownLatch latch = new CountDownLatch(1);
		ServerHttpHeadersWriter slow = (exchange) -> Mono.delay(Duration.ofMillis(100))
				.doOnSuccess((__) -> slowDone.set(true)).then();
		ServerHttpHeadersWriter second = (exchange) -> Mono.fromRunnable(() -> {
			latch.countDown();
			assertThat(slowDone.get()).describedAs("ServerLogoutHandler should be executed sequentially").isTrue();
		});
		CompositeServerHttpHeadersWriter writer = new CompositeServerHttpHeadersWriter(slow, second);
		writer.writeHttpHeaders(this.exchange).block();
		assertThat(latch.await(3, TimeUnit.SECONDS)).isTrue();
	}

}


text:
class Chef
  class Decorator < SimpleDelegator
    #
    # This decorator unchains method call chains and turns them into method calls
    # with variable args.  So this:
    #
    #   node.set_unless["foo"]["bar"] = "baz"
    #
    # Can become:
    #
    #   node.set_unless("foo", "bar", "baz")
    #
    # While this is a decorator it is not a Decorator and does not inherit because
    # it deliberately does not need or want the method_missing magic.  It is not legal
    # to call anything on the intermediate values and only supports method chaining with
    # #[] until the chain comes to an end with #[]=, so does not behave like a hash or
    # array...  e.g.
    #
    #   node.default['foo'].keys is legal
    #   node.set_unless['foo'].keys is not legal now or ever
    #
    class Unchain
      attr_accessor :__path__
      attr_accessor :__method__

      def initialize(obj, method)
        @__path__        = []
        @__method__      = method
        @delegate_sd_obj = obj
      end

      def [](key)
        __path__.push(key)
        self
      end

      def []=(key, value)
        __path__.push(key)
        @delegate_sd_obj.public_send(__method__, *__path__, value)
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;

namespace Microsoft.Azure.Management.Automation
{
    /// <summary>
    /// Service operation for automation linked workspace.  (see
    /// http://aka.ms/azureautomationsdk/linkedworkspaceoperations for more
    /// information)
    /// </summary>
    internal partial class LinkedWorkspaceOperations : IServiceOperations<AutomationManagementClient>, ILinkedWorkspaceOperations
    {
        /// <summary>
        /// Initializes a new instance of the LinkedWorkspaceOperations class.
        /// </summary>
        /// <param name='client'>
        /// Reference to the service client.
        /// </param>
        internal LinkedWorkspaceOperations(AutomationManagementClient client)
        {
            this._client = client;
        }

        private AutomationManagementClient _client;

        /// <summary>
        /// Gets a reference to the
        /// Microsoft.Azure.Management.Automation.AutomationManagementClient.
        /// </summary>
        public AutomationManagementClient Client
        {
            get { return this._client; }
        }

        /// <summary>
        /// Retrieve the linked workspace for the account id.  (see
        /// http://aka.ms/azureautomationsdk/linkedworkspaceoperations for
        /// more information)
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group
        /// </param>
        /// <param name='automationAccount'>
        /// Required. The automation account name.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the get linked workspace operation.
        /// </returns>
        public async Task<LinkedWorkspaceGetResponse> GetAsync(string resourceGroupName, string automationAccount, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (automationAccount == null)
            {
                throw new ArgumentNullException("automationAccount");
            }

            // Tracing
            bool shouldTrace = TracingAdapter.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("automationAccount", automationAccount);
                TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
            }

            // Construct URL
            string url = "";
            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            if (this.Client.ResourceNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
            }
            url = url + "/automationAccounts/";
            url = url + Uri.EscapeDataString(automationAccount);
            url = url + "/linkedWorkspace";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2017-05-15-preview");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;
            try
            {
                httpRequest = new HttpRequestMessage();
                httpRequest.Method = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2014-06-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    LinkedWorkspaceGetResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new LinkedWorkspaceGetResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            WorkspaceInformation workspaceInformationInstance = new WorkspaceInformation();
                            result.WorkspaceInformation = workspaceInformationInstance;

                            JToken idValue = responseDoc["id"];
                            if (idValue != null && idValue.Type != JTokenType.Null)
                            {
                                string idInstance = ((string)idValue);
                                workspaceInformationInstance.Id = idInstance;
                            }
                        }

                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
    }
}


text:
package com.rgpt.imagefilters;

import java.awt.*;
import java.awt.image.*;

/**
 * A filter which rotates an image. These days this is easier done with Java2D, but this filter remains.
 */
public class RotateFilter extends TransformFilter {

	private float angle;
	private float cos, sin;
	private boolean resize = true;

	/**
     * Construct a RotateFilter.
     */
    public RotateFilter() {
		this(ImageMath.PI);
	}

	/**
     * Construct a RotateFilter.
     * @param angle the angle to rotate
     */
	public RotateFilter(float angle) {
		this(angle, true);
	}

	/**
     * Construct a RotateFilter.
     * @param angle the angle to rotate
     * @param resize true if the output image should be resized
     */
	public RotateFilter(float angle, boolean resize) {
		setAngle(angle);
		this.resize = resize;
	}

	/**
     * Specifies the angle of rotation.
     * @param angle the angle of rotation.
     * @angle
     * @see #getAngle
     */
	public void setAngle(float angle) {
		this.angle = angle;
		cos = (float)Math.cos(this.angle);
		sin = (float)Math.sin(this.angle);
	}

	/**
     * Returns the angle of rotation.
     * @return the angle of rotation.
     * @see #setAngle
     */
	public float getAngle() {
		return angle;
	}

    public void transform(double x, double y, double[] retcoord) {
        // Remember that the coordinate system is upside down so apply
        // the transform as if the angle were negated.
        // cos(-angle) =  cos(angle)
        // sin(-angle) = -sin(angle)
        retcoord[0] = cos * x + sin * y;
        retcoord[1] = cos * y - sin * x;
        //retcoord[0] = cos * x - sin * y;
        //retcoord[1] = cos * y + sin * x;
    }

    public void itransform(double x, double y, double[] retcoord) {
        // Remember that the coordinate system is upside down so apply
        // the transform as if the angle were negated.  Since inverting
        // the transform is also the same as negating the angle, itransform
        // is calculated the way you would expect to calculate transform.
        retcoord[0] = cos * x - sin * y;
        retcoord[1] = cos * y + sin * x;
    }

    private double coord[] = new double[2];
    protected void transformSpace1(Rectangle rect) {
      if (!resize)return;
        double minx = Double.POSITIVE_INFINITY;
        double miny = Double.POSITIVE_INFINITY;
        double maxx = Double.NEGATIVE_INFINITY;
        double maxy = Double.NEGATIVE_INFINITY;
        for (int y = 0; y <= 1; y++) {
            for (int x = 0; x <= 1; x++) {
                transform(rect.x + x * rect.width,
                          rect.y + y * rect.height,
                          coord);
                minx = Math.min(minx, coord[0]);
                miny = Math.min(miny, coord[1]);
                maxx = Math.max(maxx, coord[0]);
                maxy = Math.max(maxy, coord[1]);
            }
        }
        rect.x = (int) Math.floor(minx);
        rect.y = (int) Math.floor(miny);
        rect.width = (int) Math.ceil(maxx) - rect.x + 1;
        rect.height = (int) Math.ceil(maxy) - rect.y + 1;
    }

	protected void transformSpace(Rectangle rect) {
		if (resize) {
			Point out = new Point(0, 0);
			int minx = Integer.MAX_VALUE;
			int miny = Integer.MAX_VALUE;
			int maxx = Integer.MIN_VALUE;
			int maxy = Integer.MIN_VALUE;
			int w = rect.width;
			int h = rect.height;
			int x = rect.x;
			int y = rect.y;

			for (int i = 0; i < 4; i++)  {
				switch (i) {
				case 0: transform(x, y, out); break;
				case 1: transform(x + w, y, out); break;
				case 2: transform(x, y + h, out); break;
				case 3: transform(x + w, y + h, out); break;
				}
				minx = Math.min(minx, out.x);
				miny = Math.min(miny, out.y);
				maxx = Math.max(maxx, out.x);
				maxy = Math.max(maxy, out.y);
			}

			rect.x = minx;
			rect.y = miny;
			rect.width = maxx - rect.x;
			rect.height = maxy - rect.y;
		}
	}

	private void transform(int x, int y, Point out) {
		out.x = (int)((x * cos) + (y * sin));
		out.y = (int)((y * cos) - (x * sin));
	}

	protected void transformInverse(int x, int y, float[] out) {
		out[0] = (x * cos) - (y * sin);
		out[1] = (y * cos) + (x * sin);
	}

	public String toString() {
		return "Rotate "+(int)(angle * 180 / Math.PI);
	}

}


text:
var vumigo = require('vumigo_v02');
var AppTester = vumigo.AppTester;
var LocationApp = require('../lib/googlemaps').LocationApp;
var location = require('../../lib');
var googlemaps = location.providers.googlemaps;

describe("GoogleMaps example", function() {
    var app;
    var tester;
    var locations;

    beforeEach(function(){
        app = new LocationApp();
        tester = new AppTester(app);
        locations = [];

        locations.push({
            query: "Example Street",
            response_data: {
                results: [
                    {
                        formatted_address: "Example Street, Suburb",
                        geometry: {
                            location:{
                                latitude: '3.1415926535',
                                longitude: '2.7182818284'
                            }
                        }
                    },
                    {
                        formatted_address: "Another Street, Suburb",
                        geometry: {
                            location: {
                                latitude: '2.7182818284',
                                longitude: '3.1415926535'
                            }
                        }
                    },
                ],
                status:"OK"
            }
        });

        locations.push({
            query: "Single Street",
            response_data: {
                results: [
                    {
                        formatted_address: "Single Street, Suburb",
                        geometry: {
                            location:{
                                latitude: '1.4142135623',
                                longitude: '1.6180339887'
                            }
                        }
                    },
                ],
                status:"OK"
            }
        });

        tester
            .setup.config.app({
                name: 'test_app'
            })
            .setup(function(api) {
                locations.forEach(function(location) {
                    api.http.fixtures.add(googlemaps.fixture(location));
                });
            });
    });

    describe("When the user starts a session", function(){
        it("should ask the user for a location", function() {
            return tester
                .start()
                .check.interaction({
                    state: 'states:start',
                    reply: [
                        "Welcome to the location app.",
                        "What is your current address?"
                    ].join('\n')
                })
                .run();
        });
    });

    describe("When the user enters a location prompt with multiple results", function() {
        it("should ask the user to refine their choice", function() {
            return tester
                .input("Example Street")
                .check.interaction({
                    state: 'states:start',
                    reply: [
                        "Please select your location from the following:",
                        "1. Example Street, Suburb",
                        "2. Another Street, Suburb",
                        "n. Next",
                        "p. Prev"
                    ].join('\n')
                })
                .run();
        });
    });

    describe("When the user selects a location from the list", function() {
        it("should display the location data to the user", function() {
            return tester
                .inputs("Example Street", "1")
                .check.interaction({
                    state: 'states:end',
                    reply: [
                        'The location "Example Street, Suburb" is located',
                        'at longitude 2.7182818284 and latitude',
                        '3.1415926535'
                    ].join(' ')
                })
                .run();
        });
    });

    describe("When the user enters a location prompt with one results", function() {
        it("should display the location data to the user", function() {
            return tester
                .input("Single Street")
                .check.interaction({
                    state: 'states:end',
                    reply: [
                        'The location "Single Street, Suburb" is located',
                        'at longitude 1.6180339887 and latitude',
                        '1.4142135623'
                    ].join(' ')
                })
                .run();
        });
    });
});


text:
import intersection from "lodash.intersection";
import pull from "lodash.pull";
import isObject from "lodash.isplainobject";
import clone from "lodash.clonedeep";

/**
 * Checks if input is a true Object (checking against null and Array)
 * @param {Object} a reference object to use the properties from. Values don't
 * matter. For example, {a:true, b:true, c:false}
 * @param [Object] an optional override object. For example, you want all
 * properties 'a' to be true - pass {a:true}
 * @returns {Array} of objects with all possible combinations optionally including
 * override. In our examle, an array of 2^(3-1) objects, each containing a:true.
 * Without override we would have got 2^3 objects array
 */
function objectBooleanCombinations(
  originalIncomingObject,
  originalOverrideObject
) {
  //
  // FUNCTIONS
  // =========

  /**
   * Creates an n-length array with all possible combinations of true/false
   * @param {number} input integer
   * @returns {Array} Array of arrays each containing one possible combination of true/false
   */
  function combinations(n) {
    const r = [];
    for (let i = 0; i < 1 << n; i++) {
      const c = [];
      for (let j = 0; j < n; j++) {
        c.push(i & (1 << j) ? 1 : 0);
      }
      r.push(c);
    }
    return r;
  }
  function existy(x) {
    return x != null;
  }

  // VARIABLES
  // =========

  // CHECKS
  // ======

  if (!existy(originalIncomingObject)) {
    throw new Error("[THROW_ID_01] missing input object");
  }
  if (!isObject(originalIncomingObject)) {
    throw new Error(
      "[THROW_ID_02] the first input object must be a true object"
    );
  }
  if (existy(originalOverrideObject) && !isObject(originalOverrideObject)) {
    throw new Error(
      "[THROW_ID_03] the second override object must be a true object"
    );
  }

  const incomingObject = clone(originalIncomingObject);
  const overrideObject = clone(originalOverrideObject);

  // START
  // =====

  const propertiesToMix = Object.keys(incomingObject);
  const outcomingObjectsArray = [];
  let propertiesToBeOverridden;

  // if there's override, prepare an alternative (a subset) array propertiesToMix
  // ----------------------------------------------------------------------------

  if (existy(overrideObject) && isObject(overrideObject)) {
    // check overrideObject's contents - must be Boolean:
    Object.keys(overrideObject).forEach(val => {
      if (
        overrideObject[val] !== 0 &&
        overrideObject[val] !== 1 &&
        overrideObject[val] !== true &&
        overrideObject[val] !== false
      ) {
        throw new Error(
          "[THROW_ID_04] override object's values must contain only true/valse or 0/1"
        );
      }
    });
  }

  let override = false;
  if (existy(overrideObject) && Object.keys(overrideObject).length !== 0) {
    override = true;
  }

  if (override) {
    // find legitimate properties from the overrideObject:
    // enforce that override object had just a subset of incomingObject properties, nothing else
    propertiesToBeOverridden = intersection(
      Object.keys(overrideObject),
      Object.keys(incomingObject)
    );
    // propertiesToMix = all incoming object's properties MINUS properties to override
    propertiesToBeOverridden.forEach(elem => pull(propertiesToMix, elem));
  }

  // mix up whatever propertiesToMix has came to this point
  // ------------------------------------------------------

  const boolCombinations = combinations(Object.keys(propertiesToMix).length);
  let tempObject = {};
  boolCombinations.forEach((elem1, index1) => {
    tempObject = {};
    propertiesToMix.forEach((elem2, index2) => {
      tempObject[elem2] = boolCombinations[index1][index2] === 1 ? 1 : 0;
    });
    outcomingObjectsArray.push(tempObject);
  });

  // if there's override, append the static override values on each property of the
  // propertiesToMix array:
  // ------------------------------------------------------------------------------
  if (override) {
    outcomingObjectsArray.forEach(elem3 =>
      propertiesToBeOverridden.forEach(elem4 => {
        elem3[elem4] = overrideObject[elem4];
      })
    );
  }

  // RETURN
  // ======

  return outcomingObjectsArray;
}

export default objectBooleanCombinations;


text:
class ServiceTemplateFieldsVisibilityService
  def determine_visibility(service_template_request)
    field_names_to_hide = []
    if service_template_request
      field_names_to_hide += %i[vm_description schedule_type schedule_time]
    end

    {:hide => field_names_to_hide}
  end
end


text:
@interface MoreCell : KMTableViewCell
@property (nonatomic) BOOL hasNew;
@end