text:
<?php
class pjCaptcha
{
/**
 * Path to font file
 *
 * @access private
 * @var string
 */
	var $font = null;
/**
 * Font size in pixels
 *
 * @access private
 * @var int
 */
	var $fontSize = 12;
/**
 * Image height in pixels
 *
 * @access private
 * @var int
 */
	var $height = 35;
/**
 * Path to image background
 *
 * @access private
 * @var string
 */
	var $image = null;
/**
 * Length of word
 *
 * @access private
 * @var int
 */
	var $length = null;
/**
 * Session variable name
 *
 * @access private
 * @var string
 */
	var $sessionVariable = null;

	var $productPrefix = null;
/**
 * Image width in pixels
 *
 * @access private
 * @var int
 */
	var $width = 79;
/**
 * Constructor
 *
 * @param string $fontPath Path to font file
 * @param string $sessionVariable Session variable name
 * @param int $length Length of word
 * @access public
 * @return void
 */
	function pjCaptcha($fontPath, $productPrefix, $sessionVariable, $length = 4)
	{
		$this->font = $fontPath;
		$this->productPrefix = $productPrefix;
		$this->sessionVariable = $sessionVariable;
		$this->length = intval($length);
	}
/**
 * Output image to browser
 *
 * @param mixed $renew
 * @access public
 * @return binary
 */
	function init($renew=null)
	{
    	if (!is_null($renew))
    	{
    		$_SESSION[$this->productPrefix][$this->sessionVariable] = NULL;
    	}

		if (!isset($_SESSION[$this->productPrefix][$this->sessionVariable]) || empty($_SESSION[$this->productPrefix][$this->sessionVariable]))
		{
			$str = "";
			$length = 0;
			for ($i = 0; $i < $this->length; $i++)
			{
				//this numbers refer to numbers of the ascii table (small-caps)
				// 97 - 122 (small-caps)
				// 65 - 90 (all-caps)
				// 48 - 57 (digits 0-9)
				$str .= chr(rand(65, 90));
			}
			$_SESSION[$this->productPrefix][$this->sessionVariable] = $str;
			$rand_code = $_SESSION[$this->productPrefix][$this->sessionVariable];
		} else {
			$rand_code = $_SESSION[$this->productPrefix][$this->sessionVariable];
		}

		if (!is_null($this->image))
		{
			$image = imagecreatefrompng($this->image);
		} else {
			$image = imagecreatetruecolor($this->width, $this->height);

			$backgr_col = imagecolorallocate($image, 204, 204, 204);
			$border_col = imagecolorallocate($image, 153, 153, 153);

			imagefilledrectangle($image, 0, 0, $this->width, $this->height, $backgr_col);
			imagerectangle($image, 0, 0, $this->width - 1, $this->height - 1, $border_col);
		}

		$text_col = imagecolorallocate($image, 68, 68, 68);

		$angle = rand(-10, 10);
		$box = imagettfbbox($this->fontSize, $angle, $this->font, $rand_code);
		$x = (int)($this->width - $box[4]) / 2;
		$y = (int)($this->height - $box[5]) / 2;
		imagettftext($image, $this->fontSize, $angle, $x, $y, $text_col, $this->font, $rand_code);

		header("Content-type: image/png");
		imagepng($image);
		imagedestroy ($image);
	}
/**
 * Set path to font file
 *
 * @param string $fontPath Path to font file
 * @access public
 * @return void
 */
	function setFont($fontPath)
	{
		$this->font = $fontPath;
	}
/**
 * Set length of word
 *
 * @param int $length Length of word
 * @access public
 * @return void
 */
	function setLength($length)
	{
		if ((int) $length > 0)
		{
			$this->length = intval($length);
		}
	}
/**
 * Set session variable name
 *
 * @param string $sessionVariable Session variable name
 * @access public
 * @return void
 */
	function setSessionVariable($sessionVariable)
	{
		$this->sessionVariable = $sessionVariable;
	}
/**
 * Set image height
 *
 * @param int $height Image height in pixels
 * @access public
 * @return void
 */
	function setHeight($height)
	{
		if ((int) $height > 0)
		{
			$this->height = intval($height);
		}
	}
/**
 * Set image width
 *
 * @param int $width Image width in pixels
 * @access public
 * @return void
 */
	function setWidth($width)
	{
		if ((int) $width > 0)
		{
			$this->width = intval($width);
		}
	}
/**
 * Set font size
 *
 * @param int $fontSize Font size in pixels
 * @access public
 * @return void
 */
	function setFontSize($fontSize)
	{
		if ((int) $fontSize > 0)
		{
			$this->fontSize = intval($fontSize);
		}
	}
/**
 * Set image background
 *
 * @param string $image Path to image file
 * @access public
 * @return void
 */
	function setImage($image)
	{
		$this->image = $image;
	}
}
?>


text:
#include "tensorflow/contrib/session_bundle/session_bundle.h"

#include <string>
#include <utility>
#include <vector>

#include "google/protobuf/any.pb.h"
#include "tensorflow/contrib/session_bundle/signature.h"
#include "tensorflow/contrib/session_bundle/test_util.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/public/session_options.h"

namespace tensorflow {
namespace serving {
namespace {

// Constants for the export file names.
const char kVariablesFilename[] = "export-00000-of-00001";
const char kMetaGraphDefFilename[] = "export.meta";

// Function used to rewrite a MetaGraphDef.
using MetaGraphDefTwiddler = std::function<void(MetaGraphDef*)>;

// Copy the base half_plus_two to `export_path`.
// Outputs the files using the passed names (typically the constants above).
// The Twiddler can be used to update the MetaGraphDef before output.
Status CopyExport(const string& export_path, const string& variables_filename,
                  const string& meta_graph_def_filename,
                  const MetaGraphDefTwiddler& twiddler) {
  TF_RETURN_IF_ERROR(Env::Default()->CreateDir(export_path));
  const string orig_path = test_util::TestSrcDirPath(
      "session_bundle/example/half_plus_two/00000123");
  {
    const string source =
        tensorflow::io::JoinPath(orig_path, kVariablesFilename);
    const string sink =
        tensorflow::io::JoinPath(export_path, variables_filename);

    string data;
    TF_RETURN_IF_ERROR(ReadFileToString(Env::Default(), source, &data));
    TF_RETURN_IF_ERROR(WriteStringToFile(Env::Default(), sink, data));
  }
  {
    const string source =
        tensorflow::io::JoinPath(orig_path, kMetaGraphDefFilename);
    const string sink =
        tensorflow::io::JoinPath(export_path, meta_graph_def_filename);

    tensorflow::MetaGraphDef graph_def;
    TF_RETURN_IF_ERROR(ReadBinaryProto(Env::Default(), source, &graph_def));
    twiddler(&graph_def);
    TF_RETURN_IF_ERROR(
        WriteStringToFile(Env::Default(), sink, graph_def.SerializeAsString()));
  }
  return Status::OK();
}

void BasicTest(const string& export_path) {
  tensorflow::SessionOptions options;
  SessionBundle bundle;
  TF_ASSERT_OK(LoadSessionBundleFromPath(options, export_path, &bundle));

  const string asset_path =
      tensorflow::io::JoinPath(export_path, kAssetsDirectory);
  // Validate the assets behavior.
  std::vector<Tensor> path_outputs;
  TF_ASSERT_OK(bundle.session->Run({}, {"filename1:0", "filename2:0"}, {},
                                   &path_outputs));
  ASSERT_EQ(2, path_outputs.size());
  // Validate the two asset file tensors are set by the init_op and include the
  // base_path and asset directory.
  test::ExpectTensorEqual<string>(
      test::AsTensor<string>(
          {tensorflow::io::JoinPath(asset_path, "hello1.txt")},
          TensorShape({})),
      path_outputs[0]);
  test::ExpectTensorEqual<string>(
      test::AsTensor<string>(
          {tensorflow::io::JoinPath(asset_path, "hello2.txt")},
          TensorShape({})),
      path_outputs[1]);

  // Validate the half plus two behavior.
  Tensor input = test::AsTensor<float>({0, 1, 2, 3}, TensorShape({4, 1}));

  // Recover the Tensor names of our inputs and outputs.
  Signatures signatures;
  TF_ASSERT_OK(GetSignatures(bundle.meta_graph_def, &signatures));
  ASSERT_TRUE(signatures.default_signature().has_regression_signature());
  const tensorflow::serving::RegressionSignature regression_signature =
      signatures.default_signature().regression_signature();

  const string input_name = regression_signature.input().tensor_name();
  const string output_name = regression_signature.output().tensor_name();

  std::vector<Tensor> outputs;
  TF_ASSERT_OK(
      bundle.session->Run({{input_name, input}}, {output_name}, {}, &outputs));
  ASSERT_EQ(outputs.size(), 1);
  test::ExpectTensorEqual<float>(
      outputs[0], test::AsTensor<float>({2, 2.5, 3, 3.5}, TensorShape({4, 1})));
}

TEST(LoadSessionBundleFromPath, BasicTensorFlowContrib) {
  const string export_path = test_util::TestSrcDirPath(
      "session_bundle/example/half_plus_two/00000123");
  BasicTest(export_path);
}

TEST(LoadSessionBundleFromPath, BadExportPath) {
  const string export_path = test_util::TestSrcDirPath("/tmp/bigfoot");
  tensorflow::SessionOptions options;
  options.target = "local";
  SessionBundle bundle;
  const auto status = LoadSessionBundleFromPath(options, export_path, &bundle);
  ASSERT_FALSE(status.ok());
  const string msg = status.ToString();
  EXPECT_TRUE(msg.find("Not found") != std::string::npos) << msg;
}

class SessionBundleTest : public ::testing::Test {
 protected:
  // Copy the half_plus_two graph and apply the twiddler to rewrite the
  // MetaGraphDef.
  // Returns the path of the export.
  // ** Should only be called once per test **
  string SetupExport(MetaGraphDefTwiddler twiddler) {
    return SetupExport(twiddler, kVariablesFilename, kMetaGraphDefFilename);
  }
  // SetupExport that allows for the variables and meta_graph_def filenames
  // to be overridden.
  string SetupExport(MetaGraphDefTwiddler twiddler,
                     const string& variables_filename,
                     const string& meta_graph_def_filename) {
    // Construct a unique path name based on the test name.
    const ::testing::TestInfo* const test_info =
        ::testing::UnitTest::GetInstance()->current_test_info();
    const string export_path = tensorflow::io::JoinPath(
        testing::TmpDir(),
        strings::StrCat(test_info->test_case_name(), test_info->name()));
    TF_CHECK_OK(CopyExport(export_path, variables_filename,
                           meta_graph_def_filename, twiddler));
    return export_path;
  }

