text:
//@flow
import invariant from "invariant";
import GLSL from "./GLSL";
import type { GLSLCode } from "./GLSL";

const ShaderID = "ShaderID";

/**
 * An object that contains a `frag` GLSLCode.
 * @example
 *  {
 *    frag: GLSL`...`
 *  }
 */
type ShaderDefinition = {|
  frag: GLSLCode,
  vert?: GLSLCode,
|};

export type { ShaderDefinition };

/**
 *
 */
type ShaderIdentifier = {
  type: typeof ShaderID,
  id: string,
};

export type { ShaderIdentifier };

type ShaderIdentifierMap<T> = {
  [key: string]: T,
};

/**
 * An object map from a key string to a **ShaderDefinition**.
 * @example
 *  {
 *    helloGL: {
 *      frag: GLSL`...`
 *    }
 *  }
 */
type ShadersDefinition = {
  [key: string]: ShaderDefinition,
};

/**
 * An object map from a key string to a **ShaderIdentifier** that you can pass to `<Node shader>`
 */
type ShadersSheet<S: ShadersDefinition> = {
  [key: $Keys<S>]: ShaderIdentifier,
};

type ShaderInfo = {
  frag: GLSLCode,
  vert: GLSLCode,
};

export type { ShaderInfo };

const shaderDefinitions: ShaderIdentifierMap<ShaderDefinition> = {};
const shaderNames: ShaderIdentifierMap<string> = {};
const shaderResults: ShaderIdentifierMap<ShaderInfo> = {};

const genShaderId = ((i) => () => (++i).toString())(0);

const staticVerts = {
  "100": GLSL`
attribute vec2 _p;
varying vec2 uv;
void main() {
gl_Position = vec4(_p,0.0,1.0);
uv = vec2(0.5, 0.5) * (_p+vec2(1.0, 1.0));
}`,
  "300 es": GLSL`#version 300 es
in vec2 _p;
out vec2 uv;
void main() {
gl_Position = vec4(_p,0.0,1.0);
uv = vec2(0.5, 0.5) * (_p+vec2(1.0, 1.0));
}`,
};

export function isShaderIdentifier(shaderIdentifier: mixed): boolean {
  return (
    typeof shaderIdentifier === "object" &&
    !!shaderIdentifier &&
    shaderIdentifier.type === ShaderID &&
    typeof shaderIdentifier.id === "string"
  );
}

export function ensureShaderDefinition(
  definition: any,
  ctx?: string = ""
): ShaderDefinition {
  invariant(
    definition && typeof definition.frag === "string",
    "A `frag` GLSL code (string) is required" + ctx
  );
  return definition;
}

const versionDef = "#version";
function inferGLSLVersion(glsl) {
  const i = glsl.indexOf("\n");
  const line1 = i > -1 ? glsl.slice(0, i) : glsl;
  if (line1.startsWith(versionDef)) {
    return line1.slice(versionDef.length + 1);
  }
  return "100";
}

const addGLSLName = (glsl: string, name: ?string) =>
  !name ? glsl : glsl + "\n#define SHADER_NAME " + name + "\n";

export function shaderDefinitionToShaderInfo(
  { frag, vert }: ShaderDefinition,
  name: string
): ShaderInfo {
  frag = frag.trim();
  const version = inferGLSLVersion(frag);
  if (vert) {
    vert = vert.trim();
    const vertVersion = inferGLSLVersion(vert);
    if (version !== vertVersion) {
      throw new Error("GLSL shader vert and frag version must match");
    }
  } else {
    vert = staticVerts[version];
    if (!vert) {
      throw new Error(
        "gl-react: could not find static vertex shader for GLSL version '" +
          version +
          "'"
      );
    }
  }
  frag = addGLSLName(frag, name);
  vert = addGLSLName(vert, name);
  return {
    frag,
    vert,
  };
}

export function shaderInfoEquals(s1: ShaderInfo, s2: ShaderInfo): boolean {
  return s1.frag === s2.frag && s1.vert === s2.vert;
}

/**
 * Define shaders statically.
 * @namespace
 */
const Shaders = (global.__glReactShaders = global.__glReactShaders || {
  /**
   * @memberof Shaders
   * @param {ShadersDefinition} shadersDef - an object that statically define all shaders.
   * @returns {ShadersSheet}, an object map that returns a ShaderIdentifier for each shader key defined in the shaders definition.
   * @example
   *  const shaders = Shaders.create({
   *    helloGL: {
   *      frag: GLSL`...`
   *    }
   *  });
   *  ...
   *  <Node shader={shaders.helloGL} />
   */
  create<S: ShadersDefinition>(shadersDef: S): ShadersSheet<S> {
    const sheet = {};
    Object.keys(shadersDef).forEach((k) => {
      const definition = ensureShaderDefinition(
        shadersDef[k],
        " in Shaders.create({ " + k + ": ... })"
      );
      const id = genShaderId();
      const shaderId = Object.freeze({ type: ShaderID, id });
      shaderDefinitions[id] = definition;
      shaderNames[id] = k;
      sheet[k] = shaderId;
      const result = shaderDefinitionToShaderInfo(definition, k);
      shaderResults[id] = result;
    });
    return sheet;
  },
  getName(shaderIdentifier: ShaderIdentifier): string {
    return (
      (shaderNames[shaderIdentifier.id] || "???") +
      `#${String(shaderIdentifier.id)}`
    );
  },
  getShortName(shaderIdentifier: ShaderIdentifier): string {
    return shaderNames[shaderIdentifier.id] || "???";
  },
  get(shaderIdentifier: ShaderIdentifier): ShaderInfo {
    invariant(
      shaderIdentifier.id in shaderDefinitions,
      "Shader %s does not exist. Make sure you don't have gl-react dup issue: `npm ls gl-react`",
      shaderIdentifier.id
    );
    return shaderResults[shaderIdentifier.id];
  },
});
export default Shaders;


text:
"""Remote execution for preprocess_corpus.py."""

from __future__ import absolute_import, division, print_function

try:
    from itertools import izip_longest as zip_longest
    from itertools import izip as zip
except:
    from itertools import zip_longest

from io import StringIO
import os
import time

from fabric.api import cd, env, execute, parallel, put, run, task
from fabric.context_managers import settings
from fabric.contrib import files

from emLam.utils import get_any_index, source_target_file_list
from emLam.utils.config import get_config_file

commands = ['setup', 'do_it', 'cleanup']

class FabricError(Exception):
    pass

@task
def parallellism(cores=8):
    """
    The number of processes to be run parallelly: one per <cores> cores.
    Required, as some preprocessors (hunlp-GATE, CoreNLP) take up lots of
    resources, and it doesn't make sense to run too many of them.
    """
    result = run("cat /proc/cpuinfo | awk '/^processor/{print $3}' | tail -1")
    if result.failed:
        return 1
    else:
        return (int(result) + 1) // 8

@task
def setup_infrastructure(config, local_args):
    run('mkdir -p {}'.format(config['remote_dir']))
    # Should I do this? Work dir most likely exists anyway
    run('mkdir -p {}'.format(config['work_dir']))
    with cd(config['remote_dir']):
        put(get_config_file(local_args.configuration), 'rconfig.conf')

@task
@parallel
def setup_source(config, remote_dir):
    """Clones the git repository and updates it."""
    with cd(remote_dir):
        if files.exists('emLam'):
            if config['always_update']:
                with cd('emLam'):
                    run('git pull')
        else:
            run('git clone {}'.format(config['repository']))
        with cd('emLam'):
            run('git checkout {}'.format(config['object']))

@task
@parallel
def setup_environment(config, remote_dir, source_dir):
    # Create the tmux session
    tid = config['tmux']
    run('tmux new-session -d -s {}'.format(tid), warn_only=True)

    sentinel = '{}/pip_done'.format(remote_dir)
    if config['virtualenv']:
        if run('which virtualenv', warn_only=True).failed:
            if config['allow_user_packages']:
                run('pip install --user virtualenv')
            else:
                raise FabricError('virtualenv is not available and user '
                                  'packages are not allowed.')
        venv_dir = os.path.join(remote_dir, config['virtualenv'])
        if not files.exists(venv_dir):
            run('virtualenv -p python3 {}'.format(venv_dir))
        # It is an error to not be able to enter the environment
        source_venv = 'source {}'.format(os.path.join(venv_dir, 'bin/activate'))
        run(source_venv)
        run("tmux send -t {} '{}' ENTER".format(tid, source_venv))
        run("tmux send -t {} 'pip install -U pip setuptools' ENTER".format(
            tid))
        run("tmux send -t {} 'pip install -e {}' ENTER".format(
            tid, source_dir))
        run("tmux send -t {} 'touch {}' ENTER".format(tid, sentinel))
    elif config['allow_user_packages']:
        # Not in tmux, so that we can see if an error happens
        run('pip install --user -U pip setuptools')
        run('pip install --user -e {}'.format(source_dir))
        run('touch {}'.format(sentinel))
    else:
        raise FabricError('User packages are not allowed -- cannot run '
                          'without virtualenv.')

    for _ in range(config['install_timeout']):
        if files.exists(sentinel):
            run('rm {}'.format(sentinel))
            break
        time.sleep(1)
    else:
        raise FabricError('Could not install the emLam package.')

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks. The itertools recipe."
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

def input_chunks(local_args, processes):
    """Splits the input into equal sized chunks."""
    sfs = list(zip(
        *source_target_file_list(local_args.source, local_args.target_dir)))[0]
    t_chunks = list(grouper(sfs, sum(processes.values())))
    # t_chunks[-1] = [e for e in t_chunks[-1] if e]
    chunks = list(zip_longest(*t_chunks))
    chunks = [[f for f in chunk if f] for chunk in chunks]
    ret = {}
    i = 0
    for k, v in processes.items():
        ret[k] = [f for chunk in chunks[i:i + v] for f in chunk]
        i += v
    return ret

@task
def upload_input(inputs, remote_dir):
    """Uploads the input."""
    put(StringIO('\n'.join(inputs[env.host_string])),
        '{}/input.lst'.format(remote_dir))

def setup(remote_config, local_args):
    """
    Sets up the processing. Divides the input files among the hosts specified,
    creates the tmux sessions and virtualenvs on the remote machines, updating
    the code as necessary.
    """
    # Sets up the environment
    hosts = remote_config['Resources']['hosts']
    if not isinstance(hosts, list):
        hosts = [hosts]
    execute(setup_infrastructure, remote_config['Infrastructure'],
            local_args, hosts=hosts)
    remote_dir = remote_config['Infrastructure']['remote_dir']
    execute(setup_source, remote_config['Source'], remote_dir, hosts=hosts)
    source_dir = os.path.join(remote_dir, 'emLam')
    execute(setup_environment, remote_config['Environment'], remote_dir,
            source_dir, hosts=hosts)

    # The input files
    processes = execute(parallellism, remote_config['Resources']['num_cores'],
                        hosts=hosts)
    inputs = input_chunks(local_args, processes)
    execute(upload_input, inputs, remote_dir, hosts=hosts)

