text:
namespace performance_monitor {
namespace util {

// Metric data can be either dense or sporadic, so AggregateMetric() normalizes
// the metric data in time. |metric_infos| must be sorted in increasing time.
// Put concisely, AggregateMetric() does sample rate conversion from irregular
// metric data points to a sample period of |resolution| beginning at |start|.
// Each sampling window starts and ends at an integer multiple away from
// |start| and data points are omitted if there are no points to resample.
std::vector<MetricInfo> AggregateMetric(
    const std::vector<MetricInfo>& metric_infos,
    const base::Time& start,
    const base::TimeDelta& resolution);

// Posts |request| to the performance monitor database's sequenced thread. On
// completion |reply| is posted to the thread that called
// PostTaskToDatabaseThreadAndReply.
bool PostTaskToDatabaseThreadAndReply(const base::Closure& request,
                                      const base::Closure& reply);

// These are a collection of methods designed to create an event to store the
// pertinent information, given all the fields. Please use these methods to
// create any PerformanceMonitor events, as this will ensure strong-typing
// guards that performance_monitor::Event() will not.
scoped_ptr<Event> CreateExtensionInstallEvent(
    const base::Time& time,
    const std::string& id,
    const std::string& name,
    const std::string& url,
    const int& location,
    const std::string& version,
    const std::string& description);

scoped_ptr<Event> CreateExtensionUnloadEvent(
    const base::Time& time,
    const std::string& id,
    const std::string& name,
    const std::string& url,
    const int& location,
    const std::string& version,
    const std::string& description,
    const extension_misc::UnloadedExtensionReason& reason);

scoped_ptr<Event> CreateExtensionUninstallEvent(
    const base::Time& time,
    const std::string& id,
    const std::string& name,
    const std::string& url,
    const int& location,
    const std::string& version,
    const std::string& description);

scoped_ptr<Event> CreateExtensionEnableEvent(
    const base::Time& time,
    const std::string& id,
    const std::string& name,
    const std::string& url,
    const int& location,
    const std::string& version,
    const std::string& description);

scoped_ptr<Event> CreateExtensionUpdateEvent(
    const base::Time& time,
    const std::string& id,
    const std::string& name,
    const std::string& url,
    const int& location,
    const std::string& version,
    const std::string& description);

scoped_ptr<Event> CreateRendererFreezeEvent(
    const base::Time& time,
    const std::string& url);

scoped_ptr<Event> CreateCrashEvent(
    const base::Time& time,
    const EventType& type);

scoped_ptr<Event> CreateUncleanShutdownEvent(const base::Time& time);

scoped_ptr<Event> CreateChromeUpdateEvent(
    const base::Time& time,
    const std::string& previous_version,
    const std::string& current_version);

}  // namespace util
}  // namespace performance_monitor

#endif  // CHROME_BROWSER_PERFORMANCE_MONITOR_UTIL_H__


text:
import socketserver
import http.server
import http.client
import email.utils
import collections
import threading
import argparse
import sqlite3
import hashlib
import random
import json
import time
import sys
import os

# O servidor. Contém o recurso raíz, e um método para encontrar recursos a
# partir daquele.
class Server(socketserver.ThreadingMixIn, http.server.HTTPServer):

    # Construtor. Cria um recurso raíz e um recurso simbolizando "não
    # encontrado".
    def __init__(self, address, port):
        socketserver.ThreadingMixIn.__init__(self)
        http.server.HTTPServer.__init__(self, (address, port), Handler)
        self.root = Resource()
        self.not_found = Resource({'code': http.client.NOT_FOUND})

    # Método para encontrar um recurso dado um identificador (URI), separado
    # por '/'. Se não encontrá-lo, devolve o recurso "não encontrado". Por
    # exemplo, para encontrar o recurso identificado por "/game/abc123",
    # procura-se o recurso "game" no recurso raíz, e nele o recurso "abc123".
    def find_resource(self, uri):
        path = uri.split('/')
        path.pop(0)

        res = self.root
        for urn in path:
            try:
                res = res.children[urn]
            except KeyError:
                return self.not_found
        return res

# Esta classe é instanciada para cada requisição feita ao servidor, e é
# responsável por ler os dados de entrada, tratá-los e enviar a resposta.
# Neste programa, cada recurso é responsável por tratar requisições feitas a si
# mesmo, então o tratamento consiste em chamar o método correspondente no
# recurso e enviar como resposta o retorno.
class Handler(http.server.BaseHTTPRequestHandler):

    # Lê e retorna o tamanho da mensagem no cabeçalho. Se não estiver nele,
    # retorna zero.
    def read_length(self):
        h = 'Content-Length'
        return int(self.headers[h]) if h in self.headers else 0

    # Obtém o timestamp da requisição. Pode estar no cabeçalho, mas se não
    # estiver, usa a menor data possível para indicar que o cliente não tem
    # nenhum dado.
    def read_timestamp(self):
        field = 'If-Modified-Since'
        if field not in self.headers:
            return time.mktime(time.gmtime(0))
        return time.mktime(email.utils.parsedate((self.headers[field])))

    # Lê o corpo da mensagem formatado como JSON e retorna um dicionário
    # correspondente. Adiciona um campo timestamp correspondente à última
    # atualização do cliente. Recursos podem ou não fazer uso dele.
    def read(self):
        length = self.read_length()
        data = {'timestamp': self.read_timestamp()}
        try:
            text = self.rfile.read(length).decode('utf-8')
            data.update(json.loads(text))
        except:
            pass
        finally:
            return data

    # Responde a requisição com um código de status, campos de cabeçalho e
    # corpo da mensagem, todos opcionais. O corpo da mensagem deve ser um
    # dicionário, a ser formatado como JSON para transmissão.
    def reply(self, args={}):
        response = {'code': http.client.OK, 'data': None, 'headers': []}
        response.update(args)

        code = response['code']
        headers = response['headers'] + [('Content-Type', 'text/json')]
        text = json.dumps(response['data'])

        try:
            self.send_response(code)

            for h in headers:
                self.send_header(h[0], h[1])
            self.end_headers()

            self.wfile.write(bytes(text, 'utf-8'))
        except:
            pass

    # Trata uma requisição GET.
    def do_GET(self):
        self.reply(self.server.find_resource(self.path).do_GET(self.read()))

    # Trata uma requisição POST.
    def do_POST(self):
        self.reply(self.server.find_resource(self.path).do_POST(self.read()))

    # Trata uma requisição PUT.
    def do_PUT(self):
        self.reply(self.server.find_resource(self.path).do_PUT(self.read()))

    # Trata uma requisição DELETE.
    def do_DELETE(self):
        self.reply(self.server.find_resource(self.path).do_DELETE(self.read()))

    # Descomentar para suprimir logging de requisições respondidas.
    #def log_message(self, format, *args):
        #return

# Classe abstrata. Cada recurso tem um dicionário de recursos filhos, mapeados
# por um nome único (URN, Universal Resource Name, exemplo: "abc123").
# A concatenação dos URNs desde um recurso raíz até outro compõe o
# identificador (URI, Universal Resource Identifier, exemplo: "/game/abc123").
# A concatenação do endereço do servidor e o URI compõe a localização (URL,
# Universal Resource Location, exemplo: "http://localhost:8000/game/abc123").
# Um recurso tem métodos que respondem a requisições HTTP. Tipicamente, uma
# requisição GET retorna os dados do recurso, POST cria um recurso filho nele,
# PUT atualiza os dados e DELETE remove o recurso.
class Resource:

    # Construtor. Define o código de retorno padrão como "método não
    # permitido". É esperado que subclasses sobrescrevam este comportamento.
    def __init__(self, default_reply={'code': http.client.METHOD_NOT_ALLOWED}):
        self.children = {}
        self.on_delete = None
        self.on_add_sibling = None
        self.default_reply = default_reply
        self.lock = threading.Lock()

    # Adiciona um recurso filho. Se não especificado o URN desejado para o
    # recurso, usa-se um aleatório. Também modifica o recurso para que seu
    # ponteiro-para-função on_delete aponte para o método delete_child deste
    # objeto (com o argumento apropriado), e on_add_sibling para add_child.
    # Assim, o recurso chamar delete fará com que este objeto o remova dos
    # recursos filhos, e chamar add_sibling fará com que este adicione um
    # recurso filho.
    def add_child(self, resource, urn=None):
        if not urn:
            urn = hashlib.md5(os.urandom(4096)).hexdigest()
        with self.lock:
            self.children[urn] = resource
        with resource.lock:
            resource.on_add_sibling = self.add_child
            resource.on_delete = lambda: self.delete_child(urn)

    # Deleta um recurso filho. Recursos filhos deste objeto adicionados com
    # add_child chamarão este método ao chamar delete.
    def delete_child(self, urn):
        with self.lock:
            if urn in self.children:
                self.children.pop(urn)

    # Chama o ponteiro-para-função on_add_sibling, setado por add_child no
    # recurso pai.
    def add_sibling(self, resource, urn=None):
        if self.on_add_sibling:
            self.on_add_sibling(resource, urn)

    # Chama o ponteiro-para-função on_delete, setado por add_child no recurso
    # pai.
    def delete(self):
        if self.on_delete:
            self.on_delete()

    # Trata uma requisição GET.
    def do_GET(self, data):
        return self.default_reply

    # Trata uma requisição POST.
    def do_POST(self, data):
        return self.default_reply

    # Trata uma requisição PUT.
    def do_PUT(self, data):
        return self.default_reply

    # Trata uma requisição DELETE.
    def do_DELETE(self, data):
        return self.default_reply

# Recurso que monitora sua data de atualização, mantendo um timestamp.
# Requisições GET de clientes que já tenham o recurso atualizado serão
# bloqueadas até que o evento sinalizando atualização seja disparado.
class Monitor(Resource):

    # Construtor. Define a última data de atualização como "agora". Cria uma
    # variável para indicar se o objeto foi modificado, para que múltiplas
    # modificações possam ser feitas antes de se disparar o evento de
    # atualização.
    def __init__(self):
        Resource.__init__(self)
        self.dirty = False
        self.timestamp = time.time()
        self.update_event = threading.Event()

    # Método abstrato que obtém os dados do recurso.
    def get_data(self):
        return None

    # Se a variável que define se o objeto foi modificado for True, atualiza o
    # timestamp e dispara o evento de atualização, desbloqueando threads que
    # estejam esperando por ele.
    def notify(self):
        with self.lock:
            if self.dirty:
                self.timestamp = time.time()
                self.update_event.set()
                self.update_event.clear()
            self.dirty = False

    # Trata uma requisição GET, bloqueando se for necessário. Após a liberação,
    # retorna os dados do recurso. É thread-safe pois acessa o timestamp dentro
    # de um bloco de exclusão mútua. get_data() deve ser thread-safe.
    def do_GET(self, data):
        with self.lock:
            timestamp = self.timestamp
        if data['timestamp'] >= self.timestamp:
            self.update_event.wait()
        return {'data': self.get_data(),
                'headers': [('Last-Modified',
                             email.utils.formatdate(self.timestamp))]}