  tensorflow::SessionOptions options_;
  SessionBundle bundle_;
  Status status_;
};

TEST_F(SessionBundleTest, Basic) {
  const string export_path = SetupExport([](MetaGraphDef*) {});
  BasicTest(export_path);
}

TEST_F(SessionBundleTest, UnshardedVariableFile) {
  // Test that we can properly read the variables when exported
  // without sharding.
  const string export_path =
      SetupExport([](MetaGraphDef*) {}, "export", kMetaGraphDefFilename);
  BasicTest(export_path);
}

TEST_F(SessionBundleTest, ServingGraph_Empty) {
  const string path = SetupExport([](MetaGraphDef* def) {
    (*def->mutable_collection_def())[kGraphKey].clear_any_list();
  });
  status_ = LoadSessionBundleFromPath(options_, path, &bundle_);
  EXPECT_FALSE(status_.ok());
  EXPECT_TRUE(StringPiece(status_.error_message())
                  .contains("Expected exactly one serving GraphDef"))
      << status_.error_message();
}

TEST_F(SessionBundleTest, ServingGraphAny_IncorrectType) {
  const string path = SetupExport([](MetaGraphDef* def) {
    // Pack an unexpected type in the GraphDef Any.
    (*def->mutable_collection_def())[kGraphKey].clear_any_list();
    auto* any = (*def->mutable_collection_def())[kGraphKey]
                    .mutable_any_list()
                    ->add_value();
    any->PackFrom(AssetFile());
  });
  status_ = LoadSessionBundleFromPath(options_, path, &bundle_);
  EXPECT_FALSE(status_.ok());
  EXPECT_TRUE(StringPiece(status_.error_message())
                  .contains("Expected Any type_url for: tensorflow.GraphDef"))
      << status_.error_message();
}

TEST_F(SessionBundleTest, ServingGraphAnyValue_Corrupted) {
  const string path = SetupExport([](MetaGraphDef* def) {
    // Pack an unexpected type in the GraphDef Any.
    (*def->mutable_collection_def())[kGraphKey].clear_any_list();
    auto* any = (*def->mutable_collection_def())[kGraphKey]
                    .mutable_any_list()
                    ->add_value();
    any->PackFrom(GraphDef());
    any->set_value("junk junk");
  });
  status_ = LoadSessionBundleFromPath(options_, path, &bundle_);
  EXPECT_FALSE(status_.ok());
  EXPECT_TRUE(StringPiece(status_.error_message()).contains("Failed to unpack"))
      << status_.error_message();
}

TEST_F(SessionBundleTest, AssetFileAny_IncorrectType) {
  const string path = SetupExport([](MetaGraphDef* def) {
    // Pack an unexpected type in the AssetFile Any.
    (*def->mutable_collection_def())[kAssetsKey].clear_any_list();
    auto* any = (*def->mutable_collection_def())[kAssetsKey]
                    .mutable_any_list()
                    ->add_value();
    any->PackFrom(GraphDef());
  });
  status_ = LoadSessionBundleFromPath(options_, path, &bundle_);
  EXPECT_FALSE(status_.ok());
  EXPECT_TRUE(
      StringPiece(status_.error_message())
          .contains(
              "Expected asset Any type_url for: tensorflow.serving.AssetFile"))
      << status_.error_message();
}

TEST_F(SessionBundleTest, AssetFileAny_ValueCorrupted) {
  const string path = SetupExport([](MetaGraphDef* def) {
    // Pack an unexpected type in the AssetFile Any.
    (*def->mutable_collection_def())[kAssetsKey].clear_any_list();
    auto* any = (*def->mutable_collection_def())[kAssetsKey]
                    .mutable_any_list()
                    ->add_value();
    any->PackFrom(AssetFile());
    any->set_value("junk junk");
  });
  status_ = LoadSessionBundleFromPath(options_, path, &bundle_);
  EXPECT_FALSE(status_.ok());
  EXPECT_TRUE(StringPiece(status_.error_message()).contains("Failed to unpack"))
      << status_.error_message();
}

TEST_F(SessionBundleTest, InitOp_TooManyValues) {
  const string path = SetupExport([](MetaGraphDef* def) {
    // Pack multiple init ops in to the collection.
    (*def->mutable_collection_def())[kInitOpKey].clear_node_list();
    auto* node_list =
        (*def->mutable_collection_def())[kInitOpKey].mutable_node_list();
    node_list->add_value("foo");
    node_list->add_value("bar");
  });
  status_ = LoadSessionBundleFromPath(options_, path, &bundle_);
  EXPECT_FALSE(status_.ok());
  EXPECT_TRUE(StringPiece(status_.error_message())
                  .contains("Expected exactly one serving init op"))
      << status_.error_message();
}

TEST_F(SessionBundleTest, PossibleExportDirectory) {
  const string export_path = SetupExport([](MetaGraphDef*) {});
  EXPECT_TRUE(IsPossibleExportDirectory(export_path));

  EXPECT_FALSE(
      IsPossibleExportDirectory(io::JoinPath(export_path, kAssetsDirectory)));
}

}  // namespace
}  // namespace serving
}  // namespace tensorflow

redpajama_set_name: RedPajamaGithub


text:
package com.icfcc.db.dal.internal;

import com.icfcc.db.dal.internal.util.message.Messages;

import java.util.ArrayList;
import java.util.List;

/**
 * This class creates the different objects needed by the generator
 */
public class ObjectFactory {
    private static List<ClassLoader> classLoaders;

    static {
        classLoaders = new ArrayList<>();
    }

    /**
     * Utility class. No instances allowed
     */
    private ObjectFactory() {
        super();
    }

    /**
     * Adds a custom classloader to the collection of classloaders
     * searched for resources.  Currently, this is only used
     * when searching for properties files that may be
     * referenced in the configuration file.
     *
     * @param classLoader class loader
     */
    public static synchronized void addClassLoader(
            ClassLoader classLoader) {
        ObjectFactory.classLoaders.add(classLoader);
    }

    /**
     * This method returns a class loaded from the context classloader, or the
     * classloader supplied by a client. This is appropriate for JDBC drivers,
     * model root classes, etc. It is not appropriate for any class that extends
     * one of the supplied classes or interfaces.
     *
     * @param type type
     * @return the Class loaded from the external classloader
     * @throws ClassNotFoundException class not found
     */
    public static Class<?> classForName(String type)
            throws ClassNotFoundException {

        Class<?> clazz;

        for (ClassLoader classLoader : classLoaders) {
            try {
                clazz = Class.forName(type, true, classLoader);
                return clazz;
            } catch (Throwable e) {
                // ignore - fail safe below
            }
        }

        return internalClassForName(type);
    }

    public static Object createObject(String type) {
        Object answer;

        try {
            Class<?> clazz = classForName(type);
            answer = clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(Messages.getString("RuntimeError.0", type), e);
        }

        return answer;
    }

    public static Class<?> internalClassForName(String type)
            throws ClassNotFoundException {
        Class<?> clazz = null;

        try {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            clazz = Class.forName(type, true, cl);
        } catch (Exception e) {
            // ignore - failsafe below
        }

        if (clazz == null) {
            clazz = Class.forName(type, true, ObjectFactory.class.getClassLoader());
        }

        return clazz;
    }

}


text:
/* Custom Stylesheet */
/**
 * Use this file to override Materialize files so you can update
 * the core Materialize files in the future
 *
 * Made By MaterializeCSS.com
 */

nav ul a,
nav .brand-logo {
  color: #444;
}
.dropdown-content li > span{
  color:black;
}
.minheight{
  height: 200px;
 }
 .padding{
  padding-top:5px !important;
  margin-left:-2px;
}
 .greycolor{
  background-color: lightgray;
 }
.brand-logo{
  background-image: 'deloitte.jpg'
}
 .color{
  background-color:#0e5fd8 !important;
 }
p {
  line-height: 2rem;
}

.button-collapse {
  color: #26a69a;
}

.parallax-container {
  min-height: 620px;
  line-height: 0;
  height: auto;
  color: rgba(255,255,255,.9);
}
  .parallax-container .section {
    width: 100%;
  }

@media only screen and (max-width : 992px) {
  .parallax-container .section {
    position: absolute;
    top: 40%;
  }
  #index-banner .section {
    top: 10%;
  }
}

@media only screen and (max-width : 600px) {
  #index-banner .section {
    top: 0;
  }
}

.icon-block {
  padding: 0 15px;
}

footer.page-footer {
  margin: 0;
}
.modal-backdrop {
  display:none;
}
.modal-open .modal {
  width: 300px;
  margin: 0 auto;
}
.rmargin{
 padding-right:0px !important;
 padding-left: 5px !important;

}

.modal {
  position: fixed;
  top: 56px;
  right: 0px;
  bottom:50px;
  display: inline-block;
  width:500px !important;
  left:auto;
  z-index: 10040;
  overflow: auto;
  overflow-y: auto;
}
.select-wrapper input.select-dropdown{
  height:2.1rem;
  background-color: none;
  /* border :3px solid #4db6ac; */
  /* background-color: #4db6ac !important; */
   border-bottom: none !important;
}
.modal-open {
  overflow: hidden !important;
}
.select-wrapper input.select-dropdown{
  background-color: rgba(0, 0, 0, 0.06);
  padding-left:6px;
  padding-right:2px;
}
.margin-top{
  margin-top:10px;
}
body {

  overflow-x: hidden;
  overflow-y: scroll !important;
}

.precontainer{

  border: solid 1px rgba(51,51,51,0.12);
   background-color: rgba(0, 0, 0, 0.06);
  padding-top:5px;
  clear:both;

}
.precontainer p{
  line-height: 1.2rem !important;
  margin:3px !important;
}
.precontainer .row{
  margin-bottom:0px;
}
.s12 .section{
  padding-bottom: 0px;
  padding-top: 0px;
}
.modal.modal-fixed-footer .modal-content{
  height: calc(100%);
}
.leftspace{
  padding-left:4px !important;
}
.left #palceholder{
  left:1rem !important;
}
.slide-right{
  right:-510px;
}
.slide-left{
  right:0px;
}
.input-field ul{
  max-height:400px;
  z-index:1005;
  overflow-y:auto;
 -webkit-transition: property duration timing-function delay;
  -moz-transition: property duration timing-function delay;
  transition: property duration timing-function delay;
}
.logo-img {
  max-height: 68px!important;
  padding: 7px 0!important;
}
h5 a{
  color:white;
}

h5 a:hover{
  color:white;
}
/* .btncolour{
  background-color:#03a9f4;

}
.btncolour:hover{
  background-color:#03a9f4;
} */


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements. See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership. The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License. You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied. See the License for the
  specific language governing permissions and limitations
  under the License.

-->
<x_dimension name="daydim" xmlns="uri:lens:cube:0.1">
  <attributes>
    <dim_attribute _type="boolean" name="is_weekend" description="is weekend?">
    </dim_attribute>
    <dim_attribute _type="int" name="day_number_of_year" description="day number in year">
    </dim_attribute>
    <dim_attribute _type="int" name="id" description="code">
    </dim_attribute>
    <dim_attribute _type="string" name="full_date" description="full date">
    </dim_attribute>
    <dim_attribute _type="int" name="calendar_quarter" description="quarter id">
    </dim_attribute>
  </attributes>
  <expressions/>
  <join_chains/>
  <properties>
    <property name="cube.col.is_weekend.description" value="is weekend?"/>
    <property name="cube.dimension.calendar_quarter.class" value="org.apache.lens.cube.metadata.BaseDimAttribute"/>
    <property name="cube.dimension.id.type" value="int"/>
    <property name="cube.table.daydim.weight" value="0.0"/>
    <property name="cube.col.calendar_quarter.description" value="quarter id"/>
    <property name="base.daydim.expressions.list.size" value="0"/>
    <property name="dimension.daydim.attributes.list.size" value="1"/>
    <property name="cube.dimension.day_number_of_year.class" value="org.apache.lens.cube.metadata.BaseDimAttribute"/>
    <property name="cube.dimension.day_number_of_year.type" value="int"/>
    <property name="cube.dimension.is_weekend.class" value="org.apache.lens.cube.metadata.BaseDimAttribute"/>
    <property name="cube.col.full_date.description" value="full date"/>
    <property name="cube.col.id.description" value="code"/>
    <property name="dimension.daydim.timed.dimension" value="dt"/>
    <property name="cube.dimension.is_weekend.type" value="boolean"/>
    <property name="cube.dimension.id.class" value="org.apache.lens.cube.metadata.BaseDimAttribute"/>
    <property name="cube.dimension.full_date.class" value="org.apache.lens.cube.metadata.BaseDimAttribute"/>
    <property name="cube.dimension.full_date.type" value="string"/>
    <property name="cube.col.day_number_of_year.description" value="day number in year"/>
    <property name="cube.dimension.calendar_quarter.type" value="int"/>
    <property name="dimension.daydim.attributes.list0"
              value="is_weekend,day_number_of_year,id,full_date,calendar_quarter"/>
    <property name="dimension.daydim.joinchains.list.size" value="0"/>
  </properties>
</x_dimension>


text:
"use strict";

const fs = require("fs");
const path = require("path");
const root = process.cwd();
const node_modulesFolder = path.resolve(root, "node_modules");
const webpackDependencyFolder = path.resolve(root, "node_modules/webpack");