@task
def run_emLam(remote_config, processes):
    tid = remote_config['Environment']['tmux']
    infconf = remote_config['Infrastructure']

    cmd_line = remote_config['cmd_line']
    p_idx = get_any_index(cmd_line, '-P', '--processes')
    if p_idx:
        cmd_line[p_idx + 1] = processes[env.host_string]
    else:
        cmd_line.extend(['-P', processes[env.host_string]])

    run("tmux send -t {} 'cd {}' ENTER".format(
        tid, os.path.abspath(infconf['work_dir'])))
    run("tmux send -t {} 'python {} {} > {} 2>&1' ENTER".format(
        tid, os.path.join(infconf['remote_dir'], 'emLam',
                          'scripts', 'preprocess_corpus.py'),
        ' '.join(map(str, cmd_line)),
        os.path.join(infconf['remote_dir'], 'emLam.log')))

def do_it(remote_config, local_args):
    """Runs the jobs parallelly."""
    hosts = remote_config['Resources']['hosts']

    # Parallellism
    processes = execute(parallellism, remote_config['Resources']['num_cores'],
                        hosts=hosts)
    execute(run_emLam, remote_config, processes, hosts=hosts)

def cleanup(remote_config, local_args):
    """
    Cleans up: removes the remote directory, uninstalls the Python packages
    and kills the tmux session.
    """
    hosts = remote_config['Resources']['hosts']
    infconf = remote_config['Infrastructure']
    envconf = remote_config['Environment']

    if infconf['delete_remote_dir']:
        execute(run, 'rm -rf {}'.format(infconf['remote_dir']), hosts=hosts)

    with settings(warn_only=True):
        if not envconf['virtualenv'] and envconf['allow_user_packages']:
            execute(run, 'pip uninstall emLam virtualenv', hosts=hosts)

        execute(run, 'tmux kill-session -t {}'.format(envconf['tmux']),
                hosts=hosts)

redpajama_set_name: RedPajamaGithub


text:
 1">

                «

            @{{ page }}

        <li v-if="pagination.current_page < pagination.last_page">

                »


text:
package com.githinho.services;

import com.githinho.OrthancException;
import com.githinho.OrthancService;
import okhttp3.ResponseBody;
import retrofit2.Call;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public abstract class BaseService {

    protected OrthancService service;

    public BaseService(OrthancService service) {
        this.service = service;
    }

    protected <T> T checkResponse(Call<T> call) throws IOException, OrthancException {
        retrofit2.Response response = call.execute();
        if (response.isSuccessful()) {
            return (T) response.body();
        } else {
            throw new OrthancException("code = " + response.code());
        }
    }

    protected boolean writeResponseBodyToDisk(ResponseBody body, String file) {
        try {
            File downloadFile = new File(file);
            downloadFile.getParentFile().mkdirs();
//            FileWriter writer = new FileWriter(downloadFile);
            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[4096];
//                long fileSize = body.contentLength();
//                long fileSizeDownloaded = 0;
                inputStream = body.byteStream();
                outputStream = new FileOutputStream(downloadFile);

                while (true) {
                    int read = inputStream.read(fileReader);
                    if (read == -1) {
                        break;
                    }
                    outputStream.write(fileReader, 0, read);
//                    fileSizeDownloaded += read;
//                    SystemInfo.out.println("file download: " + fileSizeDownloaded + " of " + fileSize);
                }
                outputStream.flush();
                return true;
            } catch (IOException e) {
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }
}


text:
/**
 * @class
 * Initializes a new instance of the Product class.
 * @constructor
 * The product documentation.
 *
 * @member {string} [productId] Unique identifier representing a specific
 * product for a given latitude & longitude. For example, uberX in San
 * Francisco will have a different product_id than uberX in Los Angeles.
 *
 * @member {string} [description] Description of product.
 *
 * @member {string} [displayName] Display name of product.
 *
 * @member {string} [capacity] Capacity of product. For example, 4 people.
 * Default value: '100' .
 *
 * @member {string} [image] Image URL representing the product.
 *
 */
export interface Product {
  productId?: string;
  description?: string;
  displayName?: string;
  capacity?: string;
  image?: string;
}

/**
 * @class
 * Initializes a new instance of the CatalogDictionary class.
 * @constructor
 * @member {object} [productDictionary] Dictionary of products
 *
 */
export interface CatalogDictionary {
  productDictionary?: { [propertyName: string]: Product };
}

/**
 * @class
 * Initializes a new instance of the CatalogArray class.
 * @constructor
 * @member {array} [productArray] Array of products
 *
 */
export interface CatalogArray {
  productArray?: Product[];
}

/**
 * @class
 * Initializes a new instance of the CatalogArrayOfDictionary class.
 * @constructor
 * @member {array} [productArrayOfDictionary] Array of dictionary of products
 *
 */
export interface CatalogArrayOfDictionary {
  productArrayOfDictionary?: { [propertyName: string]: Product }[];
}

/**
 * @class
 * Initializes a new instance of the CatalogDictionaryOfArray class.
 * @constructor
 * @member {object} [productDictionaryOfArray] Dictionary of Array of product
 *
 */
export interface CatalogDictionaryOfArray {
  productDictionaryOfArray?: { [propertyName: string]: Product[] };
}

/**
 * @class
 * Initializes a new instance of the ErrorModel class.
 * @constructor
 * @member {number} [status]
 *
 * @member {string} [message]
 *
 */
export interface ErrorModel {
  status?: number;
  message?: string;
}


text:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block title %} - Rechnung{% endblock %}

{% block content %}
{% if stunden_not_payed %}
    <form class="form" action="{% url "rechnung" %}" method="post">

                {% crispy form %}

                    <button class="btn btn-primary btn-block" type="submit" name="rechnung" value="Rechnung als PDF ausgeben"> Rechnung als PDF ausgeben</button>

            {% if custom_error %}

                <button type="button" class="close" data-dismiss="alert">×</button>

{{ custom_error }}

            {% endif %}

Einträge auswählen, um diese zur Rechnung hinzuzufügen*

(Ausgewähte Einträge, die nicht dem oben angegebenen Rechnungempfänger entsprechen, werden bei der Rechnungserstellung ignoriert.)

<input type="checkbox" id="toggle-all">

                        Datum
                        Firma
                        Startzeit
                        Endzeit
                        Arbeitnehmer
                        Protokoll
                        Stunden
                        Bezahlt

                    {% for row in stunden_not_payed %}

                        {% if row.id in stunden_ids %}

<input type="checkbox" class="toggle-me" name="checks[]" value="{{ row.id }}" checked>

                        {% else %}

<input type="checkbox" class="toggle-me" name="checks[]" value="{{ row.id }}">

                        {% endif %}
                        {{row.datum}}
                        {{row.firma}}
                        {{row.startzeit|time:"H:i"}}
                        {{row.endzeit|time:"H:i"}}
                        {{row.arbeitnehmer}}
                        {{row.protokoll}}
                        {{row.stunden}}
                        Nein

{% endfor %}

                <button class="btn btn-default" type="submit" name="bezahlt_markieren" value="Ausgewählte Einträge als bezahlt markieren" formnovalidate> Ausgewählte Einträge als bezahlt markieren</button>

    </form>
{% else %}

                Information: Derzeit sind keine unbezahlten Einträge vorhanden, daher kann im Moment keine Rechnung erstellt werden.

             Home

{% endif %}
{% endblock %}


text:
package com.intellij.openapi.vcs;

import com.intellij.codeInsight.CodeSmellInfo;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * @author yole
 */
public abstract class CodeSmellDetector {
  public static CodeSmellDetector getInstance(Project project) {
    return ServiceManager.getService(project, CodeSmellDetector.class);
  }

  /**
   * Performs pre-checkin code analysis on the specified files.
   *
   * @param files the files to analyze.
   * @return the list of problems found during the analysis.
   * @throws ProcessCanceledException if the analysis was cancelled by the user.
   * @since 5.1
   */
  @NotNull
  public abstract List<CodeSmellInfo> findCodeSmells(@NotNull List<VirtualFile> files) throws ProcessCanceledException;

  /**
   * Shows the specified list of problems found during pre-checkin code analysis in a Messages pane.
   *
   * @param smells the problems to show.
   * @since 5.1
   */
  public abstract void showCodeSmellErrors(@NotNull List<CodeSmellInfo> smells);

}


text:
import os
from setuptools import setup

import timer

github_url = 'https://github.com/gabegaster/python-timer'

def read(fname):
    with open(os.path.join(os.path.dirname(__file__), fname)) as f:
        return f.readlines()

# read in the description from README
long_description = "\n".join(read("README.md"))

install_requires = []

setup(
    name="python-timer",
    version=timer.VERSION,
    description=("A wrapper for long-running tasks that iterate over many things, "
                 "printing friendly 'percentage done' messages to standard error."),
    long_description=long_description,
    url=github_url,
    download_url="%s/archives/master" % github_url,
    author='Gabe Gaster',
    author_email='gabe@datascopeanalytics.com',
    license='MIT',
    packages=[
        'timer',
    ],
    install_requires=install_requires,
    zip_safe=False,
    classifiers=[
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        'Topic :: Software Development'
    ],
)


text:
<?php

namespace BCRM\BackendBundle\Command;

use BCRM\BackendBundle\Entity\Event\Event;
use BCRM\BackendBundle\Exception\CommandException;
use BCRM\BackendBundle\Service\Event\SendTicketMailCommand;
use Doctrine\Common\Util\Debug;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class SendTicketsMailCommand extends ContainerAwareCommand
{
    /**
     * @var OutputInterface
     */
    private $output;

    protected function configure()
    {
        $this
            ->setName('bcrm:tickets:send')
            ->setDescription('Send tickets');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->output = $output;
        /** @var \BCRM\BackendBundle\Entity\Event\RegistrationRepository $registrationRepo */
        /** @var \BCRM\BackendBundle\Entity\Event\EventRepository $eventRepo */
        $eventRepo = $this->getContainer()->get('bcrm.backend.repo.event');
        $event     = $eventRepo->getNextEvent()->getOrThrow(new CommandException('No event.'));
        $this->sendNewTicketNotificationsFor($event);
    }

    protected function sendNewTicketNotificationsFor(Event $event)
    {
        /** @var \BCRM\BackendBundle\Entity\Event\TicketRepository $repo */
        $repo = $this->getContainer()->get('bcrm.backend.repo.ticket');
        /** @var \LiteCQRS\Bus\CommandBus $commandBus */
        $commandBus = $this->getContainer()->get('command_bus');
        foreach ($repo->getToNotify($event) as $ticket) {
            if ($this->output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) {
                $this->output->writeln(sprintf('Sending ticket notification for %s', $ticket));
            }
            $command                = new SendTicketMailCommand();
            $command->ticket        = $ticket;
            $command->event         = $event;
            $command->schemeAndHost = $this->getContainer()->getParameter('scheme_and_host');
            $commandBus->handle($command);
        }
    }
}