# Um objeto monitora um conjunto de atributos.
class Object(Monitor):

    # Construtor.
    def __init__(self):
        Monitor.__init__(self)
        self.attributes = {'hp': 10, 'type': None,
                           'posx': 0, 'posy': 0,
                           'movx': 0, 'movy': 0,
                           'lookx': 1, 'looky': 1}

    # Implementado de Monitor. Uma requisição GET retorna uma cópia dos
    # atributos do objeto em formato dicionário.
    def get_data(self):
        with self.lock:
            return self.attributes.copy()

    # Computa dano ao objeto. Se chegar a 0, é deletado.
    def add_damage(self, source):
        if self is source:
            return
        with self.lock:
            self.dirty = True
            self.attributes['hp'] -= 1
            if self.attributes['hp'] < 1:
                self.delete()

    # Método que trata colisão com outro objeto. Em princípio, o objeto pára de
    # se mover.
    def collide(self, player):
        with self.lock:
            for i in ['movx', 'movy']:
                self.dirty = True
                self.attributes[i] = 0

    # Método que move o objeto. Recebe um dicionário que mapeia cada X para um
    # dicionário que mapeia para cada Y um objeto para verificar se já existem
    # objetos no destino. Se houver, chama o método de tratamento de colisão.
    # Se não houver, atualiza o dicionário.
    def move(self, occupied):
        with self.lock:
            x, y = self.attributes['posx'], self.attributes['posy']
            mx, my = self.attributes['movx'], self.attributes['movy']
            lx, ly = self.attributes['lookx'], self.attributes['looky']
        if mx == 0 and my == 0:
            return

        # Se está olhando para onde está se movendo, ganha bônus.
        x += mx + (1 if lx == mx else 0)
        y += my + (1 if ly == my else 0)

        # Tratamento de colisão.
        if x in occupied and y in occupied[x] and occupied[x][y] is not self:
            self.collide(occupied[x][y])
            occupied[x][y].collide(self)
            return

        # Movido com sucesso.
        occupied[x][y] = self
        with self.lock:
            self.dirty = True
            self.attributes['posx'] = x
            self.attributes['posy'] = y

    # Método abstrato que executa o script do objeto a partir dos outros objetos.
    def execute(self, others):
        pass

# Um objeto que não se move mas é destruível.
class Rock(Object):

    # Construtor. Recebe a posição inicial.
    def __init__(self, x, y):
        Object.__init__(self)
        self.attributes.update({'hp': 5, 'type': 'rock',
                                'posx': x, 'posy': y})

# Um jogador é um objeto com atributos adicionais.
class Player(Object):

    # Construtor. Recebe o script, e uma senha para que o cliente possa fazer
    # modificações.
    def __init__(self, name, password, script):
        Object.__init__(self)
        self.name = name
        self.password = password
        self.script = script
        self.attributes.update({'hp': 10, 'type': 'player',
                                'shots': 0, 'shooting': False, 'kills': 0})

    # Atira, criando um recurso irmão da classe Projectile. Máximo 5 tiros por
    # vez.
    def add_shot(self):
        with self.lock:
            if self.attributes['shots'] >= 5:
                return
            self.attributes['shots'] += 1
            self.dirty = True
        urn = hashlib.md5(os.urandom(4096)).hexdigest()
        self.add_sibling(Projectile(self), urn)

    # Indica que um tiro foi removido.
    def remove_shot(self):
        with self.lock:
            self.attributes['shots'] -= 1
            self.dirty = True

    # Adiciona 1 aos kills do jogador.
    def add_kill(self):
        with self.lock:
            self.dirty = True
            self.attributes['kills'] += 1

            # Banco de dados.
            try:
                c = sqlite3.connect("script_battle.db")
                cc = c.cursor()
            except:
                pass
            try:
                cc.execute('create table score (name text not null unique, kills int not null default 0, primary key (name))')
            except:
                pass
            try:
                cc.execute('insert into score (name) values (?)', (self.name,))
            except:
                pass
            try:
                cc.execute('update score set kills=kills+1 where name=?', (self.name,))
            except:
                pass
            try:
                c.commit()
                c.close()
            except:
                pass

    # Sobrescrito de Object. Se o jogador morrer, cede um kill para o jogador
    # que o matou.
    def add_damage(self, source):
        Object.add_damage(self, source)
        with self.lock:
            if self.attributes['hp'] < 1:
                source.add_kill()

    # Sobrescrito de Object. Expõe uma cópia de alguns atributos do jogador e
    # dos outros jogadores. Ao final, atualiza os dados, e atira se for
    # necessário.
    def execute(self, others):
        attributes = self.get_data()
        players = [p.get_data() for p in others]
        exec(self.script, {'attributes': attributes, 'players': players})

        # Verifica diferenças nos atributos e na cópia passada. TODO validar.
        with self.lock:
            for i in ['movx', 'movy', 'lookx', 'looky', 'shooting']:
                if self.attributes[i] != attributes[i]:
                    self.attributes[i] = attributes[i]
                    self.dirty = True

        # Verifica se o jogador está atirando.
        if attributes['shooting']:
            self.add_shot()

    # Sobrescrito de Resource. Altera o script.
    def do_PUT(self, data):
        for i in['password', 'script']:
            if i not in data:
                return {'code': http.client.EXPECTATION_FAILED}
        if data['password'] != self.password:
            return {'code': http.client.FORBIDDEN}

        with self.lock:
            self.script = data['script']

        return {'code': http.client.ACCEPTED}

    # Sobrescrito de Resource. Deleta o jogador.
    def do_DELETE(self, data):
        if 'password' not in data:
            return {'code': http.client.EXPECTATION_FAILED}
        if data['password'] != self.password:
            return {'code': http.client.FORBIDDEN}

        self.delete()

        return {'code': http.client.NO_CONTENT}

# Um projétil é um objeto que move em uma direção até colidir com outro
# jogador, ou até passar do seu alcance.
class Projectile(Object):

    # Construtor. Recebe o jogador de origem para determinar a direção de
    # movimento, e é posicionado um passo à frente para não coincidir com ele.
    def __init__(self, player):
        Object.__init__(self)
        self.player = player
        self.range = 20

        a = player.get_data()
        x, y = a['posx'], a['posy']
        lx, ly = a['lookx'], a['looky']

        self.attributes.update({'hp': 1, 'type': 'projectile',
                                'posx': x + 2 * lx, 'posy': y + 2 * ly,
                                'movx': lx, 'movy': ly})

    # Sobrescrito de Resource. Reduz a contagem de tiros no jogador de origem.
    def delete(self):
        Resource.delete(self)
        self.player.remove_shot()

    # Sobrescrito de Object. Um projétil que colide com outro objeto reduz o HP
    # daquele, e se deleta.
    def collide(self, other):
        a = other.get_data()
        other.add_damage(self.player)
        self.delete()

    # Sobrescrito de Object. Cada movimento reduz o alcance do projétil, e se
    # chegar a zero, é deletado.
    def move(self, occupied):
        Object.move(self, occupied)
        with self.lock:
            self.range -= 1
            if self.range < 1:
                self.delete()

# Monitor cujos dados são os recursos filhos. Adição ou remoção marcará este
# recurso como modificado.
class Container(Monitor):

    # Sobrescrito de Monitor. Retorna uma lista de URNs dos recursos filhos.
    def get_data(self):
        with self.lock:
            return [urn for urn in self.children]

    # Sobrescrito de Resource. Ao adicionar um recurso filho, marca este objeto
    # como modificado.
    def add_child(self, resource, urn=None):
        Resource.add_child(self, resource, urn)
        with self.lock:
            self.dirty = True

    # Sobrescrito de Resource. Ao remover um recurso filho, marca este objeto
    # como modificado.
    def delete_child(self, urn):
        Resource.delete_child(self, urn)
        with self.lock:
            self.dirty = True

# O jogo é um Container cujo recursos filhos monitorados são os jogadores.
# Ainda, a cada intervalo de tempo, chama os métodos dos jogadores que definem
# a lógica do jogo.
class Game(Container, threading.Thread):

    # Construtor. Recebe o intervalo de tempo entre cada passo do jogo.
    def __init__(self, time_step):
        threading.Thread.__init__(self)
        Container.__init__(self)
        self.time_step = time_step

    # Uma requisição POST cria um recurso filho (um jogador), validando dados
    # de entrada. Retorna uma resposta com o campo Location do cabeçalho
    # contendo a URN do jogador criado.
    def do_POST(self, data):
        for i in['name', 'password', 'script']:
            if i not in data:
                return {'code': http.client.EXPECTATION_FAILED}

        name = data['name']
        password = data['password']
        script = data['script']

        # O nome deve ser único.
        with self.lock:
            if name in self.children:
                return {'code': http.client.EXPECTATION_FAILED} # TODO outro código

        self.add_child(Player(name, password, script), name)
        return {'code': http.client.CREATED,
                'headers': [('Location', name)]}

    # Retorna um dicionário que mapeia para cada X um dicionário que mapeia,
    # para cada Y, um jogador, assim substituindo uma matriz.
    def get_occupied(self):
        d = collections.defaultdict(dict)
        with self.lock:
            d.update({p.get_data()['posx']: {p.get_data()['posy']: p}
                      for p in self.children.copy().values()})
        return d

    # Sobrescrito de Thread. Executa operações pendentes e chama o método move
    # de cada jogador, fornecendo um dicionário de posições ocupadas por outros
    # jogadores. O próprio jogador então trata colisões com outros.
    def run(self):
        while True:
            time.sleep(self.time_step)

            # Movimenta jogadores.
            with self.lock:
                players = self.children.copy().values()
            for p in players:
                p.move(self.get_occupied())

            # Executa os scripts e notifica caso hajam modificações.
            for p in players:
                p.execute(players)
                p.notify()

            # Notifica clientes caso hajam modificações.
            self.notify()
            for p in players:
                p.notify()