function setup() {
	return Promise.all([
		checkSymlinkExistsAsync().then(async hasSymlink => {
			if (!hasSymlink) {
				await ensureYarnInstalledAsync();
				await runSetupSymlinkAsync();
				if (!(await checkSymlinkExistsAsync())) {
					throw new Error("windows symlink was not successfully created");
				}
			}
		})
	])
		.then(() => {
			process.exitCode = 0;
		})
		.catch(e => {
			console.error(e);
			process.exitCode = 1;
		});
}

async function runSetupSymlinkAsync() {
	await exec("yarn", ["install"], "Install dependencies");
	await exec("yarn", ["link"], "Create webpack symlink");
	await exec("yarn", ["link", "webpack"], "Link webpack into itself");
}

function checkSymlinkExistsAsync() {
	return new Promise((resolve, reject) => {
		if (
			fs.existsSync(node_modulesFolder) &&
			fs.existsSync(webpackDependencyFolder) &&
			fs.lstatSync(webpackDependencyFolder).isSymbolicLink()
		) {
			resolve(true);
		} else {
			resolve(false);
		}
	});
}

async function ensureYarnInstalledAsync() {
	const semverPattern =
		/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/;
	let hasYarn = false;
	try {
		const stdout = await execGetOutput("yarn", ["-v"], "Check yarn version");
		hasYarn = semverPattern.test(stdout);
	} catch (e) {
		hasYarn = false;
	}
	if (!hasYarn) await installYarnAsync();
}

function installYarnAsync() {
	return exec("npm", ["install", "-g", "yarn"], "Install yarn");
}

function exec(command, args, description) {
	console.log(`Setup: ${description}`);
	return new Promise((resolve, reject) => {
		let cp = require("child_process").spawn(command, args, {
			cwd: root,
			stdio: "inherit",
			shell: true
		});
		cp.on("error", error => {
			reject(new Error(`${description} failed with ${error}`));
		});
		cp.on("exit", exitCode => {
			if (exitCode) {
				reject(`${description} failed with exit code ${exitCode}`);
			} else {
				resolve();
			}
		});
	});
}

function execGetOutput(command, args, description) {
	console.log(`Setup: ${description}`);
	return new Promise((resolve, reject) => {
		let cp = require("child_process").spawn(command, args, {
			cwd: root,
			stdio: [process.stdin, "pipe", process.stderr],
			shell: true
		});
		cp.on("error", error => {
			reject(new Error(`${description} failed with ${error}`));
		});
		cp.on("exit", exitCode => {
			if (exitCode) {
				reject(`${description} failed with exit code ${exitCode}`);
			} else {
				resolve(Buffer.concat(buffers).toString("utf-8").trim());
			}
		});
		const buffers = [];
		cp.stdout.on("data", data => buffers.push(data));
	});
}

setup();


text:
'use strict';

/**
 * Module dependencies.
 */
const app = require('./config');
const server = app.start();


text:
title: Overview
page_title: Overview - Virtual Keyboard
description: RadVirtualKeyboard is a software component that allows the input of characters without the need for physical keys.
slug: winforms-virtual-keyboard-overview
tags: virtual, keyboard
published: True
position: 0
CTAControlName: VirtualKeyboard
---

# Virtual Keyboard

Since **R1 2020** Telerik UI for WinForms suite offers a **RadVirtualKeyboard** control. It is a software component that allows the input of characters without the need for physical keys. The interaction with the virtual keyboard happens mostly via a touchscreen interface, but can also take place in a different form in virtual or augmented reality.
On a desktop computer, a virtual keyboard might provide an alternative input mechanism for users with disabilities who cannot use a conventional keyboard, or for bi- or multi- lingual users who switch frequently between different character sets or alphabets, which may be confusing over time. Although hardware keyboards are available with dual keyboard layouts (e.g. Cyrillic/Latin letters in various national layouts), the on-screen keyboard provides a handy substitute while working at different stations or on laptops, which seldom come with dual layouts.

{% if site.has_cta_panels == true %}
{% include cta-panel-overview.html %}
{% endif %}

**RadVirtualKeyboard** will serve the need of a virtual keyboard with consistent theming for each WinForms application with Telerik UI for WinForms controls.

![winforms/virtual-keyboard-overview 001](images/virtual-keyboard-overview001.png)

## Key Features

* Provides the possibility for text input in a keyboardless environment.

* Predefined layouts.

* Support for defining custom layouts

* Support for XML files.

* System synchronization: Windows input language change will be monitored. When the keyboard layout is changed, the symbols on the keyboard keys are also updated based on the current Windows input locale.

# See Also

* [Structure]({%slug winforms-virtual-keyboard-structure%})
* [Getting Started]({%slug winforms-virtual-keyboard-getting-started%})


text:
class Say < Linkbot::Plugin

  def initialize
    register :regex => /^!say (.+)/i
    help "!say (phrase) - Make linkbot repeat after you. Not that useful."
  end

  def on_message(message, matches)
    "#{matches[0]}"
  end

end


text:
package org.apache.wiki.auth.authorize;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.wiki.api.core.Context;
import org.apache.wiki.api.core.Engine;
import org.apache.wiki.api.core.Session;
import org.apache.wiki.api.exceptions.NoRequiredPropertyException;
import org.apache.wiki.api.exceptions.WikiException;
import org.apache.wiki.auth.AuthenticationManager;
import org.apache.wiki.auth.Authorizer;
import org.apache.wiki.auth.GroupPrincipal;
import org.apache.wiki.auth.NoSuchPrincipalException;
import org.apache.wiki.auth.UserManager;
import org.apache.wiki.auth.WikiPrincipal;
import org.apache.wiki.auth.WikiSecurityException;
import org.apache.wiki.auth.user.UserProfile;
import org.apache.wiki.event.WikiEvent;
import org.apache.wiki.event.WikiEventListener;
import org.apache.wiki.event.WikiEventManager;
import org.apache.wiki.event.WikiSecurityEvent;
import org.apache.wiki.ui.InputValidator;
import org.apache.wiki.util.ClassUtil;

import java.security.Principal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;

/**
 *

 * Facade class for storing, retrieving and managing wiki groups on behalf of AuthorizationManager, JSPs and other presentation-layer
 * classes. GroupManager works in collaboration with a back-end {@link GroupDatabase}, which persists groups to permanent storage.
 *

 *

 * Note: prior to JSPWiki 2.4.19, GroupManager was an interface; it is now a concrete, final class. The aspects of GroupManager
 * which previously extracted group information from storage (e.g., wiki pages) have been refactored into the GroupDatabase interface.
 *

 * @since 2.4.19
 */
public class DefaultGroupManager implements GroupManager, Authorizer, WikiEventListener {

    private static final Logger LOG = LogManager.getLogger( DefaultGroupManager.class );

    protected Engine m_engine;

    protected WikiEventListener m_groupListener;

    private GroupDatabase m_groupDatabase;

    /** Map with GroupPrincipals as keys, and Groups as values */
    private final Map< Principal, Group > m_groups = new HashMap<>();

    /** {@inheritDoc} */
    @Override
    public Principal findRole( final String name ) {
        try {
            final Group group = getGroup( name );
            return group.getPrincipal();
        } catch( final NoSuchPrincipalException e ) {
            return null;
        }
    }

    /** {@inheritDoc} */
    @Override
    public Group getGroup( final String name ) throws NoSuchPrincipalException {
        final Group group = m_groups.get( new GroupPrincipal( name ) );
        if( group != null ) {
            return group;
        }
        throw new NoSuchPrincipalException( "Group " + name + " not found." );
    }

    /** {@inheritDoc} */
    @Override
    public GroupDatabase getGroupDatabase() throws WikiSecurityException {
        if( m_groupDatabase != null ) {
            return m_groupDatabase;
        }

        String dbClassName = "<unknown>";
        String dbInstantiationError = null;
        Throwable cause = null;
        try {
            final Properties props = m_engine.getWikiProperties();
            dbClassName = props.getProperty( PROP_GROUPDATABASE );
            if( dbClassName == null ) {
                dbClassName = XMLGroupDatabase.class.getName();
            }
            LOG.info( "Attempting to load group database class {}" + dbClassName );
            m_groupDatabase = ClassUtil.buildInstance( "org.apache.wiki.auth.authorize", dbClassName );
            m_groupDatabase.initialize( m_engine, m_engine.getWikiProperties() );
            LOG.info( "Group database initialized." );
        } catch( final ReflectiveOperationException e ) {
            LOG.error( "UserDatabase {} cannot be instantiated", dbClassName, e );
            dbInstantiationError = "Access GroupDatabase class " + dbClassName + " denied";
            cause = e;
        } catch( final NoRequiredPropertyException e ) {
            LOG.error( "Missing property: " + e.getMessage() + "." );
            dbInstantiationError = "Missing property: " + e.getMessage();
            cause = e;
        }

        if( dbInstantiationError != null ) {
            throw new WikiSecurityException( dbInstantiationError + " Cause: " + cause.getMessage(), cause );
        }

        return m_groupDatabase;
    }

    /** {@inheritDoc} */
    @Override
    public Principal[] getRoles() {
        return m_groups.keySet().toArray( new Principal[0] );
    }

    /** {@inheritDoc} */
    @Override
    public void initialize( final Engine engine, final Properties props ) throws WikiSecurityException {
        m_engine = engine;

        try {
            m_groupDatabase = getGroupDatabase();
        } catch( final WikiException e ) {
            throw new WikiSecurityException( e.getMessage(), e );
        }

        // Load all groups from the database into the cache
        final Group[] groups = m_groupDatabase.groups();
        synchronized( m_groups ) {
            for( final Group group : groups ) {
                // Add new group to cache; fire GROUP_ADD event
                m_groups.put( group.getPrincipal(), group );
                fireEvent( WikiSecurityEvent.GROUP_ADD, group );
            }
        }

        // Make the GroupManager listen for WikiEvents (WikiSecurityEvents for changed user profiles)
        engine.getManager( UserManager.class ).addWikiEventListener( this );

        // Success!
        LOG.info( "Authorizer GroupManager initialized successfully; loaded " + groups.length + " group(s)." );
    }

    /** {@inheritDoc} */
    @Override
    public boolean isUserInRole( final Session session, final Principal role ) {
        // Always return false if session/role is null, or if role isn't a GroupPrincipal
        if ( session == null || !( role instanceof GroupPrincipal ) || !session.isAuthenticated() ) {
            return false;
        }

        // Get the group we're examining
        final Group group = m_groups.get( role );
        if( group == null ) {
            return false;
        }

        // Check each user principal to see if it belongs to the group
        for( final Principal principal : session.getPrincipals() ) {
            if( AuthenticationManager.isUserPrincipal( principal ) && group.isMember( principal ) ) {
                return true;
            }
        }
        return false;
    }

    /** {@inheritDoc} */
    @Override
    public Group parseGroup( String name, String memberLine, final boolean create ) throws WikiSecurityException {
        // If null name parameter, it's because someone's creating a new group
        if( name == null ) {
            if( create ) {
                name = "MyGroup";
            } else {
                throw new WikiSecurityException( "Group name cannot be blank." );
            }
        } else if( ArrayUtils.contains( Group.RESTRICTED_GROUPNAMES, name ) ) {
            // Certain names are forbidden
            throw new WikiSecurityException( "Illegal group name: " + name );
        }
        name = name.trim();

        // Normalize the member line
        if( InputValidator.isBlank( memberLine ) ) {
            memberLine = "";
        }
        memberLine = memberLine.trim();

        // Create or retrieve the group (may have been previously cached)
        final Group group = new Group( name, m_engine.getApplicationName() );
        try {
            final Group existingGroup = getGroup( name );

            // If existing, clone it
            group.setCreator( existingGroup.getCreator() );
            group.setCreated( existingGroup.getCreated() );
            group.setModifier( existingGroup.getModifier() );
            group.setLastModified( existingGroup.getLastModified() );
            for( final Principal existingMember : existingGroup.members() ) {
                group.add( existingMember );
            }
        } catch( final NoSuchPrincipalException e ) {
            // It's a new group.... throw error if we don't create new ones
            if( !create ) {
                throw new NoSuchPrincipalException( "Group '" + name + "' does not exist." );
            }
        }

        // If passed members not empty, overwrite
        final String[] members = extractMembers( memberLine );
        if( members.length > 0 ) {
            group.clear();
            for( final String member : members ) {
                group.add( new WikiPrincipal( member ) );
            }
        }

        return group;
    }