text:
package com.loadburn.heron.plugin;

import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Stage;
import com.loadburn.heron.annotations.Decoration;
import com.loadburn.heron.annotations.Heron;
import com.loadburn.heron.annotations.Path;
import com.loadburn.heron.annotations.Show;
import com.loadburn.heron.complier.Compilers;
import com.loadburn.heron.complier.Templates;
import com.loadburn.heron.route.HeronPage;
import com.loadburn.heron.utils.generics.ClassesUtils;

import java.util.List;
import java.util.Set;

import static com.google.inject.matcher.Matchers.annotatedWith;

/**
 * @author slacrey (scstlinfeng@yahoo.com)
 *         Date: 13-11-18
 */
public class ScanWebPackagePlugin implements Plugin {

    private final HeronPage wildfire;
    private final List<Package> packages;
    private final Compilers compilers;

    @Inject
    private final Templates templates = null;

    @Inject
    private final Injector injector = null;

    @Inject
    private final Stage currentStage = null;

    @Inject
    public ScanWebPackagePlugin(HeronPage wildfire, @Heron List<Package> packages, Compilers compilers) {
        this.wildfire = wildfire;
        this.packages = packages;
        this.compilers = compilers;
    }

    @Override
    public void startup() {
        Set<Class<?>> set = Sets.newHashSet();
        for (Package pkg : packages) {

            set.addAll(ClassesUtils.matching(
                    annotatedWith(Path.class).or(
                            annotatedWith(Show.class))
            ).in(pkg));

        }

        Set<HeronPage.Page> pagesToCompile = scanPagesToCompile(set);
        extendedPages(pagesToCompile);

        if (Stage.DEVELOPMENT != currentStage) {
            compileToPages(pagesToCompile);
        }
    }

    @Override
    public void shutdown() {

    }

    private Set<HeronPage.Page> scanPagesToCompile(Set<Class<?>> set) {
        Set<HeronPage.Page> pagesToCompile = Sets.newHashSet();
        Set<Templates.TemplateDescription> templates = Sets.newHashSet();
        for (Class<?> pageClass : set) {
            Path path = pageClass.getAnnotation(Path.class);
            if (null != path) {
                pagesToCompile.addAll(wildfire.path(path.value(), pageClass));
            }
            if (pageClass.isAnnotationPresent(Show.class)) {
                templates.add(new Templates.TemplateDescription(pageClass,
                        pageClass.getAnnotation(Show.class).value()));
            }
        }

        // 预加载页面模板
        if (Stage.DEVELOPMENT != currentStage) {
            this.templates.loadAll(templates);
        }

        return pagesToCompile;
    }

    private void extendedPages(Set<HeronPage.Page> pagesToCompile) {
        Set<HeronPage.Page> pageExtensions = Sets.newHashSet();
        for (HeronPage.Page page : pagesToCompile) {
            if (page.pageClass().isAnnotationPresent(Decoration.class)) {
                analyseExtension(pageExtensions, page.pageClass());
            }
        }
        pagesToCompile.addAll(pageExtensions);
    }

    private void analyseExtension(Set<HeronPage.Page> pagesToCompile, final Class<?> extendClassArgument) {
        // store the page with a special page name used by ExtendWidget
        Class<?> extendClass = extendClassArgument;
        pagesToCompile.add(wildfire.decorate(extendClass));

        while (extendClass != Object.class) {
            extendClass = extendClass.getSuperclass();
            if (extendClass.isAnnotationPresent(Decoration.class)) {
                analyseExtension(pagesToCompile, extendClass);
            } else if (extendClass.isAnnotationPresent(Show.class)) {
                return;
            }
        }
        throw new IllegalStateException("Could not find super class annotated with @Show on parent of class: " + extendClassArgument);
    }

    private void compileToPages(Set<HeronPage.Page> pagesToCompile) {
        for (HeronPage.Page page : pagesToCompile) {
            compilers.compilePage(page);
        }
    }

}


text:
package com.facebook.buck.apple;

import com.dd.plist.NSNumber;
import com.dd.plist.NSObject;
import com.dd.plist.NSString;
import com.facebook.buck.cxx.CxxPlatform;
import com.facebook.buck.cxx.CxxPreprocessorInput;
import com.facebook.buck.cxx.HeaderVisibility;
import com.facebook.buck.cxx.NativeTestable;
import com.facebook.buck.log.Logger;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.rules.AbstractBuildRule;
import com.facebook.buck.rules.AddToRuleKey;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildableContext;
import com.facebook.buck.rules.HasPostBuildSteps;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.rules.coercer.Either;
import com.facebook.buck.shell.DefaultShellStep;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.CopyStep;
import com.facebook.buck.step.fs.FindAndReplaceStep;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.buck.step.fs.MkdirStep;
import com.facebook.buck.step.fs.WriteFileStep;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.ProcessExecutor;
import com.facebook.buck.util.ProcessExecutorParams;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.io.Files;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

/**
 * Creates a bundle: a directory containing files and subdirectories, described by an Info.plist.
 */
public class AppleBundle extends AbstractBuildRule implements HasPostBuildSteps, NativeTestable {
  private static final Logger LOG = Logger.get(AppleBundle.class);
  private static final String CODE_SIGN_ENTITLEMENTS = "CODE_SIGN_ENTITLEMENTS";
  private static final String CODE_SIGN_IDENTITY = "CODE_SIGN_IDENTITY";

  @AddToRuleKey
  private final String extension;

  @AddToRuleKey
  private final SourcePath infoPlist;

  @AddToRuleKey
  private final ImmutableMap<String, String> infoPlistSubstitutions;

  @AddToRuleKey
  private final Optional<BuildRule> binary;

  @AddToRuleKey
  private final AppleBundleDestinations destinations;

  @AddToRuleKey
  private final Set<SourcePath> resourceDirs;

  @AddToRuleKey
  private final Set<SourcePath> resourceFiles;

  @AddToRuleKey
  private final Set<SourcePath> dirsContainingResourceDirs;

  @AddToRuleKey
  private final Optional<ImmutableSet<SourcePath>> resourceVariantFiles;

  @AddToRuleKey
  private final Tool ibtool;

  @AddToRuleKey
  private final Tool dsymutil;

  @AddToRuleKey
  private final Tool strip;

  @AddToRuleKey
  private final ImmutableSortedSet<BuildTarget> tests;

  @AddToRuleKey
  private final String platformName;

  @AddToRuleKey
  private final String sdkName;

  @AddToRuleKey
  private final Optional<ImmutableSet<ProvisioningProfileMetadata>> provisioningProfiles;

  @AddToRuleKey
  private final Optional<CodeSignIdentity> codeSignIdentity;

  private final ImmutableSet<SourcePath> extensionBundlePaths;

  private final Optional<AppleAssetCatalog> assetCatalog;

  private final String binaryName;
  private final Path bundleRoot;
  private final Path binaryPath;
  private final Path bundleBinaryPath;
  private final Path dsymPath;
  private final boolean hasDebugSymbols;

  AppleBundle(
      BuildRuleParams params,
      SourcePathResolver resolver,
      Either<AppleBundleExtension, String> extension,
      SourcePath infoPlist,
      Map<String, String> infoPlistSubstitutions,
      Optional<BuildRule> binary,
      AppleBundleDestinations destinations,
      Set<SourcePath> resourceDirs,
      Set<SourcePath> resourceFiles,
      Set<SourcePath> dirsContainingResourceDirs,
      ImmutableSet<SourcePath> extensionBundlePaths,
      Optional<ImmutableSet<SourcePath>> resourceVariantFiles,
      Tool ibtool,
      Tool dsymutil,
      Tool strip,
      Optional<AppleAssetCatalog> assetCatalog,
      Set<BuildTarget> tests,
      AppleSdk sdk,
      ImmutableSet<CodeSignIdentity> allValidCodeSignIdentities,
      Optional<SourcePath> provisioningProfileSearchPath) {
    super(params, resolver);
    this.extension = extension.isLeft() ?
        extension.getLeft().toFileExtension() :
        extension.getRight();
    this.infoPlist = infoPlist;
    this.infoPlistSubstitutions = ImmutableMap.copyOf(infoPlistSubstitutions);
    this.binary = binary;
    this.destinations = destinations;
    this.resourceDirs = resourceDirs;
    this.resourceFiles = resourceFiles;
    this.dirsContainingResourceDirs = dirsContainingResourceDirs;
    this.extensionBundlePaths = extensionBundlePaths;
    this.resourceVariantFiles = resourceVariantFiles;
    this.ibtool = ibtool;
    this.dsymutil = dsymutil;
    this.strip = strip;
    this.assetCatalog = assetCatalog;
    this.binaryName = getBinaryName(getBuildTarget());
    this.bundleRoot = getBundleRoot(getBuildTarget(), this.extension);
    this.binaryPath = this.destinations.getExecutablesPath()
        .resolve(this.binaryName);
    this.tests = ImmutableSortedSet.copyOf(tests);
    this.platformName = sdk.getApplePlatform().getName();
    this.sdkName = sdk.getName();

    // We need to resolve the possible set of profiles and code sign identity at construction time
    // because they form part of the rule key.
    if (binary.isPresent() && ApplePlatform.needsCodeSign(this.platformName)) {
      final Path searchPath;
      if (provisioningProfileSearchPath.isPresent()) {
        searchPath = resolver.getResolvedPath(provisioningProfileSearchPath.get());
      } else {
        searchPath = Paths.get(System.getProperty("user.home") +
                "/Library/MobileDevice/Provisioning Profiles");
      }

      Optional<ImmutableSet<ProvisioningProfileMetadata>> provisioningProfiles;
      try {
        provisioningProfiles = Optional.of(
            ProvisioningProfileCopyStep.findProfilesInPath(searchPath));
      } catch (InterruptedException e) {
        // We get here if the user pressed Ctrl-C during the profile discovery step.
        // In this case, we'll fail anyway since the set of profiles will be empty.
        provisioningProfiles = Optional.of(ImmutableSet.<ProvisioningProfileMetadata>of());
      }
      this.provisioningProfiles = provisioningProfiles;

      Optional<CodeSignIdentity> foundIdentity = Optional.absent();
      Optional<String> customIdentity = InfoPlistSubstitution.getVariableExpansionForPlatform(
          CODE_SIGN_IDENTITY,
          this.platformName,
          this.infoPlistSubstitutions);
      if (customIdentity.isPresent()) {
        LOG.debug("Bundle specifies custom code signing identity: " + customIdentity.get());
        if (CodeSignIdentity.isHash(customIdentity.get())) {
          for (CodeSignIdentity identity : allValidCodeSignIdentities) {
            if (identity.getHash().equals(customIdentity.get())) {
              foundIdentity = Optional.of(identity);
              break;
            }
          }
        } else {
          for (CodeSignIdentity identity : allValidCodeSignIdentities) {
            if (identity.getFullName().startsWith(customIdentity.get())) {
              foundIdentity = Optional.of(identity);
              break;
            }
          }
        }
      } else if (!allValidCodeSignIdentities.isEmpty()) {
        LOG.debug("Using default code signing identity");
        Iterator<CodeSignIdentity> it = allValidCodeSignIdentities.iterator();
        foundIdentity = Optional.of(it.next());
      }
      if (!foundIdentity.isPresent()) {
        throw new HumanReadableException("The platform " + platformName + " for this target " +
            "requires code signing but couldn't find a compatible code signing identity to use.");
      }
      LOG.debug("Code signing identity is " + foundIdentity.toString());
      this.codeSignIdentity = foundIdentity;
    } else {
      this.provisioningProfiles = Optional.absent();
      this.codeSignIdentity = Optional.absent();
    }
    bundleBinaryPath = bundleRoot.resolve(binaryPath);
    dsymPath = bundleBinaryPath
        .getParent()
        .getParent()
        .resolve(bundleBinaryPath.getFileName().toString() + ".dSYM");
    hasDebugSymbols = binary.isPresent() && binary.get().getPathToOutput() != null;
  }

