text:
Button to toggle between fullscreen and normal mode.

## HTML Definition

```html
<vg-player>
    <vg-controls>
        <vg-fullscreen></vg-fullscreen>
    </vg-controls>

    <video #myMedia
           [vgMedia]="myMedia"
           id="my-video"
           src="http://static.videogular.com/assets/videos/videogular.mp4"
           type="video/mp4">
    </video>
</vg-player>
```

redpajama_set_name: RedPajamaGithub


text:
set -euo pipefail
set -x

if [[ $# -ne 1 ]]; then
    echo "Usage: $0 <Vespa version>"
    exit 1
fi

readonly VESPA_RELEASE="$1"
export JAVA_HOME=$(dirname $(dirname $(readlink -f /usr/bin/java)))

function is_published {
    local TMP_MVN_REPO=/tmp/maven-repo
    echo $TMP_MVN_REPO
    mkdir -p $TMP_MVN_REPO
    rm -rf $TMP_MVN_REPO/com/yahoo/vespa
    # Because the transfer of artifacts to Maven Central is not atomic we can't just check a simple pom or jar to be available. Because of this we
    # check that the publication is complete enough to compile a Java sample app
    if mvn -V -B -pl ai.vespa.examples:album-recommendation-java -Dmaven.repo.local=$TMP_MVN_REPO -Dmaven.javadoc.skip=true -Dmaven.source.skip=true -DskipTests clean package; then
        return 0
    else
        return 1
    fi
}

function wait_until_published {
    cnt=0
    until is_published; do
        ((cnt+=1))
        # Wait max 60 minutes
        if (( $cnt > 60 )); then
            echo "ERROR: Artifacts with version ${VESPA_RELEASE} not found on central maven repo."
            exit 1
        fi
        echo "Waiting 60 seconds for version ${VESPA_RELEASE} on central maven repo ($cnt times)."
        sleep 60
    done
}

ssh-add -D
set +x
ssh-add <(echo $SAMPLE_APPS_DEPLOY_KEY | base64 -d)
set -x

git clone git@github.com:vespa-engine/sample-apps.git
cd sample-apps

# Update Vespa version property in pom.xml
mvn -V -B versions:set-property -Dproperty=vespa_version -DnewVersion=${VESPA_RELEASE}

wait_until_published

changes=$(git status --porcelain | wc -l)

if (( changes > 0 )); then
    echo "Updating Vespa version to ${VESPA_RELEASE}."
    git commit -a -m "Update Vespa version to ${VESPA_RELEASE}."
    git pull --rebase
    git push
fi


text:
iris.screen(
    function (self) {
        self.create = function () {
            console.log("Welcome Screen Created");
            self.tmpl(iris.path.welcome.html);

            self.screens("screens", [
                ["home/:year/:month", iris.path.home.js]
            ]);
        };
    },
    iris.path.welcome.js
);


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;

namespace FlowSimulation.Test
{
    /// <summary>
    /// Логика взаимодействия для App.xaml
    /// </summary>
    public partial class App : Application
    {
    }
}


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

    Copyright (C) 2016 Selerity, Inc. (support@seleritycorp.com)

    Licensed 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.

-->
<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>

  <parent>
    <groupId>com.seleritycorp.pom</groupId>
    <artifactId>ApplicationBasePom</artifactId>
    <version>1.0.0</version>
  </parent>

  <groupId>com.seleritycorp.rds.downloader</groupId>
  <artifactId>RdsDataDownloader</artifactId>
  <version>1.0.2-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Rds Data Downloader</name>
  <description>Automatic downloading of Rds data</description>

  <scm></scm>

  <dependencies>
    <dependency>
      <groupId>com.seleritycorp.common.base</groupId>
      <artifactId>CommonBase</artifactId>
    </dependency>
    <dependency>
      <groupId>com.seleritycorp.common.base</groupId>
      <artifactId>CommonBase</artifactId>
      <type>test-jar</type>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>shade</goal>
            </goals>
            <phase>package</phase>
            <configuration>
              <filters>
                <filter>
                  <artifact>log4j:log4j</artifact>
                  <excludes>
                    <exclude>org/apache/log4j/Appender.class</exclude>
                    <exclude>org/apache/log4j/AppenderSkeleton.class</exclude>
                    <exclude>org/apache/log4j/AsyncAppender$DiscardSummary.class</exclude>
                    <exclude>org/apache/log4j/AsyncAppender$Dispatcher.class</exclude>
                    <exclude>org/apache/log4j/AsyncAppender.class</exclude>
                    <exclude>org/apache/log4j/BasicConfigurator.class</exclude>
                    <exclude>org/apache/log4j/Category.class</exclude>
                    <exclude>org/apache/log4j/CategoryKey.class</exclude>
                    <exclude>org/apache/log4j/ConsoleAppender$SystemErrStream.class</exclude>
                    <exclude>org/apache/log4j/ConsoleAppender$SystemOutStream.class</exclude>
                    <exclude>org/apache/log4j/ConsoleAppender.class</exclude>
                    <exclude>org/apache/log4j/DailyRollingFileAppender.class</exclude>
                    <exclude>org/apache/log4j/DefaultCategoryFactory.class</exclude>
                    <exclude>org/apache/log4j/DefaultThrowableRenderer.class</exclude>
                    <exclude>org/apache/log4j/Dispatcher.class</exclude>
                    <exclude>org/apache/log4j/EnhancedPatternLayout.class</exclude>
                    <exclude>org/apache/log4j/EnhancedThrowableRenderer.class</exclude>
                    <exclude>org/apache/log4j/FileAppender.class</exclude>
                    <exclude>org/apache/log4j/HTMLLayout.class</exclude>
                    <exclude>org/apache/log4j/Hierarchy.class</exclude>
                    <exclude>org/apache/log4j/Layout.class</exclude>
                    <exclude>org/apache/log4j/Level.class</exclude>
                    <exclude>org/apache/log4j/LogMF.class</exclude>
                    <exclude>org/apache/log4j/LogManager.class</exclude>
                    <exclude>org/apache/log4j/LogSF.class</exclude>
                    <exclude>org/apache/log4j/LogXF.class</exclude>
                    <exclude>org/apache/log4j/Logger.class</exclude>
                    <exclude>org/apache/log4j/MDC.class</exclude>
                    <exclude>org/apache/log4j/NDC$DiagnosticContext.class</exclude>
                    <exclude>org/apache/log4j/NDC.class</exclude>
                    <exclude>org/apache/log4j/NameValue.class</exclude>
                    <exclude>org/apache/log4j/PatternLayout.class</exclude>
                    <exclude>org/apache/log4j/Priority.class</exclude>
                    <exclude>org/apache/log4j/PropertyConfigurator.class</exclude>
                    <exclude>org/apache/log4j/PropertyWatchdog.class</exclude>
                    <exclude>org/apache/log4j/ProvisionNode.class</exclude>
                    <exclude>org/apache/log4j/RollingCalendar.class</exclude>
                    <exclude>org/apache/log4j/RollingFileAppender.class</exclude>
                    <exclude>org/apache/log4j/SimpleLayout.class</exclude>
                    <exclude>org/apache/log4j/SortedKeyEnumeration.class</exclude>
                    <exclude>org/apache/log4j/TTCCLayout.class</exclude>
                    <exclude>org/apache/log4j/WriterAppender.class</exclude>
                    <exclude>org/apache/log4j/pattern/BridgePatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/BridgePatternParser.class</exclude>
                    <exclude>org/apache/log4j/pattern/CachedDateFormat.class</exclude>
                    <exclude>org/apache/log4j/pattern/ClassNamePatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/DatePatternConverter$DefaultZoneDateFormat.class</exclude>
                    <exclude>org/apache/log4j/pattern/DatePatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/FileDatePatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/FileLocationPatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/FormattingInfo.class</exclude>
                    <exclude>org/apache/log4j/pattern/FullLocationPatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/IntegerPatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/LevelPatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/LineLocationPatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/LineSeparatorPatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/LiteralPatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/LogEvent.class</exclude>
                    <exclude>org/apache/log4j/pattern/LoggerPatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/LoggingEventPatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/MessagePatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/MethodLocationPatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/NDCPatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/NameAbbreviator$DropElementAbbreviator.class</exclude>
                    <exclude>org/apache/log4j/pattern/NameAbbreviator$MaxElementAbbreviator.class</exclude>
                    <exclude>org/apache/log4j/pattern/NameAbbreviator$NOPAbbreviator.class</exclude>
                    <exclude>org/apache/log4j/pattern/NameAbbreviator$PatternAbbreviator.class</exclude>
                    <exclude>org/apache/log4j/pattern/NameAbbreviator$PatternAbbreviatorFragment.class</exclude>
                    <exclude>org/apache/log4j/pattern/NameAbbreviator.class</exclude>
                    <exclude>org/apache/log4j/pattern/NamePatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/PatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/PatternParser$ReadOnlyMap.class</exclude>
                    <exclude>org/apache/log4j/pattern/PatternParser.class</exclude>
                    <exclude>org/apache/log4j/pattern/PropertiesPatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/RelativeTimePatternConverter$CachedTimestamp.class</exclude>
                    <exclude>org/apache/log4j/pattern/RelativeTimePatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/SequenceNumberPatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/ThreadPatternConverter.class</exclude>
                    <exclude>org/apache/log4j/pattern/ThrowableInformationPatternConverter.class</exclude>
                    <exclude>org/apache/log4j/spi/AppenderAttachable.class</exclude>
                    <exclude>org/apache/log4j/spi/Configurator.class</exclude>
                    <exclude>org/apache/log4j/spi/DefaultRepositorySelector.class</exclude>
                    <exclude>org/apache/log4j/spi/ErrorCode.class</exclude>
                    <exclude>org/apache/log4j/spi/ErrorHandler.class</exclude>
                    <exclude>org/apache/log4j/spi/Filter.class</exclude>
                    <exclude>org/apache/log4j/spi/HierarchyEventListener.class</exclude>
                    <exclude>org/apache/log4j/spi/LocationInfo.class</exclude>
                    <exclude>org/apache/log4j/spi/LoggerFactory.class</exclude>
                    <exclude>org/apache/log4j/spi/LoggerRepository.class</exclude>
                    <exclude>org/apache/log4j/spi/LoggingEvent.class</exclude>
                    <exclude>org/apache/log4j/spi/NOPLogger.class</exclude>
                    <exclude>org/apache/log4j/spi/NOPLoggerRepository.class</exclude>
                    <exclude>org/apache/log4j/spi/NullWriter.class</exclude>
                    <exclude>org/apache/log4j/spi/OptionHandler.class</exclude>
                    <exclude>org/apache/log4j/spi/RendererSupport.class</exclude>
                    <exclude>org/apache/log4j/spi/RepositorySelector.class</exclude>
                    <exclude>org/apache/log4j/spi/RootCategory.class</exclude>
                    <exclude>org/apache/log4j/spi/RootLogger.class</exclude>
                    <exclude>org/apache/log4j/spi/ThrowableInformation.class</exclude>
                    <exclude>org/apache/log4j/spi/ThrowableRenderer.class</exclude>
                    <exclude>org/apache/log4j/spi/ThrowableRendererSupport.class</exclude>
                    <exclude>org/apache/log4j/spi/TriggeringEventEvaluator.class</exclude>
                    <exclude>org/apache/log4j/spi/VectorWriter.class</exclude>
                    <exclude>org/apache/log4j/varia/DenyAllFilter.class</exclude>
                    <exclude>org/apache/log4j/varia/ExternallyRolledFileAppender.class</exclude>
                    <exclude>org/apache/log4j/varia/FallbackErrorHandler.class</exclude>
                    <exclude>org/apache/log4j/varia/HUP.class</exclude>
                    <exclude>org/apache/log4j/varia/HUPNode.class</exclude>
                    <exclude>org/apache/log4j/varia/LevelMatchFilter.class</exclude>
                    <exclude>org/apache/log4j/varia/LevelRangeFilter.class</exclude>
                    <exclude>org/apache/log4j/varia/NullAppender.class</exclude>
                    <exclude>org/apache/log4j/varia/ReloadingPropertyConfigurator.class</exclude>
                    <exclude>org/apache/log4j/varia/Roller.class</exclude>
                    <exclude>org/apache/log4j/varia/StringMatchFilter.class</exclude>
                    <exclude>org/apache/log4j/xml/DOMConfigurator$1.class</exclude>
                    <exclude>org/apache/log4j/xml/DOMConfigurator$2.class</exclude>
                    <exclude>org/apache/log4j/xml/DOMConfigurator$3.class</exclude>
                    <exclude>org/apache/log4j/xml/DOMConfigurator$4.class</exclude>
                    <exclude>org/apache/log4j/xml/DOMConfigurator$5.class</exclude>
                    <exclude>org/apache/log4j/xml/DOMConfigurator$ParseAction.class</exclude>
                    <exclude>org/apache/log4j/xml/DOMConfigurator.class</exclude>
                    <exclude>org/apache/log4j/xml/Log4jEntityResolver.class</exclude>
                    <exclude>org/apache/log4j/xml/SAXErrorHandler.class</exclude>
                    <exclude>org/apache/log4j/xml/UnrecognizedElementHandler.class</exclude>
                    <exclude>org/apache/log4j/xml/XMLLayout.class</exclude>
                    <exclude>org/apache/log4j/xml/XMLWatchdog.class</exclude>
                  </excludes>
                </filter>
              </filters>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
<?php

	namespace Uneak\AssetsBundle\Webpack\Configuration;

	use Uneak\AssetsBundle\Javascript\JsItem\JsAbstract;

	class Module extends JsAbstract implements ExtraInterface {

		use ExtraTrait;

		private $noParse = null;
		private $rules;

		/**
		 * @return \Uneak\AssetsBundle\Webpack\Configuration\ModuleRules
		 */
		public function rules() {
			if (!$this->rules) {
				$this->rules = new ModuleRules();
			}
			return $this->rules;
		}

		/**
		 * @return null
		 */
		public function getNoParse() {
			return $this->noParse;
		}

		/**
		 * @param null $noParse
		 */
		public function setNoParse($noParse) {
			$this->noParse = $noParse;
		}

		protected function _getData() {
			return array(
				'noParse' => $this->getNoParse(),
				'rules'   => $this->rules,
			);
		}

	}


text:
You can contribute to the development of tools or the framework. Read the manual [how we collaborate](https://docs.google.com/document/d/1UOXjD0SKxN7vDQGC31ddVd-kaVXClSCzfGPvYjqQrFQ/edit?usp=sharing)

## Cloning the repository

Vizabi depends on [Git] (http://git-scm.com/), [Npm](https://github.com/npm/npm), [Gulp](http://gulpjs.com/) [Sass](http://sass-lang.com/install), and [SCSS Lint](https://github.com/brigade/scss-lint).

**Installation Requirements For Mac Users**

1. Install git http://git-scm.com/download/mac
2. Install nodejs https://nodejs.org/en/
3. Install Gulp `npm install --global gulp` (run with sudo if needed)
4. Install sass `gem install sass` (run with sudo if needed)
5. Install scss_lint `gem install scss_lint` (run with sudo if needed)

**Clone this repo** and run the following commands in vizabi root folder:

```shell
npm install
```

If you are still puzzled what it is or it just doesn't work, read a [more detailed instruction](https://github.com/Gapminder/vizabi/wiki/Quickstart-for-Windows)
(it's for Windows, but you'll figure things out if you have a Mac or Linux)

## Build the project

In order to run the project in **development mode**, type the following:

```shell
gulp
```

The browser will open on `http://localhost:8080/preview/`

In order to only build the project, type the following (you'll rarely need this):

```shell
gulp build
```

You can find the build output under ```build/``` folder.


text:
from . import ExplorationTechnique

class TechniqueBuilder(ExplorationTechnique):
    """
    This meta technique could be used to hook a couple of simulation manager methods
    without actually creating a new exploration technique, for example:

    class SomeComplexAnalysis(Analysis):

        def do_something():
            simgr = self.project.factory.simulation_manager()
            simgr.use_tech(ProxyTechnique(step_state=self._step_state))
            simgr.run()

        def _step_state(self, state):
            # Do stuff!
            pass

    In the above example, the _step_state method can access all the necessary stuff,
    hidden in the analysis instance, without passing that instance to a one-shot-styled
    exploration technique.
    """

    def __init__(self, setup=None, step_state=None, step=None, successors=None,
                 filter=None, selector=None, complete=None):
        super(TechniqueBuilder, self).__init__()
        self.setup = _its_a_func(setup) or super(TechniqueBuilder, self).setup
        self.step_state = _its_a_func(step_state) or super(TechniqueBuilder, self).step_state
        self.step = _its_a_func(step) or super(TechniqueBuilder, self).step
        self.filter = _its_a_func(filter) or super(TechniqueBuilder, self).filter
        self.successors = _its_a_func(successors) or super(TechniqueBuilder, self).successors
        self.selector = _its_a_func(selector) or super(TechniqueBuilder, self).selector
        self.complete = _its_a_func(complete) or super(TechniqueBuilder, self).complete

def _its_a_func(func):
    """
    In case the target func doesn't have it's `im_func` attr set.

    :param func:
    :return:
    """
    if func is not None:
        func.im_func = True
    return func


text:
<?php namespace Fedex\Services;

/**
 * Class LabelSpecification
 * @package Fedex\Services
 */
class LabelSpecification {

	/**
	 * @return array
	 */
	public function get() {
		return [
			'LabelFormatType' => 'COMMON2D',// valid values COMMON2D, LABEL_DATA_ONLY
			'ImageType'       => 'PDF',	// valid values DPL, EPL2, PDF, ZPLII and PNG
			'LabelStockType'  => 'PAPER_8.5X11_TOP_HALF_LABEL'
		];
	}
}


text:
#include "PlatformDetermination.h"
#include "Exceptions.h"
#include "CPfilepaths.h"
#include "CPstrings.h"
#include "CoolPropTools.h"

#include <fstream>
#include <algorithm>
#include <sys/types.h>
#include <sys/stat.h>
#include <cerrno>

// This will kill the horrible min and max macros
#ifndef NOMINMAX
#    define NOMINMAX
#endif

#if defined(__ISWINDOWS__)
#    define UNICODE
#    define _UNICODE
#    include "Windows.h"
#    include <windows.h>  // for the CreateDirectory function
#else
#    include <unistd.h>
#    if !defined(__powerpc__)
#        include <pwd.h>
#    endif
#endif

#if defined(__ISWINDOWS__)
/// From http://stackoverflow.com/a/17827724/1360263
bool IsBrowsePath(const std::wstring& path) {
    return (path == L"." || path == L"..");
}
unsigned long long CalculateDirSize(const std::wstring& path, std::vector<std::wstring>* errVect) {
    unsigned long long size = 0;
    WIN32_FIND_DATAW data;
    HANDLE sh = NULL;
    sh = FindFirstFileW((path + L"\\*").c_str(), &data);

    if (sh == INVALID_HANDLE_VALUE) {
        //if we want, store all happened error
        if (errVect != NULL) errVect->push_back(path);
        return size;
    }

    do {
        // skip current and parent
        if (!IsBrowsePath(data.cFileName)) {
            // if found object is ...
            if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                // directory, then search it recursievly
                size += CalculateDirSize(path + L"\\" + data.cFileName, NULL);
            else
                // otherwise get object size and add it to directory size
                size += data.nFileSizeHigh * (unsigned long long)(MAXDWORD) + data.nFileSizeLow;
        }

    } while (FindNextFileW(sh, &data));  // do

    FindClose(sh);

    return size;
}
#elif defined(__ANDROID__) || defined(__powerpc__)
// Android doesn't have ftw.h, also doesn't accept not having this file
unsigned long long CalculateDirSize(const std::string& path) {
    return 0;
}
#else
#    include <ftw.h>
#    include <stdint.h>
#    include <iostream>

static thread_local unsigned long long ftw_summer;  // An evil global variable for the ftw function
int ftw_function(const char* fpath, const struct stat* sb, int tflag, struct FTW* ftwbuf) {
    ftw_summer += sb->st_size;
    return 0; /* To tell nftw() to continue */
}
unsigned long long CalculateDirSize(const std::string& path) {
    ftw_summer = 0;
    int flags = 0 | FTW_DEPTH | FTW_PHYS;
    nftw(path.c_str(), ftw_function, 20, flags);
    double temp = ftw_summer;
    ftw_summer = 0;
    return temp;
}
#endif

std::vector<char> get_binary_file_contents(const char* filename) {
    std::ifstream in(filename, std::ios::in | std::ios::binary);
    if (in) {
        std::vector<char> contents;
        in.seekg(0, std::ios::end);
        contents.resize((unsigned int)in.tellg());
        in.seekg(0, std::ios::beg);
        in.read(&contents[0], contents.size());
        in.close();
        return (contents);
    }
    throw(errno);
}

void make_dirs(std::string file_path) {
    std::replace(file_path.begin(), file_path.end(), '\\', '/');  // replace all '\' with '/'

#if defined(__ISWINDOWS__)
    const char sep = '\\';  // well, Windows (and DOS) allows forward slash "/", too :)
#else
    const char sep = '/';
#endif

    std::vector<std::string> pathsplit = strsplit(file_path, '/');
    std::string path = pathsplit[0];  // will throw if pathsplit.size() == 0
    for (std::size_t i = 0, sz = pathsplit.size(); i < sz; i++) {
        if (!path_exists(path)) {
#if defined(__ISWINDOWS__)  // Defined for 32-bit and 64-bit windows
            int errcode = CreateDirectoryA((LPCSTR)path.c_str(), NULL);
            if (errcode == 0) {
                switch (GetLastError()) {
                    case ERROR_ALREADY_EXISTS:
                        break;
                    case ERROR_PATH_NOT_FOUND:
                        throw CoolProp::ValueError(format("Unable to make the directory %s", path.c_str()));
                    default:
                        break;
                }
            }
#else
#    if defined(__powerpc__)
#    else
            mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
#    endif
#endif
        }
        if (i < (sz - 1)) path += format("%c%s", sep, pathsplit[i + 1].c_str());
    }
};

std::string get_separator(void) {
#if defined(__ISLINUX__)
    return std::string("/");
#elif defined(__ISAPPLE__)
    return std::string("/");
#elif defined(__ISWINDOWS__)
    return std::string("\\");
#else
    throw CoolProp::NotImplementedError("This function is not defined for your platform.");
#endif
}

std::string get_home_dir(void) {
// See http://stackoverflow.com/questions/2552416/how-can-i-find-the-users-home-dir-in-a-cross-platform-manner-using-c
#if defined(__ISLINUX__)
    char* home = NULL;
    home = getenv("HOME");
    return std::string(home);
#elif defined(__ISAPPLE__)
    char* home = NULL;
    home = getenv("HOME");
    if (home == NULL) {
        struct passwd* pwd = getpwuid(getuid());
        if (pwd) {
            home = pwd->pw_dir;
        }
    }
    if (home == NULL) {
        throw CoolProp::NotImplementedError("Could not detect home directory.");
    }
    return std::string(home);
#elif defined(__ISWINDOWS__)
#    if defined(_MSC_VER)
#        pragma warning(push)
#        pragma warning(disable : 4996)
#    endif
    char* pUSERPROFILE = getenv("USERPROFILE");
    if (pUSERPROFILE != NULL) {
        return std::string(pUSERPROFILE);
    } else {
        char* pHOMEDRIVE = getenv("HOMEDRIVE");
        char* pHOMEPATH = getenv("HOMEPATH");
        if (pHOMEDRIVE != NULL && pHOMEPATH != NULL) {
            return std::string(pHOMEDRIVE) + std::string(pHOMEPATH);
        } else {
            return std::string("");
        }
    }
#    if defined(_MSC_VER)
#        pragma warning(pop)
#    endif
#else
    throw CoolProp::NotImplementedError("This function is not defined for your platform.");
#endif
};

bool path_exists(const std::string& path) {
    std::string path_cpy;
    if (endswith(path, get_separator())) {
        path_cpy = path.substr(0, path.size() - 1);
    } else {
        path_cpy = path;
    }

#if defined(__ISWINDOWS__)  // Defined for 32-bit and 64-bit windows
    struct _stat buf;
    // Get data associated with path using the windows libraries,
    // and if you can (result == 0), the path exists
    if (_stat(path_cpy.c_str(), &buf) == 0) {
        return true;
    } else {
        return false;
    }
#elif defined(__ISLINUX__) || defined(__ISAPPLE__)
    struct stat st;
    if (lstat(path_cpy.c_str(), &st) == 0) {
        if (S_ISDIR(st.st_mode)) return true;
        if (S_ISREG(st.st_mode)) return true;
        return false;
    } else {
        return false;
    }
#else
    throw CoolProp::NotImplementedError("This function is not defined for your platform.");
#endif
};

std::string join_path(const std::string& one, const std::string& two) {
    std::string result;
    std::string separator = get_separator();
    if (!endswith(one, separator) && !one.empty()) {
        result = one + separator;
    } else {
        result = one;
    }
    result.append(two);
    return result;
}

std::string get_file_contents(const char* filename) {
    std::ifstream in(filename, std::ios::in | std::ios::binary);
    if (in) {
        std::string contents;
        in.seekg(0, std::ios::end);
        contents.resize((unsigned int)in.tellg());
        in.seekg(0, std::ios::beg);
        in.read(&contents[0], contents.size());
        in.close();
        return (contents);
    }
    throw(errno);
}


text:
/**
 * @author Gordon from Blumberg
 * @description Module for units, creates and characters
 * @version 1.0.0
 */

define(['GBL', 'protounit', 'config'], function(gbl, pu, cg) {
    "use strict";

	var unit={};

    unit.name='unit.js';
    unit.version='1.0.0';

    /* Properties for opts:
     * race: str;
     * avaSrc: str;
     */

    unit.Unit=function(opts) {
        var parsOpts={};

        this._super(opts);

        this.race=(opts.race in cg.races)?opts.race:'human';

        this.avaSrc=opts.avaSrc;
    }.inherit(pu.Protounit);

    unit.Unit.prototype.extend({
        prefixes:[
            {pref: 'race', dep: 'base'},
            {pref: 'modCreate', dep: 'base'},
            {pref: 'modOther', dep: 'base'},
            {pref: 'modTrain', dep: 'base'},
            {pref: 'modSkill', dep: 'base'},
            {pref: 'modEquip', dep: 'base'},
            {pref: 'modSpell', dep: 'base'},
            {pref: 'base', dep: 'sum(race$,modCreate$)'},
            {pref: 'own', dep: 'sum(base$,modTrain$,modSkill$)'},
            {pref: 'temp', dep: 'sum(modOther$,modEquip$,modSpell$)'},
            {pref: 'act', dep: 'sum(own$,temp$)'}
        ],
        setAva:function(src) {
            this.elem.css({backgroundImage:'url(img/creatures/'+src+')'})
        },
        createElement:function(opts) {  //opts is object for method createElement
            this.elem=createElement('div',opts)
        },
        setPosition:function(hex) {
            var th=this,
                bf=currentBattlefield,
                hexCoor=hex.getCoords().center,
                az,el=th.elem[0];
            th.currentPosition=hex;
            if (th.direction===undefined) th.direction=3;
            az=(720+bf.getAngleAzimut()-th.direction*60)%360;
            el.reflect=(az>90&&az<270)?1:0;
            el.x=hexCoor.x;
            el.y=hexCoor.y;
            if (!th.elem.isChildren(bf.scene3d)) th.elem.insertTo(bf.scene3d)
        }
    },true);

    return unit;
});


text:
package com.basistech.rosette.apimodel;

import com.basistech.rosette.annotations.JacksonMixin;
import lombok.Builder;
import lombok.Value;

import java.util.List;

/**
 * Sentences with all extracted syntactical dependencies in it
 */
@Value
@Builder
@JacksonMixin
public class SentenceWithDependencies {

    /**
     * @return start token index
     */
    private final Integer startTokenIndex;

    /**
     * @return end token index
     */
    private final Integer endTokenIndex;

    /**
     * @return list of syntactical dependencies
     */
    private final List<Dependency> dependencies;
}


text:
<?php

class BookletAttributesTest extends PHPUnit_Framework_TestCase
{
    private $attributes;

    public function testPackWithRoot()
    {
        $this->assertXmlStringEqualsXmlFile(dirname(__FILE__) . '/../../fixtures/booklet_attributes.xml', $this->attributes->pack(true));
    }

    public function testPackWithoutRoot()
    {
        $this->assertXmlStringEqualsXmlFile(dirname(__FILE__) . '/../../fixtures/booklet_attributes.xml', $this->attributes->pack());
    }

    protected function setUp()
    {
        $this->attributes = new InkRouter_Models_Attributes_BookletAttributes();
        $this->attributes
            ->setCover('plus')
            ->setBinding('saddle')
            ->setPages(8)
            ->setTabbing(3)
            ->setShrinkWrapping(12)
            ->setHoleMaking('R3 3/16')
            ->setCoverSubstrate('14PT');
    }
}


text:
package net.jxta.impl.xindice.core.indexer;

import net.jxta.impl.xindice.core.DBException;
import net.jxta.impl.xindice.core.data.Key;
import net.jxta.impl.xindice.core.filer.BTree;
import net.jxta.impl.xindice.core.filer.BTreeCorruptException;

import java.io.File;
import java.io.IOException;

/**
 * NameIndexer is a basic implementation of the Indexer interface.
 * It is used for maintaining element and element@attribute unique
 * indexes.
 */

public final class NameIndexer extends BTree implements Indexer {

    private static final short PAGESIZE = 4096;
    // TODO: MAXKEYSIZE might need tuning
    private static final short MAXKEYSIZE = 256;

    private FileHeader fileHeader;

    public NameIndexer() {
        super();
        fileHeader = getFileHeader();
        fileHeader.setPageSize(PAGESIZE);
        fileHeader.setMaxKeySize(MAXKEYSIZE);
    }

    public void setLocation(String dir, String file) {
        setFile(new File(dir, file + ".idx"));
    }

    public synchronized void remove(Key key) throws DBException {
        try {
            removeValue(key);
        } catch (IOException e) {
            throw new BTreeCorruptException("Corruption detected on remove");
        }
    }

    public synchronized void add(Key key, long pos) throws DBException {
        try {
            addValue(key, pos);
            flush();
        } catch (IOException e) {
            throw new BTreeCorruptException("Corruption detected on add");
        }
    }
}


text:
module.exports = function() {
  this.num = null
  this.message = null
  this.stmt = ""
  this.params = []
}


text:
YUI.add('datasource-io', function (Y, NAME) {

/**
 * Provides a DataSource implementation which can be used to retrieve data via the IO Utility.
 *
 * @module datasource
 * @submodule datasource-io
 */

/**
 * IO subclass for the DataSource Utility.
 * @class DataSource.IO
 * @extends DataSource.Local
 * @constructor
 */
var DSIO = function() {
    DSIO.superclass.constructor.apply(this, arguments);
};

    /////////////////////////////////////////////////////////////////////////////
    //
    // DataSource.IO static properties
    //
    /////////////////////////////////////////////////////////////////////////////
Y.mix(DSIO, {
    /**
     * Class name.
     *
     * @property NAME
     * @type String
     * @static
     * @final
     * @value "dataSourceIO"
     */
    NAME: "dataSourceIO",

    /////////////////////////////////////////////////////////////////////////////
    //
    // DataSource.IO Attributes
    //
    /////////////////////////////////////////////////////////////////////////////

    ATTRS: {
        /**
         * Pointer to IO Utility.
         *
         * @attribute io
         * @type Y.io
         * @default Y.io
         */
        io: {
            value: Y.io,
            cloneDefaultValue: false
        },

        /**
         * Default IO Config.
         *
         * @attribute ioConfig
         * @type Object
         * @default null
         */
         ioConfig: {
            value: null
         }
    }
});

Y.extend(DSIO, Y.DataSource.Local, {
    /**
    * Internal init() handler.
    *
    * @method initializer
    * @param config {Object} Config object.
    * @private
    */
    initializer: function(config) {
        this._queue = {interval:null, conn:null, requests:[]};
    },

    /**
    * IO success callback.
    *
    * @method successHandler
    * @param id {String} Transaction ID.
    * @param response {String} Response.
    * @param e {Event.Facade} Event facade.
    * @private
    */
    successHandler: function (id, response, e) {
        var defIOConfig = this.get("ioConfig"),
            payload = e.details[0];

        delete Y.DataSource.Local.transactions[e.tId];

        payload.data = response;
        this.fire("data", payload);

        Y.log("Received IO data response for \"" + e.request + "\"", "info", "datasource-io");

        if (defIOConfig && defIOConfig.on && defIOConfig.on.success) {
            defIOConfig.on.success.apply(defIOConfig.context || Y, arguments);
        }
    },

    /**
    * IO failure callback.
    *
    * @method failureHandler
    * @param id {String} Transaction ID.
    * @param response {String} Response.
    * @param e {Event.Facade} Event facade.
    * @private
    */
    failureHandler: function (id, response, e) {
        var defIOConfig = this.get("ioConfig"),
            payload = e.details[0];

        delete Y.DataSource.Local.transactions[e.tId];

        payload.error = new Error("IO data failure");
        Y.log("IO data failure", "error", "datasource-io");

        payload.data = response;
        this.fire("data", payload);

        Y.log("Received IO data failure for \"" + e.request + "\"", "info", "datasource-io");

        if (defIOConfig && defIOConfig.on && defIOConfig.on.failure) {
            defIOConfig.on.failure.apply(defIOConfig.context || Y, arguments);
        }
    },

    /**
    * @property _queue
    * @description Object literal to manage asynchronous request/response
    * cycles enabled if queue needs to be managed (asyncMode/ioConnMode):
    *

    *
interval {Number}

    *
Interval ID of in-progress queue.

    *
conn

    *
In-progress connection identifier (if applicable).

    *
requests {Object[]}

    *
Array of queued request objects: {request:request, callback:callback}.

    *

    * @type Object
    * @default {interval:null, conn:null, requests:[]}
    * @private
    */
    _queue: null,

    /**
     * Passes query string to IO. Fires response event when
     * response is received asynchronously.
     *
     * @method _defRequestFn
     * @param e {Event.Facade} Event Facade with the following properties:
     *

     *
tId (Number)

Unique transaction ID.

     *
request (Object)

The request.

     *
callback (Object)

The callback object with the following properties:
     *

     *
success (Function)

Success handler.

     *
failure (Function)

Failure handler.

     *

     *

     *
cfg (Object)

Configuration object.

     *

     * @protected
     */
    _defRequestFn: function(e) {
        var uri = this.get("source"),
            io = this.get("io"),
            defIOConfig = this.get("ioConfig"),
            request = e.request,
            cfg = Y.merge(defIOConfig, e.cfg, {
                on: Y.merge(defIOConfig, {
                    success: this.successHandler,
                    failure: this.failureHandler
                }),
                context: this,
                "arguments": e
            });

        // Support for POST transactions
        if(Y.Lang.isString(request)) {
            if(cfg.method && (cfg.method.toUpperCase() === "POST")) {
                cfg.data = cfg.data ? cfg.data+request : request;
            }
            else {
                uri += request;
            }
        }
        Y.DataSource.Local.transactions[e.tId] = io(uri, cfg);
        return e.tId;
    }
});

Y.DataSource.IO = DSIO;

}, '3.11.0', {"requires": ["datasource-local", "io-base"]});


text:
package org.emboss.jemboss.gui.form;

import javax.swing.text.*;

import java.awt.Toolkit;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

/**
*
* JTextfield for int fields in the EMBOSS form
*
*/
public class TextFieldInt extends TextFieldSink
{

  private Toolkit toolkit;
  private NumberFormat integerFormatter;

  public TextFieldInt()
  {
    super();
    toolkit = Toolkit.getDefaultToolkit();
    integerFormatter = NumberFormat.getNumberInstance(Locale.UK);
    integerFormatter.setParseIntegerOnly(true);
  }

  public int getValue()
  {
    int retVal = 0;
    try
    {
      retVal = integerFormatter.parse(getText()).intValue();
    }
    catch (ParseException e)
    {
      // This should never happen because insertString allows
      // only properly formatted data to get in the field.
      //toolkit.beep();
    }
    return retVal;
  }

  public void setValue(int value)
  {
    setText(integerFormatter.format(value));
  }

  protected Document createDefaultModel()
  {
    return new WholeNumberDocument();
  }

  protected class WholeNumberDocument extends PlainDocument
  {
    public void insertString(int offs,
                             String str,
                             AttributeSet a)
              throws BadLocationException
    {
      char[] source = str.toCharArray();
      char[] result = new char[source.length];
      int j = 0;

      for (int i = 0; i < result.length; i++)
      {
        if (Character.isDigit(source[i]) ||
            source[i] == '-')
          result[j++] = source[i];
        else
        {
          if(source[i] != ',')
          {
            toolkit.beep();
            System.err.println("invalid character entered: " + source[i]);
          }
        }
      }
      super.insertString(offs, new String(result, 0, j), a);
    }
  }
}


text:
using namespace std;
using namespace EG3;

JAVACC_STRING_TYPE ReadFileFully(char *file_name) {
//	JAVACC_STRING_TYPE s;
//#if WIDE_CHAR
//	wifstream in;
//#else
//	ifstream in;
//#endif
//	in.open(file_name, ios::in);
//	// Very inefficient.
//	while (!in.eof()) {
//		s += in.get();
//	}
	return "1 + 2 * (a + b);\n";//s;
}

int main(int argc, char** argv) {
	cout << "Reading from standard input..." << endl;
	JAVACC_STRING_TYPE s = ReadFileFully(argv[1]);
	try {
	CharStream *stream = new CharStream(s.c_str(), s.size() - 1, 1, 1);
	ParserTokenManager *scanner = new ParserTokenManager(stream);
	Parser parser(scanner);
	ASTStart* n = parser.Start();
	n->dump("");
	cout << "Thank you." << endl;
	} catch (const ParseException& e) {

	}
	return 0;
}


text:
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Alessandro Tasora, Radu Serban
// =============================================================================

#include "chrono/geometry/ChLineSegment.h"
#include "chrono/physics/ChLinkTrajectory.h"

namespace chrono {

using namespace geometry;

// Register into the object factory, to enable run-time dynamic creation and persistence
CH_FACTORY_REGISTER(ChLinkTrajectory)

ChLinkTrajectory::ChLinkTrajectory() : modulo_s(false) {
    // initializes type
    type = LinkType::TRAJECTORY;

    // default s(t) function. User will provide better fx.
    space_fx = std::make_shared<ChFunction_Ramp>(0, 1.);

    // default trajectory is a segment
    trajectory_line = std::make_shared<ChLineSegment>();

    // Mask: initialize our LinkMaskLF (lock formulation mask)
    // to X  only. It was a LinkMaskLF because this class inherited from LinkLock.
    ((ChLinkMaskLF*)mask)->SetLockMask(true, true, true, false, false, false, false);

    ChangedLinkMask();
}

ChLinkTrajectory::ChLinkTrajectory(const ChLinkTrajectory& other) : ChLinkLock(other) {
    space_fx = std::shared_ptr<ChFunction>(other.space_fx->Clone());            // deep copy
    trajectory_line = std::shared_ptr<ChLine>(other.trajectory_line->Clone());  // deep copy
}

void ChLinkTrajectory::Set_space_fx(std::shared_ptr<ChFunction> m_funct) {
    space_fx = m_funct;
}

void ChLinkTrajectory::Set_trajectory_line(std::shared_ptr<geometry::ChLine> mline) {
    trajectory_line = mline;
}

void ChLinkTrajectory::UpdateTime(double time) {
    ChTime = time;

    double tstep = BDF_STEP_HIGH;
    double tr_time = space_fx->Get_y(time);
    double tr_timeB = space_fx->Get_y(time + tstep);
    double tr_timeA = space_fx->Get_y(time - tstep);

    if (trajectory_line) {
        Vector result, resultB, resultA;
        if (modulo_s) {
            tr_time = fmod(tr_time, 1);
            tr_timeA = fmod(tr_timeA, 1);
            tr_timeB = fmod(tr_timeB, 1);
        }
        trajectory_line->Evaluate(result, tr_time);
        trajectory_line->Evaluate(resultA, tr_timeA);
        trajectory_line->Evaluate(resultB, tr_timeB);

        ChMatrix33<> mw;
        mw.Set_A_quaternion(marker2->GetAbsCoord().rot);

        // if line coordinate is relative to body2:
        marker2->Impose_Rel_Coord(CSYSNORM);
        deltaC.pos = result;
        deltaC_dt.pos = (resultB - resultA) * 1 / (2 * tstep);
        deltaC_dtdt.pos = (resultA + resultB - result * 2) * 4 / pow(2 * tstep, 2);
        /*
        // if line coordinate is relative to absolute space:
        deltaC.pos = mw.MatrT_x_Vect(
                            Vsub (result, marker2->GetAbsCoord().pos));  // ***  CORRECT?
        deltaC_dt.pos =  mw.MatrT_x_Vect(
                            Vmul( Vsub(resultB, resultA), 1/(2*tstep)) );
        deltaC_dtdt.pos =  mw.MatrT_x_Vect (
                            Vmul   ( Vadd (Vadd (resultA, resultB),
                                   Vmul (result,-2)), 4/pow(2*tstep, 2) ) );
        */
        deltaC.rot = QUNIT;
        deltaC_dt.rot = QNULL;
        deltaC_dtdt.rot = QNULL;
    } else {
        GetLog() << "NO TRAJECTORY \n";
    }
}

void ChLinkTrajectory::Initialize(std::shared_ptr<ChBody> mbody1,
                                  std::shared_ptr<ChBody> mbody2,
                                  const ChVector<>& mpos1,
                                  std::shared_ptr<geometry::ChLine> mline) {
    ChLinkMarkers::Initialize(mbody1, mbody2, true, ChCoordsys<>(mpos1), ChCoordsys<>());
    this->Set_trajectory_line(mline);
}

void ChLinkTrajectory::ArchiveOUT(ChArchiveOut& marchive) {
    // version number
    marchive.VersionWrite<ChLinkTrajectory>();

    // serialize parent class
    ChLinkLock::ArchiveOUT(marchive);

    // serialize all member data:
    marchive << CHNVP(space_fx);
    marchive << CHNVP(trajectory_line);
    marchive << CHNVP(modulo_s);
}

void ChLinkTrajectory::ArchiveIN(ChArchiveIn& marchive) {
    // version number
    int version = marchive.VersionRead<ChLinkTrajectory>();

    // deserialize parent class
    ChLinkLock::ArchiveIN(marchive);

    // deserialize all member data:
    marchive >> CHNVP(space_fx);
    marchive >> CHNVP(trajectory_line);
    marchive >> CHNVP(modulo_s);
}

}  // end namespace chrono


text:
/**
 * AanwezigheidController
 *
 * @description :: Server-side logic for managing Aanwezigheids
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {

	getAanwezigheidslijst: function(req,res){
		Aanwezigheid.findOne({planning: req.param('planningID')})
			.populate('statussen')
			.exec(function callback(err,lijst){
			if(err) return res.negotiate(err);
			if(!lijst) return res.json(401, {err:'Aanwezigheidslijst niet gevonden'});
					res.json(lijst);
			});
	},

	updateAanwezigheidslijst: function(req,res){

		var statusOBJ = req.body;

			async.each(statusOBJ, function( statusobj, klaar){
				Aanwezigheidsstatus.update({aanwezigheidID: req.param('lijstID'),gebruikerID: statusobj.gebruikerID},{status: statusobj.status})
					.exec(function(err,rapport){
					if(err) return res.negotiate(err);
						klaar(err,statusobj);
					});

				},function(err){
					res.send('succes');
			});

	}
};


text:
namespace content {

class MockDeviceOrientationListener
    : public blink::WebDeviceOrientationListener {
 public:
  MockDeviceOrientationListener() : did_change_device_orientation_(false) {
    memset(&data_, 0, sizeof(data_));
  }
  virtual ~MockDeviceOrientationListener() { }

  virtual void didChangeDeviceOrientation(
      const blink::WebDeviceOrientationData& data) override {
    memcpy(&data_, &data, sizeof(data));
    did_change_device_orientation_ = true;
  }

  bool did_change_device_orientation() const {
    return did_change_device_orientation_;
  }
  void set_did_change_device_orientation(bool value) {
    did_change_device_orientation_ = value;
  }
  const blink::WebDeviceOrientationData& data() const {
    return data_;
  }

 private:
  bool did_change_device_orientation_;
  blink::WebDeviceOrientationData data_;

  DISALLOW_COPY_AND_ASSIGN(MockDeviceOrientationListener);
};

class DeviceOrientationEventPumpForTesting : public DeviceOrientationEventPump {
 public:
  DeviceOrientationEventPumpForTesting()
      : DeviceOrientationEventPump(0) { }
  ~DeviceOrientationEventPumpForTesting() override {}

  void OnDidStart(base::SharedMemoryHandle renderer_handle) {
    DeviceOrientationEventPump::OnDidStart(renderer_handle);
  }
  void SendStartMessage() override {}
  void SendStopMessage() override {}
  void FireEvent() override {
    DeviceOrientationEventPump::FireEvent();
    Stop();
    base::MessageLoop::current()->QuitWhenIdle();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(DeviceOrientationEventPumpForTesting);
};

class DeviceOrientationEventPumpTest : public testing::Test {
 public:
  DeviceOrientationEventPumpTest() {
      EXPECT_TRUE(shared_memory_.CreateAndMapAnonymous(
          sizeof(DeviceOrientationHardwareBuffer)));
  }

 protected:
  void SetUp() override {
    const DeviceOrientationHardwareBuffer* null_buffer = NULL;
    listener_.reset(new MockDeviceOrientationListener);
    orientation_pump_.reset(new DeviceOrientationEventPumpForTesting);
    buffer_ = static_cast<DeviceOrientationHardwareBuffer*>(
        shared_memory_.memory());
    ASSERT_NE(null_buffer, buffer_);
    memset(buffer_, 0, sizeof(DeviceOrientationHardwareBuffer));
    ASSERT_TRUE(shared_memory_.ShareToProcess(base::GetCurrentProcessHandle(),
        &handle_));
  }

  void InitBuffer() {
    blink::WebDeviceOrientationData& data = buffer_->data;
    data.alpha = 1;
    data.hasAlpha = true;
    data.beta = 2;
    data.hasBeta = true;
    data.gamma = 3;
    data.hasGamma = true;
    data.allAvailableSensorsAreActive = true;
  }

  void InitBufferNoData() {
    blink::WebDeviceOrientationData& data = buffer_->data;
    data.allAvailableSensorsAreActive = true;
  }

  MockDeviceOrientationListener* listener() { return listener_.get(); }
  DeviceOrientationEventPumpForTesting* orientation_pump() {
    return orientation_pump_.get();
  }
  base::SharedMemoryHandle handle() { return handle_; }
  DeviceOrientationHardwareBuffer* buffer() { return buffer_; }

 private:
  scoped_ptr<MockDeviceOrientationListener> listener_;
  scoped_ptr<DeviceOrientationEventPumpForTesting> orientation_pump_;
  base::SharedMemoryHandle handle_;
  base::SharedMemory shared_memory_;
  DeviceOrientationHardwareBuffer* buffer_;

  DISALLOW_COPY_AND_ASSIGN(DeviceOrientationEventPumpTest);
};

TEST_F(DeviceOrientationEventPumpTest, DidStartPolling) {
  base::MessageLoop loop;

  InitBuffer();
  orientation_pump()->Start(listener());
  orientation_pump()->OnDidStart(handle());

  base::MessageLoop::current()->Run();

  const blink::WebDeviceOrientationData& received_data = listener()->data();
  EXPECT_TRUE(listener()->did_change_device_orientation());
  EXPECT_TRUE(received_data.allAvailableSensorsAreActive);
  EXPECT_EQ(1, static_cast<double>(received_data.alpha));
  EXPECT_TRUE(received_data.hasAlpha);
  EXPECT_EQ(2, static_cast<double>(received_data.beta));
  EXPECT_TRUE(received_data.hasBeta);
  EXPECT_EQ(3, static_cast<double>(received_data.gamma));
  EXPECT_TRUE(received_data.hasGamma);
}

TEST_F(DeviceOrientationEventPumpTest, FireAllNullEvent) {
  base::MessageLoop loop;

  InitBufferNoData();
  orientation_pump()->Start(listener());
  orientation_pump()->OnDidStart(handle());

  base::MessageLoop::current()->Run();

  const blink::WebDeviceOrientationData& received_data = listener()->data();
  EXPECT_TRUE(listener()->did_change_device_orientation());
  EXPECT_TRUE(received_data.allAvailableSensorsAreActive);
  EXPECT_FALSE(received_data.hasAlpha);
  EXPECT_FALSE(received_data.hasBeta);
  EXPECT_FALSE(received_data.hasGamma);
}

TEST_F(DeviceOrientationEventPumpTest, UpdateRespectsOrientationThreshold) {
  base::MessageLoop loop;

  InitBuffer();
  orientation_pump()->Start(listener());
  orientation_pump()->OnDidStart(handle());

  base::MessageLoop::current()->Run();

  const blink::WebDeviceOrientationData& received_data = listener()->data();
  EXPECT_TRUE(listener()->did_change_device_orientation());
  EXPECT_TRUE(received_data.allAvailableSensorsAreActive);
  EXPECT_EQ(1, static_cast<double>(received_data.alpha));
  EXPECT_TRUE(received_data.hasAlpha);
  EXPECT_EQ(2, static_cast<double>(received_data.beta));
  EXPECT_TRUE(received_data.hasBeta);
  EXPECT_EQ(3, static_cast<double>(received_data.gamma));
  EXPECT_TRUE(received_data.hasGamma);

  buffer()->data.alpha =
      1 + DeviceOrientationEventPump::kOrientationThreshold / 2.0;
  listener()->set_did_change_device_orientation(false);

  // Reset the pump's listener.
  orientation_pump()->Start(listener());

  base::MessageLoop::current()->PostTask(FROM_HERE,
      base::Bind(&DeviceOrientationEventPumpForTesting::FireEvent,
                 base::Unretained(orientation_pump())));
  base::MessageLoop::current()->Run();

  EXPECT_FALSE(listener()->did_change_device_orientation());
  EXPECT_TRUE(received_data.allAvailableSensorsAreActive);
  EXPECT_EQ(1, static_cast<double>(received_data.alpha));
  EXPECT_TRUE(received_data.hasAlpha);
  EXPECT_EQ(2, static_cast<double>(received_data.beta));
  EXPECT_TRUE(received_data.hasBeta);
  EXPECT_EQ(3, static_cast<double>(received_data.gamma));
  EXPECT_TRUE(received_data.hasGamma);

  buffer()->data.alpha =
      1 + DeviceOrientationEventPump::kOrientationThreshold;
  listener()->set_did_change_device_orientation(false);

  // Reset the pump's listener.
  orientation_pump()->Start(listener());

  base::MessageLoop::current()->PostTask(FROM_HERE,
      base::Bind(&DeviceOrientationEventPumpForTesting::FireEvent,
                 base::Unretained(orientation_pump())));
  base::MessageLoop::current()->Run();

  EXPECT_TRUE(listener()->did_change_device_orientation());
  EXPECT_EQ(1 + DeviceOrientationEventPump::kOrientationThreshold,
      static_cast<double>(received_data.alpha));
}

}  // namespace content


text:
require 'mathcha/mathcha_helper'
require 'mathcha/mathcha_verify'

ActionView::Base.send(:include, Mathcha::MathchaHelper)
ActionController::Base.send(:include, Mathcha::MathchaVerify)


text:
package org.pentaho.di.job.entries.deletefile;

import org.pentaho.di.job.entry.validator.AbstractFileValidator;
import org.pentaho.di.job.entry.validator.AndValidator;
import org.pentaho.di.job.entry.validator.FileExistsValidator;
import org.pentaho.di.job.entry.validator.JobEntryValidatorUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.vfs2.FileObject;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.job.entry.validator.ValidatorContext;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.resource.ResourceEntry;
import org.pentaho.di.resource.ResourceEntry.ResourceType;
import org.pentaho.di.resource.ResourceReference;
import org.pentaho.metastore.api.IMetaStore;
import org.w3c.dom.Node;

/**
 * This defines a 'delete file' job entry. Its main use would be to delete trigger files, but it will delete any file.
 *
 * @author Sven Boden
 * @since 10-02-2007
 *
 */
public class JobEntryDeleteFile extends JobEntryBase implements Cloneable, JobEntryInterface {
  private static Class<?> PKG = JobEntryDeleteFile.class; // for i18n purposes, needed by Translator2!!

  private String filename;
  private boolean failIfFileNotExists;

  public JobEntryDeleteFile( String n ) {
    super( n, "" );
    filename = null;
    failIfFileNotExists = false;
  }

  public JobEntryDeleteFile() {
    this( "" );
  }

  public Object clone() {
    JobEntryDeleteFile je = (JobEntryDeleteFile) super.clone();
    return je;
  }

  public String getXML() {
    StringBuilder retval = new StringBuilder( 50 );

    retval.append( super.getXML() );
    retval.append( "      " ).append( XMLHandler.addTagValue( "filename", filename ) );
    retval.append( "      " ).append( XMLHandler.addTagValue( "fail_if_file_not_exists", failIfFileNotExists ) );
    if ( parentJobMeta != null ) {
      parentJobMeta.getNamedClusterEmbedManager().registerUrl( filename );
    }

    return retval.toString();
  }

  public void loadXML( Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers,
    Repository rep, IMetaStore metaStore ) throws KettleXMLException {
    try {
      super.loadXML( entrynode, databases, slaveServers );
      filename = XMLHandler.getTagValue( entrynode, "filename" );
      failIfFileNotExists = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "fail_if_file_not_exists" ) );
    } catch ( KettleXMLException xe ) {
      throw new KettleXMLException( BaseMessages.getString(
        PKG, "JobEntryDeleteFile.Error_0001_Unable_To_Load_Job_From_Xml_Node" ), xe );
    }
  }

  public void loadRep( Repository rep, IMetaStore metaStore, ObjectId id_jobentry, List<DatabaseMeta> databases,
    List<SlaveServer> slaveServers ) throws KettleException {
    try {
      filename = rep.getJobEntryAttributeString( id_jobentry, "filename" );
      failIfFileNotExists = rep.getJobEntryAttributeBoolean( id_jobentry, "fail_if_file_not_exists" );
    } catch ( KettleException dbe ) {
      throw new KettleException( BaseMessages.getString(
        PKG, "JobEntryDeleteFile.ERROR_0002_Unable_To_Load_From_Repository", id_jobentry ), dbe );
    }
  }

  public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_job ) throws KettleException {
    try {
      rep.saveJobEntryAttribute( id_job, getObjectId(), "filename", filename );
      rep.saveJobEntryAttribute( id_job, getObjectId(), "fail_if_file_not_exists", failIfFileNotExists );
    } catch ( KettleDatabaseException dbe ) {
      throw new KettleException( BaseMessages.getString(
        PKG, "JobEntryDeleteFile.ERROR_0003_Unable_To_Save_Job_To_Repository", id_job ), dbe );
    }
  }

  public void setFilename( String filename ) {
    this.filename = filename;
  }

  public String getFilename() {
    return filename;
  }

  public String getRealFilename() {
    return environmentSubstitute( getFilename() );
  }

  public Result execute( Result previousResult, int nr ) {
    Result result = previousResult;
    result.setResult( false );

    //Set Embedded NamedCluter MetatStore Provider Key so that it can be passed to VFS
    if ( parentJobMeta.getNamedClusterEmbedManager() != null ) {
      parentJobMeta.getNamedClusterEmbedManager()
        .passEmbeddedMetastoreKey( this, parentJobMeta.getEmbeddedMetastoreProviderKey() );
    }

    if ( filename != null ) {
      String realFilename = getRealFilename();

      FileObject fileObject = null;
      try {
        fileObject = KettleVFS.getFileObject( realFilename, this );

        if ( !fileObject.exists() ) {
          if ( isFailIfFileNotExists() ) {
            // File doesn't exist and fail flag is on.
            result.setResult( false );
            logError( BaseMessages.getString(
              PKG, "JobEntryDeleteFile.ERROR_0004_File_Does_Not_Exist", realFilename ) );
          } else {
            // File already deleted, no reason to try to delete it
            result.setResult( true );
            if ( log.isBasic() ) {
              logBasic( BaseMessages.getString( PKG, "JobEntryDeleteFile.File_Already_Deleted", realFilename ) );
            }
          }
        } else {
          boolean deleted = fileObject.delete();
          if ( !deleted ) {
            logError( BaseMessages.getString(
              PKG, "JobEntryDeleteFile.ERROR_0005_Could_Not_Delete_File", realFilename ) );
            result.setResult( false );
            result.setNrErrors( 1 );
          }
          if ( log.isBasic() ) {
            logBasic( BaseMessages.getString( PKG, "JobEntryDeleteFile.File_Deleted", realFilename ) );
          }
          result.setResult( true );
        }
      } catch ( Exception e ) {
        logError( BaseMessages.getString(
          PKG, "JobEntryDeleteFile.ERROR_0006_Exception_Deleting_File", realFilename, e.getMessage() ), e );
        result.setResult( false );
        result.setNrErrors( 1 );
      } finally {
        if ( fileObject != null ) {
          try {
            fileObject.close();
          } catch ( IOException ex ) { /* Ignore */
          }
        }
      }
    } else {
      logError( BaseMessages.getString( PKG, "JobEntryDeleteFile.ERROR_0007_No_Filename_Is_Defined" ) );
    }

    return result;
  }

  public boolean isFailIfFileNotExists() {
    return failIfFileNotExists;
  }

  public void setFailIfFileNotExists( boolean failIfFileExists ) {
    this.failIfFileNotExists = failIfFileExists;
  }

  public boolean evaluates() {
    return true;
  }

  public List<ResourceReference> getResourceDependencies( JobMeta jobMeta ) {
    List<ResourceReference> references = super.getResourceDependencies( jobMeta );
    if ( !Utils.isEmpty( filename ) ) {
      String realFileName = jobMeta.environmentSubstitute( filename );
      ResourceReference reference = new ResourceReference( this );
      reference.getEntries().add( new ResourceEntry( realFileName, ResourceType.FILE ) );
      references.add( reference );
    }
    return references;
  }

  public void check( List<CheckResultInterface> remarks, JobMeta jobMeta, VariableSpace space,
    Repository repository, IMetaStore metaStore ) {
    ValidatorContext ctx = new ValidatorContext();
    AbstractFileValidator.putVariableSpace( ctx, getVariables() );
    AndValidator.putValidators( ctx, JobEntryValidatorUtils.notNullValidator(), JobEntryValidatorUtils.fileExistsValidator() );
    if ( isFailIfFileNotExists() ) {
      FileExistsValidator.putFailIfDoesNotExist( ctx, true );
    }
    JobEntryValidatorUtils.andValidator().validate( this, "filename", remarks, ctx );
  }

  public static void main( String[] args ) {
    List<CheckResultInterface> remarks = new ArrayList<CheckResultInterface>();
    new JobEntryDeleteFile().check( remarks, null, new Variables(), null, null );
    System.out.printf( "Remarks: %s\n", remarks );
  }

}


text:
package ui // import "miniflux.app/ui"

import (
	"net/http"

	"miniflux.app/http/request"
	"miniflux.app/http/response/json"
	"miniflux.app/http/route"
	"miniflux.app/model"
)

func (h *handler) showWebManifest(w http.ResponseWriter, r *http.Request) {
	type webManifestShareTargetParams struct {
		URL  string `json:"url"`
		Text string `json:"text"`
	}

	type webManifestShareTarget struct {
		Action  string                       `json:"action"`
		Method  string                       `json:"method"`
		Enctype string                       `json:"enctype"`
		Params  webManifestShareTargetParams `json:"params"`
	}

	type webManifestIcon struct {
		Source string `json:"src"`
		Sizes  string `json:"sizes"`
		Type   string `json:"type"`
	}

	type webManifest struct {
		Name            string                 `json:"name"`
		Description     string                 `json:"description"`
		ShortName       string                 `json:"short_name"`
		StartURL        string                 `json:"start_url"`
		Icons           []webManifestIcon      `json:"icons"`
		ShareTarget     webManifestShareTarget `json:"share_target"`
		Display         string                 `json:"display"`
		ThemeColor      string                 `json:"theme_color"`
		BackgroundColor string                 `json:"background_color"`
	}

	displayMode := "standalone"
	if request.IsAuthenticated(r) {
		user, err := h.store.UserByID(request.UserID(r))
		if err != nil {
			json.ServerError(w, r, err)
			return
		}
		displayMode = user.DisplayMode
	}
	themeColor := model.ThemeColor(request.UserTheme(r), "light")
	manifest := &webManifest{
		Name:            "Miniflux",
		ShortName:       "Miniflux",
		Description:     "Minimalist Feed Reader",
		Display:         displayMode,
		StartURL:        route.Path(h.router, "unread"),
		ThemeColor:      themeColor,
		BackgroundColor: themeColor,
		Icons: []webManifestIcon{
			{Source: route.Path(h.router, "appIcon", "filename", "icon-120.png"), Sizes: "120x120", Type: "image/png"},
			{Source: route.Path(h.router, "appIcon", "filename", "icon-192.png"), Sizes: "192x192", Type: "image/png"},
			{Source: route.Path(h.router, "appIcon", "filename", "icon-512.png"), Sizes: "512x512", Type: "image/png"},
		},
		ShareTarget: webManifestShareTarget{
			Action:  route.Path(h.router, "bookmarklet"),
			Method:  http.MethodGet,
			Enctype: "application/x-www-form-urlencoded",
			Params:  webManifestShareTargetParams{URL: "uri", Text: "text"},
		},
	}

	json.OK(w, r, manifest)
}


text:
namespace Nz
{
	class Buffer;
	class RendererImpl;
	class RenderDevice;
	class RenderSurface;
	class RenderWindow;
	class RenderWindowImpl;

	using CreateRendererImplFunc = RendererImpl*(*)();

	class NAZARA_RENDERER_API RendererImpl
	{
		public:
			RendererImpl() = default;
			virtual ~RendererImpl();

			virtual std::unique_ptr<RenderSurface> CreateRenderSurfaceImpl() = 0;
			virtual std::unique_ptr<RenderWindowImpl> CreateRenderWindowImpl(RenderWindow& owner) = 0;

			virtual std::shared_ptr<RenderDevice> InstanciateRenderDevice(std::size_t deviceIndex, const RenderDeviceFeatures& enabledFeatures) = 0;

			virtual RenderAPI QueryAPI() const = 0;
			virtual std::string QueryAPIString() const = 0;
			virtual UInt32 QueryAPIVersion() const = 0;

			virtual const std::vector<RenderDeviceInfo>& QueryRenderDevices() const = 0;

			virtual bool Prepare(const ParameterList& parameters) = 0;
	};
}

#endif // NAZARA_RENDERER_RENDERERIMPL_HPP


text:
<?php

namespace Symfony\Component\DependencyInjection\Loader\Configurator\Traits;

trait PublicTrait
{
    /**
     * @return $this
     */
    final public function public(): static
    {
        $this->definition->setPublic(true);

        return $this;
    }

    /**
     * @return $this
     */
    final public function private(): static
    {
        $this->definition->setPublic(false);

        return $this;
    }
}


text:
class RemoveShownInIrcFromLogs < ActiveRecord::Migration[5.0]
  def change
    remove_column :logs, :shown_in_irc, :boolean
  end
end


text:
package src.john01dav.serverforge.api.events;
import cpw.mods.fml.common.eventhandler.Event;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import src.john01dav.serverforge.api.Player;
import src.john01dav.serverforge.events.CancellableEvent;

public class InteractEvent implements CancellableEvent{
    public static final int AIR_FACE = -1;
    public static final int TOP_FACE = 1;
    public static final int BOTTOM_FACE = 0;
    public static final int SIDE1_FACE = 2;
    public static final int SIDE2_FACE = 3;
    public static final int SIDE3_FACE = 4;
    public static final int SIDE4_FACE = 5;
    public static final int RIGHT_CLICK_BLOCK = 6;
    public static final int RIGHT_CLICK_AIR = 6;
    public static final int LEFT_CLICK_BLOCK = 6;
    private PlayerInteractEvent playerInteractEvent;
    private Player player;
    private int action;
    private boolean cancelled = false;

    public InteractEvent(PlayerInteractEvent playerInteractEvent){
        this.playerInteractEvent = playerInteractEvent;

        switch(playerInteractEvent.action){
            case RIGHT_CLICK_BLOCK:
                action = RIGHT_CLICK_BLOCK;
            break;
            case RIGHT_CLICK_AIR:
                action = RIGHT_CLICK_AIR;
            break;
            case LEFT_CLICK_BLOCK:
                action = LEFT_CLICK_BLOCK;
            break;
        }

        player = Player.get(playerInteractEvent.entityPlayer);
        setCancelled(playerInteractEvent.isCanceled());
    }

    public void setCancelled(boolean cancelled){
        this.cancelled = cancelled;
    }

    public boolean getCancelled(){
        return cancelled;
    }

    /**
     * Returns the X coordinate this event happens at
     * @return the X coordinate this event happens at
     */
    public int getX(){
        return playerInteractEvent.x;
    }

    /**
     * Returns the Y coordinate this event happens at
     * @return the Y coordinate this event happens at
     */
    public int getY(){
        return playerInteractEvent.y;
    }

    /**
     * Returns the Z coordinate this event happens at
     * @return the Z coordinate this event happens at
     */
    public int getZ(){
        return playerInteractEvent.z;
    }

    /**
     * Returns the face that is being clicked, refer to the integer constants on this class for more details
     * @return The face that is being clicked
     */
    public int getFace(){
        return playerInteractEvent.face;
    }

    /**
     * Returns whether or not an air block is being clicked
     * @return whether or not an air block is being clicked
     */
    public boolean isAir(){
        if(playerInteractEvent.useBlock == Event.Result.DEFAULT){
            return false;
        }else{
            return true;
        }
    }

    /**
     * Returns the action that was done to trigger this event, see the integer constants on this class for more details
     * @return the action that was done to trigger this event
     */
    public int getAction(){
        return action;
    }

    /**
     * Returns the player associated with this event
     * @return The player associated with this event
     */
    public Player getPlayer(){
        return player;
    }

}


text:
Table of Contents
=================
* [Introduction](#introduction)
* [Dataset creation](#dataset-creation)
* [Model definition](#model-creation)
* [Verification](#verification)

## Introduction

An image autoencoder may be used to learn a compressed representation of an image. An autoencoder comprises two parts:
- an encoder, which learns a representation of the image, using fewer neurons than the input image
- a decoder, which learns to reconstruct the original input from the compressed representation.

The output layer of the encoder is the input layer of the decoder. This layer can be understood as a bottleneck that constrains the autoencoder to learn a compressed representation of the input.
During training, the objective is to minimize the difference between the original input and the reconstructed input.

## Dataset Creation

The autoencoder may be created in DIGITS by using a generic dataset and model. To create a generic dataset, DIGITS expects to be provided with a set of LMDB-encoded databases.
If you followed the introductory walkthrough on [GettingStarted](../../docs/GettingStarted.md), you should have the MNIST dataset created in DIGITS already and DIGITS will have conveniently created the associated LMDB database and mean image file for you.
Click on your MNIST image classification model to display dataset information: this will allow you to find the path to the job directory which includes the train database and mean image file:

![MNIST image classification dataset](mnist-classification-dataset.png)

In this example the path is `/fast-scratch/gheinrich/ws/digits/digits/jobs/20151111-210842-a4ec`.

The next step is to create a generic dataset that DIGITS can use to train a generic model on. To this avail, click on `New Dataset\Images\Other` on the main page:

![Create generic dataset](create-generic-dataset.png)

In the generic dataset creation form you need to provide the paths to the train database `.../jobs/20151111-210842-a4ec/train_db` and the mean image `.../jobs/20151111-210842-a4ec/mean.binaryproto`. Other fields can be left blank:

![Create generic dataset form](create-generic-dataset-form.png)

## Model creation

Now that you have a generic dataset to train on, you may create a generic model by clicking on `New Model\Images\Other` on the main page:

![Create generic model](create-model.png)

Select the dataset you just created and under the `Custom network` tab, select `Torch`. There you can paste the following network definition:
```lua
local autoencoder = nn.Sequential()
autoencoder:add(nn.MulConstant(0.00390625))
autoencoder:add(nn.View(-1):setNumInputDims(3))  -- 1*28*8 -> 784
autoencoder:add(nn.Linear(784,300))
autoencoder:add(nn.ReLU())
autoencoder:add(nn.Linear(300,50))
autoencoder:add(nn.ReLU())
autoencoder:add(nn.Linear(50,300))
autoencoder:add(nn.ReLU())
autoencoder:add(nn.Linear(300,784))
autoencoder:add(nn.View(1,28,28):setNumInputDims(1)) -- 784 -> 1*28*28

function autoencoderLabelHook(input, dblabel)
    -- label is the input
    return input
end

-- return function that returns network definition
return function(params)
    return {
        model = autoencoder,
        loss = nn.MSECriterion(),
        trainBatchSize = 64,
        validationBatchSize = 100,
        labelHook = autoencoderLabelHook,
    }
end
```

This is the definition of a simple linear autoencoder which learns to compress an input of 784 nodes into a layer of just 50 nodes. Note how the model is symmetrically defined,
with the encoder and decoder at opposite sides of the smallest layer of 50 nodes.

Since this is unsupervised training, a hook is required to tell DIGITS what to compare the network output against: here we are just setting the target label to be equal to
the input image through this function:

```lua
function autoencoderLabelHook(input, dblabel)
    -- label is the input
    return input
end
```

We are using the MSE loss criterion in order to minimize the difference between the input and the reconstructed image.

After training for 30 epochs the loss function should look similar to this:

![Training loss](training-loss.png)

## Verification

Now we can assess the quality of the autoencoder. On the model page, select an image from the MNIST test set (one that the network has never seen during training) and
enable network visualizations then click `Test One`:

![Test single image](test-single-image.png)

A new window will appear showing the original image:

![Original image](original-image.png)

The normalized image after mean subtraction and scaling (this is the image that the network will try to reconstruct):

![Normalized image](normalized-image.png)

The compressed representation of the image (50 nodes out of the original 784 nodes):

![Compressed Image](compressed-image.png)

The reconstructed image, which looks similar to the normalized image:

![Reconstructed Image](reconstructed-image.png)


text:
layout: default
title: Code fun
---

See Me

          {% for post in paginator.posts %}

            	{{ post.date | date: '%B %d, %Y' }}

{{ post.title }}

{% if post.description %}{{ post.description  | strip_html | strip_newlines | truncate: 250 }}{% else %}{{ post.content | strip_html | strip_newlines | truncate: 250 }}{% endif %}

          {% endfor %}

          {% if paginator.previous_page %}
            Newer Posts
          {% endif %}
          {% if paginator.next_page %}
            Older Posts
          {% endif %}


text:
"""A service to test loading services. It doesn't do anything."""

###############################################################################
#
# TODO: [ ]
#
###############################################################################

# standard library imports
import configparser
import json
import logging
import time

# related third party imports
import requests

# application specific imports
import samantha.context as context
from samantha.core import subscribe_to
from samantha.plugins.plugin import Plugin
from samantha.tools import eventbuilder

__version__ = "1.4.0a1"

# Initialize the logger
LOGGER = logging.getLogger(__name__)

# TODO Wrap this in a function and make it callable via event
config = configparser.ConfigParser()
if config.read("variables_private.ini"):
    # this should be ['variables_private.ini'] if the config was found
    twitch_config = config["twitch"]
    SECRETS = {
        "oauth_token": twitch_config.get("oauth_token"),
        "client_id": twitch_config.get("client_id"),
        "api_version": twitch_config.getint("api_version")
    }
else:
    LOGGER.warning("No config found! Are you sure the file %s exists?",
                   "samantha/variables_private.ini")
    SECRETS = None

PLUGIN = Plugin("Twitch", SECRETS is not None, LOGGER, __file__)

STREAM_LIST = context.get_children("media.twitch", default={})

FAILS = 0
# Fail-counter. Used to track consecutive fails of the plugin. Since the list
# of streams is accessed every minute it's not too bad if ine of the checks
# completely fails, as long as the following ones succeed again.
# As soon as the failcounter reaches 3 the user will be notified, before that
# he/she doesn't have to be bothered.

@subscribe_to(["system.onstart", "time.schedule.min"])
def check_followed_streams(key, data):
    """Check for new online streams on twitch.tv."""
    global FAILS

    def _fail(msg):
        """Handle fails of the parent function. """
        global FAILS
        FAILS += 1  # raise the failcounter
        if FAILS <= 3:
            LOGGER.warning("Contacting Twitch failed/returned invalid data on "
                           "the last %d attempts. Current error: %s",
                           FAILS, msg)
        else:
            LOGGER.error("Contacting Twitch failed/returned invalid data on "
                         "the last %d attempts. Current error: %s", FAILS, msg)
        return msg

    # Make the http-request
    url = "https://api.twitch.tv/kraken/streams/followed"
    req = None
    tries = 0
    while tries <= 3 and req is None:
        try:
            tries += 1
            req = requests.get(url, params=SECRETS, timeout=15)
            tries = 0
        except (requests.exceptions.ConnectionError,
                requests.exceptions.SSLError,
                requests.exceptions.Timeout) as e:
            LOGGER.warning("Connecting to Twitch failed on attempt %d. "
                           "Retrying in two seconds. Error: %s", tries, e)
            time.sleep(2)

    if req is None:
        LOGGER.warning("Connecting to Twitch failed three times in a row.")
        return _fail("Warn: Connecting to Twitch failed three times in a row.")

    # Replace null-fields with "null"-strings
    text = req.text.replace('null', '"null"')
    try:
        data = json.loads(text)
    except ValueError as e:
        # Thrown by json if parsing a string fails due to an invalid format.
        LOGGER.warning("The call to Twitch's API returned invalid data. "
                       "Error: %s Data: %s", e, text)
        return _fail("Warn: The call to Twitch's API returned invalid data.")
    new_streamlist = {}
    # parse the data
    if "streams" in data:
        # If so, streams are available
        data = data["streams"]
        FAILS = 0  # reset the failcounter
        for item in data:
            # Get the account name (unique!) for the current item
            channelname = item["channel"]["name"] \
                .encode("utf-8").decode("utf-8")
            current_game = item["channel"]["game"] \
                .encode("utf-8").decode("utf-8")
            # save the stream's data in a new list
            new_streamlist[channelname] = item
            if (channelname not in STREAM_LIST or
                    STREAM_LIST[channelname] is None):
                # The stream came online since the last check
                LOGGER.debug(u"'%s' is now online. Playing '%s'",
                             channelname, current_game)
                eventbuilder.eEvent(
                    sender_id=PLUGIN.name,
                    keyword="media.twitch.availability.online.{}".format(
                        channelname),
                    data=item).trigger()
                context.set_property(
                    "media.twitch.{}".format(channelname), item)
                if channelname in STREAM_LIST:
                    # remove the channel from STREAM_LIST so that it can be
                    # refilled with the new data
                    del STREAM_LIST[channelname]
            else:
                # The channel was already online at the last check
                if current_game == STREAM_LIST[channelname]["channel"]["game"]:
                    # The game hasn't changed
                    LOGGER.debug("'%s' is still playing '%s'.",
                                 channelname, current_game)
                else:
                    # The game changed
                    LOGGER.debug("'%s' is now playing '%s'",
                                 channelname, current_game)
                    eventbuilder.eEvent(
                        sender_id=PLUGIN.name,
                        keyword="media.twitch.gamechange.{}".format(
                            channelname),
                        data=item).trigger()
                    context.set_property(
                        "media.twitch.{}".format(channelname), item)
                if channelname in STREAM_LIST:
                    # refilled with the new data
                    # remove the channel from STREAM_LIST so that it can be
                    del STREAM_LIST[channelname]
    else:
        LOGGER.warning("The data didn't include the 'streams' field.")
        return _fail("Warn: The data didn't include the 'streams' field: %s" % data)

    while len(STREAM_LIST) > 0:
        # STREAM_LIST now contains only those streams that were online
        # during the last check but have gone offline since.
        channelname, channeldata = STREAM_LIST.popitem()
        if channeldata is not None:
            LOGGER.debug("'%s' is now offline.", channelname)
            key = "media.twitch.availability.offline.{}".format(channelname)
            eventbuilder.eEvent(sender_id=PLUGIN.name,
                                keyword=key,
                                data=channeldata).trigger()
            context.set_property(
                "media.twitch.{}".format(channelname), None)

    # update the existing STREAM_LIST with the new streams
    for channelname in new_streamlist:
        STREAM_LIST[channelname] = new_streamlist[channelname]
    return "Streams updated successfully."


text:
'use strict';

var Promise = require('es6-promise');
var commons = require('./_common.js');

/**
 * Processes an array of data and calls an `onComplete` callback with `error` and `spikes` parameters.
 *
 * @example
 ```js
 slayer()
 .fromArray(arrayData, function(err, spikes){
    if (err){
      console.error(err);
      return;
    }

    console.log(spikes);   // { x: 4, y: 12, id: '21232f297a57a5a743894a0e4a801fc3' }
  });
 ```
 *
 * @api
 * @name Slayer.prototype.fromArray
 * @this {Slayer}
 * @param data {Array.<Object|Number>}
 */
function fromArray(data){
  var self = this;

  return new Promise(function(resolve) {
    if (!Array.isArray(data)){
      throw new TypeError('The data argument should be an array of time series values.');
    }

    var spikes = data
      .map(self.getValueY.bind(self))
      .map(self.filterDataItem.bind(self))
      .map(self.algorithm.bind(self, self.config.minPeakDistance))
      .map(commons.objectMapper.bind(self, data))
      .filter(commons.cleanEmptyElement.bind(null, self.config.transformedValueProperty));

    resolve(spikes);
  });
}

module.exports = fromArray;


text:
package eu.ydp.empiria.player.client.module.selection.handlers;

import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import eu.ydp.empiria.player.client.module.components.choicebutton.ChoiceButtonBase;

public class ChoiceButtonMouseOutHandler implements MouseOutHandler {

    private ChoiceButtonBase button;

    @Inject
    public ChoiceButtonMouseOutHandler(@Assisted ChoiceButtonBase button) {
        this.button = button;
    }

    @Override
    public void onMouseOut(MouseOutEvent event) {
        button.setMouseOver(false);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    android:tint="@color/md_blue_grey_100" >

    <solid android:color="@color/md_blue_grey_100"/>
</shape>


text:
layout: default
---

Digital engagement, web designer, developer

Head of Digital at EQtwo. 11 years experience in digital engagement. Living in London.

Skills

Strategy

Communication

Design

Full Stack Developer

Data Analysis

Reporting

Copywriting

More about me

Languages and frameworks

Javascript

PHP

Swift

HTML5

CSS3

Python

Objective-C

Rust

jQuery

Node

Laravel

Ember

Slim

Electron

React

Redux

My Projects


text:
Exon quantification pipeline - quantification module (EQP-QM)
=============================================================

EQP-QM is a Unix based RNA-seq quantification module which uses SAM/BAM
genome alignment files as input and creates gene, exon, and junctions counts.

Version
-------

This document corresponds to EQP-QM version 2.1.0

Installation of EQP-QM
----------------------

For the installation of EQP-QM just copy the files and directories
obtained from unpacking the GitHub download into a directory that is contained
in your `PATH` environment variable. Please note that the relative directory
structure must be maintained as the shell scripts `eqp-setup.sh` and
`eqp-quantify.sh` assume that auxilliary scripts and Java programs are
located at certain paths relative to their location. So the content of
the directory containing the two scripts `eqp-setup.sh` and
`eqp-quantify.sh` should be:
`LICENSE.txt  bin/              eqp-setup.sh   manual/      util-scripts/`
`README.md    eqp-quantify.sh   java/          test-files/`
(where only `eqp-setup.sh`, `eqp-quantify.sh`, `bin`, `java`, and
`util-scripts` are really relevant).

Dependencies
------------

* Python (>= version 3.6.2, imported libraries: copy, gettext, gzip,
  numpy, os, re, sets, sys, textwrap, warnings, argparse)
* R (>= version 2.10.1)
* Java (>= version 1.6)
* samtools (>= version 1.3)
* bedtools (>= version 2.24.0)

Running EQP-QM
--------------

In order to be able to use EQP-QM to quantify genes, exons, and junctions
it is necessary to execute two preparatory steps:

1. First a number of annotation files required by EQP-QM need to be
   created. This is achieved by running the script `eqp-setup.sh` on a GTF
   file which contains the genome annotation for the genome that will be
   used to align the sample Fastq files. `eqp-setup.sh` is called as
   follows:

   `eqp-setup.sh <GTF file> <data directory>`

   Here `<data directory>` is the directory in which all necessary
   annotation files for EQP-QM are created. It needs to be supplied in
   the quantification step. The setup will take a while to complete but it
   is only necessary to execute this step once for each GTF file.

   **GTF file**:
   Only entries with feature type `exon` which contain a `gene_id` field
   are used by `eqp-setup.sh` (and, thus, for the quantification of genes,
   exons, and junctions).

   **Caveat**: Note that the standard GTF file provided by UCSC contains the
   transcript id in the `gene_id` field (which equals the
   `transcript_id` field). In this case EQP-QM will generate counts for
   the transcripts; however, please note that these cannot be considered
   as transcript abundance estimates; in particular, one read can contribute
   to many transcripts. Ensembl GTF files work without problems.

2. Secondly the Fastq files need to be aligned against the chosen
   reference genome using a (splice-aware) aligner of your choice (e.g.
   HiSAT, STAR, or Tophat2) to create SAM/BAM files.

   **Caveat**: Please note that the chromosome names for NCBI/UCSC are
   different from the chromosome names used by Ensembl. So it is not
   possible to use a genome downloaded from NCBI/UCSC for alignment and
   an Ensembl GTF file for the genome annotation. In general, please
   make sure that the identifiers in the genome Fasta file and the GTF
   file are consistent.

Note that the above two steps are independent of each other and can be
executed in parallel.

Once the alignment and the setup of EQP-QM are finished, the quantification
step can be invoked on a SAM/BAM file via:

`eqp-quantify.sh -d <data directory> <output directory> <SAM/BAM file>`

This will create the files `<SAM/BAM file base>`-gene.cnt,
`<SAM/BAM file base>`-gene.cnt, and `<SAM/BAM file base>`-junction.cnt in
the directory `<output directory>` where `<SAM/BAM file base>` is the basename
of `<SAM/BAM file>` without extension `.sam` or `.bam`.

The run time depends on the number of reads in the SAM/BAM file. Expect
~0.5-1h for ~10M paired-end reads. EQP-QM needs at least 10GB of main
memory.

Testing EQP-QM
--------------

In order to test that the installation of EQP-QM worked correctly and all
requirements are met, execute the script:

`test-files/run-test.sh`

This will create reference files by calling `eqp-setup.sh` on the GTF-file:
`test-files/gtf-files/Homo_sapiens.GRCh38.76-test.gtf`
and then run `eqp-quantify.sh` on the BAM file:
`test-files/sam-files/test-alignment-file.bam`

Note that `eqp-setup.sh` and `eqp-quantify.sh` need to be contained in a directory
which is included in your PATH environment variable and the subdirectories `bin`,
`java`, and `util-scripts` need to be contained in the same directory as `eqp-setup.sh`
and `eqp-quantify.sh`.

This creates the three count files:
`test-files/count-files/test-alignment-file-gene.cnt`
`test-files/count-files/test-alignment-file-exon.cnt`
`test-files/count-files/test-alignment-file-junction.cnt`

which are then compared with the previously generated count files in the directory
`comparison-files`. If the test is successful, then the message `Test successfully
completed.` will be printed as the last line of the output.

## `eqp-quantify.sh` options

Usage: `eqp-quantify.sh <options> -d <setup dir> <output dir> <SAM/BAM file>`

where `<options>` is
`[-g] [-e] [-j] [-E <exon overlap>] [-J <junction overlap>] [-W <min read weight>]`
`[-s <direction>] [-o <output prefix>] [--nosort] [--unambig] [--unweighted]`
`[-w <weight file>]`

`output dir`: directory used for the count files
`SAM/BAM file`: the file containing the alignments of the
   reads against the genome with the aligner.
`-d STRING`: Use STRING as the directory that contains the auxilliary
  files (needs to be supplied)
`-g`: compute gene counts [computed by default, without -g,-e,-j]
`-e`: compute exon counts [computed by default, without -g,-e,-j]
`-j`: compute junction counts [computed by default, without -g,-e,-j]
`-E INT`: Minimal overlap of a read with an exon [5]
`-J INT`: Minimal overlap of a read with both exons on a junction [8]
`-W FLOAT`: Minimal weight of a read; reads with a lower weight are
          disregarded [0.01]
`-s STRING`: process reads as strand-specific in direction STRING
(*forward* for orientation fr or *backward* for orientation rf)
`-o STRING`: A directory STRING is created in the current working directory
    and all intermediate files are stored in a directory structure under
    this directory; furthermore, the count files are generated in the current
    working directory with the prefix STRING.
`--nosort`: the alignment file is already sorted by names; do not sort it.
`--unambig`: count only reads that can be assigned unambiguously to a single gene
   or exon when creating the gene or exon counts
`--unweighted`: do not use read weights in the generation of counts
`-w STRING`: use STRING as weight file instead of computing it from the genomic
   alignments

License
=======

Copyright 2015 Novartis Institutes for Biomedical Research

Licensed 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.


text:
import { suite, test, slow, timeout, skip, only } from "mocha-typescript";
import * as assert from "assert";

import { AutoRest } from "../lib/autorest-core";
import { RealFileSystem } from "../lib/file-system";
import { CreateFolderUri, ResolveUri } from "../lib/ref/uri";
import { Message, Channel } from "../lib/message";
import { PumpMessagesToConsole } from './test-utility';

@suite class EndToEnd {
  @test async "network full game"() {
    const autoRest = new AutoRest(new RealFileSystem());
    // PumpMessagesToConsole(autoRest);
    autoRest.AddConfiguration({
      "input-file": [
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/applicationGateway.json",
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/checkDnsAvailability.json",
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/expressRouteCircuit.json",
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/loadBalancer.json",
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/network.json",
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/networkInterface.json",
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/networkSecurityGroup.json",
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/networkWatcher.json",
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/publicIpAddress.json",
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/routeFilter.json",
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/routeTable.json",
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/serviceCommunity.json",
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/usage.json",
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/virtualNetwork.json",
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/virtualNetworkGateway.json",
        "https://github.com/Azure/azure-rest-api-specs/blob/master/specification/network/resource-manager/Microsoft.Network/stable/2017-03-01/vmssNetworkInterface.json"]
    });

    autoRest.AddConfiguration({
      "override-info": {
        title: "Network"
      }
    });

    // TODO: generate for all, probe results

    const success = await autoRest.Process().finish;
    assert.strictEqual(success, true);
  }

  @test async "other configuration scenario"() {
    const autoRest = new AutoRest(new RealFileSystem(), ResolveUri(CreateFolderUri(__dirname), "../../test/resources/literate-example/readme-complicated.md"));
    // PumpMessagesToConsole(autoRest);

    const config = await autoRest.view;
    assert.strictEqual(config["shouldwork"], true);

  }

  @test async "complicated configuration scenario"() {
    const autoRest = new AutoRest(new RealFileSystem(), ResolveUri(CreateFolderUri(__dirname), "../../test/resources/literate-example/readme-complicated.md"));
    // PumpMessagesToConsole(autoRest);
    autoRest.AddConfiguration({
      "cmd-line-true": true,
      "cmd-line-false": false,
      "cmd-line-complex": {
        "true": true,
        "false": false
      }
    });

    const config = await autoRest.view;
    assert.strictEqual(config.InputFileUris.length, 1);

    const messages: Message[] = [];

    autoRest.Message.Subscribe((_, m) => { if (m.Channel === Channel.Warning) { messages.push(m); } });
    assert.equal(await autoRest.Process().finish, true);
    assert.notEqual(messages.length, 0);
  }
  // testing end-to-end for non-arm type validation rules. Since all validation rules are currently defaulted to
  // ARM, non-ARM documents should show 0 validation messages
  // TODO: fix this test when validation rules are properly categorized
  @test async "non-arm type spec testing"() {
    const autoRest = new AutoRest(new RealFileSystem(), ResolveUri(CreateFolderUri(__dirname), "../../test/resources/validation-options/readme.md"));
    autoRest.AddConfiguration({
      "openapi-type": "default",
      "azure-validator": true
    });

    const config = await autoRest.view;
    const messages: Message[] = [];

    autoRest.Message.Subscribe((_, m) => { messages.push(m); });
    assert.equal(await autoRest.Process().finish, true);
    assert.notEqual(messages.length, 0);
    // flag any fatal errors
    assert.equal(messages.filter(m => m.Channel === Channel.Fatal).length, 0);
  }
  @test async "arm type spec testing"() {
    const autoRest = new AutoRest(new RealFileSystem(), ResolveUri(CreateFolderUri(__dirname), "../../test/resources/validation-options/readme.md"));
    autoRest.AddConfiguration({
      "openapi-type": "arm",
      "azure-validator": true
    });

    const config = await autoRest.view;

    const messages: Message[] = [];

    autoRest.Message.Subscribe((_, m) => { messages.push(m); });
    // PumpMessagesToConsole(autoRest);
    assert.equal(await autoRest.Process().finish, true);
    // flag any fatal errors
    assert.equal(messages.filter(m => m.Channel === Channel.Fatal).length, 0);
    assert.notEqual(messages.length, 0);
  }
}