    /** {@inheritDoc} */
    @Override
    public void removeGroup( final String index ) throws WikiSecurityException {
        if( index == null ) {
            throw new IllegalArgumentException( "Group cannot be null." );
        }

        final Group group = m_groups.get( new GroupPrincipal( index ) );
        if( group == null ) {
            throw new NoSuchPrincipalException( "Group " + index + " not found" );
        }

        // Delete the group
        // TODO: need rollback procedure
        synchronized( m_groups ) {
            m_groups.remove( group.getPrincipal() );
        }
        m_groupDatabase.delete( group );
        fireEvent( WikiSecurityEvent.GROUP_REMOVE, group );
    }

    /** {@inheritDoc} */
    @Override
    public void setGroup( final Session session, final Group group ) throws WikiSecurityException {
        // TODO: check for appropriate permissions

        // If group already exists, delete it; fire GROUP_REMOVE event
        final Group oldGroup = m_groups.get( group.getPrincipal() );
        if( oldGroup != null ) {
            fireEvent( WikiSecurityEvent.GROUP_REMOVE, oldGroup );
            synchronized( m_groups ) {
                m_groups.remove( oldGroup.getPrincipal() );
            }
        }

        // Copy existing modifier info & timestamps
        if( oldGroup != null ) {
            group.setCreator( oldGroup.getCreator() );
            group.setCreated( oldGroup.getCreated() );
            group.setModifier( oldGroup.getModifier() );
            group.setLastModified( oldGroup.getLastModified() );
        }

        // Add new group to cache; announce GROUP_ADD event
        synchronized( m_groups ) {
            m_groups.put( group.getPrincipal(), group );
        }
        fireEvent( WikiSecurityEvent.GROUP_ADD, group );

        // Save the group to back-end database; if it fails, roll back to previous state. Note that the back-end
        // MUST timestammp the create/modify fields in the Group.
        try {
            m_groupDatabase.save( group, session.getUserPrincipal() );
        }

        // We got an exception! Roll back...
        catch( final WikiSecurityException e ) {
            if( oldGroup != null ) {
                // Restore previous version, re-throw...
                fireEvent( WikiSecurityEvent.GROUP_REMOVE, group );
                fireEvent( WikiSecurityEvent.GROUP_ADD, oldGroup );
                synchronized( m_groups ) {
                    m_groups.put( oldGroup.getPrincipal(), oldGroup );
                }
                throw new WikiSecurityException( e.getMessage() + " (rolled back to previous version).", e );
            }
            // Re-throw security exception
            throw new WikiSecurityException( e.getMessage(), e );
        }
    }

    /** {@inheritDoc} */
    @Override
    public void validateGroup( final Context context, final Group group ) {
        final InputValidator validator = new InputValidator( MESSAGES_KEY, context );

        // Name cannot be null or one of the restricted names
        try {
            checkGroupName( context, group.getName() );
        } catch( final WikiSecurityException e ) {
        }

        // Member names must be "safe" strings
        final Principal[] members = group.members();
        for( final Principal member : members ) {
            validator.validateNotNull( member.getName(), "Full name", InputValidator.ID );
        }
    }

    /** {@inheritDoc} */
    @Override
    public void checkGroupName( final Context context, final String name ) throws WikiSecurityException {
        // TODO: groups cannot have the same name as a user

        // Name cannot be null
        final InputValidator validator = new InputValidator( MESSAGES_KEY, context );
        validator.validateNotNull( name, "Group name" );

        // Name cannot be one of the restricted names either
        if( ArrayUtils.contains( Group.RESTRICTED_GROUPNAMES, name ) ) {
            throw new WikiSecurityException( "The group name '" + name + "' is illegal. Choose another." );
        }
    }

    /**
     * Extracts carriage-return separated members into a Set of String objects.
     *
     * @param memberLine the list of members
     * @return the list of members
     */
    protected String[] extractMembers( final String memberLine ) {
        final Set< String > members = new HashSet<>();
        if( memberLine != null ) {
            final StringTokenizer tok = new StringTokenizer( memberLine, "\n" );
            while( tok.hasMoreTokens() ) {
                final String uid = tok.nextToken().trim();
                if( !uid.isEmpty() ) {
                    members.add( uid );
                }
            }
        }
        return members.toArray( new String[0] );
    }

    // events processing .......................................................

    /** {@inheritDoc} */
    @Override
    public synchronized void addWikiEventListener( final WikiEventListener listener ) {
        WikiEventManager.addWikiEventListener( this, listener );
    }

    /** {@inheritDoc} */
    @Override
    public synchronized void removeWikiEventListener( final WikiEventListener listener ) {
        WikiEventManager.removeWikiEventListener( this, listener );
    }

    /** {@inheritDoc} */
    @Override
    public void actionPerformed( final WikiEvent event ) {
        if( !( event instanceof WikiSecurityEvent ) ) {
            return;
        }

        final WikiSecurityEvent se = ( WikiSecurityEvent )event;
        if( se.getType() == WikiSecurityEvent.PROFILE_NAME_CHANGED ) {
            final Session session = se.getSrc();
            final UserProfile[] profiles = ( UserProfile[] )se.getTarget();
            final Principal[] oldPrincipals = new Principal[] { new WikiPrincipal( profiles[ 0 ].getLoginName() ),
                    new WikiPrincipal( profiles[ 0 ].getFullname() ), new WikiPrincipal( profiles[ 0 ].getWikiName() ) };
            final Principal newPrincipal = new WikiPrincipal( profiles[ 1 ].getFullname() );

            // Examine each group
            int groupsChanged = 0;
            try {
                for( final Group group : m_groupDatabase.groups() ) {
                    boolean groupChanged = false;
                    for( final Principal oldPrincipal : oldPrincipals ) {
                        if( group.isMember( oldPrincipal ) ) {
                            group.remove( oldPrincipal );
                            group.add( newPrincipal );
                            groupChanged = true;
                        }
                    }
                    if( groupChanged ) {
                        setGroup( session, group );
                        groupsChanged++;
                    }
                }
            } catch( final WikiException e ) {
                // Oooo! This is really bad...
                LOG.error( "Could not change user name in Group lists because of GroupDatabase error:" + e.getMessage() );
            }
            LOG.info( "Profile name change for '" + newPrincipal + "' caused " + groupsChanged + " groups to change also." );
        }
    }

}


text:
Some basic conventions for contributing to this project.

### General

* Non-trivial changes should be discussed in an issue first
* Develop in a topic branch, not master
* Squash your commits

### Commit Message Format

Each commit message should include a **type**, a **scope** and a **subject**:

```
 <type>(<scope>): <subject>
```

Lines should not exceed 100 characters:

```
 #270 fix(config): only override publicPath when served by webpack
 #269 feat(ChangeDetection): add change detection module
```

#### Type

Must be one of the following:

* **feat**: A new feature
* **fix**: A bug fix
* **docs**: Documentation only changes
* **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing
  semi-colons, etc)
* **refactor**: A code change that neither fixes a bug or adds a feature
* **test**: Adding missing tests
* **chore**: Changes to the build process or auxiliary tools and libraries such as documentation
  generation

#### Scope

The scope could be anything specifying place of the commit change.

#### Subject

The subject contains succinct description of the change:

* use the imperative, present tense: "change" not "changed" nor "changes"
* don't capitalize first letter
* no dot (.) at the end


text:
require('../../helper');

var app = require(global.settings.app_root + '/app/controllers/app')();
var assert = require('../../support/assert');
var querystring = require('querystring');
var shapefile = require('shapefile');
var _ = require('underscore');
var zipfile = require('zipfile');
var fs      = require('fs');

// allow lots of emitters to be set to silence warning
app.setMaxListeners(0);