  public static String getBinaryName(BuildTarget buildTarget) {
    return buildTarget.getShortName();
  }

  public static Path getBundleRoot(BuildTarget buildTarget, String extension) {
    return BuildTargets
        .getGenPath(buildTarget, "%s")
        .resolve(getBinaryName(buildTarget) + "." + extension);
  }

  public String getExtension() {
    return extension;
  }

  @Override
  public Path getPathToOutput() {
    return bundleRoot;
  }

  public Path getInfoPlistPath() {
    return getMetadataPath().resolve("Info.plist");
  }

  public Path getUnzippedOutputFilePathToBinary() {
    return this.binaryPath;
  }

  private Path getMetadataPath() {
    return bundleRoot.resolve(destinations.getMetadataPath());
  }

  public String getPlatformName() { return platformName; }

  public Optional<BuildRule> getBinary() { return binary; }

  @Override
  public ImmutableList<Step> getBuildSteps(
      BuildContext context,
      BuildableContext buildableContext) {
    ImmutableList.Builder<Step> stepsBuilder = ImmutableList.builder();

    Path metadataPath = getMetadataPath();

    Path infoPlistInputPath = getResolver().getPath(infoPlist);
    Path infoPlistSubstitutionTempPath =
        BuildTargets.getScratchPath(getBuildTarget(), "%s.plist");
    Path infoPlistOutputPath = metadataPath.resolve("Info.plist");

    stepsBuilder.add(
        new MakeCleanDirectoryStep(bundleRoot),
        new MkdirStep(metadataPath),
        // TODO(user): This is only appropriate for .app bundles.
        new WriteFileStep(
            getProjectFilesystem(),
            "APPLWRUN",
            metadataPath.resolve("PkgInfo"),
            /* executable */ false),
        new FindAndReplaceStep(
          infoPlistInputPath,
          infoPlistSubstitutionTempPath,
          InfoPlistSubstitution.createVariableExpansionFunction(
              withDefaults(
                  infoPlistSubstitutions,
                  ImmutableMap.of(
                      "EXECUTABLE_NAME", binaryName,
                      "PRODUCT_NAME", binaryName
                  ))
          )),
        new PlistProcessStep(
            infoPlistSubstitutionTempPath,
            infoPlistOutputPath,
            getInfoPlistAdditionalKeys(platformName, sdkName),
            getInfoPlistOverrideKeys(platformName),
            PlistProcessStep.OutputFormat.BINARY));

    if (hasDebugSymbols) {
      stepsBuilder.add(
          new MkdirStep(bundleRoot.resolve(this.destinations.getExecutablesPath())));
      buildableContext.recordArtifact(dsymPath);
      stepsBuilder.add(
          CopyStep.forFile(
              binary.get().getPathToOutput(),
              bundleBinaryPath));
      stepsBuilder.add(
          new DsymStep(
              dsymutil.getCommandPrefix(getResolver()),
              bundleBinaryPath,
              dsymPath));
      stepsBuilder.add(
          new DefaultShellStep(
              ImmutableList.<String>builder()
                  .addAll(strip.getCommandPrefix(getResolver()))
                  .add("-S")
                  .add(getProjectFilesystem().resolve(bundleBinaryPath).toString())
                  .build()));
    }

    Path bundleDestinationPath = bundleRoot.resolve(this.destinations.getResourcesPath());
    for (SourcePath dir : resourceDirs) {
      stepsBuilder.add(new MkdirStep(bundleDestinationPath));
      stepsBuilder.add(
          CopyStep.forDirectory(
              getResolver().getPath(dir),
              bundleDestinationPath,
              CopyStep.DirectoryMode.DIRECTORY_AND_CONTENTS));
    }
    for (SourcePath dir : dirsContainingResourceDirs) {
      stepsBuilder.add(new MkdirStep(bundleDestinationPath));
      stepsBuilder.add(
          CopyStep.forDirectory(
              getResolver().getPath(dir),
              bundleDestinationPath,
              CopyStep.DirectoryMode.CONTENTS_ONLY));
    }
    for (SourcePath file : resourceFiles) {
      stepsBuilder.add(new MkdirStep(bundleDestinationPath));
      Path resolvedFilePath = getResolver().getPath(file);
      Path destinationPath = bundleDestinationPath.resolve(resolvedFilePath.getFileName());
      addResourceProcessingSteps(resolvedFilePath, destinationPath, stepsBuilder);
    }

    addStepsToCopyExtensionBundlesDependencies(stepsBuilder);

    if (resourceVariantFiles.isPresent()) {
      for (SourcePath variantSourcePath : resourceVariantFiles.get()) {
        Path variantFilePath = getResolver().getPath(variantSourcePath);

        Path variantDirectory = variantFilePath.getParent();
        if (variantDirectory == null || !variantDirectory.toString().endsWith(".lproj")) {
          throw new HumanReadableException(
              "Variant files have to be in a directory with name ending in '.lproj', " +
                  "but '%s' is not.",
              variantFilePath);
        }

        Path bundleVariantDestinationPath =
            bundleDestinationPath.resolve(variantDirectory.getFileName());
        stepsBuilder.add(new MkdirStep(bundleVariantDestinationPath));

        Path destinationPath = bundleVariantDestinationPath.resolve(variantFilePath.getFileName());
        addResourceProcessingSteps(variantFilePath, destinationPath, stepsBuilder);
      }
    }

    if (assetCatalog.isPresent()) {
      Path bundleDir = assetCatalog.get().getOutputDir();
      stepsBuilder.add(
          CopyStep.forDirectory(
              bundleDir,
              bundleRoot,
              CopyStep.DirectoryMode.CONTENTS_ONLY));
    }

    // Copy the .mobileprovision file if the platform requires it.
    if (provisioningProfiles.isPresent()) {
      Optional<Path> entitlementsPlist = Optional.absent();
      final String srcRoot = context.getProjectRoot().resolve(
          getBuildTarget().getBasePath()).toString();
      Optional<String> entitlementsPlistString =
          InfoPlistSubstitution.getVariableExpansionForPlatform(
              CODE_SIGN_ENTITLEMENTS,
              platformName,
              withDefaults(
                  infoPlistSubstitutions,
                  ImmutableMap.of(
                      "SOURCE_ROOT", srcRoot,
                      "SRCROOT", srcRoot
                  )));
      if (entitlementsPlistString.isPresent()) {
        entitlementsPlist = Optional.of(Paths.get(entitlementsPlistString.get()));
      }

      final Path signingEntitlementsTempPath =
          BuildTargets.getScratchPath(getBuildTarget(), "%s.xcent");

      stepsBuilder.add(
          new ProvisioningProfileCopyStep(
              getProjectFilesystem(),
              infoPlistOutputPath,
              Optional.<String>absent(),  // Provisioning profile UUID -- find automatically.
              entitlementsPlist,
              provisioningProfiles.get(),
              bundleDestinationPath.resolve("embedded.mobileprovision"),
              signingEntitlementsTempPath)
      );

      stepsBuilder.add(
          new CodeSignStep(
              bundleDestinationPath,
              signingEntitlementsTempPath,
              codeSignIdentity.get().getHash()
          )
      );
    }

    // Ensure the bundle directory is archived so we can fetch it later.
    buildableContext.recordArtifact(getPathToOutput());

    return stepsBuilder.build();
  }

  @Override
  public ImmutableList<Step> getPostBuildSteps(
      BuildContext context,
      BuildableContext buildableContext) {
    if (!hasDebugSymbols) {
      return ImmutableList.of();
    }
    return ImmutableList.<Step>of(
        new Step() {
          @Override
          public int execute(ExecutionContext context) throws IOException, InterruptedException {
            ProcessExecutorParams params = ProcessExecutorParams
                .builder()
                .addCommand("lldb")
                .build();
            return context.getProcessExecutor().launchAndExecute(
                params,
                ImmutableSet.<ProcessExecutor.Option>of(),
                Optional.of(
                    String.format("target create %s\ntarget symbols add %s", bundleRoot, dsymPath)),
                Optional.<Long>absent(),
                Optional.<Function<Process, Void>>absent()).getExitCode();
          }

          @Override
          public String getShortName() {
            return "register debug symbols";
          }

          @Override
          public String getDescription(ExecutionContext context) {
            return String.format(
                "register debug symbols for binary '%s': '%s'",
                bundleRoot,
                dsymPath);
          }
        });
  }