# Main.
if __name__ == '__main__':
    # Cria argumentos de linha de comando.
    parser = argparse.ArgumentParser(description='Servidor do jogo.',
            formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-p', '--port', type=int, default=8000,
            help='A porta para hospedar o servidor.')
    parser.add_argument('-s', '--step', type=float, default=0.1,
            help='O intervalo de tempo em segundos entre atualizações.')
    parser.add_argument('-r', '--rocks', type=int, default=20,
            help='O número de pedras no campo, assim como a distância máxima.')
    args = parser.parse_args()

    # Cria o servidor.
    server = Server('localhost', args.port)

    # Cria o jogo e adiciona pedras.
    game = Game(args.step)
    server.root.add_child(game, 'game')
    for i in range(args.rocks):
        game.add_child(Rock(random.randrange(args.rocks),
                            random.randrange(args.rocks)))

    # Inicia o jogo e o servidor.
    game.start()
    server.serve_forever()

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<title>TODO list</title>
	<link href="css/bootstrap.min.css" rel="stylesheet">
	<link href="css/bootstrap-theme.min.css" rel="stylesheet">
	<link href="css/datepicker.css" rel="stylesheet">
	<link href="css/styles.css" rel="stylesheet">

All Tasks

Done

Not Done


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

module Printf
  extend FFI::Library
  # TODO need to update the path if os get updated
  ffi_lib '/usr/lib/x86_64-linux-gnu/libstdc++.so.6'
  attach_function :says, :puts, [ :string ], :int
end

configure do
  set :port, ENV['PORT']
  set :bind, '0.0.0.0'
end

get "/" do
  begin
    Printf.says 'Hello'
  rescue
    return "FAIL"
  end

  "PASS"
end

get '/version' do
  want = params['want']
  return "FAIL: ?want must not be empty" unless want

  if RUBY_VERSION != want
    return "FAIL: RUBY_VERSION=#{RUBY_VERSION}, want #{want}"
  end

  "PASS"
end


text:
using System;

namespace HostedService
{
    public class WeatherForecast
    {
        public DateTime Date { get; set; }

        public int TemperatureC { get; set; }

        public int TemperatureF => 32 + (int) (TemperatureC / 0.5556);

        public string Summary { get; set; }
    }
}


text:
package com.jetbrains.rest.run.sphinx;

import com.intellij.execution.Location;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.junit.RuntimeConfigurationProducer;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.jetbrains.rest.RestFile;
import com.jetbrains.rest.run.RestRunConfiguration;
import com.jetbrains.rest.run.RestRunConfigurationType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

/**
 * User : catherine
 */
public class SphinxConfigurationProducer extends RuntimeConfigurationProducer implements Cloneable {
  private PsiDirectory mySourceFile = null;

  public SphinxConfigurationProducer() {
    super(RestRunConfigurationType.getInstance().SPHINX_FACTORY);
  }

  public PsiElement getSourceElement() {
    return mySourceFile;
  }

  protected RunnerAndConfigurationSettings createConfigurationByElement(final Location location, final ConfigurationContext context) {
    PsiElement element = location.getPsiElement();
    if (!(element instanceof PsiDirectory)) return null;

    mySourceFile = (PsiDirectory)element;
    boolean hasRstFile = false;
    boolean hasConf = false;
    for (PsiFile file : mySourceFile.getFiles()) {
      if ("conf.py".equals(file.getName()))
        hasConf = true;
      if (file instanceof RestFile) {
        hasRstFile = true;
      }
    }
    if (!hasRstFile || !hasConf) return null;
    final Project project = mySourceFile.getProject();
    RunnerAndConfigurationSettings settings = cloneTemplateConfiguration(project, context);
    SphinxRunConfiguration configuration = (SphinxRunConfiguration) settings.getConfiguration();
    final VirtualFile vFile = mySourceFile.getVirtualFile();
    configuration.setInputFile(vFile.getPath());

    configuration.setName(((PsiDirectory)element).getName());
    if (configuration.getTask().isEmpty())
      configuration.setTask("html");
    final VirtualFile parent = vFile.getParent();
    if (parent != null) {
      configuration.setWorkingDirectory(parent.getPath());
    }
    configuration.setName(configuration.suggestedName());
    Module module = ModuleUtil.findModuleForPsiElement(element);
    if (module != null) {
      configuration.setUseModuleSdk(true);
      configuration.setModule(module);
    }
    return settings;
  }

  @Nullable
  @Override
  protected RunnerAndConfigurationSettings findExistingByElement(Location location,
                                                                 @NotNull List<RunnerAndConfigurationSettings> existingConfigurations,
                                                                 ConfigurationContext context) {
    PsiElement element = location.getPsiElement();
    if (!(element instanceof PsiDirectory)) return null;
    final VirtualFile vFile = ((PsiDirectory)element).getVirtualFile();
    String path = vFile.getPath();
    for (RunnerAndConfigurationSettings configuration : existingConfigurations) {
      final String scriptName = ((RestRunConfiguration)configuration.getConfiguration()).getInputFile();
      if (FileUtil.toSystemIndependentName(scriptName).equals(FileUtil.toSystemIndependentName(path))) {
        return configuration;
      }
    }
    return null;
  }

  public int compareTo(final Object o) {
    return PREFERED;
  }
}


text:
/* Assert.js type declarations */

export default assert;

export enum assertionTypes {
    FAIL = 0,
    IS_TRUTHY = 1,
    IS_FALSY = 2,
    IS_EMPTY = 3,
    IS_NOT_EMPTY = 4,
    IS_DEFINED = 5,
    IS_UNDEFINED = 6,
    IS_BOOL = 7,
    IS_NOT_BOOL = 8,
    IS_NUMBER = 9,
    IS_NOT_NUMBER = 10,
    IS_FLOAT = 11,
    IS_NOT_FLOAT = 12,
    IS_NAN = 13,
    IS_NOT_NAN = 14,
    IS_STRING = 15,
    IS_NOT_STRING = 16,
    IS_ARRAY = 17,
    IS_NOT_ARRAY = 18,
    IS_FUNCTION = 19,
    IS_NOT_FUNCTION = 20,
    IS_SYMBOL = 21,
    IS_NOT_SYMBOL = 22,
    INSTANCE_OF = 23,
    NOT_INSTANCE_OF = 24,
    IS_TRUE = 25,
    IS_NOT_TRUE = 26,
    IS_FALSE = 27,
    IS_NOT_FALSE = 28,
    IS_NULL = 29,
    IS_NOT_NULL = 30,
    MATCH = 31,
}

/**
    * Property holding status of assertions activity
    * @type {boolean}
    */
export let enabled: boolean;
/**
    * Disable assertions
    */
export function disable(): void;
/**
    * Enable assertions
    */
export function enable(): void;

/**
    * Basic assertion exception class
    * It is used to be thrown when assertion failed
    * You can precise discover assertion which caused error by type or id
    * @extends Error
    */
export class AssertionException extends Error {
        protected type: assertionTypes;
        protected id: string;
        /**
            * Create AssertionException based on type, message and id
            * @param {assertionTypes} type - Assertion type
            * @param {string} message - Custom error message
            * @param {string} id - Exception id
            */
        constructor(type: assertionTypes, message: string, id: string);
        /**
            * Get type of exception
            * @returns {assertionTypes}
            */
        getType(): assertionTypes;
        /**
            * Get id of exception
            * @returns {string}
            */
        getId(): string;
}

/**
  * Always throw AssertError
  * @param message
  * @param id
  * @returns {void}
  */
export function fail(message?: string, id?: string): void;

/**
  * Assert if given value is truthy
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isTruthy(value: any, message?: string, id?: string): void;

/**
  * Assert if given value is falsy
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isFalsy(value: any, message?: string, id?: string): void;

/**
  * Assert if given value is empty
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isEmpty(value: any, message?: string, id?: string): void;

/**
  * Assert if given value is not empty
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isNotEmpty(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is defined (have type other than undefined)
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isDefined(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is undefined
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isUndefined(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is boolean
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns void
  */