describe('export.shapefile', function() {

// SHP tests

it('SHP format, unauthenticated', function(done){
    assert.response(app, {
        url: '/api/v1/sql?q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=shp',
        headers: {host: 'vizzuality.cartodb.com'},
        encoding: 'binary',
        method: 'GET'
    },{ }, function(res){
        assert.equal(res.statusCode, 200, res.body);
        var cd = res.header('Content-Disposition');
        assert.equal(true, /^attachment/.test(cd), 'SHP is not disposed as attachment: ' + cd);
        assert.equal(true, /filename=cartodb-query.zip/gi.test(cd));
        var tmpfile = '/tmp/myshape.zip';
        var err = fs.writeFileSync(tmpfile, res.body, 'binary');
        if (err) {
            return done(err);
        }
        var zf = new zipfile.ZipFile(tmpfile);
        assert.ok(_.contains(zf.names, 'cartodb-query.shp'), 'SHP zipfile does not contain .shp: ' + zf.names);
        assert.ok(_.contains(zf.names, 'cartodb-query.shx'), 'SHP zipfile does not contain .shx: ' + zf.names);
        assert.ok(_.contains(zf.names, 'cartodb-query.dbf'), 'SHP zipfile does not contain .dbf: ' + zf.names);
        assert.ok(_.contains(zf.names, 'cartodb-query.prj'), 'SHP zipfile does not contain .prj: ' + zf.names);
        // TODO: check DBF contents
        fs.unlinkSync(tmpfile);
        done();
    });
});

it('SHP format, unauthenticated, POST', function(done){
    assert.response(app, {
        url: '/api/v1/sql',
        data: 'q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=shp',
        headers: {host: 'vizzuality.cartodb.com', 'Content-Type': 'application/x-www-form-urlencoded' },
        method: 'POST'
    },{ }, function(res){
        assert.equal(res.statusCode, 200, res.body);
        var cd = res.header('Content-Disposition');
        assert.equal(true, /^attachment/.test(cd), 'SHP is not disposed as attachment: ' + cd);
        assert.equal(true, /filename=cartodb-query.zip/gi.test(cd), 'Unexpected SHP filename: ' + cd);
        done();
    });
});

it('SHP format, big size, POST', function(done){
    assert.response(app, {
        url: '/api/v1/sql',
        data: querystring.stringify({
          q: 'SELECT 0 as fname, st_makepoint(i,i) FROM generate_series(0,81920) i',
          format: 'shp'
        }),
        headers: {host: 'vizzuality.cartodb.com', 'Content-Type': 'application/x-www-form-urlencoded' },
        method: 'POST'
    },{ }, function(res){
        assert.equal(res.statusCode, 200, res.body);
        var cd = res.header('Content-Disposition');
        assert.equal(true, /^attachment/.test(cd), 'SHP is not disposed as attachment: ' + cd);
        assert.equal(true, /filename=cartodb-query.zip/gi.test(cd), 'Unexpected SHP filename: ' + cd);
        assert.ok(res.body.length > 81920, 'SHP smaller than expected: ' + res.body.length);
        done();
    });
});

it('SHP format, unauthenticated, with custom filename', function(done){
    assert.response(app, {
        url: '/api/v1/sql?q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=shp&filename=myshape',
        headers: {host: 'vizzuality.cartodb.com'},
        encoding: 'binary',
        method: 'GET'
    },{ }, function(res){
        assert.equal(res.statusCode, 200, res.body);
        var cd = res.header('Content-Disposition');
        assert.equal(true, /^attachment/.test(cd), 'SHP is not disposed as attachment: ' + cd);
        assert.equal(true, /filename=myshape.zip/gi.test(cd));
        var tmpfile = '/tmp/myshape.zip';
        var err = fs.writeFileSync(tmpfile, res.body, 'binary');
        if (err) {
            return done(err);
        }
        var zf = new zipfile.ZipFile(tmpfile);
        assert.ok(_.contains(zf.names, 'myshape.shp'), 'SHP zipfile does not contain .shp: ' + zf.names);
        assert.ok(_.contains(zf.names, 'myshape.shx'), 'SHP zipfile does not contain .shx: ' + zf.names);
        assert.ok(_.contains(zf.names, 'myshape.dbf'), 'SHP zipfile does not contain .dbf: ' + zf.names);
        assert.ok(_.contains(zf.names, 'myshape.prj'), 'SHP zipfile does not contain .prj: ' + zf.names);
        fs.unlinkSync(tmpfile);
        done();
    });
});

it('SHP format, unauthenticated, with custom, dangerous filename', function(done){
    assert.response(app, {
        url: '/api/v1/sql?q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=shp&filename=b;"%20()[]a',
        headers: {host: 'vizzuality.cartodb.com'},
        encoding: 'binary',
        method: 'GET'
    },{ }, function(res){
        assert.equal(res.statusCode, 200, res.body);
        var fname = "b_______a";
        var cd = res.header('Content-Disposition');
        assert.equal(true, /^attachment/.test(cd), 'SHP is not disposed as attachment: ' + cd);
        assert.equal(true, /filename=b_______a.zip/gi.test(cd), 'Unexpected SHP filename: ' + cd);
        var tmpfile = '/tmp/myshape.zip';
        var err = fs.writeFileSync(tmpfile, res.body, 'binary');
        if (err) {
            return done(err);
        }
        var zf = new zipfile.ZipFile(tmpfile);
        assert.ok(_.contains(zf.names, fname + '.shp'), 'SHP zipfile does not contain .shp: ' + zf.names);
        assert.ok(_.contains(zf.names, fname + '.shx'), 'SHP zipfile does not contain .shx: ' + zf.names);
        assert.ok(_.contains(zf.names, fname + '.dbf'), 'SHP zipfile does not contain .dbf: ' + zf.names);
        assert.ok(_.contains(zf.names, fname+ '.prj'), 'SHP zipfile does not contain .prj: ' + zf.names);
        fs.unlinkSync(tmpfile);
        done();
    });
});

it('SHP format, authenticated', function(done){
    assert.response(app, {
        url: '/api/v1/sql?q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=shp&api_key=1234',
        headers: {host: 'vizzuality.cartodb.com'},
        encoding: 'binary',
        method: 'GET'
    },{ }, function(res){
        assert.equal(res.statusCode, 200, res.body);
        var cd = res.header('Content-Disposition');
        assert.equal(true, /filename=cartodb-query.zip/gi.test(cd));
        var tmpfile = '/tmp/myshape.zip';
        var err = fs.writeFileSync(tmpfile, res.body, 'binary');
        if (err) {
            return done(err);
        }
        var zf = new zipfile.ZipFile(tmpfile);
        assert.ok(_.contains(zf.names, 'cartodb-query.shp'), 'SHP zipfile does not contain .shp: ' + zf.names);
        assert.ok(_.contains(zf.names, 'cartodb-query.shx'), 'SHP zipfile does not contain .shx: ' + zf.names);
        assert.ok(_.contains(zf.names, 'cartodb-query.dbf'), 'SHP zipfile does not contain .dbf: ' + zf.names);
        assert.ok(_.contains(zf.names, 'cartodb-query.prj'), 'SHP zipfile does not contain .prj: ' + zf.names);
        // TODO: check contents of the DBF
        fs.unlinkSync(tmpfile);
        done();
    });
});

// See https://github.com/Vizzuality/CartoDB-SQL-API/issues/66
it('SHP format, unauthenticated, with utf8 data', function(done){
    var query = querystring.stringify({
        q: "SELECT '♥♦♣♠' as f, st_makepoint(0,0,4326) as the_geom",
        format: 'shp',
        filename: 'myshape'
      });
    assert.response(app, {
        url: '/api/v1/sql?' + query,
        headers: {host: 'vizzuality.cartodb.com'},
        encoding: 'binary',
        method: 'GET'
    },{ }, function(res){
        assert.equal(res.statusCode, 200, res.body);
        var tmpfile = '/tmp/myshape.zip';
        var err = fs.writeFileSync(tmpfile, res.body, 'binary');
        if (err) {
            return done(err);
        }
        var zf = new zipfile.ZipFile(tmpfile);
        var buffer = zf.readFileSync('myshape.dbf');
        fs.unlinkSync(tmpfile);
        var strings = buffer.toString();
        assert.ok(/♥♦♣♠/.exec(strings), "Cannot find '♥♦♣♠' in here:\n" + strings);
        done();
    });
});

// See https://github.com/Vizzuality/CartoDB-SQL-API/issues/66
it('mixed type geometry', function(done){
    var query = querystring.stringify({
        q: "SELECT 'POINT(0 0)'::geometry as g UNION ALL SELECT 'LINESTRING(0 0, 1 0)'::geometry",
        format: 'shp'
      });
    assert.response(app, {
        url: '/api/v1/sql?' + query,
        headers: {host: 'vizzuality.cartodb.com'},
        encoding: 'binary',
        method: 'GET'
    },{ }, function(res){
        assert.deepEqual(res.headers['content-type'], 'application/json; charset=utf-8');
        assert.deepEqual(res.headers['content-disposition'], 'inline');
        assert.equal(res.statusCode, 400, res.statusCode + ': ' +res.body);
        var parsedBody = JSON.parse(res.body);
        var expectedBody = {"error":["ERROR 1: Attempt to write non-point (LINESTRING) geometry to point shapefile."]};
        assert.deepEqual(parsedBody, expectedBody);
        done();
    });
});

// See https://github.com/Vizzuality/CartoDB-SQL-API/issues/87
it('errors are not confused with warnings', function(done){
    var query = querystring.stringify({
        q: [
            "SELECT 'POINT(0 0)'::geometry as g, 1 as a_very_very_very_long_field_name",
            "SELECT 'LINESTRING(0 0, 1 0)'::geometry, 2"
        ].join(" UNION ALL "),
        format: 'shp'
      });
    assert.response(app, {
        url: '/api/v1/sql?' + query,
        headers: {host: 'vizzuality.cartodb.com'},
        encoding: 'binary',
        method: 'GET'
    },{ }, function(res){
        assert.deepEqual(res.headers['content-type'], 'application/json; charset=utf-8');
        assert.deepEqual(res.headers['content-disposition'], 'inline');
        assert.equal(res.statusCode, 400, res.statusCode + ': ' +res.body);
        var parsedBody = JSON.parse(res.body);
        var expectedBody = {"error":["ERROR 1: Attempt to write non-point (LINESTRING) geometry to point shapefile."]};
        assert.deepEqual(parsedBody, expectedBody);
        done();
    });
});

it('skipfields controls fields included in SHP output', function(done){
    var query = querystring.stringify({
        q: "SELECT 111 as skipme, 222 as keepme, 'POINT(0 0)'::geometry as g",
        format: 'shp',
        skipfields: 'skipme',
        filename: 'myshape'
      });
    assert.response(app, {
        url: '/api/v1/sql?' + query,
        headers: {host: 'vizzuality.cartodb.com'},
        encoding: 'binary',
        method: 'GET'
    },{ }, function(res){
        assert.equal(res.statusCode, 200, res.body);
        var tmpfile = '/tmp/myshape.zip';
        var err = fs.writeFileSync(tmpfile, res.body, 'binary');
        if (err) {
            return done(err);
        }
        var zf = new zipfile.ZipFile(tmpfile);
        var buffer = zf.readFileSync('myshape.dbf');
        fs.unlinkSync(tmpfile);
        var strings = buffer.toString();
        assert.ok(!/skipme/.exec(strings), "Could not skip 'skipme' field:\n" + strings);
        done();
    });
});

it('SHP format, concurrently', function(done){
    var concurrency = 1;
    var waiting = concurrency;
    function validate(res){
        var cd = res.header('Content-Disposition');
        assert.equal(true, /^attachment/.test(cd), 'SHP is not disposed as attachment: ' + cd);
        assert.equal(true, /filename=cartodb-query.zip/gi.test(cd));
        var tmpfile = '/tmp/myshape.zip';
        var err = fs.writeFileSync(tmpfile, res.body, 'binary');
        if (err) {
            return done(err);
        }
        var zf = new zipfile.ZipFile(tmpfile);
        assert.ok(_.contains(zf.names, 'cartodb-query.shp'), 'SHP zipfile does not contain .shp: ' + zf.names);
        assert.ok(_.contains(zf.names, 'cartodb-query.shx'), 'SHP zipfile does not contain .shx: ' + zf.names);
        assert.ok(_.contains(zf.names, 'cartodb-query.dbf'), 'SHP zipfile does not contain .dbf: ' + zf.names);
        assert.ok(_.contains(zf.names, 'cartodb-query.prj'), 'SHP zipfile does not contain .prj: ' + zf.names);
        // TODO: check DBF contents
        fs.unlinkSync(tmpfile);
        if ( ! --waiting ) {
            done();
        }
    }
    for (var i=0; i<concurrency; ++i) {
        assert.response(
            app,
            {
                url: '/api/v1/sql?q=SELECT%20*%20FROM%20untitle_table_4%20LIMIT%201&format=shp',
                headers: {host: 'vizzuality.cartodb.com'},
                encoding: 'binary',
                method: 'GET'
            },
            {
                status: 200
            },
            validate
        );
    }
});

// See https://github.com/CartoDB/CartoDB-SQL-API/issues/111
it('point with null first', function(done){
    var query = querystring.stringify({
        q: "SELECT null::geometry as g UNION ALL SELECT 'SRID=4326;POINT(0 0)'::geometry",
        format: 'shp'
      });
    assert.response(app, {
        url: '/api/v1/sql?' + query,
        headers: {host: 'vizzuality.cartodb.com'},
        encoding: 'binary',
        method: 'GET'
    },{ }, function(res){
        assert.equal(res.statusCode, 200, res.body);
        var cd = res.header('Content-Disposition');
        assert.equal(true, /filename=cartodb-query.zip/gi.test(cd));
        var tmpfile = '/tmp/myshape.zip';
        var err = fs.writeFileSync(tmpfile, res.body, 'binary');
        if (err) {
            return done(err);
        }
        var zf = new zipfile.ZipFile(tmpfile);
        assert.ok(_.contains(zf.names, 'cartodb-query.shp'), 'SHP zipfile does not contain .shp: ' + zf.names);
        assert.ok(_.contains(zf.names, 'cartodb-query.shx'), 'SHP zipfile does not contain .shx: ' + zf.names);
        assert.ok(_.contains(zf.names, 'cartodb-query.dbf'), 'SHP zipfile does not contain .dbf: ' + zf.names);
        assert.ok(_.contains(zf.names, 'cartodb-query.prj'), 'SHP zipfile does not contain .prj: ' + zf.names);
        // TODO: check contents of the DBF
        fs.unlinkSync(tmpfile);
        done();
    });
});

    var limit = 1200;

    it('expects ' + limit + ' rows in public table', function(done){

        var filename = 'test_1200';

        assert.response(app, {
                url: '/api/v1/sql?' + querystring.stringify({
                    q: "SELECT * from populated_places_simple_reduced limit " + limit,
                    format: 'shp',
                    filename: filename
                }),
                headers: { host: 'vizzuality.cartodb.com' },
                encoding: 'binary',
                method: 'GET'
            },
            {
                status: 200
            },
            function(res, err) {
                if (err) {
                    return done(err);
                }

                var tmpShpPath = '/tmp/'+filename+'.zip';
                err = fs.writeFileSync(tmpShpPath, res.body, 'binary');
                if (err) {
                    return done(err);
                }

                var zf = new zipfile.ZipFile(tmpShpPath);
                zf.names.forEach(function(name) {
                    var buffer = zf.readFileSync(name);
                    var tmpDbfPath = '/tmp/' + name;
                    err = fs.writeFileSync(tmpDbfPath, buffer);
                    if (err) {
                        return done(err);
                    }
                });
                shapefile.read('/tmp/'+filename, function(err, collection) {
                    if (err) {
                        return done(err);
                    }
                    assert.equal(collection.features.length, limit);
                    done();
                });

            }
        );
    });

});