  public void addStepsToCopyExtensionBundlesDependencies(
      ImmutableList.Builder<Step> stepsBuilder) {
    for (SourcePath sourcePath : extensionBundlePaths) {
      Path plugInsDestPath = bundleRoot.resolve(destinations.getPlugInsPath());
      stepsBuilder.add(new MkdirStep(plugInsDestPath));
      stepsBuilder.add(
        CopyStep.forDirectory(
            getResolver().getPath(sourcePath),
            plugInsDestPath,
            CopyStep.DirectoryMode.DIRECTORY_AND_CONTENTS));
    }
  }

  static ImmutableMap<String, String> withDefaults(
      ImmutableMap<String, String> map,
      ImmutableMap<String, String> defaults) {
    ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String>builder()
        .putAll(map);
    for (ImmutableMap.Entry<String, String> entry : defaults.entrySet()) {
      if (!map.containsKey(entry.getKey())) {
        builder = builder.put(entry.getKey(), entry.getValue());
      }
    }
    return builder.build();
  }

  static ImmutableMap<String, NSObject> getInfoPlistOverrideKeys(
      String platformName) {
    ImmutableMap.Builder<String, NSObject> keys = ImmutableMap.builder();

    if (platformName.contains("osx")) {
      keys.put("LSRequiresIPhoneOS", new NSNumber(false));
    } else {
      keys.put("LSRequiresIPhoneOS", new NSNumber(true));
    }

    return keys.build();
  }

  static ImmutableMap<String, NSObject> getInfoPlistAdditionalKeys(
      String platformName,
      String sdkName) {
    ImmutableMap.Builder<String, NSObject> keys = ImmutableMap.builder();

    if (platformName.contains("osx")) {
      keys.put("NSHighResolutionCapable", new NSNumber(true));
      keys.put("NSSupportsAutomaticGraphicsSwitching", new NSNumber(true));
    }

    keys.put("DTPlatformName", new NSString(platformName));
    keys.put("DTSDKName", new NSString(sdkName));

    return keys.build();
  }

  private void addResourceProcessingSteps(
      Path sourcePath,
      Path destinationPath,
      ImmutableList.Builder<Step> stepsBuilder) {
    String sourcePathExtension = Files.getFileExtension(sourcePath.toString())
        .toLowerCase(Locale.US);
    switch (sourcePathExtension) {
      case "plist":
      case "stringsdict":
        LOG.debug("Converting plist %s to binary plist %s", sourcePath, destinationPath);
        stepsBuilder.add(
            new PlistProcessStep(
                sourcePath,
                destinationPath,
                ImmutableMap.<String, NSObject>of(),
                ImmutableMap.<String, NSObject>of(),
                PlistProcessStep.OutputFormat.BINARY));
        break;
      case "xib":
        String compiledNibFilename = Files.getNameWithoutExtension(destinationPath.toString()) +
            ".nib";
        Path compiledNibPath = destinationPath.getParent().resolve(compiledNibFilename);
        LOG.debug("Compiling XIB %s to NIB %s", sourcePath, destinationPath);
        stepsBuilder.add(
            new IbtoolStep(
                ibtool.getCommandPrefix(getResolver()),
                sourcePath,
                compiledNibPath));
        break;
      default:
        stepsBuilder.add(CopyStep.forFile(sourcePath, destinationPath));
        break;
    }
  }

  @Override
  public boolean isTestedBy(BuildTarget testRule) {
    if (tests.contains(testRule)) {
      return true;
    }

    if (binary.isPresent()) {
      BuildRule binaryRule = binary.get();
      if (binaryRule instanceof NativeTestable) {
        return ((NativeTestable) binaryRule).isTestedBy(testRule);
      }
    }

    return false;
  }