export function isBool(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is not boolean
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isNotBool(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is number
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns void
  */
export function isNumber(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is not number
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns void
  */
export function isNotNumber(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is float (number with value after decimal point)
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns void
  */
export function isFloat(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is not float (number with value after decimal point)
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns void
  */
export function isNotFloat(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is Not a Number
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns void
  */
export function isNaN(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is other than Not a Number
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns void
  */
export function isNotNaN(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is string
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns void
  */
export function isString(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is not string
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns void
  */
export function isNotString(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is an array
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns void
  */
export function isArray(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is not an array
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns void
  */
export function isNotArray(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is function
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isFunction(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is not function
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isNotFunction(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is Symbol
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns void
  */
export function isSymbol(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is not an Symbol
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns void
  */
export function isNotSymbol(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is an expected instance
  * @param value
  * @param {Function} expectedInstance
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isInstanceOf(value: any, expectedInstance: Function, message?: string, id?: string): void;

/**
  * Check if provided value is not instance of excluded instance
  * @param value
  * @param {Function} excludedInstance
  * @param {string} message
  * @param {string} id
  */
export function isNotInstanceOf(value: any, excludedInstance: Function, message?: string, id?: string): void;

/**
  * Check if provided value is true
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isTrue(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is not true
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isNotTrue(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is false
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isFalse(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is not false
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isNotFalse(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is null
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isNull(value: any, message?: string, id?: string): void;

/**
  * Check if provided value is not null
  * @param value
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function isNotNull(value: any, message?: string, id?: string): void;

/**
  * Check if provided value match provided RegExp
  * @param {string} value
  * @param {RegExp} regExp
  * @param {string} message
  * @param {string} id
  * @returns {void}
  */
export function match(value: string, regExp: RegExp, message?: string, id?: string): void;


text:
from __future__ import absolute_import, division, print_function, unicode_literals

from datetime import datetime, date
from dateutil import parser

from amaascore.assets.fund import Fund

class ExchangeTradedFund(Fund):

    @staticmethod
    def pricing_method():  # Only ETF is market priced, other funds default to derived type (most likely user manually key in price)
        return 'Market'

    def __init__(self, asset_manager_id, asset_id, nav=None, expense_ratio=None, net_assets=None,
                 asset_issuer_id=None, asset_status='Active', description='', display_name='', roll_price=False,
                 country_id=None, venue_id=None, currency=None, creation_date=None, issue_date=date.min,
                 fund_type=None, comments=None, links=None, references=None,
                 *args, **kwargs):
        super(ExchangeTradedFund, self).__init__(asset_manager_id=asset_manager_id, asset_id=asset_id,
                                                 asset_issuer_id=asset_issuer_id,
                                                 asset_status=asset_status, roll_price=roll_price,
                                                 display_name=display_name, description=description,
                                                 country_id=country_id, venue_id=venue_id,
                                                 creation_date=creation_date, fund_type='ETF',
                                                 net_assets=net_assets, nav=nav, expense_ratio=expense_ratio,
                                                 currency=currency, issue_date=issue_date,
                                                 comments=comments, links=links, references=references,
                                                 *args, **kwargs)


text:
var job = null;
var bSwingRight = true;
var sCurrentLeft = "swing-left";
var sCurrentRight = "swing-right";

function swing() {

	if (bSwingRight == 0) {
		$('.tag').removeClass(sCurrentLeft);
		$('.tag').addClass(sCurrentRight);
	} else {
		$('.tag').removeClass(sCurrentRight);
		$('.tag').addClass(sCurrentLeft);
	}

	bSwingRight = !bSwingRight;

	job = setTimeout(swing, 1000);
}

$(document).ready(function() {
	swing();
});


text:
/* global process, require */

var gulp = require('gulp');
var gutil = require('gulp-util');

var connect = require('gulp-connect');

var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');

var karma = require('karma').server;
var path = require('path');

var karma = require('karma');
var karmaParseConfig = require('karma/lib/config').parseConfig;

function runKarma(configFilePath, options, cb) {

  configFilePath = path.resolve(configFilePath);

  var server = karma.server;
  var log = gutil.log;
  var colors = gutil.colors;
  var config = karmaParseConfig(configFilePath, {});

  Object.keys(options).forEach(function(key) {
    config[key] = options[key];
  });

  server.start(config, function(exitCode) {
    log('Karma has exited with ' + colors.red(exitCode));
    cb();
    process.exit(exitCode);
  });
}

gulp.task('lint', function() {
  return gulp.src([
      './lib/**/*.js',
      './test/**/*.js'
    ])
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

gulp.task('watch', function () {
  gulp.watch([
    './lib/**/*.js',
    './test/**/*.js',
    './gulpfile.js'
  ], ['lint']);
  gulp.run('test-dev');
});

gulp.task('test', function(cb) {
  runKarma('karma.conf.js', {
    autoWatch: false,
    singleRun: true,
    browsers: ['PhantomJS']
  }, cb);
});

gulp.task('test-dev', function(cb) {
  runKarma('karma.conf.js', {
    autoWatch: true,
    singleRun: false
  }, cb);
});

gulp.task('prepare-testapp', function () {
  gulp.src([
    './bower_components/**',
    './lib/**',
  ], {
    base: '.'
  }).pipe(gulp.dest('./testapp'));

  connect.server({
    root: 'testapp',
    port: 3333
  });
});

gulp.task('default', function() {
  gulp.start('lint');
});


text:
package net.clanwolf.starmap.server.beans;

import javax.persistence.EntityManager;

import io.nadron.util.Credentials;
import net.clanwolf.starmap.server.persistence.daos.jpadaoimpl.UserDAO;
import net.clanwolf.starmap.server.persistence.pojos.UserPOJO;

/**
 * @author Undertaker
 *
 */
public class UserLogin {

	public static UserPOJO login(EntityManager em, Credentials c) {
		return UserDAO.getInstance().findByCredentials(em, c);
	}
}


text:
using System.Collections.Generic;

namespace CouchMan
{
    public class ViewsHolder
    {
        public ViewsHolder()
        {
            views = new Dictionary<string, MapString>();
        }
        public Dictionary<string, MapString> views { get; set; }
    }

    public class Rootobject
    {
        public Rootobject()
        {
            rows = new List<Row>();
        }
        public List<Row> rows { get; set; }
    }

    public class Row
    {
        public Doc doc { get; set; }
        public Controllers controllers { get; set; }
    }

    public class Doc
    {
        public Meta meta { get; set; }
        public ViewsHolder json { get; set; }
    }

    public class Meta
    {
        public string id { get; set; }
        public string rev { get; set; }
    }

    public class Controllers
    {
        public string compact { get; set; }
        public string setUpdateMinChanges { get; set; }
    }
}


text:
package org.jetbrains.plugins.groovy.mvc;

import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.ModifiableModuleModel;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.StdModuleTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.impl.ModifiableModelCommitter;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.roots.libraries.LibraryUtil;
import com.intellij.openapi.roots.ui.configuration.actions.ModuleDeleteProvider;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.util.ArrayUtil;
import com.intellij.util.CommonProcessors;
import com.intellij.util.Consumer;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.java.JavaSourceRootType;
import org.jetbrains.jps.model.module.JpsModuleSourceRootType;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author peter
 */
public class MvcModuleStructureUtil {
  private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.mvc.MvcModuleStructureUtil");
  @NonNls public static final String PLUGINS_DIRECTORY = "plugins";
  @NonNls public static final String APPLICATION_PROPERTIES = "application.properties";
  public static final Key<String> LAST_MVC_VERSION = Key.create("LAST_MVC_VERSION");

  private MvcModuleStructureUtil() {
  }

  @Nullable
  public static ContentEntry findContentEntry(ModuleRootModel rootModel, VirtualFile root) {
    for (ContentEntry entry : rootModel.getContentEntries()) {
      if (Comparing.equal(entry.getFile(), root)) {
        return entry;
      }
    }

    return null;
  }

  @Nullable
  private static Consumer<ModifiableRootModel> addSourceRootsAndLibDirectory(@NotNull final VirtualFile root,
                                                                             final MvcProjectStructure structure) {
    ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(structure.myModule);

    Map<VirtualFile, JpsModuleSourceRootType<?>> sourceRoots = new HashMap<VirtualFile, JpsModuleSourceRootType<?>>();
    for (ContentEntry entry : moduleRootManager.getContentEntries()) {
      for (SourceFolder folder : entry.getSourceFolders()) {
        sourceRoots.put(folder.getFile(), folder.getRootType());
      }
    }

    root.refresh(false, true);

    final List<Consumer<ContentEntry>> actions = ContainerUtil.newArrayList();

    for (Map.Entry<JpsModuleSourceRootType<?>, Collection<String>> entry : structure.getSourceFolders().entrySet()) {
      JpsModuleSourceRootType<?> rootType = entry.getKey();

      for (String src : entry.getValue()) {
        addSourceFolder(root, src, rootType, actions, sourceRoots);
      }
    }

    for (final String src : structure.getInvalidSourceFolders()) {
      removeSrcFolderFromRoots(root.findFileByRelativePath(src), actions, sourceRoots);
    }

    for (final VirtualFile excluded : structure.getExcludedFolders(root)) {
      if (moduleRootManager.getFileIndex().isInContent(excluded)) {
        actions.add(new Consumer<ContentEntry>() {
          public void consume(ContentEntry contentEntry) {
            contentEntry.addExcludeFolder(excluded);
          }
        });
      }
    }

    final Consumer<ModifiableRootModel> modifyLib = addJarDirectory(root, structure.myModule, structure.getUserLibraryName());

    if (actions.isEmpty() && modifyLib == null && findContentEntry(moduleRootManager, root) != null) {
      return null;
    }

    return new Consumer<ModifiableRootModel>() {
      public void consume(ModifiableRootModel model) {
        ContentEntry contentEntry = findContentEntry(model, root);
        if (contentEntry == null) {
          contentEntry = model.addContentEntry(root);
        }

        for (final Consumer<ContentEntry> action : actions) {
          action.consume(contentEntry);
        }
        if (modifyLib != null) {
          modifyLib.consume(model);
        }
      }
    };
  }

  public static void removeSrcFolderFromRoots(final VirtualFile file,
                                              List<Consumer<ContentEntry>> actions,
                                              Map<VirtualFile, JpsModuleSourceRootType<?>> sourceRoots) {
    if (sourceRoots.containsKey(file)) {
      actions.add(new Consumer<ContentEntry>() {
        public void consume(ContentEntry contentEntry) {
          SourceFolder[] folders = contentEntry.getSourceFolders();
          for (SourceFolder folder : folders) {
            if (Comparing.equal(folder.getFile(), file)) {
              contentEntry.removeSourceFolder(folder);
            }
          }
        }
      });
    }
  }

  @Nullable
  public static Consumer<ModifiableRootModel> addJarDirectory(VirtualFile root, Module module, final String libName) {
    final VirtualFile libDir = root.findFileByRelativePath("lib");
    if (libDir == null || !libDir.isDirectory() || ProjectRootManager.getInstance(module.getProject()).getFileIndex().isIgnored(libDir)) {
      return null;
    }

    final Library library = findUserLibrary(module, libName);
    if (library != null && library.isJarDirectory(libDir.getUrl())) {
      return null;
    }

    return new Consumer<ModifiableRootModel>() {
      public void consume(ModifiableRootModel model) {
        Library.ModifiableModel libModel = modifyDefaultLibrary(model, libName);
        libModel.addJarDirectory(libDir, false);
        libModel.commit();
      }
    };
  }

  public static Library.ModifiableModel modifyDefaultLibrary(ModifiableRootModel model, String libName) {
    LibraryTable libTable = model.getModuleLibraryTable();

    for (Library library : libTable.getLibraries()) {
      if (library.getName() != null && library.getName().startsWith(libName)) {
        return library.getModifiableModel();
      }
    }

    Library library = LibraryUtil.createLibrary(libTable, libName + " (" + model.getModule().getName() + ')');

    for (OrderEntry entry : model.getOrderEntries()) {
      if (!(entry instanceof LibraryOrderEntry)) continue;

      LibraryOrderEntry libraryEntry = (LibraryOrderEntry)entry;
      if (libraryEntry.isModuleLevel() && libraryEntry.getLibrary() == library) {
        libraryEntry.setExported(true);
      }
    }

    return library.getModifiableModel();
  }

  private static void addSourceFolder(@NotNull VirtualFile root,
                                      @NotNull String relativePath,
                                      final JpsModuleSourceRootType<?> rootType,
                                      List<Consumer<ContentEntry>> actions,
                                      Map<VirtualFile, JpsModuleSourceRootType<?>> sourceRoots) {
    final VirtualFile src = root.findFileByRelativePath(relativePath);
    if (src == null) {
      return;
    }

    JpsModuleSourceRootType<?> existingRootType = sourceRoots.get(src);

    if (rootType == JavaSourceRootType.TEST_SOURCE && (existingRootType != null && existingRootType != JavaSourceRootType.TEST_SOURCE)) { // see http://youtrack.jetbrains.net/issue/IDEA-70642
      actions.add(new Consumer<ContentEntry>() {
        @Override
        public void consume(ContentEntry entry) {
          for (SourceFolder folder : entry.getSourceFolders()) {
            if (Comparing.equal(folder.getFile(), src)) {
              entry.removeSourceFolder(folder);
              entry.addSourceFolder(src, rootType);
              break;
            }
          }
        }
      });
      return;
    }

    actions.add(new Consumer<ContentEntry>() {
      public void consume(ContentEntry contentEntry) {
        contentEntry.addSourceFolder(src, rootType);
      }
    });
  }

  public static void updateModuleStructure(Module module, MvcProjectStructure structure, @NotNull VirtualFile root) {
    List<Consumer<ModifiableRootModel>> actions = getUpdateProjectStructureActions(Collections.singletonList(root), structure);

    if (!actions.isEmpty()) {
      final ModifiableRootModel model = ModuleRootManager.getInstance(module).getModifiableModel();
      boolean success = false;
      try {
        for (final Consumer<ModifiableRootModel> action : actions) {
          action.consume(model);
        }
        model.commit();
        success = true;
      }
      finally {
        if (!success) {
          model.dispose();
        }
      }
    }
  }

  private static boolean checkValidity(VirtualFile pluginDir) {
    pluginDir.refresh(false, false);
    return pluginDir.isValid();
  }

  private static List<Consumer<ModifiableRootModel>> getUpdateProjectStructureActions(Collection<VirtualFile> appRoots,
                                                                                MvcProjectStructure structure) {
    for (final VirtualFile appRoot : ModuleRootManager.getInstance(structure.myModule).getContentRoots()) {
      appRoot.refresh(false, false);
    }

    List<Consumer<ModifiableRootModel>> actions = ContainerUtil.newArrayList();
    removeInvalidSourceRoots(actions, structure);
    cleanupDefaultLibrary(structure.myModule, actions, appRoots, structure.getUserLibraryName());
    moveupLibrariesFromMavenPlugin(structure.myModule, actions);

    List<VirtualFile> rootsToFacetSetup = new ArrayList<VirtualFile>(appRoots.size());
    for (VirtualFile appRoot : appRoots) {
      if (checkValidity(appRoot)) {
        ContainerUtil.addIfNotNull(addSourceRootsAndLibDirectory(appRoot, structure), actions);
        rootsToFacetSetup.add(appRoot);
      }
    }

    List<Runnable> facetActions = new ArrayList<Runnable>();
    structure.setupFacets(facetActions, rootsToFacetSetup);
    for (final Runnable action : facetActions) {
      actions.add(new Consumer<ModifiableRootModel>() {
        @Override
        public void consume(ModifiableRootModel model) {
          action.run();
        }
      });
    }

    return actions;
  }

  @Nullable
  private static OrderEntry[] moveupLibrariesFromMavenPlugin(ModuleRootModel moduleRootModel) {
    LibraryOrderEntry newestLibrary = null;
    int firstLibraryIndex = 0;
    int newestLibraryIndex = 0;

    OrderEntry[] orderEntries = moduleRootModel.getOrderEntries();
    for (int i = 0; i < orderEntries.length; i++) {
      if (orderEntries[i] instanceof LibraryOrderEntry) {
        LibraryOrderEntry libraryEntry = (LibraryOrderEntry)orderEntries[i];
        String libraryName = libraryEntry.getLibraryName();
        if (libraryName != null && libraryName.contains("slf4j-api")) {
          if (newestLibrary == null) {
            newestLibrary = libraryEntry;
            firstLibraryIndex = i;
            newestLibraryIndex = i;
          }
          else {
            if (libraryName.compareTo(newestLibrary.getLibraryName()) > 0) {
              newestLibraryIndex = i;
              newestLibrary = libraryEntry;
            }
          }
        }
      }
    }

    if (firstLibraryIndex == newestLibraryIndex) return null;

    OrderEntry[] res = orderEntries.clone();
    ArrayUtil.swap(res, firstLibraryIndex, newestLibraryIndex);
    return res;
  }

  private static void moveupLibrariesFromMavenPlugin(final Module module, List<Consumer<ModifiableRootModel>> actions) {
    if (moveupLibrariesFromMavenPlugin(ModuleRootManager.getInstance(module)) != null) {
      actions.add(new Consumer<ModifiableRootModel>() {
        @Override
        public void consume(ModifiableRootModel modifiableRootModel) {
          OrderEntry[] orderEntries = moveupLibrariesFromMavenPlugin(modifiableRootModel);
          if (orderEntries != null) {
            modifiableRootModel.rearrangeOrderEntries(orderEntries);
          }
        }
      });
    }
  }

  private static void removeInvalidSourceRoots(List<Consumer<ModifiableRootModel>> actions, MvcProjectStructure structure) {
    final Set<SourceFolder> toRemove = ContainerUtil.newTroveSet();
    final Set<ContentEntry> toRemoveContent = ContainerUtil.newTroveSet();
    for (ContentEntry entry : ModuleRootManager.getInstance(structure.myModule).getContentEntries()) {
      final VirtualFile file = entry.getFile();
      if (file == null || !structure.isValidContentRoot(file)) {
        toRemoveContent.add(entry);
      }

      for (SourceFolder folder : entry.getSourceFolders()) {
        if (folder.getFile() == null) {
          toRemove.add(folder);
        }
      }
    }

    if (!toRemove.isEmpty() || !toRemoveContent.isEmpty()) {
      actions.add(new Consumer<ModifiableRootModel>() {
        public void consume(ModifiableRootModel model) {
          for (final ContentEntry entry : toRemoveContent) {
            model.removeContentEntry(entry);
          }

          for (ContentEntry entry : model.getContentEntries()) {
            for (SourceFolder folder : entry.getSourceFolders()) {
              if (toRemove.remove(folder)) {
                entry.removeSourceFolder(folder);
              }
            }
          }
        }
      });
    }
  }

  public static void cleanupDefaultLibrary(Module module,
                                           List<Consumer<ModifiableRootModel>> actions,
                                           Collection<VirtualFile> appRoots,
                                           final String libName) {
    final Library library = findUserLibrary(module, libName);
    if (library == null) {
      return;
    }

    final VirtualFileManager virtualFileManager = VirtualFileManager.getInstance();

    final List<String> toRemoveUrls = new ArrayList<String>();

    for (String url : library.getUrls(OrderRootType.CLASSES)) {
      VirtualFile virtualFile = virtualFileManager.findFileByUrl(url);

      if (virtualFile == null) {
        toRemoveUrls.add(url);
      }
      else {
        if (library.isJarDirectory(url)) {
          if (!virtualFile.getName().equals("lib") || !appRoots.contains(virtualFile.getParent())) {
            toRemoveUrls.add(url);
          }
        }
      }
    }

    if (!toRemoveUrls.isEmpty()) {
      actions.add(new Consumer<ModifiableRootModel>() {
        public void consume(ModifiableRootModel model) {
          final Library.ModifiableModel modifiableModel = modifyDefaultLibrary(model, libName);
          for (String url : toRemoveUrls) {
            modifiableModel.removeRoot(url, OrderRootType.CLASSES);
          }
          modifiableModel.commit();
        }
      });
    }
  }

  public static boolean hasModulesWithSupport(Project project, final MvcFramework framework) {
    for (Module module : ModuleManager.getInstance(project).getModules()) {
      if (framework.hasSupport(module)) {
        return true;
      }
    }

    return false;
  }

  public static List<Module> getAllModulesWithSupport(Project project, MvcFramework framework) {
    List<Module> modules = new ArrayList<Module>();
    for (Module module : ModuleManager.getInstance(project).getModules()) {
      if (framework.hasSupport(module)) {
        modules.add(module);
      }
    }
    return modules;
  }

  @Nullable
  private static Library extractNonModuleLibraries(List<Library> result,
                                                   ModuleRootManager rootManager,
                                                   boolean providedOnly,
                                                   String userLibraryName) {
    Library userLibrary = null;

    for (OrderEntry entry : rootManager.getOrderEntries()) {
      if (entry instanceof LibraryOrderEntry) {
        LibraryOrderEntry libraryEntry = (LibraryOrderEntry)entry;
        Library library = libraryEntry.getLibrary();

        if (library != null) {
          String libraryName = libraryEntry.getLibraryName();
          if (libraryName != null && libraryName.startsWith(userLibraryName)) {
            userLibrary = library;
          }
          else {
            if (library.getTable() != null && (!providedOnly || !libraryEntry.getScope().isForProductionRuntime())) {
              result.add(library);
            }
          }
        }
      }
    }

    return userLibrary;
  }

  private static Set<String> getJarUrls(@Nullable Library library) {
    if (library == null) return Collections.emptySet();

    Set<String> res = new HashSet<String>();

    for (String url : library.getUrls(OrderRootType.CLASSES)) {
      if (!library.isJarDirectory(url)) {
        res.add(url);
      }
    }

    return res;
  }

  public static void syncAuxModuleSdk(@NotNull Module appModule, @NotNull Module pluginsModule, @NotNull final MvcFramework framework) {
    final ModuleRootManager auxRootManager = ModuleRootManager.getInstance(pluginsModule);
    final ModuleRootManager appRootManager = ModuleRootManager.getInstance(appModule);

    final boolean isSdkEquals = Comparing.equal(auxRootManager.getSdk(), appRootManager.getSdk());

    List<Library> appLibraries = new ArrayList<Library>();
    Library appUserLibrary = extractNonModuleLibraries(appLibraries, appRootManager, false, framework.getUserLibraryName());

    List<Library> auxLibraries = new ArrayList<Library>();
    Library auxUserLibrary = extractNonModuleLibraries(auxLibraries, auxRootManager, false, framework.getUserLibraryName());

    final boolean isLibrariesEquals = appLibraries.equals(auxLibraries) && getJarUrls(auxUserLibrary).equals(getJarUrls(appUserLibrary));

    if (!isSdkEquals || !isLibrariesEquals) {
      AccessToken token = WriteAction.start();
      try {
        final ModifiableRootModel model = auxRootManager.getModifiableModel();

        if (!isSdkEquals) {
          copySdk(appRootManager, model);
        }

        if (!isLibrariesEquals) {
          copyUserLibraries(appRootManager, model, framework);
        }

        model.commit();
      }
      finally {
        token.finish();
      }
    }
  }

  @Nullable
  public static PropertiesFile findApplicationProperties(@NotNull Module module, MvcFramework framework) {
    VirtualFile root = framework.findAppRoot(module);
    if (root == null) return null;

    VirtualFile appChild = root.findChild(APPLICATION_PROPERTIES);
    if (appChild == null || !appChild.isValid()) return null;

    PsiManager manager = PsiManager.getInstance(module.getProject());
    PsiFile psiFile = manager.findFile(appChild);
    if (psiFile instanceof PropertiesFile) {
      return (PropertiesFile)psiFile;
    }
    return null;
  }

  public static void removeAuxiliaryModule(Module toRemove) {
    List<ModifiableRootModel> usingModels = new SmartList<ModifiableRootModel>();

    Project project = toRemove.getProject();
    ModuleManager moduleManager = ModuleManager.getInstance(project);

    for (Module module : moduleManager.getModules()) {
      if (module == toRemove) {
        continue;
      }

      ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
      for (OrderEntry entry : moduleRootManager.getOrderEntries()) {
        if (entry instanceof ModuleOrderEntry && toRemove == ((ModuleOrderEntry)entry).getModule()) {
          usingModels.add(moduleRootManager.getModifiableModel());
          break;
        }
      }
    }

    final ModifiableModuleModel moduleModel = moduleManager.getModifiableModel();

    ModuleDeleteProvider.removeModule(toRemove, null, usingModels, moduleModel);

    ModifiableRootModel[] rootModels = usingModels.toArray(new ModifiableRootModel[usingModels.size()]);
    ModifiableModelCommitter.multiCommit(rootModels, moduleModel);
  }

  @NotNull
  public static Module createAuxiliaryModule(@NotNull Module appModule, final String moduleName, final MvcFramework framework) {
    ModuleManager moduleManager = ModuleManager.getInstance(appModule.getProject());
    final ModifiableModuleModel moduleModel = moduleManager.getModifiableModel();
    final String moduleFilePath = new File(appModule.getModuleFilePath()).getParent() + "/" + moduleName + ".iml";
    final VirtualFile existing = LocalFileSystem.getInstance().findFileByPath(moduleFilePath);
    if (existing != null) {
      try {
        existing.delete("Grails/Griffon plugins maintenance");
      }
      catch (IOException e) {
        LOG.error(e);
      }
    }

    moduleModel.newModule(moduleFilePath, StdModuleTypes.JAVA.getId());
    moduleModel.commit();

    Module pluginsModule = moduleManager.findModuleByName(moduleName);
    assert pluginsModule != null;

    ModifiableRootModel newRootModel = ModuleRootManager.getInstance(pluginsModule).getModifiableModel();
    ModifiableRootModel appModel = ModuleRootManager.getInstance(appModule).getModifiableModel();

    copySdkAndLibraries(appModel, newRootModel, framework);

    newRootModel.commit();
    appModel.commit();

    return pluginsModule;
  }

  public static void ensureDependency(@NotNull Module from, @NotNull Module to, boolean exported) {
    if (!from.equals(to) && !hasDependency(from, to)) {
      ModuleRootModificationUtil.addDependency(from, to, DependencyScope.COMPILE, exported);
    }
  }

  public static boolean hasDependency(@NotNull Module from, @NotNull Module to) {
    for (OrderEntry entry : ModuleRootManager.getInstance(from).getOrderEntries()) {
      if (entry instanceof ModuleOrderEntry) {
        final ModuleOrderEntry moduleOrderEntry = (ModuleOrderEntry)entry;
        if (to == moduleOrderEntry.getModule()) {
          return true;
        }
      }
    }
    return false;
  }

  public static void removeDependency(@NotNull Module from, @NotNull Module to) {
    if (!from.equals(to) && hasDependency(from, to)) {
      final ModifiableRootModel fromModel = ModuleRootManager.getInstance(from).getModifiableModel();
      for (OrderEntry entry : fromModel.getOrderEntries()) {
        if (entry instanceof ModuleOrderEntry) {
          final ModuleOrderEntry moduleOrderEntry = (ModuleOrderEntry)entry;
          if (to == moduleOrderEntry.getModule()) {
            fromModel.removeOrderEntry(moduleOrderEntry);
          }
        }
      }
      fromModel.commit();
    }
  }

  public static void copySdk(ModuleRootModel from, ModifiableRootModel to) {
    if (from.isSdkInherited()) {
      to.inheritSdk();
    }
    else {
      to.setSdk(from.getSdk());
    }
  }

  public static void copySdkAndLibraries(ModuleRootModel from, ModifiableRootModel to, @NotNull MvcFramework framework) {
    copySdk(from, to);
    copyUserLibraries(from, to, framework);
  }

  public static void copyUserLibraries(ModuleRootModel from, ModifiableRootModel to, @NotNull MvcFramework framework) {
    Library userLibraryTo = null;

    for (OrderEntry entry : to.getOrderEntries()) {
      if (entry instanceof LibraryOrderEntry) {
        LibraryOrderEntry libraryEntry = (LibraryOrderEntry)entry;
        Library library = libraryEntry.getLibrary();

        if (library != null) {
          String libraryName = libraryEntry.getLibraryName();
          if (libraryName != null && libraryName.startsWith(framework.getUserLibraryName())) {
            userLibraryTo = library;
          }
          else {
            if (library.getTable() != null && (!libraryEntry.getScope().isForProductionRuntime() || framework.isSDKLibrary(library))) {
              to.removeOrderEntry(entry);
            }
          }
        }
      }
    }

    Library userLibraryFrom = null;

    for (OrderEntry entry : from.getOrderEntries()) {
      if (entry instanceof LibraryOrderEntry) {
        LibraryOrderEntry libraryEntry = (LibraryOrderEntry)entry;
        Library library = libraryEntry.getLibrary();

        if (library != null) {
          String libraryName = library.getName();
          if (libraryName != null && libraryName.startsWith(framework.getUserLibraryName())) {
            userLibraryFrom = library;
          }
          else {
            if (library.getTable() != null) {
              LibraryOrderEntry libraryOrderEntry = to.addLibraryEntry(library);
              libraryOrderEntry.setScope(DependencyScope.PROVIDED);
            }
          }
        }
      }
    }

    if (userLibraryTo == null) {
      if (userLibraryFrom == null) return;

      userLibraryTo = to.getModuleLibraryTable().createLibrary(framework.getUserLibraryName() + " (" + to.getModule().getName() + ')');
    }
    else {
      OrderEntry[] orderEntries = to.getOrderEntries().clone();

      for (int i = 0; i < orderEntries.length; i++) {
        OrderEntry orderEntry = orderEntries[i];
        if (orderEntry instanceof LibraryOrderEntry) {
          if (userLibraryTo == ((LibraryOrderEntry)orderEntry).getLibrary()) {
            System.arraycopy(orderEntries, i + 1, orderEntries, i, orderEntries.length - i - 1);
            orderEntries[orderEntries.length - 1] = orderEntry;
            to.rearrangeOrderEntries(orderEntries);
            break;
          }
        }
      }
    }

    Library.ModifiableModel model = userLibraryTo.getModifiableModel();
    for (String url : model.getUrls(OrderRootType.CLASSES)) {
      if (!model.isJarDirectory(url)) {
        model.removeRoot(url, OrderRootType.CLASSES);
      }
    }

    if (userLibraryFrom != null) {
      for (String url : userLibraryFrom.getUrls(OrderRootType.CLASSES)) {
        if (!userLibraryFrom.isJarDirectory(url)) {
          model.addRoot(url, OrderRootType.CLASSES);
        }
      }
    }

    model.commit();
  }

  public static Consumer<ModifiableRootModel> removeStaleContentEntries(final Collection<VirtualFile> pluginDirs) {
    return new Consumer<ModifiableRootModel>() {
      public void consume(ModifiableRootModel modifiableRootModel) {
        for (final ContentEntry entry : modifiableRootModel.getContentEntries()) {
          if (!pluginDirs.contains(entry.getFile())) {
            modifiableRootModel.removeContentEntry(entry);
          }
        }
      }
    };
  }

  public static void updateAuxModuleStructure(Module auxModule, Collection<VirtualFile> pluginDirs, MvcFramework framework) {
    final MvcProjectStructure structure = framework.createProjectStructure(auxModule, true);
    final List<Consumer<ModifiableRootModel>> actions = getUpdateProjectStructureActions(pluginDirs, structure);
    for (final ContentEntry root : ModuleRootManager.getInstance(auxModule).getContentEntries()) {
      if (!pluginDirs.contains(root.getFile())) {
        actions.add(removeStaleContentEntries(pluginDirs));
        break;
      }
    }

    if (!actions.isEmpty()) {
      actions.add(exportDefaultLibrary(structure.getUserLibraryName()));
    }

    if (!actions.isEmpty()) {
      final ModifiableRootModel model = ModuleRootManager.getInstance(auxModule).getModifiableModel();
      for (final Consumer<ModifiableRootModel> pluginsUpdateAction : actions) {
        pluginsUpdateAction.consume(model);
      }
      model.commit();
    }
  }

  public static Consumer<ModifiableRootModel> exportDefaultLibrary(final String libraryName) {
    return new Consumer<ModifiableRootModel>() {
      public void consume(ModifiableRootModel modifiableRootModel) {
        for (final OrderEntry entry : modifiableRootModel.getOrderEntries()) {
          if (entry instanceof LibraryOrderEntry) {
            final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry)entry;
            String lName = libraryOrderEntry.getLibraryName();
            if (lName != null && lName.startsWith(libraryName)) {
              libraryOrderEntry.setExported(true);
            }
          }
        }
      }
    };
  }

  private static boolean hasChildDirectory(VirtualFile file) {
    for (VirtualFile virtualFile : file.getChildren()) {
      if (virtualFile.isDirectory()) return true;
    }

    return false;
  }

  public static void updateGlobalPluginModule(@NotNull Project project, @NotNull MvcFramework framework) {
    MultiMap<VirtualFile, Module> map = new MultiMap<VirtualFile, Module>();

    for (Module module : ModuleManager.getInstance(project).getModules()) {
      if (framework.hasSupport(module)) {
        VirtualFile globalPluginsDir = refreshAndFind(framework.getGlobalPluginsDir(module));
        if (globalPluginsDir != null && hasChildDirectory(globalPluginsDir)) {
          map.putValue(globalPluginsDir, module);
        }
      }
    }

    Map<VirtualFile, Module> globalAuxModules = new HashMap<VirtualFile, Module>();

    for (Module module : ModuleManager.getInstance(project).getModules()) {
      if (framework.isGlobalPluginModule(module)) {
        VirtualFile[] contentRoots = ModuleRootManager.getInstance(module).getContentRoots();

        VirtualFile parent = null;

        if (contentRoots.length > 0) {
          parent = contentRoots[0].getParent();
          if (!map.containsKey(parent)) {
            parent = null;
          }
          else {
            for (int i = 1; i < contentRoots.length; i++) {
              if (!Comparing.equal(parent, contentRoots[i].getParent())) {
                parent = null;
                break;
              }
            }
          }
        }

        if (parent == null) {
          removeAuxiliaryModule(module);
        }
        else {
          globalAuxModules.put(parent, module);
        }
      }
    }

    for (VirtualFile virtualFile : map.keySet()) {
      if (!globalAuxModules.containsKey(virtualFile)) {
        Module appModule = map.get(virtualFile).iterator().next();
        Module module =
          createAuxiliaryModule(appModule, generateUniqueModuleName(project, framework.getGlobalPluginsModuleName()), framework);
        globalAuxModules.put(virtualFile, module);
      }
    }

    assert map.size() == globalAuxModules.size();

    for (VirtualFile virtualFile : map.keySet()) {
      List<VirtualFile> pluginRoots = new ArrayList<VirtualFile>();

      for (VirtualFile child : virtualFile.getChildren()) {
        if (child.isDirectory()) {
          pluginRoots.add(child);
        }
      }

      assert !pluginRoots.isEmpty();

      Module auxModule = globalAuxModules.get(virtualFile);

      updateAuxModuleStructure(auxModule, pluginRoots, framework);

      for (Module appModule : map.get(virtualFile)) {
        ensureDependency(appModule, auxModule, false);

        Module commonPluginsModule = framework.findCommonPluginsModule(appModule);
        if (commonPluginsModule != null) {
          ensureDependency(commonPluginsModule, auxModule, false);
        }
      }
    }
  }

  private static String generateUniqueModuleName(@NotNull Project project, String prefix) {
    ModuleManager manager = ModuleManager.getInstance(project);
    int i = 0;
    do {
      String res = i == 0 ? prefix : prefix + i;
      i++;

      if (manager.findModuleByName(res) == null) return res;
    }
    while (true);
  }

  @Nullable
  public static Module updateAuxiliaryPluginsModuleRoots(Module appModule, MvcFramework framework) {
    Module commonPluginsModule = framework.findCommonPluginsModule(appModule);

    Set<VirtualFile> pluginRoots = new HashSet<VirtualFile>();

    VirtualFile globalPluginsDir = refreshAndFind(framework.getGlobalPluginsDir(appModule));

    for (VirtualFile pluginRoot : framework.getCommonPluginRoots(appModule, true)) {
      if (checkValidity(pluginRoot)) {
        if (globalPluginsDir == null || !VfsUtil.isAncestor(globalPluginsDir, pluginRoot, true)) {
          pluginRoots.add(pluginRoot);
        }
      }
    }

    if (pluginRoots.isEmpty()) {
      if (commonPluginsModule != null) {
        removeAuxiliaryModule(commonPluginsModule);
      }
      return null;
    }

    if (commonPluginsModule == null) {
      commonPluginsModule = createAuxiliaryModule(appModule, framework.getCommonPluginsModuleName(appModule), framework);
    }

    ensureDependency(appModule, commonPluginsModule, false);
    updateAuxModuleStructure(commonPluginsModule, pluginRoots, framework);

    return commonPluginsModule;
  }

  public static Library findUserLibrary(@NotNull Module module, @NotNull final String name) {
    CommonProcessors.FindProcessor<Library> processor = new CommonProcessors.FindProcessor<Library>() {
      @Override
      protected boolean accept(Library library) {
        String libraryName = library.getName();
        return libraryName != null && libraryName.startsWith(name);
      }
    };

    OrderEnumerator.orderEntries(module).forEachLibrary(processor);

    return processor.getFoundValue();
  }

  @Nullable
  public static VirtualFile refreshAndFind(@Nullable File file) {
    return findFile(file, true);
  }

  @Nullable
  public static VirtualFile findFile(@Nullable File file, boolean refresh) {
    if (file == null) return null;

    if (refresh) {
      ApplicationManager.getApplication().assertIsDispatchThread();
      return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
    }
    else {
      return LocalFileSystem.getInstance().findFileByIoFile(file);
    }
  }

  public static boolean isEnabledStructureUpdate() {
    return !Boolean.parseBoolean(System.getProperty("grails.disable.structure.update"));
  }
}


text:
{% extends "index/base.html" %}
{% load static %}
{% block title_name %}
<title>Group List</title>
{% endblock title_name %}
{% block import_source %}

{% endblock import_source %}
{% load group_extras %}
{% block body_block %}

Group List

  {% if user.is_authenticated %}

      <button id="myGroupButton" type="button"
              class="btn btn-primary {% if include_flag = 'my_group' %} active {% endif %}">
        My Group
      </button>

      <button id="allGroupButton" type="button"
              class="btn btn-primary {% if include_flag = 'all_group' %} active {% endif %}">
        All Group
      </button>

  {% endif %}

  {% if include_flag = 'my_group' %}

      {% include "group/groupTable.html" with group_list=my_group_list %}

  {% endif %}
  {% if include_flag = 'all_group' %}

    {% include "group/groupTable.html" with group_list=all_group_list %}

  {% endif %}

{% endblock body_block %}


text:
<?xml version="1.0" encoding="utf-8"?>
<MonthlyPayments:paymentsSummary xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:MonthlyPayments="http://www.zillow.com/static/xsd/MonthlyPayments.xsd" xsi:schemaLocation="http://www.zillow.com/static/xsd/MonthlyPayments.xsd http://www.zillowstatic.com/vstatic/6b4ea3e571a1ef97dd8f1e6be94b2725/static/xsd/MonthlyPayments.xsd">
  <request>
    <price>300000</price>
    <down>15</down>
    <zip>98104</zip>
  </request>
  <message>
    <text>Request successfully processed</text>
    0
  </message>
  <response>
    <payment loanType="thirtyYearFixed">
      <rate>4.01</rate>
      <monthlyPrincipalAndInterest>1219</monthlyPrincipalAndInterest>
      <monthlyMortgageInsurance>93</monthlyMortgageInsurance>
    </payment>
    <payment loanType="fifteenYearFixed">
      <rate>3.27</rate>
      <monthlyPrincipalAndInterest>1795</monthlyPrincipalAndInterest>
      <monthlyMortgageInsurance>93</monthlyMortgageInsurance>
    </payment>
    <payment loanType="fiveOneARM">
      <rate>3.27</rate>
      <monthlyPrincipalAndInterest>1039</monthlyPrincipalAndInterest>
      <monthlyMortgageInsurance>93</monthlyMortgageInsurance>
    </payment>
    <downPayment>45000</downPayment>
    <monthlyPropertyTaxes>193</monthlyPropertyTaxes>
    <monthlyHazardInsurance>50</monthlyHazardInsurance>
  </response>
</MonthlyPayments:paymentsSummary>


text:
@class AARealNameItem, BaseResponse, NSString;

@interface AALaunchByPersonRes : WXPBGeneratedMessage
{
}

+ (void)initialize;

// Remaining properties
@property(retain, nonatomic) BaseResponse *baseResponse; // @dynamic baseResponse;
@property(retain, nonatomic) NSString *billNo; // @dynamic billNo;
@property(retain, nonatomic) NSString *msgxml; // @dynamic msgxml;
@property(nonatomic) unsigned long long payAmount; // @dynamic payAmount;
@property(retain, nonatomic) AARealNameItem *realNameInfo; // @dynamic realNameInfo;
@property(nonatomic) unsigned int retcode; // @dynamic retcode;
@property(retain, nonatomic) NSString *retmsg; // @dynamic retmsg;

@end


text:
const { request, helpers } = require('./test-env.js');
const _ = require('promdash');
const test = require('ava');

const count = 3;
const debt = { amount: 200, name: 'beer' };

let loggedUser;
let tokenHeader;

test.before(async() => {

  loggedUser = await helpers.createLoggedInUser();
  tokenHeader = loggedUser.tokenHeader;

  debt.to = (await helpers.createUser()).id;
  debt.from = await _
    .times(count, helpers.createUser)
    .concat(loggedUser)
    .map(user => user.id);

  await request.post('/debts')
    .set(...tokenHeader)
    .send(debt)
    .expect(201);
});

test('from', async t => {

  await request.get('/totals/from')
    .set(...tokenHeader)
    .expect(({ body }) => {
      t.is(body.length, 1);
      body.map(user => {
        t.is(user.fromName, loggedUser.name);
        return t.truthy(user.toName);
      });
    })
    .expect(200);

});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta name="collection" content="api">

<TITLE>
IndirectionException (Java 2 Platform SE 5.0)
</TITLE>

<META NAME="keywords" CONTENT="org.omg.CORBA.portable.IndirectionException class">
<META NAME="keywords" CONTENT="offset">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable

Class IndirectionException

java.lang.Object
  java.lang.Throwable
      java.lang.Exception
          java.lang.RuntimeException
              org.omg.CORBA.SystemException
                  org.omg.CORBA.portable.IndirectionException

All Implemented Interfaces:
Serializable

public class IndirectionException
extends SystemException

The Indirection exception is a Java specific system exception.
 It is thrown when the ORB's input stream is called to demarshal
 a value that is encoded as an indirection that is in the process
 of being demarshaled. This can occur when the ORB input stream
 calls the ValueHandler to demarshal an RMI value whose state
 contains a recursive reference to itself. Because the top-level
 ValueHandler.read_value() call has not yet returned a value,
 the ORB input stream's indirection table does not contain an entry
 for an object with the stream offset specified by the indirection
 tag. The stream offset is returned in the exception's offset field.

See Also:
InputStream,
OutputStream

Field Summary

 int
offset

          Points to the stream's offset.

Fields inherited from class org.omg.CORBA.SystemException

completed, minor

Constructor Summary

IndirectionException(int offset)

          Creates an IndirectionException with the right offset value.

Method Summary

Methods inherited from class org.omg.CORBA.SystemException

toString

Methods inherited from class java.lang.Throwable

fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

offset

public int offset

Points to the stream's offset.

Constructor Detail

IndirectionException

public IndirectionException(int offset)

Creates an IndirectionException with the right offset value.
 The stream offset is returned in the exception's offset field.
 This exception is constructed and thrown during reading
 recursively defined values off of a stream.

Parameters:
offset - the stream offset where recursion is detected.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Submit a bug or feature
For further API reference and developer documentation, see Java 2 SDK SE Developer Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 2004, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.


text:
namespace Tccc {
    export class TalkService {

        static $inject = ["apiService"];

        constructor(private apiService: ApiService) {
        }

        get(talkId: string): ng.IPromise<Talk> {
            var args = { talkId: talkId };
            var selector = (t: Server.Talk) => new Talk(t);
            return this.apiService.query("/talks/get", args, selector);
        }

        getSubmission(talkSubmissionId: string): ng.IPromise<Talk> {
            const args = {
                talkSubmissionId
            };
            return this.apiService.query("/talks/getSubmission", args);
        }

        getTalks(eventId: string): ng.IPromise<Talk[]> {
            var args = { eventId: eventId };
            var selector = (talks: Server.Talk[]) => talks.map(t => new Talk(t));
            return this.apiService.query("/talks/getTalksForEvent", args, selector);
        }

        getTalksForMostRecentEvent(): ng.IPromise<Talk[]> {
            var selector = (talks: Server.Talk[]) => talks.map(t => new Talk(t));
            return this.apiService.query("/talks/getTalksForMostRecentEvent", null, selector);
        }

        submitTalk(talk: Talk): ng.IPromise<Talk> {
            return this.apiService.post("/talks/submit", talk, dto => new Talk(dto));
        }

        updateTalk(talk: Talk): ng.IPromise<Talk> {
            return this.apiService.post("/talks/update", talk, dto => new Talk(dto));
        }

        getSubmissions(eventId: string): ng.IPromise<Talk[]> {
            var args = {
                eventId: eventId
            };
            return this.apiService.query("/talks/getSubmissions", args, (dtos: Server.Talk[]) => dtos.map(d => new Talk(d)));
        }

        getMySubmissions(): ng.IPromise<Talk[]> {
            return this.apiService.query("/talks/getMySubmissions", null, (dtos: Talk[]) => dtos.map(d => new Talk(d)));
        }

        approve(talkSubmissionId: string): ng.IPromise<Talk> {
            return this.apiService.post("/talks/approve?talkSubmissionId=" + talkSubmissionId, null, dto => new Talk(dto));
        }

        reject(talkSubmissionId: string): ng.IPromise<Talk> {
            return this.apiService.post("/talks/reject?talkSubmissionId=" + talkSubmissionId, null, dto => new Talk(dto));
        }

        searchTags(search: string): ng.IPromise<string[]> {
            const args = {
                search
            };
            return this.apiService.query("/talks/searchTags", args);
        }
    }

    App.service("talkApi", TalkService);
}


text:
/**
 * Created by jgrubb on 12/13/15.
 */

package org.jeffgrubb.myApp;

import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

public class FooConsumer extends MQBase
{
    @Override
    public void run() {
        try {
            super.run();

            Session session = super._connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            Destination destination = session.createQueue("TEST.FOO");

            MessageConsumer consumer = session.createConsumer(destination);

            Message message = consumer.receive(1000);

            if(message != null) {
                if (message instanceof TextMessage) {
                    TextMessage textMessage = (TextMessage) message;
                    String text = textMessage.getText();
                    System.out.println("Received: " + text);
                } else {
                    System.out.println("Received:" + message);
                }
            }

            consumer.close();
            session.close();
            _connection.close();

        } catch(Exception ex) {
            System.out.println("Caught exception: " + ex);
            ex.printStackTrace();
        }
    }
}


text:
require("./env");

var vows = require("vows"),
    assert = require("assert");

var suite = vows.describe("ns");

suite.addBatch({
    'dc.version': {
        topic: function () {
            return dc.version;
        },

        'should use semantic versions': function (version) {
            // from https://raw.github.com/coolaj86/semver-utils/v1.0.3/semver-utils.js
            //               |optional 'v'
            //               | | 3 segment version
            //               | |                    |optional release prefixed by '-'
            //               | |                    |                                        |optional build prefixed by '+'
            var reSemver = /^v?((\d+)\.(\d+)\.(\d+))(?:-([\dA-Za-z\-]+(?:\.[\dA-Za-z\-]+)*))?(?:\+([\dA-Za-z\-]+(?:\.[\dA-Za-z\-]+)*))?$/
            assert.match(version, reSemver);
        }
    },
    'dc.charts': {
        topic: function () {
            var chart = dc.pieChart("#id").dimension(valueDimension).group(valueGroup);
            sinon.spy(chart, "filterAll");
            sinon.spy(chart, "render");
            sinon.spy(chart, "redraw");
            return chart;
        },
        'should register chart object': function (chart) {
            assert.isTrue(dc.hasChart(chart));
        },
        'filterAll should invoke filter on each chart': function (chart) {
            dc.filterAll();
            assert.isTrue(chart.filterAll.calledOnce);
        },
        'renderAll should invoke filter on each chart': function (chart) {
            dc.renderAll();
            assert.isTrue(chart.render.calledOnce);
        },
        'should be gone after remove all': function (chart) {
            dc.deregisterAllCharts();
            assert.isFalse(dc.hasChart(chart));
        },
        teardown: function () {
            dc.deregisterAllCharts();
            resetBody();
        }
    },

    'dc.transition normal': {
        topic: function () {
            var selections = {
                transition: function () {
                    return selections;
                },
                duration: function () {
                    return selections;
                }
            };
            sinon.spy(selections, "transition");
            sinon.spy(selections, "duration");
            return selections;
        },
        'transition should be activated with duration': function (selections) {
            dc.transition(selections, 100);
            assert.isTrue(selections.transition.calledOnce);
            assert.isTrue(selections.duration.calledOnce);
        },
        'transition callback should be triggered': function (selections) {
            var triggered = false;
            dc.transition(selections, 100, function () {
                triggered = true;
            });
            assert.isTrue(triggered);
        },
        teardown: function (selections) {
            selections.transition.restore();
            selections.duration.restore();
            resetBody();
        }
    },

    'dc.transition skip': {
        topic: function () {
            var selections = {
                transition: function () {
                    return selections;
                },
                duration: function () {
                    return selections;
                }
            };
            sinon.spy(selections, "transition");
            sinon.spy(selections, "duration");
            return selections;
        },
        'transition should not be activated with 0 duration': function (selections) {
            dc.transition(selections, 0);
            assert.isFalse(selections.transition.called);
            assert.isFalse(selections.duration.called);
        },
        'transition callback should not be triggered': function (selections) {
            var triggered = false;
            dc.transition(selections, 0, function () {
                triggered = true;
            });
            assert.isFalse(triggered);
        },
        teardown: function (selections) {
            selections.transition.restore();
            selections.duration.restore();
            resetBody();
        }
    },

    'dc.units': {
        '.integers': {
            topic: function () {
                return dc.units.integers(0, 100);
            },
            'units should be based on subtraction': function (units) {
                assert.equal(units, 100);
            }
        },
        '.float': {
            topic: function () {
                return dc.units.fp.precision(0.001)(0.49999, 1.0);
            },
            'units should be generated according to the precision': function (units) {
                assert.equal(units, 501);
            }
        },
        '.ordinal': {
            topic: function () {
                return dc.units.ordinal("a", "d", ["a", "b", "c", "d"]);
            },
            'units should be based on count': function (units) {
                assert.lengthOf(units, 4);
            }
        }
    },

    'dc.round': {
        '.floor': {
            topic: function () {
                return dc.round.floor(0.33);
            },
            'should floored number': function (result) {
                assert.equal(result, 0);
            }
        }
    },

    'dc.override': {
        topic: function () {
            return {foo: function () {
                return "foo";
            }, goo: function (i) {
                return i;
            }};
        },
        'wo/ override function should work as expected': function (o) {
            assert.equal(o.foo(), "foo");
        },
        'should expose existing function': function (o) {
            dc.override(o, "foo", function () {
                return this._foo() + "2";
            });
            assert.equal(o.foo(), "foo2");
        },
        'should expose existing function with args': function (o) {
            dc.override(o, "goo", function (i) {
                return this._goo(i) + 2;
            });
            assert.equal(o.goo(1), 3);
        }
    }
});

suite.addBatch({
    'dc.charts w/ grouping': {
        topic: function () {
            var chart = dc.pieChart("#a", "groupA").dimension(valueDimension).group(valueGroup);
            sinon.spy(chart, "filterAll");
            sinon.spy(chart, "render");
            dc.pieChart("#b", "groupA").dimension(valueDimension).group(valueGroup);
            dc.bubbleChart("#c", "groupB").dimension(valueDimension).group(valueGroup);
            dc.barChart("#b1", "groupB").dimension(valueDimension).group(valueGroup);
            dc.lineChart("#b2", "groupB").dimension(valueDimension).group(valueGroup);
            dc.dataCount("#b3", "groupB").dimension(valueDimension).group(valueGroup);
            dc.dataTable("#b4", "groupB").dimension(valueDimension).group(valueGroup);
            return chart;
        },
        'should register chart object': function (chart) {
            assert.isTrue(dc.hasChart(chart));
        },
        'filterAll should not invoke filter on chart in groupA': function (chart) {
            dc.filterAll();
            assert.isFalse(chart.filterAll.calledOnce);
            chart.filterAll.reset();
        },
        'renderAll should not invoke filter on chart in groupA': function (chart) {
            dc.renderAll();
            assert.isFalse(chart.render.calledOnce);
            chart.filterAll.reset();
        },
        'filterAll by group should invoke filter on each chart within the group': function (chart) {
            dc.filterAll("groupA");
            assert.isTrue(chart.filterAll.calledOnce);
            chart.filterAll.reset();
        },
        'renderAll by group should invoke filter on each chart within the group': function (chart) {
            dc.renderAll("groupA");
            assert.isTrue(chart.render.calledOnce);
            chart.filterAll.reset();
        },
        'should be gone after remove all': function (chart) {
            dc.deregisterAllCharts();
            assert.isFalse(dc.hasChart(chart));
        },
        teardown: function () {
            dc.deregisterAllCharts();
            resetBody();
        }
    }
});

suite.addBatch({'render/redraw all call back': {
    topic: function () {
        dc.renderlet(function (group) {
            dc.__test_result.called = group ? group : true;
        });
        return dc;
    },
    'renderAll call back should be triggered': function (topic) {
        dc.__test_result = {called: false};
        dc.renderAll();
        assert.isTrue(dc.__test_result.called);
    },
    'redrawAll call back should be triggered': function (topic) {
        dc.__test_result = {called: false};
        dc.redrawAll();
        assert.isTrue(dc.__test_result.called);
    },
    'renderAll by group call back should be triggered': function (topic) {
        dc.__test_result = {called: false};
        dc.renderAll("group");
        assert.equal("group", dc.__test_result.called);
    },
    'redrawAll by group call back should be triggered': function (topic) {
        dc.__test_result = {called: false};
        dc.redrawAll("group");
        assert.equal("group", dc.__test_result.called);
    },
    teardown: function () {
        delete dc.__test_result;
        dc.renderlet(null);
    }
}});

suite.export(module);


text:
namespace viz {
class ContextProvider;

// ScopedGpuMemoryBufferTexture is a GL texture backed by a GL image and a
// GpuMemoryBuffer, so that it can be used as an overlay.
class VIZ_SERVICE_EXPORT ScopedGpuMemoryBufferTexture {
 public:
  explicit ScopedGpuMemoryBufferTexture(ContextProvider* context_provider,
                                        const gfx::Size& size,
                                        const gfx::ColorSpace& color_space);

  ScopedGpuMemoryBufferTexture();
  ~ScopedGpuMemoryBufferTexture();

  ScopedGpuMemoryBufferTexture(ScopedGpuMemoryBufferTexture&& other);
  ScopedGpuMemoryBufferTexture& operator=(ScopedGpuMemoryBufferTexture&& other);

  uint32_t id() const { return gl_id_; }
  uint32_t target() const { return target_; }
  const gfx::Size& size() const { return size_; }
  const gfx::ColorSpace& color_space() const { return color_space_; }

 private:
  void Free();

  // The ContextProvider used to free the texture when this object is destroyed,
  // so it must outlive this object.
  ContextProvider* context_provider_;
  uint32_t gl_id_;
  uint32_t target_;
  gfx::Size size_;
  gfx::ColorSpace color_space_;
};

}  // namespace viz

#endif  // COMPONENTS_VIZ_SERVICE_DISPLAY_SCOPED_GPU_MEMORY_BUFFER_TEXTURE_H_