text:
package com.akisute.yourconsole.app.model;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.akisute.yourconsole.R;
import com.akisute.yourconsole.app.dagger.ForInjecting;
import com.akisute.yourconsole.app.helper.LogcatHelper;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class ConsoleListAdapter extends BaseAdapter {

    class ViewHolder {
        @InjectView(R.id.text)
        TextView text;
        @InjectView(R.id.tag)
        TextView tag;

        ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }

    private final Context mContext;
    private final LayoutInflater mLayoutInflater;
    private final List<MText> mTextList = new ArrayList<MText>();

    @Inject
    public ConsoleListAdapter(@ForInjecting Context context) {
        mContext = context;
        mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return mTextList.size();
    }

    @Override
    public MText getItem(int position) {
        return mTextList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.list_console_item, null, false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        MText textModel = getItem(position);
        LogcatLine logcatLine = textModel.getLogcatLine();
        if (logcatLine != null) {
            viewHolder.tag.setText(logcatLine.getTag());
            viewHolder.tag.setTextColor(getColorForLogcatLine(logcatLine));
            viewHolder.text.setText(logcatLine.getLogOutput());
            viewHolder.text.setTextColor(getColorForLogcatLine(logcatLine));
        } else {
            viewHolder.tag.setText(textModel.getSenderPackageName());
            viewHolder.tag.setTextColor(mContext.getResources().getColor(R.color.font_text));
            viewHolder.text.setText(textModel.getText());
            viewHolder.text.setTextColor(mContext.getResources().getColor(R.color.font_text));
        }

        return convertView;
    }

    public void clear() {
        mTextList.clear();
        notifyDataSetChanged();
    }

    public void load() {
        clear();
        List<MText> textList = MText.getAll();
        appendTexts(textList);
    }

    public void appendTexts(List<MText> textList) {
        mTextList.addAll(textList);
        notifyDataSetChanged();
    }

    private int getColorForLogcatLine(LogcatLine logcatLine) {
        switch (logcatLine.getLogLevel()) {
            case Log.DEBUG:
                return mContext.getResources().getColor(R.color.font_logcat_debug);
            case Log.ERROR:
                return mContext.getResources().getColor(R.color.font_logcat_error);
            case Log.INFO:
                return mContext.getResources().getColor(R.color.font_logcat_info);
            case Log.VERBOSE:
                return mContext.getResources().getColor(R.color.font_logcat_verbose);
            case Log.WARN:
                return mContext.getResources().getColor(R.color.font_logcat_warn);
            case LogcatHelper.LOG_WTF:
                return mContext.getResources().getColor(R.color.font_logcat_wtf);
        }
        return mContext.getResources().getColor(R.color.font_text);
    }
}


text:
package aQute.bnd.build;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Processor;
import aQute.libg.command.Command;

public class JUnitLauncher extends ProjectLauncher {
	private final static Logger	logger	= LoggerFactory.getLogger(JUnitLauncher.class);
	boolean						junit4Main;
	private Classpath			cp;
	private Command				java;
	private long				timeout;
	// private boolean trace;
	private List<String>		fqns	= new ArrayList<>();

	public JUnitLauncher(Project project) throws Exception {
		super(project);
	}

	@Override
	public void prepare() throws Exception {
		super.prepare();
		Pattern tests = Pattern.compile(getProject().getProperty(Constants.TESTSOURCES, "(.*).java"));

		String testDirName = getProject().getProperty("testsrc", "test");
		File testSrc = getProject().getFile(testDirName)
			.getAbsoluteFile();
		if (!testSrc.isDirectory()) {
			logger.debug("no test src directory");
			return;
		}

		if (!traverse(fqns, testSrc, "", tests)) {
			logger.debug("no test files found in {}", testSrc);
			return;
		}

		timeout = Processor.getDuration(getProject().getProperty(Constants.RUNTIMEOUT), 0);
		// trace =
		// Processor.isTrue(getProject().getProperty(Constants.RUNTRACE));
		cp = new Classpath(getProject(), "junit");
		addClasspath(getProject().getTestpath());
		File output = getProject().getOutput();
		if (output.exists()) {
			addClasspath(new Container(getProject(), output));
		}
		addClasspath(getProject().getBuildpath());
	}

	@Override
	public int launch() throws Exception {
		java = new Command();
		java.add(getJavaExecutable("java"));

		java.add("-cp");
		java.add(cp.toString());
		java.addAll(getProject().getRunVM());
		java.add(getMainTypeName());
		java.addAll(fqns);
		if (timeout != 0)
			java.setTimeout(timeout + 1000, TimeUnit.MILLISECONDS);

		logger.debug("cmd line {}", java);
		try {
			int result = java.execute(System.in, System.err, System.err);
			if (result == Integer.MIN_VALUE)
				return TIMEDOUT;
			reportResult(result);
			return result;
		} finally {
			cleanup();
		}

	}

	private boolean traverse(List<String> fqns, File testSrc, String prefix, Pattern filter) {
		boolean added = false;

		if (testSrc.isDirectory()) {
			for (File sub : testSrc.listFiles()) {
				return traverse(fqns, sub, prefix + sub.getName() + ".", filter) || added;
			}
		} else if (testSrc.isFile()) {
			String name = testSrc.getName();
			Matcher m = filter.matcher(name);
			if (m.matches()) {
				fqns.add(m.group(1));
				added = true;
			}
		}
		return added;
	}

	@Override
	public String getMainTypeName() {
		return "aQute.junit.Activator";
	}
}


text:
I encapsulate the modification of a slot.
The two use-cases are: slot renaming or a changed slot type.
Both cases enforce recompilation of all the methods accessing the corresponding variable.

This is unlike the ShiftedField modification which is only used when the type of the slot does not change.


text:
#import "NSObject.h"

@class NSURL;

@protocol MTMMailboxControllerProtocol <NSObject>
@property(readonly) NSURL *tocURL;
@property(readonly) NSURL *mailLibraryURL;
- (id)revisionIDForURL:(id)arg1;
- (id)accountForAccountID:(id)arg1;
- (id)messageWithID:(id)arg1;
- (void)mailboxListWasUpdated:(id)arg1;
- (void)mailboxListWillBeUpdated:(id)arg1;
@end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="md_bold_text">strong text</string>
    <string name="md_italic_text">emphasized text</string>
</resources>


text:
<?php echo $page_title;?>

            <?php
                echo form_open($submit, 'id=main_form');
                echo form_hidden('add_flag', '1');

                $fields = array('Číslo miestnosti'=>'room_id', 'Typ miestnosti'=>'room_type',
                                'Kapacita'=>'room_capacity', 'Vybavenie'=>'room_equip'
                                );

                if(isset($editables))
                {
                    echo form_fieldset();
                    echo form_label('Číslo miestnosti');
                    $attr = array('name' => 'room_id', 'id' => 'room_id', 'value' => $editables['id_miest']);
                    echo form_input($attr);
                    echo form_fieldset_close();

                    echo form_fieldset();
                    echo form_label('Typ miestnosti');
                    $attr = array('name' => 'room_type', 'id' => 'room_type', 'value' => $editables['typ_miest']);
                    echo form_input($attr);
                    echo form_fieldset_close();

                    echo form_fieldset();
                    echo form_label('Kapacita');
                    $attr = array('name' => 'room_capacity', 'id' => 'room_capacity', 'value' => $editables['kapacita']);
                    echo form_input($attr);
                    echo form_fieldset_close();

                    echo form_fieldset();
                    echo form_label('Vybavenie');
                    $attr = array('name' => 'room_equip', 'id' => 'room_equip', 'value' => $editables['spec_vyb']);
                    echo form_input($attr);
                    echo form_fieldset_close();

                }else
                {

                    foreach ($fields as $key => $value) {
                        echo form_fieldset();
                        echo form_label($key);
                        $attr = array('name' => $value, 'id' => $value, 'value' => set_value($value));
                        echo form_input($attr);
                        echo form_fieldset_close();
                    }
                }

                echo form_submit('submit', $action);
                echo form_close();

            ?>
            <?php echo validation_errors('
'); ?>


text:
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"
#include "usb_device.h"
#include "usbd_cdc_if.h"
#include "usb_ctrl.h"
#include "uart.h"
#include <stdio.h>

/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);

/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/

/* USER CODE END PFP */

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration----------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* Configure the system clock */
  SystemClock_Config();

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  UART_Init();
//  MX_USB_DEVICE_Init();

  /* USER CODE BEGIN 2 */

  USB_Control_Init();
  USB_Control_Enable();

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */

  uint8_t HELLO_WORLD[14] = "Hello World!\n";

  printf("%s", HELLO_WORLD);

  while (1)
  {
  /* USER CODE END WHILE */
	  HAL_Delay(1000);
	  CDC_Transmit_FS(HELLO_WORLD, 13);
  /* USER CODE BEGIN 3 */

  }
  /* USER CODE END 3 */

}

/** System Clock Configuration
*/
void SystemClock_Config(void)
{

  RCC_OscInitTypeDef RCC_OscInitStruct;
  RCC_ClkInitTypeDef RCC_ClkInitStruct;
  RCC_PeriphCLKInitTypeDef PeriphClkInit;

  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  HAL_RCC_OscConfig(&RCC_OscInitStruct);

  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2);

  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB;
  PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLL_DIV1_5;
  HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit);

  HAL_RCC_MCOConfig(RCC_MCO, RCC_MCO1SOURCE_SYSCLK, RCC_MCO_DIV1);

  HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);

  HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

  /* SysTick_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}

/** Configure pins as
        * Analog
        * Input
        * Output
        * EVENT_OUT
        * EXTI
     PA8   ------> RCC_MCO
*/
void MX_GPIO_Init(void)
{

  GPIO_InitTypeDef GPIO_InitStruct;

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();

  /*Configure GPIO pin : PA8 */
  GPIO_InitStruct.Pin = GPIO_PIN_8;
  GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

#ifdef USE_FULL_ASSERT

/**
   * @brief Reports the name of the source file and the source line number
   * where the assert_param error has occurred.
   * @param file: pointer to the source file name
   * @param line: assert_param error line source number
   * @retval None
   */
void assert_failed(uint8_t* file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
    ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */

}

#endif

/**
  * @}
  */

/**
  * @}
*/

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
/* @test
   @bug 4913702
   @summary validates canEncode(char c) method for sun.nio.cs.Shift_JIS
 */

import java.nio.*;
import java.nio.charset.*;

public class SJISCanEncode {
    private Charset cs;
    private CharsetEncoder encoder;

    private void canEncodeTest(char inputChar,
                               boolean expectedResult)
                               throws Exception {
        String msg = "err: Shift_JIS canEncode() return value ";

        if (encoder.canEncode(inputChar) != expectedResult) {
            throw new Exception(msg + !(expectedResult) +
                ": "  + Integer.toHexString((int)inputChar));
        }
    }

    public static void main(String[] args) throws Exception {
        SJISCanEncode test = new SJISCanEncode();
        test.cs = Charset.forName("SJIS");
        test.encoder = test.cs.newEncoder();

        // us-ascii (mappable by Shift_JIS)
        test.canEncodeTest('\u0001', true);

        // Halfwidth Katakana
        test.canEncodeTest('\uFF01', true);

        // CJK ideograph
        test.canEncodeTest('\u4E9C', true);

        //Hiragana
        test.canEncodeTest('\u3041', true);
        // fullwidth Katakana
        test.canEncodeTest('\u30A1', true);

        // U+0080 should be unmappable
        // U+4000 is a BMP character not covered by Shift_JISe

        test.canEncodeTest('\u0080', false);
        test.canEncodeTest('\u4000', false);
    }
}


text:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Person, SearchService } from '../shared';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit, OnDestroy {
  query: string;
  searchResults: Array<Person>;
  sub: Subscription;

  constructor(private searchService: SearchService, private route: ActivatedRoute) { }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
      if (params['term']) {
        this.query = decodeURIComponent(params['term']);
        this.search();
      }
    });
  }

  search(): void {
    this.searchService.search(this.query).subscribe(
      (data: any) => { this.searchResults = data; },
      error => console.log(error)
    );
  }

  ngOnDestroy() {
    if (this.sub) {
      this.sub.unsubscribe();
    }
  }
}