  @Override
  public CxxPreprocessorInput getCxxPreprocessorInput(
      TargetGraph targetGraph,
      CxxPlatform cxxPlatform,
      HeaderVisibility headerVisibility) {
    if (binary.isPresent()) {
      BuildRule binaryRule = binary.get();
      if (binaryRule instanceof NativeTestable) {
        return ((NativeTestable) binaryRule).getCxxPreprocessorInput(
            targetGraph,
            cxxPlatform,
            headerVisibility);
      }
    }
    return CxxPreprocessorInput.EMPTY;
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <!-- b/170406291 -->

   <androidx.constraintlayout.widget.Barrier
       android:id="@+id/barrierStart"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       app:barrierDirection="start"
       app:constraint_referenced_ids="view1"
       />

   <androidx.constraintlayout.widget.Barrier
       android:id="@+id/barrierEnd"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       app:barrierDirection="end"
       app:constraint_referenced_ids="view2"
       />

   <TextView
       android:id="@+id/view1"
       android:layout_width="60dp"
       android:layout_height="40dp"
       android:text="View 1"
       app:layout_constraintHorizontal_chainStyle="packed"
       app:layout_constraintEnd_toStartOf="@+id/view2"
       app:layout_constraintStart_toStartOf="parent"
       app:layout_constraintTop_toTopOf="parent" />

   <TextView
       android:id="@+id/view2"
       android:layout_width="0dp"
       app:layout_constraintWidth_max="150dp"
       android:layout_height="40dp"
       android:text="View 2"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintStart_toEndOf="@+id/view1"
       app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


text:
1. Draft a new release on Github. Set the "Tag version" to the value of version in your application package.json, and prefix it with v. "Release title" can be anything you want.
For example, if your application package.json version is 1.0, your draft's "Tag version" would be v1.0.
2. Push some commits. Every CI build will update the artifacts attached to this draft.
3. Once you are done, publish the release. GitHub will tag the latest commit for you.

The benefit of this workflow is that it allows you to always have the latest artifacts, and the release can be published once it is ready.

### Workflow 2

1. run `npm version major/minor/patch` to tag and generate a commit
2. push the commit and the tag
3. The CI will draft a release with the correct "Tag version" from your package.json file

# Dependencies

To build for Linux and Windows the suggested way is to use the `dockerdist:linux` and `dockerdist:windows` command that use a well-tested and fully equipped docker environment to build for both.
To build the dmg container for macOS, a macOS machine is required. It's suggested to use Travis-CI in this regard.
This [documentation](https://github.com/electron-userland/electron-builder/wiki/Multi-Platform-Build) explains the needed dependencies to build locally.


text:
if (arg[1] == 'default') then
	port = '10002'
	host = '192.168.2.202'
	nodeid = 20
else
	if (arg[1] == nil) then
		print('  [ERROR] missing parameter \'port\'')
		print('  usage: lua main.lua <port> <ip address> <nodeId>')
		os.exit()
	end;

	if(arg[2] == nil) then
		print('  [ERROR] missing parameter \'id address\'')
		print('  usage: lua main.lua <port> <ip address> <nodeId>')
		os.exit()
	end;

	if(arg[3] == nil) then
		print('  [ERROR] missing parameter \'nodeId\'')
		print('  usage: lua main.lua <port> <ip address> <nodeId>')
		os.exit()
	end;

	port = arg[1]
	host = arg[2]
	nodeid = tonumber(arg[3])
end;

print(' -- listening for messages in port ' .. port)
print(' -- connecting to host ' .. host)

require"zmq"
require"lib/zhelpers"
require"math"

local json = require('cjson')
local tossam = require("tossam")
local context = zmq.init(1)
local publisher = context:socket(zmq.PUB)
local exit = false
local sck = require("socket")

publisher:bind("tcp://*:"..port)

while not(exit) do
    local mote = tossam.connect {
        protocol = "network",
        host     = host,
        port     = '10002',
        nodeid   = nodeid
    }
    if not(mote) then print("  ! connection error\n  ! aborting"); return(1); end

    mote:register [[
    nx_struct msg_serial [145] {
        nx_uint8_t id;
        nx_uint16_t source;
        nx_uint16_t target;
        nx_uint8_t  d8[4];
        nx_uint16_t d16[4];
        nx_uint32_t d32[2];
    };
    ]]

    while (mote) do
        local stat, msg, emsg = pcall(function() return mote:receive() end)
        if stat then
            print(emsg)
            if msg then
                msg.port = port
                --msg.gateway_time = os.clock() * 1000
								msg.gateway_time = sck.gettime()*1000

                print("------------------------------")
                print("msgID: "..msg.id, "Source: ".. msg.source, "Target: ".. msg.target.." Port: "..msg.port)
                print("d8:",unpack(msg.d8))
                print("d16:",unpack(msg.d16))
                print("d32:",unpack(msg.d32))
								--print("gateway_time:",os.clock() * 1000)
								print("gateway_time:",sck.gettime()*1000)

                publisher:send("event", zmq.SNDMORE)
                publisher:send(json.encode(msg))

            else
                if emsg == "closed" then
                    print("\nConnection closed!")
                    exit = true
                    break
                end
            end
        else
            print("\nreceive() got an error:"..msg)
            exit = true
            break
        end
    end

    mote:unregister()
    mote:close()
end

publisher:close()
context:term()


text:
angular.module('app.core').value('dpdConfig', ['apis', 'api-layers', 'dev-teams', 'interface-styles', 'ops-teams', 'product-managers', 'project-managers', 'technology-stacks']);
angular.module('app.core').controller('apiEditController', ['dpd', '$scope', '$routeParams', '$location',
    function (dpd, $scope, $routeParams, $location) {
        var vm = this;

        vm.load = function (id) {
            //alert('Loading ' + id);
            dpd.apis.get(id)
                .success(function (result) {
                    // use result
                    //alert(xinspect(result));
                    vm.api = result;
                })
                .error(function (err) {
                    // on error
                    alert(xinspect(err));
                })
                .finally(function () {
                    // finally
                });

        }

        if($routeParams.api_id != 'new'){
            vm.load($routeParams.api_id);
        }

        vm.save = function (api) {
            //alert(api.id);
            if (api.id != undefined) {
                //PUT
                //alert('PUTTING ' + xinspect(api));
                dpd.apis.put(api.id, api)
                    // // Do something
                    // if (error === "200") {
                    //     vm.alerts.push({ type: 'success', msg: 'Record Saved' })
                    // }
                    // if (result) {
                    //     //alert(xinspect(result));
                    // }
                .success(function (result) {
                    // use result
                    //alert(xinspect(result));

                })
                .error(function (err) {
                    // on error
                    alert(xinspect(err));
                });

            }
            else {
                //POST
                //alert('POSTING');
                api.id = undefined;
                //alert(xinspect(api));
                dpd.apis.post(api)
                    .success(function (result) {
                        // use result
                        //alert(xinspect(result));
                    })
                    .error(function (err) {
                        // on error
                        alert(xinspect(err));
                    });
            }
            $location.path('/apiList');

        }

        vm.cancel = function () {
            $location.path('/apiList');
        }

        vm.delete = function(api) {
            dpd.apis.del(api.id)
                .error(function (err) {
                    alert(xinspect(err));
                });
            $location.path('/apiList');
        }

        // Pop-Up Calendar Crap
        $scope.today = function () {
            $scope.dt = new Date();
        };
        $scope.today();

        $scope.clear = function () {
            //$scope.dt = null;
        };

        // Disable weekend selection
        $scope.disabled = function (date, mode) {
            return (mode === 'day' && (date.getDay() === 0 || date.getDay() === 6));
        };

        $scope.minDate = new Date(2000, 1, 1);
        $scope.maxDate = new Date(2025, 5, 22);

        $scope.openProjectStartDateCal = function ($event) {
            $scope.status.projectStartDateCalopened = true;
        };
        $scope.openCurrentVersionReleaseDateCal = function ($event) {
            $scope.status.currentVersionReleaseDateCalopened = true;
        };
        $scope.openNextVersionReleaseDateCal = function ($event) {
            $scope.status.nextVersionReleaseDateCalopened = true;
        };
        //$scope.setDate = function (year, month, day) {
        //    $scope.dt = new Date(year, month, day);
        //};

        $scope.dateOptions = {
            formatYear: 'yy',
            startingDay: 1
        };

        $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
        $scope.format = $scope.formats[0];

        $scope.status = {
            projectStartDateCalopened: false,
            currentVersionReleaseDateCalopened: false,
            nextVersionReleaseDateCalopened: false
        };

        var tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        var afterTomorrow = new Date();
        afterTomorrow.setDate(tomorrow.getDate() + 2);
        $scope.events =
        [
            {
                date: tomorrow,
                status: 'full'
            },
            {
                date: afterTomorrow,
                status: 'partially'
            }
        ];

        $scope.getDayClass = function (date, mode) {
            if (mode === 'day') {
                var dayToCheck = new Date(date).setHours(0, 0, 0, 0);

                for (var i = 0; i < $scope.events.length; i++) {
                    var currentDay = new Date($scope.events[i].date).setHours(0, 0, 0, 0);

                    if (dayToCheck === currentDay) {
                        return $scope.events[i].status;
                    }
                }
            }

            return '';
        };
        // End of calendar crap

        // Load Product Managers
        var loadPMs = function () {
        dpd['product-managers'].get()
                .success(function (result) {
                    // use result
                    vm.productManagers = result;
                })
                .error(function (err) {
                    // on error
                    alert(xinspect(err));
                })
                .finally(function () {
                    // finally
                });
        }
        loadPMs();

        // Load Project Managers
        var loadPjMs = function () {
        dpd['project-managers'].get()
                .success(function (result) {
                    // use result
                    vm.projectManagers = result;
                })
                .error(function (err) {
                    // on error
                    alert(xinspect(err));
                })
                .finally(function () {
                    // finally
                });
        }
        loadPjMs();

        // Load Dev Teams
        var loadDevTeams = function () {
        dpd['dev-teams'].get()
                .success(function (result) {
                    // use result
                    vm.devTeams = result;
                })
                .error(function (err) {
                    // on error
                    alert(xinspect(err));
                })
                .finally(function () {
                    // finally
                });

        }
        loadDevTeams();

        // Load Ops Teams
        var loadOpsTeams = function () {
        dpd['ops-teams'].get()
                .success(function (result) {
                    // use result
                    vm.opsTeams = result;
                })
                .error(function (err) {
                    // on error
                    alert(xinspect(err));
                })
                .finally(function () {
                    // finally
                });
        }
        loadOpsTeams();

        // Load API Layers
        var loadAPILayers = function () {
        dpd['api-layers'].get()
                .success(function (result) {
                    // use result
                    vm.apiLayers = result;
                })
                .error(function (err) {
                    // on error
                    alert(xinspect(err));
                })
                .finally(function () {
                    // finally
                });
        }
        loadAPILayers();

        // Load Technology Stacks
        var loadStacks = function () {
        dpd['technology-stacks'].get()
                .success(function (result) {
                    // use result
                    vm.technologyStacks = result;
                })
                .error(function (err) {
                    // on error
                    alert(xinspect(err));
                })
                .finally(function () {
                    // finally
                });
        }
        loadStacks();

        // Load Interface Styles
        var loadInterfaceStyles = function () {
        dpd['interface-styles'].get()
                .success(function (result) {
                    // use result
                    vm.interfaceStyles = result;
                })
                .error(function (err) {
                    // on error
                    alert(xinspect(err));
                })
                .finally(function () {
                    // finally
                });

        }
        loadInterfaceStyles();

        vm.closeAlert = function (index) {
            vm.alerts.splice(index, 1);
        };
    }]);


text:
namespace CGAL {

/*!
\ingroup PkgConvexHull2Functions

generates the counterclockwise sequence of extreme points
of the points in the range [`first`,`beyond`).
The resulting sequence is placed starting at position
`result`, and the past-the-end iterator for the resulting
sequence is returned. It is not specified at which point the
cyclic sequence of extreme points is cut into a linear sequence.
\pre The source range [`first`,`beyond`) does not contain `result`.

The default traits class `Default_traits` is the kernel in which the
value type of `InputIterator` is defined.

\cgalHeading{Requirements}

<OL>
<LI>The value type of `InputIterator` and
`OutputIterator` is equivalent to `Traits::Point_2`.
<LI>`Traits` defines the following subset of types from
the concept `ConvexHullTraits_2` and their corresponding member
functions that return instances of these types:
<UL>
<LI>`Traits::Point_2`,
<LI>`Traits::Equal_2`,
<LI>`Traits::Less_rotate_ccw_2`,
<LI>`Traits::Less_xy_2`.
</UL>
</OL>

\sa `CGAL::ch_akl_toussaint()`
\sa `CGAL::ch_bykat()`
\sa `CGAL::ch_eddy()`
\sa `CGAL::ch_graham_andrew()`
\sa `CGAL::ch_jarvis_march()`
\sa `CGAL::ch_melkman()`
\sa `CGAL::convex_hull_2()`

\cgalHeading{Implementation}

This function uses the Jarvis march (gift-wrapping)
algorithm \cgalCite{j-ichfs-73}. This algorithm requires \f$ O(n h)\f$ time
in the worst case for \f$ n\f$ input points with \f$ h\f$ extreme points.

*/
template <class InputIterator, class OutputIterator, class Traits>
OutputIterator
ch_jarvis( InputIterator first,
InputIterator beyond,
OutputIterator result,
const Traits & ch_traits = Default_traits);

} /* namespace CGAL */

namespace CGAL {

/*!
\ingroup PkgConvexHull2Subsequence

generates the counterclockwise sequence of extreme
points from a given set of input points that line between two input points.

More precisely, it generates the counterclockwise subsequence of
extreme points between `start_p` and `stop_p` of the
points in the range [`first`,`beyond`), starting at
position `result` with point `start_p`. The last point
generated is the point preceding `stop_p` in the
counterclockwise order of extreme points.

The default traits class `Default_traits` is the kernel in which the
type `ForwardIterator::value_type` is defined.

\cgalHeading{Requirements}

<OL>
<LI>`ForwardIterator::value_type` and
`OutputIterator::value_type`
are equivalent to `Traits::Point_2`.
<LI>`Traits` defines the following subset of types from
the concept `ConvexHullTraits_2` and their corresponding member
functions that return instances of these types:
<UL>
<LI>`Traits::Point_2`,
<LI>`Traits::Equal_2`,
<LI>`Traits::Less_rotate_ccw_2`.
</UL>
</OL>

\sa `CGAL::ch_jarvis()`
\sa `CGAL::lower_hull_points_2()`
\sa `CGAL::upper_hull_points_2()`

\cgalHeading{Implementation}

The function uses the Jarvis march (gift-wrapping) algorithm \cgalCite{j-ichfs-73}.
This algorithm requires \f$ O(n h)\f$ time in the worst
case for \f$ n\f$ input points with \f$ h\f$ extreme points

\pre `start_p` and `stop_p` are extreme points with respect to
the points in the range [`first`,`beyond`) and `stop_p`
is an element of range [`first`,`beyond`).
*/
template <class ForwardIterator, class OutputIterator, class Traits>
OutputIterator
ch_jarvis_march(ForwardIterator first, ForwardIterator beyond,
const Traits::Point_2& start_p,
const Traits::Point_2& stop_p,
OutputIterator result,
const Traits& ch_traits = Default_traits);

} /* namespace CGAL */


text:
if (typeof require !== 'undefined') {
  var Validator = require('../src/validator.js');
  var expect = require('chai').expect;
} else {
  var Validator = window.Validator;
  var expect = window.chai.expect;
}

describe('confirmed validation rule', function() {
  it('should fail without a matching confirmation field for the field under validation', function() {
    var validator = new Validator({
      password: 'abc'
    }, {
      password: 'confirmed'
    });
    expect(validator.passes()).to.be.false;
    expect(validator.fails()).to.be.true;
  });

  it('should fail without a matching confirmation field for the field under validation', function() {
    var validator = new Validator({
      password: 'abc',
      password_confirmation: 'abcd'
    }, {
      password: 'confirmed'
    });
    expect(validator.passes()).to.be.false;
    expect(validator.fails()).to.be.true;
    expect(validator.errors.first('password')).to.equal('The password confirmation does not match.');
  });

  it('should pass with a matching confirmation field for the field under validation', function() {
    var validator = new Validator({
      password: 'abc',
      password_confirmation: 'abc'
    }, {
      password: 'confirmed'
    });
    expect(validator.passes()).to.be.true;
    expect(validator.fails()).to.be.false;
  });
});


text:
<?php

namespace Magento\Checkout\Test\Unit\Block\Checkout;

use Magento\Checkout\Block\Checkout\AttributeMerger;
use Magento\Checkout\Block\Checkout\LayoutProcessor;
use Magento\Checkout\Helper\Data;
use Magento\Customer\Model\AttributeMetadataDataProvider;
use Magento\Customer\Model\Options;
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;
use Magento\Ui\Component\Form\AttributeMapper;
use PHPUnit_Framework_MockObject_MockObject as MockObject;

/**
 * LayoutProcessorTest covers a list of variations for
 * checkout layout processor
 */
class LayoutProcessorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var AttributeMetadataDataProvider|MockObject
     */
    private $attributeDataProvider;

    /**
     * @var AttributeMapper|MockObject
     */
    private $attributeMapper;

    /**
     * @var AttributeMerger|MockObject
     */
    private $attributeMerger;

    /**
     * @var Data|MockObject
     */
    private $dataHelper;

    /**
     * @var LayoutProcessor
     */
    private $layoutProcessor;

    protected function setUp()
    {
        $objectManager = new ObjectManager($this);

        $this->attributeDataProvider = $this->getMockBuilder(AttributeMetadataDataProvider::class)
            ->disableOriginalConstructor()
            ->setMethods(['loadAttributesCollection'])
            ->getMock();

        $this->attributeMapper = $this->getMockBuilder(AttributeMapper::class)
            ->disableOriginalConstructor()
            ->setMethods(['map'])
            ->getMock();

        $this->attributeMerger = $this->getMockBuilder(AttributeMerger::class)
            ->disableOriginalConstructor()
            ->setMethods(['merge'])
            ->getMock();

        $this->dataHelper = $this->getMockBuilder(Data::class)
            ->disableOriginalConstructor()
            ->setMethods(['isDisplayBillingOnPaymentMethodAvailable'])
            ->getMock();

        $options = $this->getMockBuilder(Options::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->layoutProcessor = new LayoutProcessor(
            $this->attributeDataProvider,
            $this->attributeMapper,
            $this->attributeMerger
        );

        $objectManager->setBackwardCompatibleProperty($this->layoutProcessor, 'checkoutDataHelper', $this->dataHelper);
        $objectManager->setBackwardCompatibleProperty($this->layoutProcessor, 'options', $options);
    }

    /**
     * @covers \Magento\Checkout\Block\Checkout\LayoutProcessor::process
     */
    public function testProcess()
    {
        $jsLayout = $this->getLayoutData();

        $this->attributeDataProvider->expects(static::once())
            ->method('loadAttributesCollection')
            ->willReturn([]);

        $this->dataHelper->expects(static::once())
            ->method('isDisplayBillingOnPaymentMethodAvailable')
            ->willReturn(true);

        $this->attributeMerger->expects(static::exactly(2))
            ->method('merge')
            ->willReturnMap([
                ['payment1_1' => $this->getBillingComponent('payment1_1')],
                ['payment2_1' => $this->getBillingComponent('payment2_1')],
            ]);

        $actual = $this->layoutProcessor->process($jsLayout);

        static::assertArrayHasKey(
            'payment1_1-form',
            $actual['components']['checkout']['children']['steps']['children']['billing-step']['children']
            ['payment']['children']['payments-list']['children']
        );
        static::assertArrayHasKey(
            'payment2_1-form',
            $actual['components']['checkout']['children']['steps']['children']['billing-step']['children']
            ['payment']['children']['payments-list']['children']
        );
        static::assertArrayNotHasKey(
            'payment2_2-form',
            $actual['components']['checkout']['children']['steps']['children']['billing-step']['children']
            ['payment']['children']['payments-list']['children']
        );
        static::assertArrayHasKey(
            'afterMethods',
            $actual['components']['checkout']['children']['steps']['children']['billing-step']
            ['children']['payment']['children']
        );
        static::assertEmpty(
            $actual['components']['checkout']['children']['steps']['children']['billing-step']
            ['children']['payment']['children']['afterMethods']['children']
        );
    }

    /**
     * @covers \Magento\Checkout\Block\Checkout\LayoutProcessor::process
     */
    public function testProcessWithBillingAddressOnPaymentPage()
    {
        $jsLayout = $this->getLayoutData();

        $this->attributeDataProvider->expects(static::once())
            ->method('loadAttributesCollection')
            ->willReturn([]);

        $this->dataHelper->expects(static::once())
            ->method('isDisplayBillingOnPaymentMethodAvailable')
            ->willReturn(false);

        $this->attributeMerger->expects(static::once())
            ->method('merge')
            ->willReturn($this->getBillingComponent('shared'));

        $actual = $this->layoutProcessor->process($jsLayout);

        static::assertEmpty(
            $actual['components']['checkout']['children']['steps']['children']['billing-step']['children']
            ['payment']['children']['payments-list']['children']
        );

        static::assertNotEmpty(
            $actual['components']['checkout']['children']['steps']['children']['billing-step']['children']
            ['payment']['children']['afterMethods']['children']
        );
        static::assertArrayHasKey(
            'billing-address-form',
            $actual['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']
            ['children']['afterMethods']['children']
        );
    }

    /**
     * Get mock layout data for testing
     * @return array
     */
    private function getLayoutData()
    {
        return [
            'components' => [
                'checkout' => [
                    'children' => [
                        'steps' => [
                            'children' => [
                                'billing-step' => [
                                    'children' => [
                                        'payment' => [
                                            'children' => [
                                                'renders' => [
                                                    'children' => [
                                                        'payment1' => [
                                                            'methods' => [
                                                                'payment1_1' => [
                                                                    'isBillingAddressRequired' => true
                                                                ]
                                                            ]
                                                        ],
                                                        'payment2' => [
                                                            'methods' => [
                                                                'payment2_1' => [
                                                                    'isBillingAddressRequired' => true
                                                                ],
                                                                'payment2_2' => [
                                                                    'isBillingAddressRequired' => false
                                                                ]
                                                            ]
                                                        ]
                                                    ]
                                                ]
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ]
        ];
    }

    /**
     * Get mock data for billing component
     * @param string $paymentCode
     * @return array
     */
    private function getBillingComponent($paymentCode)
    {
        return [
            'country_id' => [
                'sortOrder' => 115,
            ],
            'region' => [
                'visible' => false,
            ],
            'region_id' => [
                'component' => 'Magento_Ui/js/form/element/region',
                'config' => [
                    'template' => 'ui/form/field',
                    'elementTmpl' => 'ui/form/element/select',
                    'customEntry' => 'billingAddress' . $paymentCode . '.region',
                ],
                'validation' => [
                    'required-entry' => true,
                ],
                'filterBy' => [
                    'target' => '${ $.provider }:${ $.parentScope }.country_id',
                    'field' => 'country_id',
                ],
            ],
            'postcode' => [
                'component' => 'Magento_Ui/js/form/element/post-code',
                'validation' => [
                    'required-entry' => true,
                ],
            ],
            'company' => [
                'validation' => [
                    'min_text_length' => 0,
                ],
            ],
            'fax' => [
                'validation' => [
                    'min_text_length' => 0,
                ],
            ],
            'telephone' => [
                'config' => [
                    'tooltip' => [
                        'description' => __('For delivery questions.'),
                    ],
                ],
            ],
        ];
    }
}


text:
using System;
using System.Collections.Generic;

using System.Text;

namespace LibNVim.Motions
{
    class MotionMoveToStartOfLine : AbstractVimMotion, Interfaces.IVimMotionLineWise
    {
        public MotionMoveToStartOfLine(Interfaces.IVimHost host, int repeat)
            : base(host, repeat)
        {
        }

        public override VimPoint Move(Interfaces.IVimHost host)
        {
            host.MoveToStartOfLine();
            return host.CurrentPosition;
        }
    }
}


text:
"""
$Id: setup.py 204 2017-08-02 08:23:55Z aokada $
"""

from setuptools import setup, find_packages
from scripts.paplot import __version__

import sys
sys.path.append('./paplot')
sys.path.append('./tests/python')

import os

def package_files(directory):
    paths = []
    for (path, directories, filenames) in os.walk(directory):
        for filename in filenames:
            paths.append(os.path.join(path, filename))
    return paths

data_files=[
    ('paplot-data-' + __version__ + "/config_template", package_files('config_template')),
    ('paplot-data-' + __version__ + "/genome", package_files('genome')),
]
for path in package_files('example'):
    if path.endswith(".zip"): continue
    data_files.append(('paplot-data-' + __version__ + "/" + os.path.dirname(path), [path]))

setup(name='paplot',
      version=__version__,
      description="Automatic generation of cancer genome interactive report.",
      long_description="""paplot outputs files described by javascript (use D3.js, https://d3js.org/ ) and HTML.
These interactive figures  allow users to enjoy filtering, focusing and sorting the visualized contents as their necessity, without re-executing drawing tools with different parameters.
Furthermore, by moving the mouse, the user can efficiently obtain various information.
""",

      classifiers=[
          #   3 - Alpha
          #   4 - Beta
          #   5 - Production/Stable
          'Development Status :: 3 - Alpha',
          # Indicate who your project is intended for
          'Intended Audience :: Science/Research',
          'Topic :: Scientific/Engineering :: Bio-Informatics',

          'License :: OSI Approved :: MIT License',
          'Programming Language :: Python :: 2',
          'Programming Language :: Python :: 2.7',
          'Programming Language :: Python :: 3',
          'Programming Language :: Python :: 3.2',
          'Programming Language :: Python :: 3.3',
          'Programming Language :: Python :: 3.4',
          'Programming Language :: Python :: 3.5',
      ], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers

      keywords='post analysis genome bioinfomatics',
      author='Ai Okada',
      author_email='genomon.devel@gmail.com',
      url='https://github.com/Genomon-Project/paplot.git',
      license='MIT',

      package_dir = {'': 'scripts'},
      packages=['paplot', 'paplot.subcode'],
      scripts=['paplot'],
      data_files=data_files,
      include_package_data=True,
      zip_safe=False,
      install_requires=[
          # -*- Extra requirements: -*-
      ],
      entry_points="""
      # -*- Entry points: -*-
      """,
      package_data = {
          'paplot': ['lib/*/*','js/*','templates/*', 'style/*', 'layout/*'],
      },
      test_suite = 'unit_tests.suite',
)


text:
require 'spec_helper'

describe Oct  do

  before(:each) do
    @filename = 'input.txt'
    write_file(@filename, "the quick brown fox")
  end

  describe 'Aruba::API.current_dir' do

    it "should return the current dir as 'tmp/aruba'" do
      current_dir.should match(/^tmp\/aruba$/)
    end
  end

  describe "aruba_helper fullpath('input.txt')" do

    it "should return a valid expanded path to 'input.txt'" do
      path = fullpath('input.txt')
      path.should match(/tmp..*aruba/)
      File.exists?(path).should == true
    end
  end

  describe "aruba_helper get_file_contents('input.txt')" do

    it "should return the contents of 'input.txt' as a String" do
      get_file_contents('input.txt').should == 'the quick brown fox'
    end
  end

end


text:
<?php

namespace Pagekit\Kernel\Event;

use Pagekit\Event\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

class JsonResponseListener implements EventSubscriberInterface
{
    /**
     * Transforms the body of a JSON request to POST parameters.
     */
    public function onRequest($event, $request)
    {
        if ('json' === $request->getContentType() && $data = @json_decode($request->getContent(), true)) {
            $request->request->replace($data);
        }
    }

    /**
     * Converts a array to a JSON response.
     */
    public function onController($event)
    {
        $result = $event->getControllerResult();

        if (is_array($result) || is_a($result, '\JsonSerializable')) {
            $event->setResponse(new JsonResponse($result));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function subscribe()
    {
        return [
            'request'    => ['onRequest', 130],
            'controller' => ['onController', 20]
        ];
    }
}


text:
package org.edx.mobile.http;

import android.support.annotation.NonNull;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Response;

public class UserAgentInterceptor implements Interceptor {

    @NonNull
    private final String userAgent;

    public UserAgentInterceptor(@NonNull String userAgent) {
        this.userAgent = userAgent;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        return chain.proceed(chain.request().newBuilder()
                .header("User-Agent", userAgent)
                .build());
    }
}


text:
package org.springframework.security.oauth2.server.resource.web.reactive.function.client;

import java.net.URI;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.util.context.Context;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.server.resource.authentication.AbstractOAuth2TokenAuthenticationToken;
import org.springframework.security.oauth2.server.resource.web.MockExchangeFunction;
import org.springframework.web.reactive.function.client.ClientRequest;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link ServletBearerExchangeFilterFunction}
 *
 * @author Josh Cummings
 */
@ExtendWith(MockitoExtension.class)
public class ServletBearerExchangeFilterFunctionTests {

	private ServletBearerExchangeFilterFunction function = new ServletBearerExchangeFilterFunction();

	private MockExchangeFunction exchange = new MockExchangeFunction();

	private OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token-0",
			Instant.now(), Instant.now().plus(Duration.ofDays(1)));

	private Authentication authentication = new AbstractOAuth2TokenAuthenticationToken<OAuth2AccessToken>(
			this.accessToken) {
		@Override
		public Map<String, Object> getTokenAttributes() {
			return Collections.emptyMap();
		}
	};

	@Test
	public void filterWhenUnauthenticatedThenAuthorizationHeaderNull() {
		ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
		this.function.filter(request, this.exchange).block();
		assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION)).isNull();
	}

	// gh-7353
	@Test
	public void filterWhenAuthenticatedWithOtherTokenThenAuthorizationHeaderNull() {
		TestingAuthenticationToken token = new TestingAuthenticationToken("user", "pass");
		ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
		this.function.filter(request, this.exchange).contextWrite(context(token)).block();
		assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION)).isNull();
	}

	@Test
	public void filterWhenAuthenticatedThenAuthorizationHeader() {
		ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
		this.function.filter(request, this.exchange).contextWrite(context(this.authentication)).block();
		assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION))
				.isEqualTo("Bearer " + this.accessToken.getTokenValue());
	}

	@Test
	public void filterWhenExistingAuthorizationThenSingleAuthorizationHeader() {
		ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
				.header(HttpHeaders.AUTHORIZATION, "Existing").build();
		this.function.filter(request, this.exchange).contextWrite(context(this.authentication)).block();
		HttpHeaders headers = this.exchange.getRequest().headers();
		assertThat(headers.get(HttpHeaders.AUTHORIZATION)).containsOnly("Bearer " + this.accessToken.getTokenValue());
	}

	private Context context(Authentication authentication) {
		Map<Class<?>, Object> contextAttributes = new HashMap<>();
		contextAttributes.put(Authentication.class, authentication);
		return Context.of(ServletBearerExchangeFilterFunction.SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY,
				contextAttributes);
	}

}


text:
package cc.maumau.core.rcp.screen;

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

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber.Exception;

public class FrameGrabber extends Thread {

	private final FFmpegFrameGrabber frameGrabber;
	private final List<FrameGrabberListener> listeners = new ArrayList<>();

	public FrameGrabber(int x, int y, int w, int h) {
		frameGrabber = new FFmpegFrameGrabber(":0.0+" + x + "," + y);
		frameGrabber.setFormat("x11grab");
		frameGrabber.setImageWidth(w);
		frameGrabber.setImageHeight(h);
		frameGrabber.setFrameRate(3);
		setPriority(Thread.MIN_PRIORITY);
	}

	public void addListener(FrameGrabberListener listener) {
		listeners.add(listener);
	}

	public void run() {
		try {
			frameGrabber.start();
			while (!FrameGrabber.interrupted()) {
				Frame frame = frameGrabber.grab();
				for (FrameGrabberListener listener : listeners) {
					listener.onFrame(frame);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				frameGrabber.stop();
			} catch (Exception e) {
				// Ignore exception
			}
		}
	}
}


text:
from is_rotation import is_rotation
def test_is_rotation():
    assert is_rotation("tool", "oolt")
    assert is_rotation("abcde", "cdeab")
    assert not is_rotation("the", "teh")
    assert not is_rotation("clown", "nwolc")


text:
* minimal linux distro
* good for Docker containers [gliderlabs/docker-alpine](https://github.com/gliderlabs/docker-alpine)

Build is for developing and testing what will be run in a container and building Dockerfiles.

* v3.4 `vagrant init maier/alpine-3.4-x86_64`

## Usage notes

Virtualbox Guest Additions do not build/install on v3.4 of Alpine.

* private network needs be configured as static in Vagrantfile in order to use folder sharing. If it is set to DHCP, Virtualbox will not see the address assigned to the interface, therefore, Vagrant will not be able to retrieve it to configure NFS.
* folder sharing should be configured to use NFS in Vagrantfile.
* `bash` is installed by default so `config.ssh.shell="/bin/sh"` is not necessary.
* Vagrant plugin `vagrant-alpine` developed to support Alpine specific guest.
   * `vagrant plugin install vagrant-alpine`.
   * [Github repository](https://github.com/maier/vagrant-alpine/).
   * Removed creation of fake `shutdown` command.
   * Remove installation of `nfs-utils`.
   * Remove starting `rpc.statd`.

## Build environment

```shell
⁖ packer version && vagrant -v && vboxmanage --version
Packer v0.10.1
Vagrant 1.8.1
5.0.16r105871
```


text: Practice repo for github for deelopers course


text:
import rospy
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan

def distanceArray(data):

    right_summation = 0.0
    left_summation = 0.0
    for dist in data.ranges[:271]:
        dist = min(dist, range_limit)
        right_summation = right_summation + dist

    for dist in data.ranges[271:]:
        dist = min(dist, range_limit)
        left_summation = left_summation + dist

    if right_summation > left_summation + margin:
        velocity = 1.0
    elif left_summation > right_summation + margin:
        velocity = -1.0
    else:
        velocity = 0.0

    twist_msg.angular.z = velocity
    pub.publish(twist_msg)

if __name__ == "__main__":
    machine = 'husky'
    try:
        twist_msg = Twist()
        margin = 5.0
        range_limit = 1.5

        rospy.init_node('shybot')
        message = "@%s: Node is being initiated" % (rospy.get_time())

        message = "@%s: Running readDistance Function" % (rospy.get_time())
        rospy.loginfo(message)

        pub = rospy.Publisher('/husky/cmd_vel', Twist, queue_size=1)

        message = "@%s: Running publisher" % (rospy.get_time())
        rospy.loginfo(message)
        rate = rospy.Rate(20)

        rospy.Subscriber('/scan', LaserScan, distanceArray)
        rospy.spin()

    except rospy.ROSInterruptException, e:
        print e
        message = "@%s: Feedback navigation terminated." % (rospy.get_time())
        rospy.loginfo(message)

    finally:
        message = "@%s: Node is shutting down." % (rospy.get_time())
        rospy.loginfo(message)

        pub.publish(Twist())


text:
package org.hibernate.envers.test.integration.manytomany.inverseToSuperclass;
import java.util.List;

import org.hibernate.envers.Audited;

@Audited
public class DetailSuperclass {

	private long id;

	private List<Master> masters;

	public DetailSuperclass() {

	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public List<Master> getMasters() {
		return masters;
	}

	public void setMasters(List<Master> masters) {
		this.masters = masters;
	}

}


text:
package edu.mayo.mprc.fastadb;

import edu.mayo.mprc.database.bulk.TempKey;

/**
 * @author Roman Zenka
 */
public class TempStringLoading {
	private TempKey tempKey;
	private Integer newId;

	private String data;

	public TempStringLoading() {
	}

	public TempStringLoading(final TempKey tempKey, final String data) {
		this.tempKey = tempKey;
		this.data = data;
	}

	public TempKey getTempKey() {
		return tempKey;
	}

	public void setTempKey(TempKey tempKey) {
		this.tempKey = tempKey;
	}

	public Integer getNewId() {
		return newId;
	}

	public void setNewId(Integer newId) {
		this.newId = newId;
	}

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}
}


text:
require 'spec_helper'

describe ResMan::CachedKey do
  clazz = ResMan::CachedKey

  describe 'class level' do
    it 'requires an etcd client, a key, a time to live and an optional initial value' do
      expect(clazz.instance_method(:initialize).arity).to eq(-4)
    end
  end

  describe 'instance level' do
    before(:all) do
      @client =  Etcd.client
      @keyname = '/cache_key_test/key'
      @res = clazz.new(@client, @keyname, 0.5)
    end

    after(:each) do
      @client.delete(@keyname, dir: true, recursive: true) if @client.exists?(@keyname)
    end

    it 'has a value' do
      expect(@res).to respond_to(:value)
      expect(@res).to respond_to(:value=)
    end
  end

  describe 'instance level' do
    before(:all) do
      @client =  Etcd.client
      @keyname = '/cache_key_test/key'
    end

    before(:each) do
      @res = clazz.new(@client, @keyname, 0.25)
    end

    after(:each) do
      @client.delete(@keyname) if @client.exists?(@keyname)
    end

    it 'returns nil if the key does not exist' do
      expect(@res.value).to be_nil
    end

    it 'returns the value if the key does exist' do
      @client.set(@keyname, value: 42)
      expect(@res.value.to_i).to eq(42)
    end

    it 'creates the key on write' do
      expect(@client.exists?(@keyname)).to be(false)
      @res.value = 43 # set a value so the cache gets populated.
      @client.delete(@keyname)
      @res.value = 42
      expect(@client.exists?(@keyname)).to be(true)
    end

    it 'returns the value from the cache if the value changes before the ttl is up' do
      @res.value = 42
      @client.set(@keyname, value: 43)
      expect(@res.value.to_i).to be(42)
    end

    it 'returns the actual value if the ttl is up' do
      @res.value = 42
      sleep 0.26
      @client.set(@keyname, value: 43)
      expect(@res.value.to_i).to be(43)
    end
  end
end