text:
// 04.Implement the data structure "hash table" in a class HashTable<K,T>.
//    Keep the data in array of lists of key-value pairs (LinkedList<KeyValuePair<K,T>>[]) with
//    initial capacity of 16. When the hash table load runs over 75%, perform resizing to 2 times larger capacity.
//    Implement the following methods and properties:
//      Add(key, value), Find(key)value, Remove( key), Count, Clear(), this[], Keys.
//    Try to make the hash table to support iterating over its elements with foreach.

namespace _04.HashTable
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    public class HashTable<K, T> : IEnumerable<KeyValuePair<K, T>>
    {
        private LinkedList<KeyValuePair<K, T>>[] data;
        private List<K> dataPositions;
        private int count = 0;

        public HashTable()
        {
            this.data = new LinkedList<KeyValuePair<K, T>>[16];
            this.dataPositions = new List<K>();
        }

        public int Count
        {
            get { return this.count; }

            private set { this.count = value; }
        }

        public int Capacity
        {
            get { return this.data.Length; }
        }

        public IList<K> Keys
        {
            get
            {
                IList<K> keys = new List<K>();

                for (int i = 0; i < this.Count; i++)
                {
                    var pairs = this.data[i];

                    foreach (var pair in pairs)
                    {
                        keys.Add(pair.Key);
                    }
                }

                return keys;
            }
        }

        public T this[K key]
        {
            get
            {
                T elementValue = this.Find(key);

                return elementValue;
            }

            set
            {
                this.CheckAndResize();

                int index = this.MyHashCode(key, this.data.Length);

                if (this.data[index] == null)
                {
                    this.data[index] = new LinkedList<KeyValuePair<K, T>>();
                    this.dataPositions.Add(key);
                }

                bool doesKeyExist = this.data[index].Any(x => x.Key.Equals(key));
                if (doesKeyExist)
                {
                    var item = this.GetElement(key);
                    this.data[index].Remove(item);

                    this.Count--;
                }

                var toAdd = new KeyValuePair<K, T>(key, value);
                this.data[index].AddLast(new KeyValuePair<K, T>(key, value));

                this.Count++;
            }
        }

        public void Add(K key, T value)
        {
            this.CheckAndResize();

            int length = this.data.Length;
            int index = this.MyHashCode(key, this.data.Length);

            if (this.data[index] == null)
            {
                this.data[index] = new LinkedList<KeyValuePair<K, T>>();
                this.dataPositions.Add(key);
            }

            bool doesKeyExist = this.data[index].Any(x => x.Key.Equals(key));
            if (doesKeyExist)
            {
                throw new ArgumentException("Key: " + key + " exist!");
            }

            this.data[index].AddLast(new KeyValuePair<K, T>(key, value));

            this.Count++;
        }

        public T Find(K key)
        {
            int index = this.MyHashCode(key, this.data.Length);

            if (this.data[index] == null)
            {
                throw new ArgumentException("Key: " + key + " do NOT exist!");
            }

            var searchedItem = this.GetElement(key);

            return searchedItem.Value;
        }

        public void Remove(K key)
        {
            var index = this.MyHashCode(key, this.data.Length);
            var itemToRemove = this.GetElement(key);

            this.data[index].Remove(itemToRemove);

            if (this.data[index] == null)
            {
                this.dataPositions.Remove(key);
            }

            this.Count--;
        }

        public void Clear()
        {
            this.data = new LinkedList<KeyValuePair<K, T>>[16];
            this.dataPositions = new List<K>();
            this.Count = 0;
        }

        public IEnumerator<KeyValuePair<K, T>> GetEnumerator()
        {
            for (int i = 0; i < this.data.Length; i++)
            {
                if (this.data[i] != null)
                {
                    var next = this.data[i].First;
                    while (next != null)
                    {
                        yield return next.Value;
                        next = next.Next;
                    }
                }
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        private void CheckAndResize()
        {
            int length = this.data.Length * 2;

            if (this.Count >= this.data.Length * 0.75)
            {
                var resizedData = new LinkedList<KeyValuePair<K, T>>[length];

                int oldDataLength = this.data.Length;
                int newDataLength = resizedData.Length;

                foreach (var key in this.dataPositions)
                {
                    int oldIndex = this.MyHashCode(key, oldDataLength);
                    int newIndex = this.MyHashCode(key, newDataLength);

                    resizedData[newIndex] = this.data[oldIndex];
                }

                this.data = resizedData;
            }
        }

        private int MyHashCode(K key, int length)
        {
            return Math.Abs(key.GetHashCode() % length);
        }

        private KeyValuePair<K, T> GetElement(K key)
        {
            int index = this.MyHashCode(key, this.data.Length);

            if (this.data[index] == null)
            {
                throw new ArgumentException("Key: " + key + " do NOT exist!");
            }

            var searchedItem = this.data[index].First(x => x.Key.Equals(key));

            return searchedItem;
        }
    }
}


text:
package fr.letroll.ttorrentandroid.bcodec;

import org.apache.commons.io.IOUtils;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

/**
 *
 * @author shevek
 */
public class StreamBDecoder extends AbstractBDecoder {

    private final InputStream in;

    public StreamBDecoder(InputStream in) {
        this.in = in;
    }

    @Override
    protected byte readByte() throws IOException {
        int value = in.read();
        if (value == -1)
            throw new EOFException();
        return (byte) value;
    }

    @Override
    protected byte[] readBytes(int length) throws IOException {
        byte[] bytes = new byte[length];
        IOUtils.readFully(in, bytes);
        return bytes;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.waynechin</groupId>
    <artifactId>spring-cloud-simple</artifactId>
    <version>1.0-SNAPSHOT</version>
	<packaging>pom</packaging>
    <modules>
        <module>spring-cloud-config-server</module>
        <module>spring-cloud-config-client</module>
        <module>spring-cloud-eureka-server</module>
        <module>spring-cloud-eureka-client</module>
        <module>spring-cloud-eureka-consumer</module>
        <module>spring-cloud-eureka-consumer-hystrix</module>
        <module>spring-cloud-zuul</module>

    </modules>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!--监控-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--服务注册-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


text:
var express = require('express');
var app = express();

//CORS middleware
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    next();
}

app.use(allowCrossDomain);

app.get('/authorization', function(req, res){
  var redirectTo = req.query.redirect_uri + '?state=' + req.query.state + '&code=authcode1234';
  console.log('Redirecting to '+ redirectTo);
  res.redirect(redirectTo);
});

app.post('/token', function(req, res){
  console.log('Token Post Recieved');
  res.json({refresh_token: 'refresh_token_response'});
});

function run(port){
  var port = process.env.OAUTH_REDIRECT_PORT || 5000;
  console.log('Statring server on: '  + port);
  app.listen(port);
}

run();


text:
<?xml version="1.0" encoding="utf-8"?>
<labels>
	Дата
	Время
	ч
	Январь
	Февраль
	Март
	Апрель
	Май
	Июнь
	Июль
	Август
	Септябрь
	Октябрь
	Ноябрь
	Декабрь
	Понедельник
	Вторник
	Среда
	Четверг
	Пятница
	Суббота
	Воскресенье
	Пн
	Вт
	Ср
	Чт
	Пт
	Сб
	Вс
	Секунда
	Секунды
	Минута
	Минуты
	Час
	Часы
	День
	Дни
	Неделя
	Недели
	Месяц
	Месяцы
	Год
	Год
	Календарная неделя
	Неделя
	Ежедневно
	Еженедельно
	Ежемесячно
	Каждый год
	Сегодня
	Обнаружена неправильная дата (будет изменена при сохранении).
	Сегодня
	Завтра
	Послезавтра
	Вчера
	Позавчера
	Эта неделя
	Следующая неделя
	Предыдущая неделя
</labels>


text:
package labs.codesynced.autoque.visualizer;

/**
 * @author Wylan Shoemaker - 9/16/2016
 */
public class WaveForm
{

	public WaveForm(final String ID, EnumWaveFormType enumWaveFormType)
	{

	}

}


text:
@interface InAppMsgUIManager : NSObject<InAppMsgInteractionListener>

-(void) sendToQueue:(NSString*) iamId;
-(InAppMsgViewSettings*) viewSettings;

@end


text:
package edu.common.dynamicextensions.domaininterface;

/**
 * This is a primitive attribute of type date.
 * @author geetika_bangard
 */
public interface DateTypeInformationInterface extends AttributeTypeInformationInterface
{

    /**
     * Date format for the date.The user input date will be validated against this format.
     * @return Returns the format.
     */
    String getFormat();
    /**
     * @param format The format to set.
     */
    void setFormat(String format);

}


text:
define('test-app/initializers/app-version', ['exports', 'test-app/config/environment', 'ember'], function (exports, config, Ember) {

  'use strict';

  var classify = Ember['default'].String.classify;
  var registered = false;

  exports['default'] = {
    name: 'App Version',
    initialize: function initialize(container, application) {
      if (!registered) {
        var appName = classify(application.toString());
        Ember['default'].libraries.register(appName, config['default'].APP.version);
        registered = true;
      }
    }
  };

});


text:
name="$1"

notify-send $name "is entering the cubicle"

if [ "$name" = "scott" ]; then
    xdotool key alt+w
    xdotool key alt+4
    xdotool key alt+e
    xdotool key alt+5
fi


text:
class AdmisionPipeline(object):
    def process_item(self, item, spider):
        return item


text:
\hypertarget{structtesting_1_1internal_1_1_any_of_result4}{}\section{testing\+:\+:internal\+:\+:Any\+Of\+Result4$<$ M1, M2, M3, M4 $>$ Struct Template Reference}
\label{structtesting_1_1internal_1_1_any_of_result4}\index{testing\+::internal\+::\+Any\+Of\+Result4$<$ M1, M2, M3, M4 $>$@{testing\+::internal\+::\+Any\+Of\+Result4$<$ M1, M2, M3, M4 $>$}}

{\ttfamily \#include $<$gmock-\/generated-\/matchers.\+h$>$}

\subsection*{Public Types}
\begin{DoxyCompactItemize}
\item
typedef \hyperlink{classtesting_1_1internal_1_1_either_of_matcher}{Either\+Of\+Matcher}$<$ typename \hyperlink{structtesting_1_1internal_1_1_any_of_result2}{Any\+Of\+Result2}$<$ M1, M2 $>$\+::\hyperlink{structtesting_1_1internal_1_1_any_of_result4_a4f3c9aebb4f7fc24287b59a0bdf1a4a6}{type}, typename \hyperlink{structtesting_1_1internal_1_1_any_of_result2}{Any\+Of\+Result2}$<$ M3, M4 $>$\+::\hyperlink{structtesting_1_1internal_1_1_any_of_result4_a4f3c9aebb4f7fc24287b59a0bdf1a4a6}{type} $>$ \hyperlink{structtesting_1_1internal_1_1_any_of_result4_a4f3c9aebb4f7fc24287b59a0bdf1a4a6}{type}
\end{DoxyCompactItemize}

\subsection{Detailed Description}
\subsubsection*{template$<$typename M1, typename M2, typename M3, typename M4$>$\\*
struct testing\+::internal\+::\+Any\+Of\+Result4$<$ M1, M2, M3, M4 $>$}

Definition at line 414 of file gmock-\/generated-\/matchers.\+h.

\subsection{Member Typedef Documentation}
\index{testing\+::internal\+::\+Any\+Of\+Result4@{testing\+::internal\+::\+Any\+Of\+Result4}!type@{type}}
\index{type@{type}!testing\+::internal\+::\+Any\+Of\+Result4@{testing\+::internal\+::\+Any\+Of\+Result4}}
\subsubsection[{\texorpdfstring{type}{type}}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename M1, typename M2, typename M3, typename M4$>$ typedef {\bf Either\+Of\+Matcher}$<$ typename {\bf Any\+Of\+Result2}$<$M1, M2$>$\+::{\bf type}, typename {\bf Any\+Of\+Result2}$<$M3, M4$>$\+::{\bf type} $>$ {\bf testing\+::internal\+::\+Any\+Of\+Result4}$<$ M1, M2, M3, M4 $>$\+::{\bf type}}\hypertarget{structtesting_1_1internal_1_1_any_of_result4_a4f3c9aebb4f7fc24287b59a0bdf1a4a6}{}\label{structtesting_1_1internal_1_1_any_of_result4_a4f3c9aebb4f7fc24287b59a0bdf1a4a6}

Definition at line 418 of file gmock-\/generated-\/matchers.\+h.

The documentation for this struct was generated from the following file\+:\begin{DoxyCompactItemize}
\item
/home/bhargavi/\+Documents/\+S\+D\+R/\+Copy\+\_\+\+Exam\+\_\+808\+X/vendor/googletest/googlemock/include/gmock/\hyperlink{gmock-generated-matchers_8h}{gmock-\/generated-\/matchers.\+h}\end{DoxyCompactItemize}


text:
return function(code)
    -- Brainfuck language consists of 8 instructions "><+-.,[]", everything else can be removed
    local brainfuck = "[^><%+%-%.,%[%]]+"

    -- Data tape consists of "infinite" amount of cells
    local data = setmetatable({}, {__index = function() return 0 end})

    -- Data pointer begins at position 1
    local dataPointer = 1

    -- Instruction pointer begins at position 1
    local instructionPointer = 1

    -- Remove everything from the code except for the 8 instructions defined above
    code = code:gsub(brainfuck, "")

    -- Implementation of the 8 instructions starts below
    while instructionPointer <= #code do
        local instruction = code:sub(instructionPointer,instructionPointer)

        if instruction == ">" then
            dataPointer = dataPointer + 1
        elseif instruction == "<" then
            dataPointer = dataPointer - 1
        elseif instruction == "+" then
            data[dataPointer] = data[dataPointer] + 1
        elseif instruction == "-" then
            data[dataPointer] = data[dataPointer] - 1
        elseif instruction == "." then
            io.write(string.char(data[dataPointer]))
        elseif instruction == "," then
            local character = io.read(1)
            if character ~= nil then data[dataPointer] = character:byte() end
        elseif instruction == "[" then
            if data[dataPointer] == 0 then
                local i = 1
                while i ~= 0 do
                    instructionPointer = instructionPointer + 1
                    local _instruction = code:sub(instructionPointer, instructionPointer)
                    if _instruction == "[" then i = i + 1 elseif _instruction == "]" then i = i - 1 end
                end
            end
        elseif instruction == "]" then
            if data[dataPointer] ~= 0 then
                local i = 1
                while i ~= 0 do
                    instructionPointer = instructionPointer - 1
                    local _instruction = code:sub(instructionPointer, instructionPointer)
                    if _instruction == "]" then i = i + 1 elseif _instruction == "[" then i = i - 1 end
                end
            end
        end

        instructionPointer = instructionPointer + 1
    end
end


text:
#pragma once
#ifndef __ENGINE_ABSTRACTPOOLABLEINSTANTIATOR_H__
#define __ENGINE_ABSTRACTPOOLABLEINSTANTIATOR_H__

#include "memory/abstract/abstractTInstantiator.h"

/// @addtogroup Instantiators
/// @{

/**
 * A pool instantiator type, that should be used by pools since it defines
 * how objects should be created, initialised, deleted and released.
 *
 *
 * @tParam tBase    The type of the base class the instantiated type
 *                  should derive from.
 *
 * @sa  AbstractTInstantiator<tT>
 */

template< typename tBase >
class AbstractPoolableInstantiator
    : public AbstractTInstantiator< tBase >
{
public:

    /// @name Deletion
    /// @{

    /**
     * Destroys the object, by releasing the memory.
     *
     * @param [in,out]  object  The object.
     */

    virtual void Destroy(tBase *object) = 0;

    /// @}

    /// @name Initialisation
    /// @{

    /**
     * Initialises the object.
     *
     * @param [in,out]  object  The object.
     */

    virtual void Initialise(tBase *const object) = 0;

    /// @}

    /// @name Releasing
    /// @{

    /**
     * Releases the object.
     *
     * @param [in,out]  object  The object.
     */

    virtual void Release(tBase *const object) = 0;

    /// @}

};

/// @}

#endif


text:
status: publish
tags:
- oregon
- photo
- websights
published: true
title: Multnomah Falls
type: post
meta:
  aktt_tweeted: "1"
  _edit_last: "2"
  aktt_notify_twitter: "yes"
layout: post
---
Browsing through the Oregon State University Archives on Flickr, I found this cool 1940 photo of Multnomah Falls, by the Columbia River Gorge in Oregon:

Click on the picture to see a larger version.

I totally dig the old American cars, and the overall "family day trip" vibe. Also, I just love the color of this Kodachrome color picture.

The falls, by the way, were still as gorgeous as they are in this picture when I went there 65 years later.


text:
package org.apache.cassandra.config;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.apache.cassandra.config.CassandraRelevantProperties.ALLOW_DUPLICATE_CONFIG_KEYS;
import static org.apache.cassandra.config.CassandraRelevantProperties.ALLOW_NEW_OLD_CONFIG_KEYS;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public class FailStartupDuplicateParamsTest
{
    private static final List<String> baseConfig = ImmutableList.of(
        "cluster_name: Test Cluster",
        "commitlog_sync: batch",
        "commitlog_directory: build/test/cassandra/commitlog",
        "hints_directory: build/test/cassandra/hints",
        "partitioner: org.apache.cassandra.dht.ByteOrderedPartitioner",
        "saved_caches_directory: build/test/cassandra/saved_caches",
        "data_file_directories:",
        "   - build/test/cassandra/data",
        "seed_provider:" ,
        "   - class_name: org.apache.cassandra.locator.SimpleSeedProvider",
        "parameters:",
        "   - seeds: \"127.0.0.1:7012\"",
        "endpoint_snitch: org.apache.cassandra.locator.SimpleSnitch");

    @Before
    public void before()
    {
        ALLOW_DUPLICATE_CONFIG_KEYS.setBoolean(true);
        ALLOW_NEW_OLD_CONFIG_KEYS.setBoolean(false);
    }

    @Test
    public void testDuplicateParamThrows() throws IOException
    {
        ALLOW_DUPLICATE_CONFIG_KEYS.setBoolean(false);
        testYaml("found duplicate key endpoint_snitch", true,
                 "endpoint_snitch: org.apache.cassandra.locator.RackInferringSnitch");
    }

    @Test
    public void testReplacementDupesOldFirst() throws IOException
    {
        testYaml("[enable_user_defined_functions -> user_defined_functions_enabled]", true,
                 "enable_user_defined_functions: true",
                 "user_defined_functions_enabled: false");

        testYaml("[enable_user_defined_functions -> user_defined_functions_enabled]", true,
                 "enable_user_defined_functions: true",
                 "user_defined_functions_enabled: true");
    }

    @Test
    public void testReplacementDupesNewFirst() throws IOException
    {
        testYaml("[enable_user_defined_functions -> user_defined_functions_enabled]", true,
                 "user_defined_functions_enabled: false",
                 "enable_user_defined_functions: true");

    }

    @Test
    public void testReplacementDupesMultiReplace() throws IOException
    {
        /*
        @Replaces(oldName = "internode_socket_send_buffer_size_in_bytes", converter = Converters.BYTES_DATASTORAGE, deprecated = true)
        @Replaces(oldName = "internode_send_buff_size_in_bytes", converter = Converters.BYTES_DATASTORAGE, deprecated = true)
        public DataStorageSpec internode_socket_send_buffer_size = new DataStorageSpec("0B");
        */
        Predicate<String> predicate = (s) -> s.contains("[internode_send_buff_size_in_bytes -> internode_socket_send_buffer_size]") &&
                                             s.contains("[internode_socket_send_buffer_size_in_bytes -> internode_socket_send_buffer_size]");
        String message = " does not contain both [internode_send_buff_size_in_bytes] and [internode_socket_send_buffer_size_in_bytes]";

        testYaml(predicate, true,
                 message,
                 "internode_send_buff_size_in_bytes: 3",
                 "internode_socket_send_buffer_size_in_bytes: 2",
                 "internode_socket_send_buffer_size: 5B");

        // and new first:
        testYaml(predicate, true,
                 message,
                 "internode_socket_send_buffer_size: 5B",
                 "internode_socket_send_buffer_size_in_bytes: 2",
                 "internode_send_buff_size_in_bytes: 3");
    }

    private static void testYaml(String expected, boolean expectFailure, String ... toAdd) throws IOException
    {
        testYaml((s) -> s.contains(expected), expectFailure, "does not contain [" + expected + ']', toAdd);
    }

    private static void testYaml(Predicate<String> exceptionMsgPredicate, boolean expectFailure, String message, String ... toAdd) throws IOException
    {
        Path p = Files.createTempFile("config_dupes",".yaml");
        try
        {
            List<String> lines = new ArrayList<>(baseConfig);
            Collections.addAll(lines, toAdd);
            Files.write(p, lines);
            loadConfig(p.toUri().toURL(), message, exceptionMsgPredicate, expectFailure);
        }
        finally
        {
            Files.delete(p);
        }
    }

    private static void loadConfig(URL config, String message, Predicate<String> exceptionMsgPredicate, boolean expectFailure)
    {
        try
        {
            new YamlConfigurationLoader().loadConfig(config);
        }
        catch (Exception e)
        {
            assertTrue(expectFailure);
            e.printStackTrace(System.out);
            Throwable t = e;
            do
            {
                if (exceptionMsgPredicate.test(t.getMessage()))
                    return;
                t = t.getCause();
            } while (t != null);

            fail("Message\n["+e.getMessage()+ "]\n"+message);
        }
        assertFalse(expectFailure);
    }
}


text:
[React Starter kit](https://github.com/wbkd/react-starterkit) is used for generating the repo.
This [Ui](http://material-ui.com/#/home) frame work is used.

## To Run

```
$ git clone https://github.com/sandyjoshi/react_simple.git && cd react_simple
```

## Installation

Install all dependencies.

```
$ npm install
```

## Development

Builds the application and starts a webserver with livereload. By default the webserver starts at port 1337.
You can define a port with `$ gulp --port 3333`.

```
$ npm start
```

## Build

Builds a minified version of the application in the dist folder.

```
$ gulp build --type production
```

## Testing

We use [Mocha](https://mochajs.org/) to test our application.

You can run the tests that are defined under [test](./test) with

```
$ mocha --compilers js:babel-core/register

```

## Javascript

Javascript entry file: `app/scripts/main.js`


text:
package plugins.pushbullet.api.entity;

import lombok.Value;

import java.util.List;

@Value
public class Pushes {
    List<PushResult> pushes;
}


text:
mkdir /home/vagrant/.ssh
chown vagrant:vagrant /home/vagrant/.ssh
chmod 0700 /home/vagrant/.ssh


text:
<?php
namespace Chamilo\Core\Repository\ContentObject\Indicator\Package;

use Chamilo\Core\Repository\Common\Action\ContentObjectDeactivator;

class Deactivator extends ContentObjectDeactivator
{
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Akad. Nauk Estonskoi S. S. R. , Inst. Zool. Bot. , Tartu 41 (1970)

#### Original name
Lachnea acutipila P. Karst.

### Remarks
null


text:
package org.kaaproject.kaa.server.common.dao;

import static org.apache.commons.lang.StringUtils.isBlank;
import static org.apache.commons.lang.StringUtils.isNotBlank;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemAlreadyExistsException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import javax.sql.DataSource;

import org.junit.Assert;
import org.kaaproject.kaa.common.dto.ApplicationDto;
import org.kaaproject.kaa.common.dto.ChangeConfigurationNotification;
import org.kaaproject.kaa.common.dto.ChangeProfileFilterNotification;
import org.kaaproject.kaa.common.dto.ConfigurationDto;
import org.kaaproject.kaa.common.dto.ConfigurationSchemaDto;
import org.kaaproject.kaa.common.dto.EndpointGroupDto;
import org.kaaproject.kaa.common.dto.EndpointGroupStateDto;
import org.kaaproject.kaa.common.dto.EndpointNotificationDto;
import org.kaaproject.kaa.common.dto.EndpointProfileDto;
import org.kaaproject.kaa.common.dto.EndpointProfileSchemaDto;
import org.kaaproject.kaa.common.dto.EndpointUserConfigurationDto;
import org.kaaproject.kaa.common.dto.EndpointUserDto;
import org.kaaproject.kaa.common.dto.HasId;
import org.kaaproject.kaa.common.dto.KaaAuthorityDto;
import org.kaaproject.kaa.common.dto.NotificationDto;
import org.kaaproject.kaa.common.dto.NotificationSchemaDto;
import org.kaaproject.kaa.common.dto.NotificationTypeDto;
import org.kaaproject.kaa.common.dto.ProfileFilterDto;
import org.kaaproject.kaa.common.dto.ServerProfileSchemaDto;
import org.kaaproject.kaa.common.dto.TenantAdminDto;
import org.kaaproject.kaa.common.dto.TenantDto;
import org.kaaproject.kaa.common.dto.TopicDto;
import org.kaaproject.kaa.common.dto.TopicTypeDto;
import org.kaaproject.kaa.common.dto.UpdateNotificationDto;
import org.kaaproject.kaa.common.dto.UserDto;
import org.kaaproject.kaa.common.dto.ctl.CTLSchemaDto;
import org.kaaproject.kaa.common.dto.ctl.CTLSchemaMetaInfoDto;
import org.kaaproject.kaa.common.dto.logs.LogAppenderDto;
import org.kaaproject.kaa.common.dto.logs.LogHeaderStructureDto;
import org.kaaproject.kaa.common.dto.logs.LogSchemaDto;
import org.kaaproject.kaa.common.dto.user.UserVerifierDto;
import org.kaaproject.kaa.server.common.core.algorithms.generation.DefaultRecordGenerationAlgorithmImpl;
import org.kaaproject.kaa.server.common.core.configuration.BaseDataFactory;
import org.kaaproject.kaa.server.common.core.configuration.OverrideDataFactory;
import org.kaaproject.kaa.server.common.core.schema.BaseSchema;
import org.kaaproject.kaa.server.common.core.schema.KaaSchema;
import org.kaaproject.kaa.server.common.core.schema.KaaSchemaFactoryImpl;
import org.kaaproject.kaa.server.common.core.schema.OverrideSchema;
import org.kaaproject.kaa.server.common.dao.impl.ApplicationDao;
import org.kaaproject.kaa.server.common.dao.impl.ApplicationEventFamilyMapDao;
import org.kaaproject.kaa.server.common.dao.impl.CTLSchemaDao;
import org.kaaproject.kaa.server.common.dao.impl.CTLSchemaMetaInfoDao;
import org.kaaproject.kaa.server.common.dao.impl.ConfigurationDao;
import org.kaaproject.kaa.server.common.dao.impl.ConfigurationSchemaDao;
import org.kaaproject.kaa.server.common.dao.impl.EndpointGroupDao;
import org.kaaproject.kaa.server.common.dao.impl.EventClassDao;
import org.kaaproject.kaa.server.common.dao.impl.EventClassFamilyDao;
import org.kaaproject.kaa.server.common.dao.impl.HistoryDao;
import org.kaaproject.kaa.server.common.dao.impl.LogAppenderDao;
import org.kaaproject.kaa.server.common.dao.impl.LogSchemaDao;
import org.kaaproject.kaa.server.common.dao.impl.NotificationDao;
import org.kaaproject.kaa.server.common.dao.impl.NotificationSchemaDao;
import org.kaaproject.kaa.server.common.dao.impl.ProfileFilterDao;
import org.kaaproject.kaa.server.common.dao.impl.ProfileSchemaDao;
import org.kaaproject.kaa.server.common.dao.impl.SdkProfileDao;
import org.kaaproject.kaa.server.common.dao.impl.ServerProfileSchemaDao;
import org.kaaproject.kaa.server.common.dao.impl.TenantDao;
import org.kaaproject.kaa.server.common.dao.impl.TopicDao;
import org.kaaproject.kaa.server.common.dao.impl.UserDao;
import org.kaaproject.kaa.server.common.dao.impl.UserVerifierDao;
import org.kaaproject.kaa.server.common.dao.impl.sql.H2DBTestRunner;
import org.kaaproject.kaa.server.common.dao.impl.sql.PostgreDBTestRunner;
import org.kaaproject.kaa.server.common.dao.model.Notification;
import org.kaaproject.kaa.server.common.dao.model.sql.Application;
import org.kaaproject.kaa.server.common.dao.model.sql.ApplicationEventFamilyMap;
import org.kaaproject.kaa.server.common.dao.model.sql.CTLSchema;
import org.kaaproject.kaa.server.common.dao.model.sql.CTLSchemaMetaInfo;
import org.kaaproject.kaa.server.common.dao.model.sql.Configuration;
import org.kaaproject.kaa.server.common.dao.model.sql.ConfigurationSchema;
import org.kaaproject.kaa.server.common.dao.model.sql.EndpointGroup;
import org.kaaproject.kaa.server.common.dao.model.sql.EndpointProfileSchema;
import org.kaaproject.kaa.server.common.dao.model.sql.EventClass;
import org.kaaproject.kaa.server.common.dao.model.sql.EventClassFamily;
import org.kaaproject.kaa.server.common.dao.model.sql.GenericModel;
import org.kaaproject.kaa.server.common.dao.model.sql.History;
import org.kaaproject.kaa.server.common.dao.model.sql.LogAppender;
import org.kaaproject.kaa.server.common.dao.model.sql.LogSchema;
import org.kaaproject.kaa.server.common.dao.model.sql.NotificationSchema;
import org.kaaproject.kaa.server.common.dao.model.sql.ProfileFilter;
import org.kaaproject.kaa.server.common.dao.model.sql.SdkProfile;
import org.kaaproject.kaa.server.common.dao.model.sql.ServerProfileSchema;
import org.kaaproject.kaa.server.common.dao.model.sql.Tenant;
import org.kaaproject.kaa.server.common.dao.model.sql.Topic;
import org.kaaproject.kaa.server.common.dao.model.sql.User;
import org.kaaproject.kaa.server.common.dao.model.sql.UserVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;

@ActiveProfiles({"h2"})
public class AbstractTest {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractTest.class);

    protected static final Random RANDOM = new Random(0);
    protected static final String SUPER_TENANT = "SuperTenant";

    protected static final String TENANT_NAME = "Generated Test Tenant";
    protected static final String USER_NAME = "Generated Test Username";
    protected static final String TOPIC_NAME = "Generated Topic Name";
    protected static final String NOTIFICATION_SCHEMA_NAME = "Generated Notification Schema Name";
    protected static final String ENDPOINT_USER_EXTERNAL_ID = "Generated Test Endpoint User External Id";
    protected static final String ENDPOINT_USER_NAME = "Generated Test Endpoint User Name";
    public static final String DEFAULT_FQN = "org.kaaproject.kaa.ctl.TestSchema";

    @Autowired
    protected DataSource dataSource;
    @Autowired
    protected LogSchemaService logSchemaService;
    @Autowired
    protected ApplicationService applicationService;
    @Autowired
    protected TopicService topicService;
    @Autowired
    protected UserService userService;
    @Autowired
    protected UserVerifierService verifierService;
    @Autowired
    protected UserConfigurationService userConfigurationService;
    @Autowired
    protected EndpointService endpointService;
    @Autowired
    protected HistoryService historyService;
    @Autowired
    protected ProfileService profileService;
    @Autowired
    protected ConfigurationService configurationService;
    @Autowired
    protected NotificationService notificationService;
    @Autowired
    protected LogAppendersService logAppendersService;
    @Autowired
    protected CTLService ctlService;
    @Autowired
    protected ServerProfileService serverProfileService;

    @Autowired
    protected LogAppenderDao<LogAppender> appenderDao;
    @Autowired
    protected UserDao<User> userDao;
    @Autowired
    protected TenantDao<Tenant> tenantDao;
    @Autowired
    protected ApplicationDao<Application> applicationDao;
    @Autowired
    protected EndpointGroupDao<EndpointGroup> endpointGroupDao;
    @Autowired
    protected ConfigurationSchemaDao<ConfigurationSchema> configurationSchemaDao;
    @Autowired
    protected ConfigurationDao<Configuration> configurationDao;
    @Autowired
    protected ProfileSchemaDao<EndpointProfileSchema> profileSchemaDao;
    @Autowired
    protected ProfileFilterDao<ProfileFilter> profileFilterDao;
    @Autowired
    protected TopicDao<Topic> topicDao;
    @Autowired
    protected HistoryDao<History> historyDao;
    @Autowired
    protected EventClassFamilyDao<EventClassFamily> eventClassFamilyDao;
    @Autowired
    protected EventClassDao<EventClass> eventClassDao;
    @Autowired
    protected ApplicationEventFamilyMapDao<ApplicationEventFamilyMap> applicationEventFamilyMapDao;
    @Autowired
    protected LogSchemaDao<LogSchema> logSchemaDao;
    @Autowired
    protected NotificationSchemaDao<NotificationSchema> notificationSchemaDao;
    @Autowired(required = false)
    protected NotificationDao<Notification> notificationDao;
    @Autowired
    protected UserVerifierDao<UserVerifier> verifierDao;
    @Autowired
    protected SdkProfileDao<SdkProfile> sdkProfileDao;
    @Autowired
    protected CTLSchemaDao<CTLSchema> ctlSchemaDao;
    @Autowired
    protected CTLSchemaMetaInfoDao<CTLSchemaMetaInfo> ctlSchemaMetaInfoDao;
    @Autowired
    protected ServerProfileSchemaDao<ServerProfileSchema> serverProfileSchemaDao;

    protected Application application;

    public AbstractTest() {
    }

    protected String generateString(String string) {
        return string + "_" + UUID.randomUUID().toString();
    }

    protected void clearDBData() {
        try {
            String url;
            try (Connection connection = dataSource.getConnection()) {
                url = connection.getMetaData().getURL();
            }
            if (url.contains("h2")) {
                LOG.info("Deleting data from H2 database");
                new H2DBTestRunner().truncateTables(dataSource);
            } else {
                LOG.info("Deleting data from PostgreSQL database");
                new PostgreDBTestRunner().truncateTables(dataSource);
            }
        } catch (SQLException ex) {
            LOG.error("Can't delete data from databases.", ex);
        }
    }

    protected String readSchemaFileAsString(String filePath) throws IOException {
        try {
            URI uri = this.getClass().getClassLoader().getResource(filePath).toURI();
            String[] array = uri.toString().split("!");
            Path path;
            if (array.length > 1) {
                LOG.info("Creating fs for {}", array[0]);
                FileSystem fs;
                try {
                    fs = FileSystems.newFileSystem(URI.create(array[0]), new HashMap<String, String>());
                } catch (FileSystemAlreadyExistsException e) {
                    fs = FileSystems.getFileSystem(URI.create(array[0]));
                }
                path = fs.getPath(array[1]);
            } else {
                path = Paths.get(uri);
            }
            return new String(Files.readAllBytes(path));
        } catch (URISyntaxException e) {
            LOG.error("Can't generate configs {}", e);
        }
        return null;
    }

    protected ApplicationDto generateApplicationDto() {
        return generateApplicationDto(null);
    }

    protected ApplicationDto generateApplicationDto(String tenantId) {
        return generateApplicationDto(tenantId, null);
    }

    protected ApplicationDto generateApplicationDto(String tenantId, String appName) {
        ApplicationDto app = new ApplicationDto();
        if (isBlank(tenantId)) {
            app.setTenantId(generateTenantDto().getId());
        } else {
            app.setTenantId(tenantId);
        }
        if (!isBlank(appName)) {
            app.setName(appName);
        } else {
            app.setName("Test app");
        }
        return applicationService.saveApp(app);
    }

    protected EndpointGroupDto generateEndpointGroupDto(String appId) {
        return generateEndpointGroupDto(appId, generateString("GROUP_ALL"));
    }

    protected EndpointGroupDto generateEndpointGroupDto(String appId, String endpointGroupName) {
        EndpointGroupDto group = new EndpointGroupDto();
        if (isBlank(appId)) {
            appId = generateApplicationDto(null).getId();
        }
        group.setApplicationId(appId);
        group.setName(endpointGroupName);
        group.setWeight(RANDOM.nextInt());
        return endpointService.saveEndpointGroup(group);
    }

    protected List<ConfigurationSchemaDto> generateConfSchemaDto(String appId, int count) {
        return generateConfSchemaDto(appId, count, "dao/schema/testDataSchema.json");
    }

    protected List<ConfigurationSchemaDto> generateConfSchemaDto(String appId, int count, String path) {
        List<ConfigurationSchemaDto> schemas = Collections.emptyList();
        try {
            if (isBlank(appId)) {
                appId = generateApplicationDto().getId();
            }
            ConfigurationSchemaDto schemaDto;
            schemas = new ArrayList<>(count);
            for (int i = 0; i < count; i++) {
                schemaDto = new ConfigurationSchemaDto();
                schemaDto.setApplicationId(appId);
                schemaDto.setSchema(readSchemaFileAsString(path));
                schemaDto = configurationService.saveConfSchema(schemaDto);
                Assert.assertNotNull(schemaDto);
                schemas.add(schemaDto);
            }
        } catch (Exception e) {
            LOG.error("Can't generate configs {}", e);
            Assert.fail("Can't generate configuration schemas." + e.getMessage());
        }
        return schemas;
    }

    protected List<ConfigurationDto> generateConfigurationDto(String schemaId, String groupId, int count, boolean activate,
                                                              boolean useBaseSchema) {
        List<ConfigurationDto> ids = Collections.emptyList();
        try {
            ConfigurationSchemaDto schemaDto;
            if (isNotBlank(schemaId)) {
                schemaDto = configurationService.findConfSchemaById(schemaId);
            } else {
                schemaDto = generateConfSchemaDto(null, 1).get(0);
            }
            Assert.assertNotNull(schemaDto);
            KaaSchema kaaSchema = useBaseSchema ? new BaseSchema(schemaDto.getBaseSchema()) : new OverrideSchema(
                    schemaDto.getOverrideSchema());
            DefaultRecordGenerationAlgorithmImpl configurationProcessor = new DefaultRecordGenerationAlgorithmImpl(kaaSchema,
                    useBaseSchema ? new BaseDataFactory() : new OverrideDataFactory());
            ids = new ArrayList<>();
            for (int i = 0; i < count; i++) {
                ConfigurationDto dto = new ConfigurationDto();
                dto.setId(null);
                dto.setStatus(null);
                dto.setBody(configurationProcessor.getRootData().getRawData());
                dto.setSchemaId(schemaDto.getId());
                if (isBlank(groupId)) {
                    groupId = generateEndpointGroupDto(schemaDto.getApplicationId()).getId();
                }
                dto.setEndpointGroupId(groupId);
                ConfigurationDto saved = configurationService.saveConfiguration(dto);
                Assert.assertNotNull(saved);
                if (activate) {
                    ChangeConfigurationNotification notification = configurationService.activateConfiguration(saved.getId(),
                            schemaDto.getCreatedUsername());
                    saved = notification.getConfigurationDto();
                }
                ids.add(saved);
            }
        } catch (Exception e) {
            LOG.error("Can't generate configs {}", e);
            Assert.fail("Can't generate configurations. " + e.getMessage());
        }
        return ids;
    }

    protected List<EndpointProfileSchemaDto> generateProfSchemaDto(String tenantId, String appId, int count) {
        List<EndpointProfileSchemaDto> schemas = Collections.emptyList();
        try {
            if (isBlank(tenantId)) {
                tenantId = generateTenantDto().getId();
            }
            if (isBlank(appId)) {
                appId = generateApplicationDto(tenantId).getId();
            }
            EndpointProfileSchemaDto schemaDto;
            CTLSchemaDto ctlSchemaDto = ctlService.saveCTLSchema(generateCTLSchemaDto(tenantId));
            schemas = new ArrayList<>(count);
            for (int i = 0; i < count; i++) {
                schemaDto = new EndpointProfileSchemaDto();
                schemaDto.setApplicationId(appId);
                schemaDto.setCtlSchemaId(ctlSchemaDto.getId());
                schemaDto.setCreatedUsername("Test User");
                schemaDto.setName("Test Name");
                schemaDto = profileService.saveProfileSchema(schemaDto);
                Assert.assertNotNull(schemaDto);
                schemas.add(schemaDto);
            }
        } catch (Exception e) {
            LOG.error("Can't generate configs {}", e);
            Assert.fail("Can't generate configurations.");
        }
        return schemas;
    }

    protected List<ProfileFilterDto> generateFilterDto(String schemaId, String serverSchemaId, String groupId, int count, boolean activate) {
        List<ProfileFilterDto> filters = Collections.emptyList();
        try {
            EndpointProfileSchemaDto schemaDto;
            if (isBlank(schemaId)) {
                schemaDto = generateProfSchemaDto(null, null, 1).get(0);
            } else {
                schemaDto = profileService.findProfileSchemaById(schemaId);
            }
            ApplicationDto app = applicationService.findAppById(schemaDto.getApplicationId());

            ServerProfileSchemaDto serverProfileSchemaDto;
            if (isBlank(serverSchemaId)) {
                serverProfileSchemaDto = generateServerProfileSchema(app.getId(), app.getTenantId());
            } else {
                serverProfileSchemaDto = serverProfileService.findServerProfileSchema(serverSchemaId);
            }

            filters = new ArrayList<>();
            for (int i = 0; i < count; i++) {
                ProfileFilterDto dto = new ProfileFilterDto();
                dto.setId(null);
                dto.setStatus(null);
                if (isBlank(groupId)) {
                    groupId = generateEndpointGroupDto(schemaDto.getApplicationId()).getId();
                }
                dto.setEndpointGroupId(groupId);
                dto.setEndpointProfileSchemaId(schemaDto.getId());
                dto.setEndpointProfileSchemaVersion(schemaDto.getVersion());
                dto.setServerProfileSchemaId(serverProfileSchemaDto.getId());
                dto.setServerProfileSchemaVersion(serverProfileSchemaDto.getVersion());
                dto.setApplicationId(schemaDto.getApplicationId());
                ProfileFilterDto saved = profileService.saveProfileFilter(dto);
                Assert.assertNotNull(saved);
                if (activate) {
                    ChangeProfileFilterNotification notification = profileService.activateProfileFilter(saved.getId(),
                            schemaDto.getCreatedUsername());
                    saved = notification.getProfileFilterDto();
                }
                filters.add(saved);
            }
        } catch (Exception e) {
            LOG.error("Can't generate configs {}", e);
            Assert.fail("Can't generate configurations.");
        }
        return filters;
    }

    protected TenantDto generateTenantDto() {
        return generateTenantDto(generateString(TENANT_NAME));
    }

    protected TenantDto generateTenantDto(String name) {
        TenantDto tn = new TenantDto();
        tn.setName(name);
        return userService.saveTenant(tn);
    }

    protected List<LogSchemaDto> generateLogSchemaDto(String appId, int count) {
        List<LogSchemaDto> schemas = Collections.emptyList();
        try {
            if (isBlank(appId)) {
                appId = generateApplicationDto().getId();
            }
            LogSchemaDto schemaDto;
            schemas = new ArrayList<>(count);
            for (int i = 0; i < count; i++) {
                schemaDto = new LogSchemaDto();
                schemaDto.setApplicationId(appId);
                schemaDto.setSchema(new KaaSchemaFactoryImpl().createDataSchema(readSchemaFileAsString("dao/schema/testDataSchema.json"))
                        .getRawSchema());
                schemaDto.setCreatedUsername("Test User");
                schemaDto.setName("Test Name");
                schemaDto = logSchemaService.saveLogSchema(schemaDto);
                Assert.assertNotNull(schemaDto);
                schemas.add(schemaDto);
            }
        } catch (Exception e) {
            LOG.error("Can't generate log schemas {}", e);
            Assert.fail("Can't generate log schemas.");
        }
        return schemas;
    }

    protected TenantAdminDto generateTenantAdminDto(TenantDto tenantDto, String userId) {
        TenantAdminDto tenant = new TenantAdminDto();
        tenant.setName(generateString(TENANT_NAME));
        if (tenantDto == null) {
            tenantDto = generateTenantDto();
        }
        tenant.setTenant(tenantDto);
        if (isBlank(userId)) {
            List<UserDto> users = generateUsersDto(tenantDto.getId(), KaaAuthorityDto.TENANT_ADMIN, 1);
            tenant.setUserId(users.get(0).getId());
        } else {
            tenant.setUserId(userId);
        }
        tenant.setExternalUid(UUID.randomUUID().toString());
        tenant = userService.saveTenantAdmin(tenant);
        return tenant;
    }

    protected UserVerifierDto generateUserVerifierDto(String appId, String verifierToken) {
        UserVerifierDto verifier = new UserVerifierDto();
        verifier.setName("GENERATED test Verifier");
        if (isBlank(appId)) {
            appId = generateApplicationDto().getId();
        }
        verifier.setApplicationId(appId);
        if (verifierToken == null) {
            verifierToken = "token";
        }
        verifier.setVerifierToken(verifierToken);
        return verifierService.saveUserVerifier(verifier);
    }

    protected List<UserDto> generateUsersDto(String tenantId, KaaAuthorityDto authority, int count) {
        List<UserDto> users = new ArrayList<>(count);
        UserDto userDto = null;
        for (int i = 0; i < count; i++) {
            userDto = new UserDto();
            userDto.setUsername(generateString(USER_NAME));
            userDto.setTenantId(tenantId);
            userDto.setExternalUid(UUID.randomUUID().toString());
            userDto.setAuthority(authority);
            userDto = userService.saveUser(userDto);
            users.add(userDto);
        }
        return users;
    }

    protected TopicDto generateTopicDto(String appId, TopicTypeDto type) {
        TopicDto topic = new TopicDto();
        topic.setName(TOPIC_NAME);
        if (isBlank(appId)) {
            appId = generateApplicationDto().getId();
        }
        topic.setApplicationId(appId);
        if (type == null) {
            type = TopicTypeDto.MANDATORY;
        }
        topic.setType(type);
        return topicService.saveTopic(topic);
    }

    protected NotificationSchemaDto generateNotificationSchemaDto(String appId, NotificationTypeDto type) {
        NotificationSchemaDto schema = new NotificationSchemaDto();
        if (isBlank(appId)) {
            appId = generateApplicationDto().getId();
        }
        schema.setApplicationId(appId);
        schema.setName(NOTIFICATION_SCHEMA_NAME);
        String schemaBody = null;
        try {
            schemaBody = readSchemaFileAsString("dao/schema/testBaseSchema.json");
        } catch (IOException e) {
            e.printStackTrace();
            Assert.fail(e.getMessage());
        }
        schema.setSchema(new KaaSchemaFactoryImpl().createDataSchema(schemaBody).getRawSchema());
        schema.setType(type != null ? type : NotificationTypeDto.USER);
        return notificationService.saveNotificationSchema(schema);
    }

    protected List<NotificationDto> generateNotificationsDto(String schemaId, String topicId, int count, NotificationTypeDto type) {
        List<NotificationDto> notifications = new ArrayList<>(count);
        NotificationDto notification = null;
        NotificationSchemaDto schema;
        for (int i = 0; i < count; i++) {
            notification = new NotificationDto();
            if (isBlank(schemaId)) {
                schema = generateNotificationSchemaDto(null, NotificationTypeDto.USER);
            } else {
                schema = notificationService.findNotificationSchemaById(schemaId);
            }
            notification.setApplicationId(schema.getApplicationId());
            notification.setSchemaId(schema.getId());
            if (isBlank(topicId)) {
                topicId = generateTopicDto(schema.getApplicationId(), null).getId();
            }
            notification.setTopicId(topicId);
            notification.setType(type != null ? type : NotificationTypeDto.USER);
            byte[] body = null;
            try {
                body = readSchemaFileAsString("dao/schema/testBaseData.json").getBytes(Charset.forName("UTF-8"));
            } catch (IOException e) {
                e.printStackTrace();
                Assert.fail(e.getMessage());
            }
            notification.setBody(body);
            UpdateNotificationDto<NotificationDto> update = notificationService.saveNotification(notification);
            notifications.add(update.getPayload());
        }
        return notifications;
    }

    protected EndpointNotificationDto generateUnicastNotificationDto(String schemaId, String topicId, byte[] keyHash) {
        EndpointNotificationDto endpointNotification = new EndpointNotificationDto();
        endpointNotification.setEndpointKeyHash(keyHash);
        NotificationDto notification = new NotificationDto();
        NotificationSchemaDto schema;
        if (isBlank(schemaId)) {
            schema = generateNotificationSchemaDto(null, NotificationTypeDto.USER);
        } else {
            schema = notificationService.findNotificationSchemaById(schemaId);
        }
        if (isBlank(topicId)) {
            topicId = generateTopicDto(schema.getApplicationId(), null).getId();
        }
        notification.setTopicId(topicId);
        notification.setApplicationId(schema.getApplicationId());
        notification.setSchemaId(schema.getId());
        notification.setType(NotificationTypeDto.USER);
        byte[] body = null;
        try {
            body = readSchemaFileAsString("dao/schema/testBaseData.json").getBytes(Charset.forName("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
            Assert.fail(e.getMessage());
        }
        notification.setBody(body);
        endpointNotification.setNotificationDto(notification);
        UpdateNotificationDto<EndpointNotificationDto> update = notificationService.saveUnicastNotification(endpointNotification);
        return update.getPayload();
    }

    protected EndpointUserDto generateEndpointUserDto(String tenantId) {
        EndpointUserDto endpointUser = new EndpointUserDto();
        endpointUser.setExternalId(ENDPOINT_USER_EXTERNAL_ID + UUID.randomUUID().toString());
        endpointUser.setUsername(ENDPOINT_USER_NAME + UUID.randomUUID().toString());
        if (tenantId == null) {
            tenantId = UUID.randomUUID().toString();
        }
        endpointUser.setTenantId(tenantId);
        endpointUser = endpointService.saveEndpointUser(endpointUser);
        return endpointUser;
    }

    protected LogAppenderDto generateLogAppenderDto(String appId, String schemaId) {
        LogAppenderDto logAppender = null;
        ApplicationDto app = null;
        LogSchemaDto schema = null;
        if (isBlank(appId)) {
            app = generateApplicationDto();
            appId = app.getId();
        } else {
            app = applicationService.findAppById(appId);
        }
        if (isBlank(schemaId)) {
            schema = generateLogSchemaDto(appId, 1).get(0);
        }
        logAppender = new LogAppenderDto();
        logAppender.setApplicationId(appId);
        logAppender.setName("Generated Appender");
        int version = schema.getVersion();
        logAppender.setMinLogSchemaVersion(version);
        logAppender.setMaxLogSchemaVersion(version);
        logAppender.setTenantId(app.getTenantId());
        logAppender.setHeaderStructure(Arrays.asList(LogHeaderStructureDto.values()));
        return logAppendersService.saveLogAppender(logAppender);
    }

    protected EndpointUserConfigurationDto generateEndpointUserConfigurationDto(EndpointUserDto endpointUser, ApplicationDto applicationDto,
                                                                                ConfigurationSchemaDto configurationSchema) {
        return generateEndpointUserConfigurationDto(endpointUser, applicationDto, configurationSchema, UUID.randomUUID().toString());
    }

    protected EndpointUserConfigurationDto generateEndpointUserConfigurationDto(EndpointUserDto endpointUser, ApplicationDto applicationDto,
                                                                                ConfigurationSchemaDto configurationSchema, String body) {
        return generateEndpointUserConfigurationDto(endpointUser, applicationDto, configurationSchema, body, false);
    }

    protected EndpointUserConfigurationDto generateEndpointUserConfigurationDto(EndpointUserDto endpointUser, ApplicationDto applicationDto,
                                                                                ConfigurationSchemaDto configurationSchema, String body, boolean isNullAppDto) {
        EndpointUserConfigurationDto configurationDto = new EndpointUserConfigurationDto();
        configurationDto.setBody(body);

        if (endpointUser == null) {
            endpointUser = generateEndpointUserDto(null);
        }
        if (!isNullAppDto) {
            if (applicationDto == null) {
                applicationDto = generateApplicationDto();
            }
            configurationDto.setAppToken(applicationDto.getApplicationToken());
        } else {
            return userConfigurationService.saveUserConfiguration(configurationDto);
        }
        configurationDto.setUserId(endpointUser.getId());

        if (configurationSchema == null) {
            configurationSchema = generateConfSchemaDto(applicationDto.getId(), 1).get(0);
        }
        configurationDto.setSchemaVersion(configurationSchema.getVersion());

        return userConfigurationService.saveUserConfiguration(configurationDto);
    }

    protected EndpointProfileDto generateEndpointProfileDto(String appId, List<String> topicIds) {
        if (isBlank(appId)) {
            appId = generateApplicationDto().getId();
        }
        EndpointProfileDto profileDto = new EndpointProfileDto();
        profileDto.setApplicationId(appId);
        profileDto.setSubscriptions(topicIds);
        profileDto.setEndpointKeyHash("TEST_KEY_HASH".getBytes());
        profileDto.setClientProfileBody("{\"title\": \"TEST\"}");
        profileDto.setSdkToken(UUID.randomUUID().toString());
        return endpointService.saveEndpointProfile(profileDto);
    }

    protected EndpointProfileDto generateEndpointProfileDtoWithSchemaVersion(String appId, int schemaVersion, String srvProfileBody) {
        EndpointProfileDto profileDto = new EndpointProfileDto();
        profileDto.setApplicationId(appId);
        profileDto.setServerProfileVersion(schemaVersion);
        profileDto.setEndpointKeyHash("TEST_KEY_HASH".getBytes());
        profileDto.setClientProfileBody("{\"title\": \"TEST\"}");
        profileDto.setSdkToken(UUID.randomUUID().toString());
        profileDto.setServerProfileBody(srvProfileBody);
        return endpointService.saveEndpointProfile(profileDto);
    }

    protected EndpointProfileDto generateEndpointProfileWithGroupIdDto(String endpointGroupId) {
        EndpointProfileDto profileDto = new EndpointProfileDto();
        profileDto.setEndpointKeyHash(generateString("TEST_KEY_HASH").getBytes());
        String appId = generateApplicationDto().getId();
        profileDto.setApplicationId(appId);
        List<EndpointGroupStateDto> groupState = new ArrayList<>();
        groupState.add(new EndpointGroupStateDto(endpointGroupId, null, null));
        profileDto.setGroupState(groupState);
        profileDto.setClientProfileBody("{\"title\": \"TEST\"}");
        profileDto.setSdkToken(UUID.randomUUID().toString());
        return endpointService.saveEndpointProfile(profileDto);
    }

    protected CTLSchemaDto generateCTLSchemaDto(String tenantId) {
        return generateCTLSchemaDto(DEFAULT_FQN, tenantId, null, 100);
    }

    protected CTLSchemaDto generateCTLSchemaDto(String fqn, String tenantId, String applicationId, int version) {
        CTLSchemaDto ctlSchema = new CTLSchemaDto();
        ctlSchema.setMetaInfo(new CTLSchemaMetaInfoDto(fqn, tenantId, applicationId));
        ctlSchema.setVersion(version);
        String name = fqn.substring(fqn.lastIndexOf(".") + 1);
        String namespace = fqn.substring(0, fqn.lastIndexOf("."));
        StringBuilder body = new StringBuilder("{\"type\": \"record\",");
        body = body.append("\"name\": \"").append(name).append("\",");
        body = body.append("\"namespace\": \"").append(namespace).append("\",");
        body = body.append("\"version\": ").append(version).append(",");
        body = body.append("\"dependencies\": [], \"fields\": []}");
        ctlSchema.setBody(body.toString());
        return ctlSchema;
    }

    protected String ctlRandomFqn() {
        return DEFAULT_FQN + RANDOM.nextInt(100000);
    }

    protected ServerProfileSchemaDto generateServerProfileSchema(String appId, String tenantId) {
        return generateServerProfileSchema(appId, tenantId, RANDOM.nextInt(100000));
    }

    protected ServerProfileSchemaDto generateServerProfileSchema(String appId, String tenantId, int version) {
        ServerProfileSchemaDto schemaDto = new ServerProfileSchemaDto();
        if(isBlank(tenantId)) {
            ApplicationDto applicationDto = generateApplicationDto();
            appId = applicationDto.getId();
            tenantId = applicationDto.getTenantId();
        }
        schemaDto.setApplicationId(appId);
        schemaDto.setCreatedTime(System.currentTimeMillis());

        CTLSchemaDto ctlSchema = ctlService.saveCTLSchema(generateCTLSchemaDto(ctlRandomFqn(), tenantId, appId, version));
        schemaDto.setCtlSchemaId(ctlSchema.getId());
        return serverProfileService.saveServerProfileSchema(schemaDto);
    }

    protected List<String> getIds(List<? extends GenericModel> modelList) {
        List<String> ids = new ArrayList<>();
        for (GenericModel gm : modelList) {
            ids.add(gm.getStringId());
        }
        Collections.sort(ids);
        return ids;
    }

    protected List<String> getIdsDto(List<? extends HasId> hId) {
        List<String> ids = new ArrayList<>();
        for (HasId id : hId) {
            ids.add(id.getId());
        }
        Collections.sort(ids);
        return ids;
    }
}


text:
from sh import git
from requests.auth import HTTPBasicAuth
from globalvars import GlobalVars
import requests
import time
import json

class GitManager:
    @classmethod
    def add_to_blacklist(self, **kwargs):
        blacklist = kwargs.get("blacklist", "website")
        items_to_blacklist = kwargs.get("items_to_blacklist", [])
        username = kwargs.get("username", "")
        chat_profile_link = kwargs.get("chat_profile_link", "http://chat.stackexchange.com/users")
        code_permissions = kwargs.get("code_permissions", False)

        if blacklist == "website":
            blacklist_file_name = "blacklisted_websites.txt"
        elif blacklist == "keyword":
            blacklist_file_name = "bad_keywords.txt"
        elif blacklist == "username":
            blacklist_file_name = "blacklisted_usernames.txt"

        # Check if we're on master
        if git("rev-parse", "--abbrev-ref", "HEAD").strip() != "master":
            return (False, "Not currently on master.")

        # Check that we're up-to-date with origin (GitHub)
        git.remote.update()
        if git("rev-parse", "refs/remotes/origin/master").strip() != git("rev-parse", "master").strip():
            return (False, "HEAD isn't at tip of origin's master branch")

        # Check that blacklisted_websites.txt isn't modified locally. That could get ugly fast
        if blacklist_file_name in git.status():  # Also ugly
            return (False, "{0} modified locally. This is probably bad.".format(blacklist_file_name))

        # Store current commit hash
        current_commit = git("rev-parse", "HEAD").strip()

        # Add items to file
        with open(blacklist_file_name, "a+") as blacklist_file:
            last_character = blacklist_file.read()[-1:]
            if last_character != "\n":
                blacklist_file.write("\n")
            blacklist_file.write("\n".join(items_to_blacklist) + "\n")

        # Checkout a new branch (for PRs for non-code-privileged people)
        branch = "auto-blacklist-{0}".format(str(time.time()))
        git.checkout("-b", branch)

        # Clear HEAD just in case
        git.reset("HEAD")

        git.add(blacklist_file_name)
        git.commit("-m", u"Auto blacklist of {0} by {1} --autopull".format(", ".join(items_to_blacklist), username))

        if code_permissions:
            git.checkout("master")
            git.merge(branch)
            git.push()
        else:
            git.push("origin", branch)
            git.checkout("master")

            if GlobalVars.github_username is None or GlobalVars.github_password is None:
                return (False, "Tell someone to set a GH password")

            list_of_domains = ""

            for domain in range(len(items_to_blacklist)):
                list_of_domains += "\n - {0} - [MS search](https://metasmoke.erwaysoftware.com/search?utf8=%E2%9C%93&body_is_regex=1&body={0})".format(items_to_blacklist[domain])

            payload = {"title": "{0}: Blacklist {1}".format(username, ", ".join(items_to_blacklist)),
                       "body": "[{0}]({1}) requests the blacklist of the following {2}(s): \n{3}\n<!-- METASMOKE-BLACKLIST {4} -->".format(username, chat_profile_link, blacklist, list_of_domains, "|".join(items_to_blacklist)),
                       "head": branch,
                       "base": "master"}
            response = requests.post("https://api.github.com/repos/Charcoal-SE/SmokeDetector/pulls", auth=HTTPBasicAuth(GlobalVars.github_username, GlobalVars.github_password), data=json.dumps(payload))
            print(response.json())
            return (True, "You don't have code privileges, but I've [created a pull request for you]({0}).".format(response.json()["html_url"]))

        git.checkout(current_commit)  # Return to old commit to await CI. This will make Smokey think it's in reverted mode if it restarts

        return (True, "Blacklisted {0} - the entry will be applied via autopull if CI succeeds.".format(", ".join(items_to_blacklist)))

    @classmethod
    def current_git_status(self):
        return git.status()


text:
package cern.enice.jira.listeners.pvss_license_request_listener;

import java.util.List;
import java.util.Map;

public class LicenseRequestData {
	private String issueKey;
	private String messageId;
	private String assigneeEmail;
	private String reporterDetails;
	private String customFields;
	private String creationDate;
	private String description;
	private String comment;
	private List<Map<String, Object>> components;
	public String getIssueKey() {
		return issueKey;
	}
	public void setIssueKey(String issueKey) {
		this.issueKey = issueKey;
	}
	public String getMessageId() {
		return messageId;
	}
	public void setMessageId(String messageId) {
		this.messageId = messageId;
	}
	public String getAssigneeEmail() {
		return assigneeEmail;
	}
	public void setAssigneeEmail(String assigneeEmail) {
		this.assigneeEmail = assigneeEmail;
	}
	public String getReporterDetails() {
		return reporterDetails;
	}
	public void setReporterDetails(String reporterDetails) {
		this.reporterDetails = reporterDetails;
	}
	public String getCustomFields() {
		return customFields;
	}
	public void setCustomFields(String customFields) {
		this.customFields = customFields;
	}
	public String getCreationDate() {
		return creationDate;
	}
	public void setCreationDate(String creationDate) {
		this.creationDate = creationDate;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getComment() {
		return comment;
	}
	public void setComment(String comment) {
		this.comment = comment;
	}
	public List<Map<String, Object>> getComponents() {
		return components;
	}
	public void setComponents(List<Map<String, Object>> components) {
		this.components = components;
	}
}


text:
import { fakeJsonPAdResponse } from 'player-frontend/utils/fake-jsonp-ad-response';

let alreadyRan = false;
export function watchScriptSrc() {
  try {
    if (!alreadyRan) {
      Object.defineProperty(
        HTMLScriptElement.prototype,
        'src',
        {
          configurable: true,
          enumerable: false,
          get() {
            return this._src || '';
          },
          set(src) {
            const replacementSrc = swapOutScriptSrc(src);
            this._src = replacementSrc;
            this.setAttribute('src', replacementSrc);
          }
        }
      );
      alreadyRan = true;
    } else {
      console.warn('you already ran `watchScriptSrc`. This only needs to happen ONCE.');
    }
  } catch (e) {
    console.error("Oh dear! This browser won't let me overwrite `src` getter/setter for <script> tags :(", e);
  }
}

const stubMap = new Map();

export function stubJsonPResponse(pattern, ad, times = 1, callbackKey = 'cbfn') {
  stubMap.set(pattern, { ad, times, callbackKey });
}

export function restoreJsonPResponses() {
  stubMap.clear();
}

export function getSourceUrlForAd(ad, callbackFnName) {
  const blob = new Blob([fakeJsonPAdResponse(callbackFnName, ad)]);
  const url = URL.createObjectURL(blob);
  return url;
}

function swapOutScriptSrc(src) {
  for (let [pattern, meta] of stubMap) {
    if (pattern.test(src) && meta.times > 0) {
      meta.times--;
      const { ad, callbackKey } = meta;
      const { [callbackKey]: callbackFnName } = objectifyParams(src);

      if (callbackFnName) {
        return getSourceUrlForAd(ad, callbackFnName);
      }
    }
  }

  return src;
}

export function objectifyParams(url) {
  const paramString = url.split(/[?;]/)[1];
  if (paramString) {
    return paramString.split('&').reduce((acc, param) => {
      const [k, v] = param.split('=');
      acc[k] = decodeURIComponent(v);
      return acc;
    }, {});
  } else {
    return {};
  }
}


text:
std::string BrowserUpdaterClient::GetAppId() {
  return base::SysWideToUTF8(
      std::wstring(install_static::InstallDetails::Get().app_guid()));
}

updater::RegistrationRequest BrowserUpdaterClient::GetRegistrationRequest() {
  updater::RegistrationRequest req;
  req.app_id = GetAppId();
  google_brand::GetBrand(&req.brand_code);
  req.version = base::Version(version_info::GetVersionNumber());
  req.ap =
      base::SysWideToUTF8(install_static::InstallDetails::Get().update_ap());
  return req;
}


text:
title: "STACK 2020 - FWO FWF (Misc)"
header:
  overlay_image: /assets/images/stack-2020/header.jpg
  overlay_filter: 0.5
  caption: "Photo credit: Steve Johnson"

tags:
  - stack
  - writeup
  - misc
  - html
---

Summary: Three different individual messages are encoded within HTML via their classes and their styled visibilities.

![FWO FWF Challenge Description]({{ site.url }}{{ site.baseurl }}/assets/images/stack-2020/6D6F184186A85F7BD641A250BD14003A.jpg){: .align-center}

```
FWO FWF
583 MISCELLANEOUS
104 SOLVES

DESCRIPTION
As part of forensic investigations into servers operated by COViD, an investigator found this web server containing a hidden secret. Help us find the contents of this secret.

Web Server

Addendum:
If you're having trouble, check your capitalization.
```

When visiting the page (http://yhi8bpzolrog3yw17fe0wlwrnwllnhic.alttablabs.sg:40731/), we are greeted by some gibberish:

![Challenge Landing Page]({{ site.url }}{{ site.baseurl }}/assets/images/stack-2020/84AC7F26D8139BF9BA5A5007A543A6DA.jpg){: .align-center}

Looking at the HTML code, it contains multiple span elements and a style tag applying visibility to certain classes:

```html
<html>
	<body>
	<p style="font-size: 150;">
		<span class=c>F</span> <span class=c>W</span> <span class=c>O</span> <span class=a>T</span> ...
	</p>

	...

	<style>
		.a {visibility: hidden;}
		.b {visibility: hidden;}
		.c {}
	</style>

    ...

</html>
```

It appears that the style controls which span items are shown. The current shown class is 'c'.

Programmatically, we can obtain the contents of the 'a' and 'b' spans like so in the Javascript console:

```javascript
Array.from(document.getElementsByClassName('a')).map(v => v.textContent).join("")
"THE FLAGIS  HIDDENINA FILE"
Array.from(document.getElementsByClassName('b')).map(v => v.textContent).join("")
"CSG.TXT"
```

Following the clues, we can derive that the path `/CSG.TXT` exists on the web server. Visiting http://yhi8bpzolrog3yw17fe0wlwrnwllnhic.alttablabs.sg:40731/CSG.TXT confirms this.

```console
$ curl http://yhi8bpzolrog3yw17fe0wlwrnwllnhic.alttablabs.sg:40731/CSG.TXT
Rmo0Y19HdTNfZkdsWTNfaTFmMW8xWTFHbAo=
```

Decoding the text as base64 gives us some unintelligible data:

```console
$ echo Rmo0Y19HdTNfZkdsWTNfaTFmMW8xWTFHbAo= | base64 -d
Fj4c_Gu3_fGlY3_i1f1o1Y1Gl
```

Since the numbers look roughly right for the flag, only the characters should be decoded. Thus, guessing that the flag is encoded with ROT13 gives us an intelligible flag:

```console
echo Fj4c_Gu3_fGlY3_i1f1o1Y1Gl | tr 'A-Za-z' 'N-ZA-Mn-za-m'
Sw4p_Th3_sTyL3_v1s1b1L1Ty
```

**Flag:** `govtech-csg{Sw4p_Th3_sTyL3_v1s1b1L1Ty}`


text:
<?php

namespace Rudolf\Component\Plugins;

use Rudolf\Component\Hooks\Filter;
use Rudolf\Component\Html\Foot;
use Rudolf\Component\Html\Head;

class DomPlugins
{
    /**
     * @var Head
     */
    private $head;

    /**
     * @var Foot
     */
    private $foot;

    /**
     * DomPlugins constructor.
     *
     * @param Head $head
     * @param Foot $foot
     */
    public function __construct(Head $head, Foot $foot)
    {
        $this->head = $head;
        $this->foot = $foot;
    }

    public function front()
    {
        if (Filter::isHas('head_stylesheets')) {
            $head_stylesheets = Filter::apply('head_stylesheets', $this->head->getStylesheetsArray());
            $this->head->setStylesheetsArray($head_stylesheets);
        }

        if (Filter::isHas('head_scripts')) {
            $head_scripts = Filter::apply('head_scripts', $this->head->getScriptsArray());
            $this->head->setScriptsArray($head_scripts);
        }

        if (Filter::isHas('foot_scripts')) {
            $foot_scripts = Filter::apply('foot_scripts', $this->foot->getScriptsArray());
            $this->foot->setScriptsArray($foot_scripts);
        }

        if (Filter::isHas('head_before')) {
            $head_before = Filter::apply('head_before', $this->head->getBeforeArray());
            $this->head->setBeforeArray($head_before);
        }

        if (Filter::isHas('head_after')) {
            $head_after = Filter::apply('head_after', $this->head->getAfterArray());
            $this->head->setAfterArray($head_after);
        }

        if (Filter::isHas('foot_before')) {
            $foot_before = Filter::apply('foot_before', $this->foot->getBeforeArray());
            $this->foot->setBeforeArray($foot_before);
        }

        if (Filter::isHas('foot_after')) {
            $foot_after = Filter::apply('foot_after', $this->foot->getAfterArray());
            $this->foot->setAfterArray($foot_after);
        }
    }

    public function admin()
    {
        if (Filter::isHas('admin_head_stylesheets')) {
            $head_stylesheets = Filter::apply('admin_head_stylesheets', $this->head->getStylesheetsArray());
            $this->head->setStylesheetsArray($head_stylesheets);
        }

        if (Filter::isHas('admin_head_scripts')) {
            $head_scripts = Filter::apply('admin_head_scripts', $this->head->getScriptsArray());
            $this->head->setScriptsArray($head_scripts);
        }

        if (Filter::isHas('admin_foot_scripts')) {
            $foot_scripts = Filter::apply('admin_foot_scripts', $this->foot->getScriptsArray());
            $this->foot->setScriptsArray($foot_scripts);
        }

        if (Filter::isHas('admin_head_before')) {
            $head_before = Filter::apply('admin_head_before', $this->head->getBeforeArray());
            $this->head->setBeforeArray($head_before);
        }

        if (Filter::isHas('admin_head_after')) {
            $head_after = Filter::apply('admin_head_after', $this->head->getAfterArray());
            $this->head->setAfterArray($head_after);
        }

        if (Filter::isHas('admin_foot_before')) {
            $foot_before = Filter::apply('admin_foot_before', $this->foot->getBeforeArray());
            $this->foot->setBeforeArray($foot_before);
        }

        if (Filter::isHas('admin_foot_after')) {
            $foot_after = Filter::apply('admin_foot_after', $this->foot->getAfterArray());
            $this->foot->setAfterArray($foot_after);
        }
    }
}


text:
def get_current_userid():
    pass


text:
Scaling
========

PyScaler provides the infrastructure needed to automate the deployment of new
nodes in an cloud based cluster.

The deployment of a new node can be triggered manually or automatically due
a monitoring trigger.

The creation a of a new node into a cluster uses the following components:

- IaaS provider API to automate the execution of a new virtual machine.
- Puppet to provision the new virtual machine with a specific operating system configuration.
- Fabric to automate the deployment of new applications an other automatisms

Deployment steps
-----------------------------------
This sections describes the steps needed to deploy a new node

+--------------------------------------------------+--------------------------------------------+
| STEP                                             |                                            |
+==================================================+============================================+
| Deploy a new VM on EC2 (clustername,user, )      | DeployEC2Node action                       |
+--------------------------------------------------+--------------------------------------------+
| Add the node to the Elastic Load Balancer        | DeployEC2Node action                       |
+--------------------------------------------------+--------------------------------------------+
| Operating system configuration and provisioning  | OSConfiguration action                     |
+--------------------------------------------------+--------------------------------------------+
| Tomcat configuration                             | LocalScript or DistributeScript actions    |
+--------------------------------------------------+--------------------------------------------+
| Application deployment                           | LocalScript or DistributeScript actions    |
+--------------------------------------------------+--------------------------------------------+
| Cluster update                                   | LocalScript or DistributeScript actions    |
+--------------------------------------------------+--------------------------------------------+
| Notification                                     | Email action                               |
+--------------------------------------------------+--------------------------------------------+

The PyScaler distribution contains some Puppet and Fabric scripts that can be
used to automate a Tomcat deployment.


text:
'use strict';

var gulp = require('gulp');
var test = require('./gulp/test');

gulp.task('server', require('./gulp/server'));
gulp.task('clean', require('./gulp/clean'));
gulp.task('img', require('./gulp/img'));
gulp.task('js', require('./gulp/js'));
gulp.task('scss', require('./gulp/scss'));
gulp.task('cp', require('./gulp/cp'));
gulp.task('html', require('./gulp/html'));
gulp.task('watchdoges', require('./gulp/watchdoges'));
gulp.task('test', test);
gulp.task('testserver', test.bind(null, true));

gulp.task('build', [
//  'clean', // cannot be used yet, cause it deletes the entire dir :(
  'js',
  'cp',
  'scss',
  'html'
]);

gulp.task('default', [
  'server',
  'js',
  'cp',
  'scss',
  'img',
  'html',
  'watchdoges'
]);


text:
package openmarker.trove.classfile;

import java.io.DataInput;
import java.io.IOException;

/**
 * The class corresponds to the RuntimeVisibleAnnotations_attribute structure
 * defined for Java 5.
 *
 * @author Brian S O'Neill
 */
public class RuntimeVisibleAnnotationsAttr extends AnnotationsAttr {

    public RuntimeVisibleAnnotationsAttr(ConstantPool cp) {
        super(cp, RUNTIME_VISIBLE_ANNOTATIONS);
    }

    public RuntimeVisibleAnnotationsAttr(ConstantPool cp, String name) {
        super(cp, name);
    }

    public RuntimeVisibleAnnotationsAttr(ConstantPool cp, String name, int length, DataInput din)
        throws IOException
    {
        super(cp, name, length, din);
    }
}


text:
license: 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.
---

Getting Started with Android
============================

This guide describes how to set up your development environment for Cordova and run a sample application.  Note that Cordova used to be called PhoneGap, so some of the sites still use the old PhoneGap name.

1. Requirements
---------------

- Eclipse 3.4+

2. Install SDK + Cordova
------------------------

- Download and install [Eclipse Classic](http://www.eclipse.org/downloads/)
- Download and install [Android SDK](http://developer.android.com/sdk/index.html)
- Download and install [ADT Plugin](http://developer.android.com/sdk/eclipse-adt.html#installing)
- Download the latest copy of [Cordova](http://phonegap.com/download) and extract its contents. We will be working with the Android directory.

 3. Setup New Project
---------------------

- Launch Eclipse, and select menu item **New Project**
    ![](img/guide/getting-started/android/step_1.jpg)
- Then specify new application project
    ![](img/guide/getting-started/android/step_2.jpg)
- Then specify an Application Name, a Project Name and Package Name with Namespace
    ![](img/guide/getting-started/android/step_3.jpg)
- Then select a graphic
    ![](img/guide/getting-started/android/step_4.jpg)
- Then Create a Blank Activity
    ![](img/guide/getting-started/android/step_5.jpg)
- Make sure the activity doesn't inherit from anything.  You most likely won't have PhoneGap on your Eclipse Workspace.  Once this is done, click finish

- In the root directory of your project, create two new directories:
 	- **/libs**
 	- **assets/www**
- Copy **cordova-1.9.0.js** from your Cordova download earlier to **assets/www**
- Copy **cordova-1.9.0.jar** from your Cordova download earlier to **/libs**
- Copy **xml** folder from your Cordova download earlier to **/res**

- Verify that **cordova-1.9.0.jar** is listed in the Build Path for your project. Right click on the /libs folder and go to **Build Paths/ > Configure Build Path...**. Then, in the Libraries tab, add **cordova-1.9.0.jar** to the project. If Eclipse is being temperamental, you might need to refresh (F5) the project once again.

    ![](img/guide/getting-started/android/buildPath.jpg)

- Edit your project's main Java file found in the **src** folder in Eclipse:
	- Add **import org.apache.cordova.*;**
	- Change the class's extend from **Activity** to **DroidGap**
	- Replace the **setContentView()** line with **super.loadUrl("file:///android_asset/www/index.html");**

	![](img/guide/getting-started/android/javaSrc.jpg)

- Right click on AndroidManifest.xml and select **Open With > Text Editor**
- Paste the following permissions between the **<uses-sdk.../>** and **<application.../>** tags.

        <supports-screens
            android:largeScreens="true"
            android:normalScreens="true"
            android:smallScreens="true"
            android:resizeable="true"
            android:anyDensity="true" />
        <uses-permission android:name="android.permission.VIBRATE" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
        <uses-permission android:name="android.permission.READ_PHONE_STATE" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.RECEIVE_SMS" />
        <uses-permission android:name="android.permission.RECORD_AUDIO" />
        <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
        <uses-permission android:name="android.permission.READ_CONTACTS" />
        <uses-permission android:name="android.permission.WRITE_CONTACTS" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.GET_ACCOUNTS" />
        <uses-permission android:name="android.permission.BROADCAST_STICKY" />
*Note You are adding a blanket list of permissions to your application. You should remove permissions you aren't using before submitting your application to Google Play.
- Support orientation changes by pasting the following inside the **<activity>** tag.

        android:configChanges="orientation|keyboardHidden"

- Your AndroidManifest.xml file should look like

    ![](img/guide/getting-started/android/manifest.png)

4. Hello World
--------------

- Create and open a new file named **index.html** in the **assets/www** directory. Paste the following code:

        <!DOCTYPE HTML>

        <title>Cordova</title>

Hello World

5A. Deploy to Simulator
-----------------------

- Right click the project and go to **Run As > Android Application**
- Eclipse will ask you to select an appropriate AVD. If there isn't one, then you'll need to create it.

5B. Deploy to Device
--------------------

- Make sure USB debugging is enabled on your device and plug it into your system. (**Settings > Applications > Development**)
- Right click the project and go to **Run As > Android Application**

Done!
-----


text:
class Vec3;
typedef unsigned char uchar;

namespace mce
{
	class TexturePtr;
};
class BlockTessellator
{
public:
	bool forceOpaque; // 0
	bool otherb; // 1
	BlockSource* blockSource; // 4
	TextureUVCoordinateSet forcedUV; // 8
	bool useForcedUV; // 36
	bool idk; // 37
	int renderLayer; // 40
	char filler[84]; // 44
	int rotBottom; // 128
	int rotTop; // 132
	int rotNorth; // 136
	int rotSouth; // 140
	int rotWest; // 144
	int rotEast; // 148
	char filler1[500]; // 152
	mce::MaterialPtr material; // 652
	Tessellator& tessellator; // 664
	AABB aabb; // 668
public:
	bool tessellateInWorld(Block const&, const BlockPos&, unsigned char, bool);
	bool tessellateBlockInWorld(Block const&, const BlockPos&,int);
	void renderGuiBlock(const FullBlock&, const mce::TexturePtr&, float, float);

	void renderNorth(Block&, const Vec3&, const TextureUVCoordinateSet&);
	void renderEast(Block&, const Vec3&, const TextureUVCoordinateSet&);
	void renderSouth(Block&, const Vec3&, const TextureUVCoordinateSet&);
	void renderWest(Block&, const Vec3&, const TextureUVCoordinateSet&);
	void renderFaceDown(Block&, const Vec3&, const TextureUVCoordinateSet&);
	void renderFaceUp(Block&, const Vec3&, const TextureUVCoordinateSet&);

	unsigned int getLightColor(const BlockPos&);
	BlockSource& getRegion() const;
	void setRegion(BlockSource&);
	int getRenderLayer() const;
	void setRenderLayer(int);
	void setForceOpaque(bool);
	void tex1(unsigned int);
	void blend(int, int, int, int);

	void tessellateCrossInWorld(Block const&, BlockPos const&, unsigned char, bool);
	Color _getBlockColor(BlockPos const&, Block const&);
	Color _getBlockColor(BlockPos const&, Block const&, unsigned char);
	TextureUVCoordinateSet const& _getTexture(Block const&, signed char, int) const;
	Tessellator& getTessellator();

	//custom
    //bool grassblockRenderer(Block*, BlockPos const&, unsigned char, BlockSource*);
};


text:
require 'timeout'

module Libis
  module Tools

    # This module allows to run an external command safely and returns it's output, error messages and status.
    # The run method takes any number of arguments that will be used as command-line arguments. The method returns
    # a Hash with:
    # * :out => an array with lines that were printed on the external program's standard out.
    # * :err => an array with lines that were printed on the external program's standard error.
    # * :status => exit code returned by the external program.
    # * :timeout => true if the command was terminated due to a timeout.
    # * :pid => pid of the command (in case <pid>.log files need to be cleaned up)
    #
    # Optionally an option hash can be appended to the list of arguments with:
    # * :stdin_data => values sent to the command's standard input (optional, nothing sent if not present)
    # * :binmode => if present and true, will set the IO communication to binary data
    # * :timeout => if specified, SIGTERM signal is sent to the command after the number of seconds
    # * :signal => Signal sent to the command instead of the default SIGTERM
    # * :kill_after => if specified, SIGKILL signal is sent aftern the number of seconds if command is still running
    #             after initial signal was sent
    # * any other options will be handed over to the spawn command (e.g. pgroup)
    #
    # Examples:
    #
    #     require 'libis/tools/command'
    #     result = ::Libis::Tools::Command.run('ls', '-l', File.absolute_path(__FILE__))
    #     p result # => {out: [...], err: [...], status: 0}
    #
    #     require 'libis/tools/command'
    #     include ::Libis::Tools::Command
    #     result = run('ls', '-l', File.absolute_path(__FILE__))
    #     p result # => {out: [...], err: [...], status: 0}
    #
    # Note that the Command class uses Open3#popen3 internally. All arguments supplied to Command#run are passed to
    # the popen3 call. Unfortunately some older JRuby versions have some known issues with popen3. Please use and
    # test carefully in JRuby environments.
    module Command

      # Run an external program and return status, stdout and stderr.
      #
      #
      # @param [Array<String>] cmd command name optionally prepended with env and appended with command-line arguments
      # @return [Hash] a Hash with:
      #         * :status (Integer) - the exit status of the command
      #         * :out (Array<String>) - the stdout output of the command
      #         * :err (Array<String>)- the stderr output of the command
      #         * :timeout(Boolean) - if true, the command did not return in time
      #         * :pid(Integer) - the command's processID
      def self.run(*cmd)

        spawn_opts = Hash === cmd.last ? cmd.pop.dup : {}
        opts = {
            :stdin_data => spawn_opts.delete(:stdin_data) || '',
            :binmode => spawn_opts.delete(:binmode) || false,
            :timeout => spawn_opts.delete(:timeout),
            :signal => spawn_opts.delete(:signal) || :TERM,
            :kill_after => spawn_opts.delete(:kill_after),
        }
        in_r, in_w = IO.pipe
        out_r, out_w = IO.pipe
        err_r, err_w = IO.pipe
        in_w.sync = true

        if opts[:binmode]
          in_w.binmode
          out_r.binmode
          err_r.binmode
        end

        spawn_opts[:in] = in_r
        spawn_opts[:out] = out_w
        spawn_opts[:err] = err_w

        result = {
            :pid => nil,
            :status => nil,
            :out => [],
            :err => [],
            :timeout => false,
        }

        out_reader = nil
        err_reader = nil
        wait_thr = nil

        begin
          Timeout.timeout(opts[:timeout]) do
            result[:pid] = spawn(*cmd, spawn_opts)
            wait_thr = Process.detach(result[:pid])
            in_r.close
            out_w.close
            err_w.close

            out_reader = Thread.new {out_r.read}
            err_reader = Thread.new {err_r.read}

            in_w.write opts[:stdin_data]
            in_w.close

            result[:status] = wait_thr.value
          end

        rescue Timeout::Error
          result[:timeout] = true
          pid = spawn_opts[:pgroup] ? -result[:pid] : result[:pid]
          Process.kill(opts[:signal], pid)
          if opts[:kill_after]
            unless wait_thr.join(opts[:kill_after])
              Process.kill(:KILL, pid)
            end
          end

        rescue StandardError => e
          result[:err] = [e.class.name, e.message]

        ensure
          result[:status] = wait_thr.value.exitstatus if wait_thr
          result[:out] += out_reader.value.split("\n").map(&:chomp) if out_reader
          result[:err] += err_reader.value.split("\n").map(&:chomp) if err_reader
          out_r.close unless out_r.closed?
          err_r.close unless err_r.closed?
        end

        result

      end

    end

  end
end


text:
var parent = require('../../es/symbol/search');

module.exports = parent;


text:
require 'rubygems'
require 'bundler/setup'

require 'active_record'
require 'rds/authorization'
require 'rds/role'
require 'rds/user'
require 'rails'
require 'rails-api'
require 'action_controller/railtie' # allows ActionController::Base
require 'rspec/rails'

RSpec.configure do |config|
end

module TestRailsApp
  class Application < Rails::Application
    # app config here
    config.secret_token = '572c86f5ede338bd8aba8dae0fd3a326aabababc98d1e6ce34b9f5'

    # routes.draw do
    #   resources :models
    # end
  end

  class ApplicationController < ActionController::Base
    # setup
  end

end


text:
#ifndef HEADER_CURL_TOOL_URLGLOB_H
#define HEADER_CURL_TOOL_URLGLOB_H

#include "tool_setup.h"

typedef enum {
  UPTSet = 1,
  UPTCharRange,
  UPTNumRange
} URLPatternType;

typedef struct {
  URLPatternType type;
  int globindex; /* the number of this particular glob or -1 if not used
                    within {} or [] */
  union {
    struct {
      char **elements;
      int size;
      int ptr_s;
    } Set;
    struct {
      char min_c;
      char max_c;
      char ptr_c;
      int step;
    } CharRange;
    struct {
      unsigned long min_n;
      unsigned long max_n;
      int padlength;
      unsigned long ptr_n;
      unsigned long step;
    } NumRange ;
  } content;
} URLPattern;

/* the total number of globs supported */
#define GLOB_PATTERN_NUM 100

typedef struct {
  URLPattern pattern[GLOB_PATTERN_NUM];
  size_t size;
  size_t urllen;
  char *glob_buffer;
  char beenhere;
  const char *error; /* error message */
  size_t pos;        /* column position of error or 0 */
} URLGlob;

int glob_url(URLGlob**, char*, unsigned long *, FILE *);
int glob_next_url(char **, URLGlob *);
int glob_match_url(char **, char*, URLGlob *);
void glob_cleanup(URLGlob* glob);

#endif /* HEADER_CURL_TOOL_URLGLOB_H */