text:
"""
Program to analyse hydrogen bonds in a two-component system

It will classifies hydrogen bonds as trehalose-water (T-W),
trehalose-trehalose (T-T) or water-water (W-W). And for each
donor or acceptor atom it will write out the average number of hydrogen
bonds in each class.

Recognized donor atoms: H2O H3O H4O H6O HW1 HW2
Recognized acceptor atoms: O2 O3 O4 O6 OW

Examples:
    python anal_hbonds_twocomp.py --natoms 10262 -f r1_hbonds.pickle
    python anal_hbonds_twocomp.py --natoms 4170 --skip 1
"""

import argparse
import cPickle
import copy

import numpy as np

class Counts(object):
    """
    Class to take care of the counting for either an acceptor or donor
    Distinguish between trehalose-water (T-W), trehalose-trehalose (T-T)
    and water-water (W-W) hydogren bonds
    """
    def __init__(self, natoms):
        self.ww = 0
        self.tt = 0
        self.tw = 0
        self.total = 0
        self.nsnap = 0
        self.natoms = natoms
        self.curr = {}

    def __add__(self, other) :
        both = Counts(self.natoms)
        both.ww = self.ww + other.ww
        both.tt = self.tt + other.tt
        both.tw = self.tw + other.tw
        both.total = self.total + other.total
        both.nsnap = self.nsnap
        return both

    def __radd__(self, other) :
        both = Counts(self.natoms)
        both.ww = self.ww + other.ww
        both.tt = self.tt + other.tt
        both.tw = self.tw + other.tw
        both.total = self.total + other.total
        both.nsnap = self.nsnap
        return both

    def add_row(self, atomidx, row):
        """
        This will be called when a new bond is found in the
        database. It will check that only chemical hydrogen bonds
        are acounted for, i.e. it will remove double counting
        """
        if atomidx in self.curr:
            #self.curr[-atomidx] = self.curr[atomidx]
            #self.curr[atomidx] = row
            if self.curr[atomidx].distance > row.distance :
                self.curr[atomidx] = row
        else:
            self.curr[atomidx] = row

    def update(self):
        """
        This is to be called every new timestep and classifies the bonds
        """
        self.nsnap += 1
        for id, row in self.curr.iteritems():
            self._classify(row)
        self.curr = {}

    def _classify(self, row):
        """
        This classifies a hydrogen bond as either T-W, T-T or W-W
        """
        if row is None : return
        self.total += 1
        if (row.acceptor_resnm in ["0GA","1GA"] and row.donor_resnm == "SOL") or \
            (row.donor_resnm in ["0GA","1GA"] and row.acceptor_resnm == "SOL") :
            self.tw += 1
        elif row.acceptor_resnm in ["0GA","1GA"] and row.donor_resnm in ["0GA","1GA"] :
            self.tt += 1
        elif row.acceptor_resnm == "SOL"  and row.donor_resnm == "SOL" :
            self.ww += 1
        else:
            print row.acceptor_resnm , row.donor_resnm

    def _reduce(self, lst):
        if len(lst) == 0 :
            return None
        elif len(lst) == 1 :
            return lst[0]
        else :
            idx = np.argmin([row.distance for row in lst])
            return lst[idx]

    def __str__(self):
        fac = 1.0  / float(self.nsnap)
        #return "\n".join([
        #        "\tT-W:\t%.4f"%(self.tw*fac),
        #        "\tT-T:\t%.4f"%(self.tt*fac),
        #        "\tW-W:\t%.4f"%(self.ww*fac),
        #        "\tTotal:\t%.4f"%(self.total*fac),
        #    ])
        return "\t%9.2f\t%9.2f\t%9.2f\t%9.2f"%(self.tw*fac,self.tt*fac,self.ww*fac,self.total*fac)

if __name__ == '__main__':

    argparser = argparse.ArgumentParser(description="Script analyse hbond db")
    argparser.add_argument('-f', '--file', help="the pickle file", default="hbonds.pickle")
    argparser.add_argument('-n', '--natoms', type=int, help="the total number of atoms")
    argparser.add_argument('-s', '--skip', type=int, help="the number of snapshots to skip")
    args = argparser.parse_args()

    natoms = args.natoms
    p = cPickle.load(open(args.file))

    # Setup count objects for each donor and acceptor atom
    donors = "H2O H3O H4O H6O HW1 HW2".split()
    donors_counts = {d : Counts(natoms) for d in donors}
    acceptors = "O2 O3 O4 O6 OW".split()
    acceptors_counts = {a : Counts(natoms) for a in acceptors}
    lookup = np.zeros((natoms,natoms),dtype=int)
    id = 0
    for i in range(natoms):
        for j in range(natoms):
            lookup[i,j] = id
            id += 1
    pairs = []
    for d in donors :
        for a in acceptors:
            pairs.append(d+"-"+a)
    pairs_counts = {p : Counts(natoms*natoms)  for p in pairs}

    prevtime = None
    nproc = 0
    print "Starting to analyse each row in the database..."
    for row in p:
        if prevtime is not None and prevtime != row.time :
            nproc += 1
            if nproc > args.skip :
                for d in donors:
                    donors_counts[d].update()
                for a in acceptors:
                    acceptors_counts[a].update()
                for p in pairs:
                    pairs_counts[p].update()
        #if row.donor_resid == row.acceptor_resid :
        #    print row
        donors_counts[row.donor_atom].add_row(row.donor_idx-1, row)
        acceptors_counts[row.acceptor_atom].add_row(row.acceptor_idx-1, row)
        id = lookup[row.donor_idx-1,row.acceptor_idx-1]
        pairs_counts[row.donor_atom+"-"+row.acceptor_atom].curr[id] = row
        prevtime = row.time

    for d in donors:
        donors_counts[d].update()
    for a in acceptors:
        acceptors_counts[a].update()
    for p in pairs:
        pairs_counts[p].update()

    print "Analysed %d timestep \n"%(donors_counts[donors[0]].nsnap)
    print "\n%10s%9s%9s%9s%9s"%("","T-W","T-T","W-W","Tot.")
    total_counts = donors_counts[donors[0]]
    print "-- Donors: --"
    print "%10s"%donors[0],
    print donors_counts[donors[0]]
    for d in donors[1:]:
        total_counts += donors_counts[d]
        print "%10s"%d,
        print donors_counts[d]
    print "%10s"%"Total",
    print total_counts

    print "-- Acceptors: --"
    total_counts = acceptors_counts[acceptors[0]]
    print "%10s"%acceptors[0],
    print acceptors_counts[acceptors[0]]
    for a in acceptors[1:]:
        total_counts += acceptors_counts[a]
        print "%10s"%a,
        print acceptors_counts[a]
    print "%10s"%"Total",
    print total_counts

    print "-- Pairs: --"
    total_counts = pairs_counts[pairs[0]]
    print "%10s"%pairs[0],
    print pairs_counts[pairs[0]]
    for p in pairs[1:]:
        total_counts += pairs_counts[p]
        print "%10s"%p,
        print pairs_counts[p]
    print "%10s"%"Total",
    print total_counts


text:
Qambi is a rebuild of [heartbeat](https://abudaan.github.io/heartbeat) in es2016. It is still work in progress and not all functionality has been ported yet. If you need a well-tested sequencer for your project you'd better use heartbeat.

##### Installation

Recommended is to install qambi via npm:

```
$ npm install qambi
```

But you can also add qambi as an AMD module:
```javascript
requirejs.config({
  paths: {
    qambi: 'https://abumarkub.org/qambi/dist/qambi-umd.min'
  }
})

```

Or as a global variable:
```html
  <script src="https://abumarkub.org/qambi/dist/qambi-umd.min.js"></script>
  <script src="https://abumarkub.org/qambi/dist/globals.js"></script>
```
The last script file creates global variables for all qambi modules. This is not mandatory: if you add it you can for instance create a new song with `new Song()`, if you omit it you have to type `new qambi.Song()`.

##### Examples

A simple example that plays back an existing MIDI file:

``` javascript
import qambi from 'qambi'

qambi.init({
    song: {
      type: 'Song',
      url: './midi/minute_waltz.mid'
    },
    piano: {
      type: 'Instrument',
      url: './instruments/heartbeat/city-piano-light.json'
    }
  })
  .then(data => {

    let {song, piano} = data

    song.getTracks().forEach(track => {
      track.setInstrument(piano)
    })

    song.play()
  })

```

Some live examples can be found [here](http://abudaan.github.io/qambi/examples/index.html), more examples in the [examples](https://github.com/abudaan/qambi/tree/gh-pages/examples) folder of the repository. Like qambi itself, all examples are written in es2016 so they need to be compiled to es5 before you can run them in a browser. In the repository I have included the compiled build.js files for all examples so you can run them right away. However, if you want to experiment with the examples you need to compile them before you see your changes. The simplest way to do this is:

 - cd into the examples folder and run `npm install` (only needed the first time)
 - cd into the folder of the example that you want to experiment with and run `npm run watch`

Now the main.js file will be compiled immediately after every edit of the file.

##### Playgrounds

You can try qambi without installation by using the qambi templates on [jsbin](http://jsbin.com/kosuva/edit?js,output) or [codepen](http://codepen.io/abudaan/pen/YqmMbK?editors=0010)

##### Documentation

Documentation is work in progress, see the [wiki](https://github.com/abudaan/qambi/wiki).


text:
"""Test QtGui."""

import sys

import pytest

from qtpy import PYQT5, PYQT_VERSION, PYSIDE2, PYSIDE6, QtGui
from qtpy.tests.utils import not_using_conda

@pytest.mark.skipif(
    sys.platform.startswith('linux') and not_using_conda(),
    reason="Fatal Python error: Aborted on Linux CI when not using conda")
def test_qfontmetrics_width(qtbot):
    """Test QFontMetrics and QFontMetricsF width"""
    assert QtGui.QFontMetrics.width is not None
    assert QtGui.QFontMetricsF.width is not None
    font = QtGui.QFont("times", 24)
    font_metrics = QtGui.QFontMetrics(font)
    font_metricsF = QtGui.QFontMetricsF(font)
    width = font_metrics.width("Test")
    widthF = font_metricsF.width("Test")
    assert width in range(40, 62)
    assert 39 <= widthF <= 63

@pytest.mark.skipif(
    sys.platform.startswith('linux') and not_using_conda(),
    reason="Fatal Python error: Aborted on Linux CI when not using conda")
def test_qdrag_functions(qtbot):
    """Test functions mapping for QtGui.QDrag."""
    assert QtGui.QDrag.exec_ is not None
    drag = QtGui.QDrag(None)
    drag.exec_()

def test_qguiapplication_functions():
    """Test functions mapping for QtGui.QGuiApplication."""
    assert QtGui.QGuiApplication.exec_ is not None

@pytest.mark.skipif(
    sys.platform.startswith('linux') and not_using_conda(),
    reason="Segmentation fault/Aborted on Linux CI when not using conda")
def test_qtextdocument_functions(pdf_writer):
    """Test functions mapping for QtGui.QTextDocument."""
    assert QtGui.QTextDocument.print_ is not None
    text_document = QtGui.QTextDocument("Test")
    print_device, output_path = pdf_writer
    text_document.print_(print_device)
    assert output_path.exists()

@pytest.mark.skipif(PYQT5 and PYQT_VERSION.startswith('5.9'),
                    reason="A specific setup with at least sip 4.9.9 is needed for PyQt5 5.9.*"
                           "to work with scoped enum access")
def test_enum_access():
    """Test scoped and unscoped enum access for qtpy.QtWidgets.*."""
    assert QtGui.QColor.Rgb == QtGui.QColor.Spec.Rgb
    assert QtGui.QFont.AllUppercase == QtGui.QFont.Capitalization.AllUppercase
    assert QtGui.QIcon.Normal == QtGui.QIcon.Mode.Normal
    assert QtGui.QImage.Format_Invalid == QtGui.QImage.Format.Format_Invalid

@pytest.mark.skipif(not (PYSIDE2 or PYSIDE6), reason="PySide{2,6} specific test")
def test_qtextcursor_moveposition():
    """Test monkeypatched QTextCursor.movePosition"""
    doc = QtGui.QTextDocument("foo bar baz")
    cursor = QtGui.QTextCursor(doc)

    assert not cursor.movePosition(QtGui.QTextCursor.Start)
    assert cursor.movePosition(QtGui.QTextCursor.EndOfWord, mode=QtGui.QTextCursor.KeepAnchor)
    assert cursor.selectedText() == "foo"

    assert cursor.movePosition(QtGui.QTextCursor.Start)
    assert cursor.movePosition(QtGui.QTextCursor.WordRight, n=2, mode=QtGui.QTextCursor.KeepAnchor)
    assert cursor.selectedText() == "foo bar "

    assert cursor.movePosition(QtGui.QTextCursor.Start)
    assert cursor.position() == cursor.anchor()
    assert cursor.movePosition(QtGui.QTextCursor.NextWord, QtGui.QTextCursor.KeepAnchor, 3)
    assert cursor.selectedText() == "foo bar baz"


text:
@implementation EFTextField

- initWithCoder:(NSCoder *)coder;
{
    if ( self = [super initWithCoder: coder] ) {
		shouldDrawDisabledText = YES;
	}
    return self;
}

- (void)
setEnabled:(BOOL)yn;
{
	NSColor *color;

	shouldDrawDisabledText = (yn) ? NO : YES;

	if ( shouldDrawDisabledText ) color = [NSColor disabledControlTextColor];
	else color = [NSColor controlTextColor];

	[self setTextColor:color];
}

- (BOOL)
isEnabled;
{
	return ( shouldDrawDisabledText ) ? NO : YES;
}

@end


text:
package com;

import java.sql.*;

import javax.sql.rowset.CachedRowSet;

import com.sun.rowset.CachedRowSetImpl;

public class ConnectionClass {
	private static final String FOR_NAME = "com.mysql.cj.jdbc.Driver";
	private static final String DATABASE = "jdbc:mysql://localhost:3306/dtuclassroom";
	private static final String USER = "root";
	private static final String PWD = "";

	private static ConnectionClass connection;

	private ConnectionClass() {

	}

	public static ConnectionClass getInstance() {
		if (connection == null) {
			connection = new ConnectionClass();
		}
		return connection;
	}

	public ResultSet getResultSet(String query) {
		ResultSet rs = null;
		CachedRowSet rowset = null;
		try {
			Class.forName(FOR_NAME);
			Connection con = DriverManager.getConnection(DATABASE, USER, PWD);
			System.out.println(query);
			Statement st = con.createStatement();
			rs = st.executeQuery(query);
			rowset = new CachedRowSetImpl();
			rowset.populate(rs);
			con.close();
		} catch (Exception e) {
			System.out.println(e);
		}
		return rowset;
	}

	public boolean updateDb(String query) {
		boolean result = false;
		try {
//			Class.forName(FOR_NAME);
			Connection con = DriverManager.getConnection(DATABASE, USER, PWD);
			System.out.println(query);
			Statement st = con.createStatement();
			int x = st.executeUpdate(query);
			if(x > 0) { result = true; }
			con.close();
		} catch (Exception e) {
			System.out.println(e);
		}
		return result;
	}

}


text:
package ru.stqa.kate.addressbook.tests;

import org.testng.Assert;
import org.testng.annotations.Test;
import ru.stqa.kate.addressbook.model.GroupData;

import java.util.List;

public class GroupDeletionTest extends TestBase {

    @Test
    public void testGroupDeletion() {
      app.getNavigationHelper().gotoGroupPage();
      if(!app.getGroupsHelper().isThereAGroup()){
        app.getGroupsHelper().CreateGroup(new GroupData("Test1", null, "Test2"));
      }
      List<GroupData> before = app.getGroupsHelper().getGroupList();
      app.getGroupsHelper().selectGroup(before.size()-1);
      app.getGroupsHelper().deleteselectedGroup();
      app.getGroupsHelper().returnToGroupPage();
      List<GroupData> after = app.getGroupsHelper().getGroupList();
      Assert.assertEquals(after.size(), before.size()-1);

      before.remove(before.size()-1);

        Assert.assertEquals(before, after);

    }

}


text:
package db

import (
	"encoding/json"
	"errors"
	"fmt"
	"strconv"
	"time"

	"github.com/gomodule/redigo/redis"

	"github.com/mundipagg/boleto-api/config"
	"github.com/mundipagg/boleto-api/log"
	"github.com/mundipagg/boleto-api/models"
)

//Redis Classe de Conexão com o Banco REDIS
type Redis struct {
	conn redis.Conn
}

//CreateRedis Cria instancia do Struct Redis
func CreateRedis() *Redis {
	return new(Redis)
}

func (r *Redis) openConnection() error {
	dbID, _ := strconv.Atoi(config.Get().RedisDatabase)
	o := redis.DialDatabase(dbID)
	ps := redis.DialPassword(config.Get().RedisPassword)
	tOut := redis.DialConnectTimeout(15 * time.Second)
	userTLS := redis.DialUseTLS(config.Get().RedisSSL)

	c, err := redis.Dial("tcp", config.Get().RedisURL, o, ps, tOut, userTLS)
	if err != nil {
		return err
	}

	r.conn = c
	return nil
}

func (r *Redis) closeConnection() {
	r.conn.Close()
}

//SetBoletoHTML Grava um boleto em formato Html no Redis
func (r *Redis) SetBoletoHTML(b, mID, pk string, lg *log.Log) {
	err := r.openConnection()
	if err != nil {
		lg.Warn(err.Error(), fmt.Sprintf("OpenConnection [SetBoletoHTML] - Could not connection to Redis Database "))
	} else {

		key := fmt.Sprintf("%s:%s:%s", "boleto:html", mID, pk)
		ret, err := r.conn.Do("SETEX", key, config.Get().RedisExpirationTime, b)

		res := fmt.Sprintf("%s", ret)

		if res != "OK" {
			lg.Warn(res, fmt.Sprintf("SetBoletoHTML [SetBoletoHTML] - Could not record HTML in Redis Database: %s", key))
		} else if err != nil {
			lg.Warn(err.Error(), fmt.Sprintf("Error Redis [SetBoletoHTML] - Could not record HTML in Redis Database: %s", key))
		}

		r.closeConnection()
	}
}

//GetBoletoHTMLByID busca um boleto pelo ID que vem na URL
//O retorno será um objeto HTML do Boleto (caso ainda esteja em cache) e o tempo decorrido da operação (em milisegundos)
func (r *Redis) GetBoletoHTMLByID(id string, pk string, lg *log.Log) (string, int64) {

	start := time.Now()

	err := r.openConnection()

	if err != nil {
		lg.Warn(err.Error(), fmt.Sprintf("OpenConnection [GetBoletoHTMLByID] - Could not connection to Redis Database"))
		return "", time.Since(start).Milliseconds()
	}

	key := fmt.Sprintf("%s:%s:%s", "boleto:html", id, pk)
	ret, err := r.conn.Do("GET", key)
	r.closeConnection()

	// TODO: handle error better than just log and return an empty string
	if err != nil {
		lg.Error(err.Error(), fmt.Sprintf("OpenConnection [GetBoletoHTMLByID] - Error executing redis command %s", err))
		return "", time.Since(start).Milliseconds()
	}

	if ret == nil {
		return "", time.Since(start).Milliseconds()
	}

	return fmt.Sprintf("%s", ret), time.Since(start).Milliseconds()
}

//SetBoletoJSON Grava um boleto em formato JSON no Redis
func (r *Redis) SetBoletoJSON(b, mID, pk string, lg *log.Log) error {
	err := r.openConnection()

	if err != nil {
		lg.Warn(err.Error(), fmt.Sprintf("OpenConnection [SetBoletoJSON] - Could not connection to Redis Database "))
		return err
	}

	key := fmt.Sprintf("%s:%s:%s", "boleto:json", mID, pk)
	ret, err := r.conn.Do("SET", key, b)
	res := fmt.Sprintf("%s", ret)

	r.closeConnection()

	if err != nil {
		lg.Warn(err.Error(), fmt.Sprintf("SetBoletoJSON [SetBoletoJSON] - Could not record JSON in Redis Database: %s", key))
		return err
	}

	if res != "OK" {
		lg.Warn("could not record JSON", fmt.Sprintf("SetBoletoJSON [SetBoletoJSON] - Error could not record JSON in Redis Database: %s", key))
		return errors.New("could not record JSON")
	}

	return nil
}

// GetBoletoJSONByKey Recupera um boleto do tipo JSON do Redis
func (r *Redis) GetBoletoJSONByKey(key string, lg *log.Log) (models.BoletoView, error) {
	err := r.openConnection()

	if err != nil {
		lg.Warn(err.Error(), fmt.Sprintf("OpenConnection [GetBoletoJSONByKey] - Could not connection to Redis Database "))
		return models.BoletoView{}, err
	}

	ret, err := r.conn.Do("GET", key)
	r.closeConnection()

	if err != nil {
		lg.Warn(err.Error(), fmt.Sprintf("GetData [GetBoletoJSONByKey] - Error could not to get data - "+key))
		return models.BoletoView{}, err
	}

	if ret != nil {
		result := models.BoletoView{}
		r := fmt.Sprintf("%s", ret)
		err = json.Unmarshal([]byte(r), &result)

		if err != nil {
			lg.Warn(err.Error(), fmt.Sprintf("Deserialize [GetBoletoJSONByKey] - Could not deserialize json - "+key))
		}

		return result, err
	} else {
		lg.Warn("not found data", fmt.Sprintf("GetData [GetBoletoJSONByKey] - Data not found - "+key))
		return models.BoletoView{}, errors.New("not found data")
	}
}

// DeleteBoletoJSONByKey Deleta um boleto do tipo JSON do Redis
func (r *Redis) DeleteBoletoJSONByKey(key string, lg *log.Log) error {
	err := r.openConnection()

	if err != nil {
		lg.Warn(err.Error(), fmt.Sprintf("OpenConnection [DeleteBoletoJSONByKey] - Could not connection to Redis Database "))
		return err
	} else {
		_, err := r.conn.Do("DEL", key)
		r.closeConnection()

		if err != nil {
			lg.Warn(err.Error(), fmt.Sprintf("Delete data [DeleteBoletoJSONByKey] - Error on delete key: "+key))
			return err
		}
	}

	return nil
}

// GetAllJSON Recupera todas as keys JSON do Redis
func (r *Redis) GetAllJSON(lg *log.Log) ([]string, error) {

	err := r.openConnection()
	if err != nil {
		lg.Warn(err.Error(), fmt.Sprintf("OpenConnection [GetAllJson] - Could not connection to Redis Database "))
		return nil, err
	}

	var keys []string

	arr, err := redis.Values(r.conn.Do("SCAN", 0, "MATCH", "boleto:json:*", "COUNT", 500))
	if err != nil {
		lg.Warn(err.Error(), fmt.Sprintf("ReadDb [GetAllJson] - Could not get all json from database"))
		return nil, err
	}

	keys, err = redis.Strings(arr[1], nil)

	r.closeConnection()

	if err != nil {
		lg.Warn(err.Error(), fmt.Sprintf("Stringify Keys [GetAllJson] - Error when setting keys in the array"))
		return nil, err
	}

	return keys, nil

}