text:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# SPDX-License-Identifier: Apache-2.0
# Copyright 2016-2020 Eotvos Lorand University, Budapest, Hungary

import argparse
from hlir16.hlir import *
from compiler_log_warnings_errors import *
import compiler_log_warnings_errors

from compiler_load_p4 import load_from_p4

from compiler_exception_handling import *
import compiler_common

import re
import os
import sys
import pkgutil

generate_code_files = True

# Inside the compiler, these variables are considered singleton.
args = []
hlir = None

def replace_insert2(insert):
    simple = re.split(r'^\$([a-zA-Z_][a-zA-Z_0-9]*)$', insert)
    if len(simple) == 3:
        return ("{}", simple[1])

    # replace $$[light][text1]{expr}{text2} inserts, where all parts except {expr} are optional
    m = re.match(r'(?P<type>\$\$?)(\[(?P<light>[^\]]+)\])?(\[(?P<text1>[^\]]+)\])?{\s*(?P<expr>[^}]*)\s*}({(?P<text2>[^}]+)})?', insert)

    light = m.group("light")
    txt1  = m.group('text1') or ''
    expr  = m.group('expr')
    txt2  = m.group('text2') or ''

    # no highlighting
    if m.group("type") == '$':
        fmt = f'{escape_brace(txt1)}{{}}{escape_brace(txt2)}'
    else:
        light_param = f",{light}" if light not in (None, "") else ""
        fmt = f'" T4LIT({escape_brace(txt1)}{{}}{escape_brace(txt2)}{light_param}) "'

    return (fmt, expr)

def replace_insert(insert):
    simple = re.split(r'^\$([a-zA-Z_][a-zA-Z_0-9]*)$', insert)
    if len(simple) == 3:
        yield (simple[1],)
        return

    # replace $$[light][text1]{expr}{text2} inserts, where all parts except {expr} are optional
    m = re.match(r'(?P<type>\$\$?)(\[(?P<light>[^\]]+)\])?(\[(?P<text1>[^\]]+)\])?{\s*(?P<expr>[^}]*)\s*}({(?P<text2>[^}]+)})?', insert)
    if not m:
        yield insert
        return

    light = m.group("light")
    txt1  = m.group('text1') or ''
    expr  = m.group('expr')
    txt2  = m.group('text2') or ''

    # no highlighting
    if m.group("type") == '$':
        yield escape_brace(txt1)
        yield (escape_brace(expr),)
        yield escape_brace(txt2)
    else:
        light_param = f",{light}" if light not in (None, "") else ""
        yield '" T4LIT("'
        yield escape_brace(txt1)
        yield (escape_brace(expr),)
        yield escape_brace(txt2)
        if light:
            yield f",{light}"
        yield ') "'

def adjust_indentation(indenter, line_idx, file):
    indent_levels = {
        "[": ( 0, True),
        "{": (+1, True),
        "}": (-1, False),
    }

    old_indent = compiler_common.file_indentation_level

    indent_change, return_old_indent = indent_levels[indenter]
    compiler_common.file_indentation_level += indent_change

    # #{ starts a new indentation level from the next line
    # also, #} unindents starting this line
    if indenter == '{' and compiler_common.file_indentation_level == 0:
        addError("Compiler", f"Too much unindent in {file}:{line_idx}")

    return old_indent if return_old_indent else compiler_common.file_indentation_level

def escape_slash(s):
    return re.sub(r'(\\|")', r'\\\1', s)

def escape_brace(s):
    return re.sub(r'(\{|\})', r'\1\1', s)

def split_and_translate(content, extra_content="", no_quote_allowed=False):
    parts = re.split(r'(\$+(?:(?:\[[^\]]*\])*(?:\{[^\}]*\})+|[a-zA-Z_][a-zA-Z_0-9]*))', content)
    return translate_line_main_content2(parts, extra_content, no_quote_allowed)

def translate_line_main_content(parts, extra_content, no_quote_allowed):
    replaceds = [repl for part in parts for repl in replace_insert(part)]
    raws = [part[0] if type(part) is tuple else part for part in replaceds]

    no_apostrophes = all("'" not in raw for raw in raws)
    no_quotes = all('"' not in raw for raw in raws)

    if no_apostrophes or no_quotes:
        quote = "'" if no_apostrophes else '"'
        has_inserts = any(type(part) is tuple for part in replaceds)

        has_bad_inserts = any(type(part) is tuple and any('(' in p for p in part) for part in replaceds)
        if has_bad_inserts:
            return translate_line_main_content2(parts, extra_content, no_quote_allowed)

        esc = escape_brace if has_inserts else (lambda p: p)
        content = "".join((f'{{{part[0]}}}' if part[0] != '' else '') + "".join(esc(p) for p in part[1:]) if type(part) is tuple else esc(part) for part in replaceds)
        formatter = 'f' if has_inserts else ''
        return False, f'{formatter}{quote}{content}{quote}'

    return translate_line_main_content2(parts, extra_content, no_quote_allowed)

def translate_line_main_content2(parts, extra_content, no_quote_allowed):
    if len(parts) == 1:
        if no_quote_allowed and '\\' not in parts[0] and '"' not in parts[0]:
            return False, parts[0]
        return True, f'"{escape_slash(parts[0])}"'

    match_with_rests = [(replace_insert2(parts[1+2*i]), parts[2+2*i]) for i in range((len(parts)-1)//2)]

    all_fmt = "".join(((re.sub(r'\{\}', '', fmt) if expr == "" else fmt) + escape_brace(txt) for (fmt, expr), txt in match_with_rests))
    all_fmt = escape_slash(f'{escape_brace(parts[0])}{all_fmt}') + extra_content
    if "'" not in all_fmt:
        quote = "'"
        all_fmt = re.sub(r'\\"', '"', all_fmt)
    else:
        quote = '"'

    all_escapes_txt = ", ".join((escape_brace(expr) or '""' for (fmt, expr), txt in match_with_rests if expr != ""))

    if all_escapes_txt == "":
        if no_quote_allowed:
            return False, f'{all_fmt}'.strip()
        return True, f'{quote}{all_fmt}{quote}'
    else:
        return True, f'{quote}{all_fmt}{quote}.format({all_escapes_txt})'

def translate_line_with_insert(file, genfile, line_idx, line):
    """Gets a line that contains an insert
       and transforms it to a Python code section."""
    _empty, indent, maybe_pre, indenter, content, _empty2 = re.split(r'^([ \t]*)#(pre|aft)?([\[\{\}])(.*)$', line)

    line_indent = adjust_indentation(indenter, line_idx, file)
    prepend_append_funname = "prepend" if maybe_pre == "pre" else "append" if maybe_pre == "aft" else ""
    prepend_append_txt = f"[{maybe_pre}]" if maybe_pre != "" else ""
    no_hint = "nohint" in args['hint']
    extra_content = f" // {prepend_append_txt} {file_prefix(file, genfile)}{line_idx}" if not no_hint and maybe_pre else ""

    _is_escaped, line = split_and_translate(content, extra_content)

    if maybe_pre:
        return f'{indent}{prepend_append_funname}_statement({line})'

    par_indent = f', indent_level = {line_indent}' if line_indent != 0 else ''
    par_lineno = f', lineno = {line_idx}' if line_idx is not None else ''
    return f'{indent}generated_code += add_code({line}{par_indent}{par_lineno})'

def increase(idx):
    if idx is None:
        return None
    return idx + 1

def add_empty_lines(code_lines):
    """Returns an enumerated list of the lines.
    When an empty line separates follows an escaped code part,
    an empty line is inserted into the generated list with None as line number."""
    new_lines = []
    is_block_with_sequence = False
    last_indent = 0
    already_added = False
    for idx, line in code_lines:
        if "#[" in line:
            is_block_with_sequence = True

        if not line.strip() and last_indent == 0 and not already_added:
            new_lines.append((idx, line))
            new_lines.append((None, "#["))
            last_indent = 0
            already_added = True
        else:
            if not line.strip():
                continue
            new_lines.append((increase(idx), line))
            last_indent = len(line) - len(line.lstrip())
            already_added = False

    return new_lines

def add_gen_in_def(code_lines, orig_file):
    """If a function's name starts with 'gen_' in a generated file,
    that function produces code.
    This is a helper function that initialises and returns the appropriate variable.
    Also, if "return" is encountered on a single line,
    the requisite return value is inserted."""
    new_lines = []
    is_inside_gen = False
    for idx, line in code_lines:
        if is_inside_gen:
            if re.match(r'^[ \t]*return[ \t]*$', line):
                line = re.sub(r'^([ \t]*)return[ \t]*$', r'\1return generated_code', line)

            is_separator_line  = re.match(r'^#[ \t]*([^ \t])\1\1*', line)
            is_method_line     = re.sub(r'[ \t]*#.*', '', line).strip() != "" and line.lstrip() == line
            is_unindented_line = re.match(r'^[^ \t]', line)
            if is_separator_line or is_method_line or is_unindented_line:
                new_lines.append((None, '    return generated_code'))
                new_lines.append((None, ''))
                is_inside_gen = False

        if line.startswith('def gen_'):
            new_lines.append((idx, line))
            new_lines.append((None, '    generated_code = ""'))
            is_inside_gen = True
            continue

        new_lines.append((idx, line))

    if is_inside_gen:
        new_lines.append((None, '    return generated_code'))
        new_lines.append((None, ''))

    return new_lines

def file_prefix(file, genfile):
    nopath = os.path.basename(file)
    noext = re.sub(r'([.](sugar|c|py))?[.][^.]*$', '', nopath)

    if "on" in args['hint']:
        # "set the default"
        args['hint'] = ['simple']

    if "nofile"  in args['hint']: return ''
    if "noext"   in args['hint']: return f'{noext}:'
    if "simple"  in args['hint']: return ':' if genfile == '?' else f'{noext}:'
    if "simpler" in args['hint']: return  '' if genfile == '?' else 'g' if noext == 'codegen' else noext
    if "nopath"  in args['hint']: return f'{nopath}:'
    return f'{file}:'

def translate_file_contents(file, genfile, code, prefix_lines="", add_lines=True, relpath=None):
    """Returns the code transformed into runnable Python code.
       Translated are #[generated_code, #=generator_expression and ${var} constructs."""
    no_hint = "nohint" in args['hint']

    new_lines = prefix_lines.splitlines()
    new_lines += """
# SPDX-License-Identifier: Apache-2.0
# Copyright 2019 Eotvos Lorand University, Budapest, Hungary

# Autogenerated file (from {0}), do not modify directly.
# Generator: T4P4S (https://github.com/P4ELTE/t4p4s/)

import compiler_common
import re

def add_code(line, indent_level = 0, lineno = None, file = "{0}"):
    global generated_code

    line_ends = {{
        "line_comment": "\\n",
        "inline_comment": "",
        "no_comment": "\\n",
        "no_comment_inline": "",
    }}

    sugar_style = compiler_common.file_sugar_style[-1]

    stripped_line = line.strip()
    no_sugar_on_line = stripped_line.startswith('//') or stripped_line.startswith('# ') or stripped_line == ""

    indent = compiler_common.file_indent_str * indent_level
    if 'inline' in compiler_common.file_sugar_style[-1]:
        indent = ''

    sugared = sugar(no_sugar_on_line, file, lineno, sugar_style)
    line_end = line_ends[sugar_style]
    return f'{{indent}}{{stripped_line}}{{sugared}}{{line_end}}'

def sugar(no_sugar_on_line, file, lineno, sugar_style):
    if {1} or no_sugar_on_line or file is None or lineno is None:
        return ""

    if sugar_style == 'line_comment':
        return f" // {{file}}{{lineno}}"
    if sugar_style == 'inline_comment':
        return f" /* {{file}}{{lineno}} */"
    return ""

generated_code += "// Autogenerated file (from {0} via {2}), do not modify directly.\\n"
generated_code += "// Generator: T4P4S (https://github.com/P4ELTE/t4p4s/)\\n"
generated_code += "\\n"

""".format(file_prefix(file, genfile), no_hint, os.path.relpath(file, relpath) if relpath is not None else file).splitlines()

    code_lines = enumerate(code.splitlines())
    code_lines = add_gen_in_def(code_lines, file)

    if add_lines:
        code_lines = add_empty_lines(code_lines)

    has_translatable_comment = re.compile(r'^([ \t]*)#(pre|aft)?([\[\{\}])(.*)$')

    for idx, code_line in code_lines:
        new_line = code_line
        if has_translatable_comment.match(code_line):
            new_line = translate_line_with_insert(file, genfile, idx, code_line)
        elif re.match(r'^[ \t]*#= .*$', code_line):
            line_regex = r'^([ \t]*)#=[ \t]*(.*)$'
            with compiler_common.SugarStyle('no_comment'):
                line_indent, line_content = re.match(line_regex, code_line).groups()
                is_escaped, code_part = split_and_translate(line_content, no_quote_allowed=True)
                if is_escaped:
                    code_part = f'eval({code_part})'

            new_line = f'{line_indent}generated_code += {code_part}'

            if args['desugar_info'] == "comment":
                # sugar_filename = os.path.basename(file)
                # sugar_filename = re.sub("([.]sugar)?[.]py", "", sugar_filename)
                sugar_filename = file
                new_line += f" ## {os.path.relpath(sugar_filename, '.')}:{idx}"

        stripped = new_line.strip()

        # won't mark empty lines and continued lines
        if stripped != "" and new_line.strip()[-1] != '\\' and idx is not None and not stripped.startswith('generated_code +='):
            # TODO idx is sometimes off by one?
            new_line += f" ## {os.path.relpath(file, '.')}:{int(idx) + 1}"

        new_lines.append(new_line)

    return '\n'.join(new_lines) + "\n"

def generate_code(file, genfile, localvars={}):
    """The file contains Python code with #[ inserts.
       The comments (which have to be indented properly)
       contain code to be output,
       their contents are collected in the variable generated_code.
       Inside the comments, refer to Python variables as ${variable_name}."""
    with open(file, "r") as orig_file:
        code = orig_file.read()
        code = translate_file_contents(file, genfile, code, relpath="src/")

        if (depth := compiler_common.file_indentation_level) != 0:
            print(f"Warning: indentation is {depth} level{'' if depth == 1 else 's'} too deep in file {file}", file=sys.stderr)
            compiler_common.file_indentation_level = 0

        if generate_code_files:
            write_file(genfile, code)

        localvars['generated_code'] = ""
        module_name = genfile

        localvars['t4p4sdir'] = os.path.relpath(os.path.join(args['generated_dir'], '..', "gen"))
        exec(compile(code, module_name, 'exec'), localvars, localvars)

        return re.sub(r'\n{3,}', '\n\n', localvars['generated_code'])

def generate_desugared_py():
    """Some Python source files also use the sugared syntax.
    The desugared files are generated here."""
    import glob
    for fromfile in glob.glob("src/utils/*.sugar.py"):
        with open(fromfile, "r") as orig_file:
            code = orig_file.read()
            prefix_lines = "generated_code = \"\"\n"

            tofile = re.sub("[.]sugar[.]py$", ".py", fromfile)
            compiler_common.current_compilation = { 'from': fromfile, 'to': tofile, 'use_real_random': args['use_real_random'], 'hlir': hlir }
            code = translate_file_contents(fromfile, tofile, code, prefix_lines=prefix_lines, add_lines=False, relpath="src/")
            compiler_common.current_compilation = None

            write_file(tofile, code)

def output_desugared_c(filename, filepath, idx):
    outfile = os.path.join(args['generated_dir'], re.sub(r'\.([ch])\.py$', r'.\1', filename))
    outpyfile = os.path.join(args['desugared_path'], filename)

    genfile = '?'
    compiler_common.current_compilation = { 'orig': filename, 'from': genfile, 'to': outfile, 'use_real_random': args['use_real_random'], 'multi': args['multi'], 'multi_idx': idx, 'skip_output': False, 'hlir': hlir }
    code = generate_code(filepath, outpyfile, {'hlir': hlir})
    is_multicompiled = 'is_multicompiled' in compiler_common.current_compilation
    skip_output = compiler_common.current_compilation['skip_output']
    compiler_common.current_compilation = None

    if not skip_output:
        if is_multicompiled:
            outfile = os.path.join(args['generated_dir'], 'multi', re.sub(r'\.([ch])\.py$', rf'_{idx}.\1', filename))

        write_file(outfile, code)

    return is_multicompiled

def generate_desugared_c(filename, filepath):
    global hlir

    genfile = os.path.join(args['desugared_path'], re.sub(r'\.([ch])\.py$', r'.\1.gen.py', filename))

    compiler_log_warnings_errors.filename = filename
    compiler_log_warnings_errors.filepath = filepath
    compiler_log_warnings_errors.genfile = genfile
    compiler_log_warnings_errors.outfile = outfile

    is_multicompiled = output_desugared_c(filename, filepath, 0)

    if is_multicompiled:
        for idx in range(1, args['multi']):
            output_desugared_c(filename, filepath, idx)

def make_dir(path, description):
    if not os.path.isdir(path):
        os.makedirs(path)
        args['verbose'] and print(f" GEN {path} ({description})")

def make_dirs(cache_dir_name):
    """Makes directories if they do not exist"""
    if not os.path.isdir(args['compiler_files_dir']):
        print("Compiler files path is missing", file=sys.stderr)
        sys.exit(1)

    make_dir(args['desugared_path'], 'desugared compiler files')
    make_dir(args['generated_dir'], 'generated files')
    make_dir(os.path.join(args['generated_dir'], 'multi'), os.path.join('generated files', 'multi'))

    if cache_dir_name and not os.path.isdir(cache_dir_name):
        os.mkdir(cache_dir_name)

def file_contains_exact_text(filename, text):
    """Returns True iff the file exists and it already contains the given text."""
    if not os.path.isfile(filename):
        return False

    with open(filename, "r") as infile:
        intext = infile.read()
        return text == intext

    return False

def write_file(filename, text):
    """Writes the given text to the given file."""

    if filename == '?':
        return

    if file_contains_exact_text(filename, text):
        return

    if filename.endswith(".gen.py"):
        args['verbose'] and print("  P4", os.path.basename(filename))

    with open(filename, "w") as genfile:
        genfile.write(text)

def get_core_count():
    try:
        import psutil
        return psutil.core_count()
    except:
        try:
            import multiprocessing
            return multiprocessing.cpu_count()
        except:
            return 1

def init_args():
    """Parses the command line arguments and loads them
    into the global variable args."""
    parser = argparse.ArgumentParser(description='T4P4S compiler')
    parser.add_argument('p4_file', help='The source file')
    parser.add_argument('-x', '--multi', help='Multiplex rate for multicompiled modules', required=True, type=int)
    parser.add_argument('-v', '--p4v', help='Use P4-14 (default is P4-16)', required=False, choices=[16, 14], type=int, default=16)
    parser.add_argument('-p', '--p4c_path', help='P4C path', required=False)
    parser.add_argument('-c', '--compiler_files_dir', help='Source directory of the compiler\'s files', required=False, default=os.path.join("src", "hardware_indep"))
    parser.add_argument('-g', '--generated_dir', help='Output directory for hardware independent files', required=True)
    parser.add_argument('-desugared_path', help='Output directory for the compiler\'s files', required=False, default=argparse.SUPPRESS)
    parser.add_argument('-desugar_info', help='Markings in the generated source code', required=False, choices=["comment", "pragma", "none"], default="comment")
    parser.add_argument('-verbose', help='Verbosity', required=False, default=False, action='store_const', const=True)
    parser.add_argument('-hint', help='Filename hint style in generated code comments', required=False, default=[], action='append')
    parser.add_argument('-recompile', help='Force recompilation: ignore cache files', required=False, default=False, action='store_const', const=True)
    parser.add_argument('-beautify', help='Beautification', required=False, default=False, action='store_const', const=True)
    parser.add_argument('-use_real_random', help='Use random values in unspecified cases', required=False, default=False, action='store_const', const=True)
    parser.add_argument('--p4dbg', help='Debugging', required=False, default=False, action='store_const', const=True)
    parser.add_argument('--p4opt', help='Debug option passed to P4-to-JSON compiler', required=False, default=[], action='append')
    parser.add_argument('--p4incdir', help='Include directory to P4-to-JSON compiler', required=False, default=[], action='append')

    args = vars(parser.parse_args())

    if 'desugared_path' not in args:
        args['desugared_path'] = os.path.relpath(os.path.join(args['generated_dir'], '..', "gen"))

    cache_dir_name = os.path.relpath(os.path.join(args['generated_dir'], '..', "cache"))

    if args['hint'] == []:
        args['hint'] = ['nohint']

    return args, cache_dir_name

def generate_files():
    bases = (args['compiler_files_dir'], os.path.join(args['compiler_files_dir'], 'multi'))
    exts = [".c.py", ".h.py"]

    generate_desugared_py()
    for base, filename in ((base, f) for base in bases for f in os.listdir(base) if os.path.isfile(os.path.join(base, f)) for ext in exts if f.endswith(ext)):
        generate_desugared_c(filename, os.path.join(base, filename))

def main():
    try:
        global args
        args, cache_dir_name = init_args()
        make_dirs(cache_dir_name)

        global hlir
        hlir = load_from_p4(args, cache_dir_name)
        generate_files()

        showErrors()
        showWarnings()
    except T4P4SHandledException:
        sys.exit(1)
    except:
        cuco = compiler_common.current_compilation
        if cuco:
            stagetxt = f"{cuco['stage']['name']}: " if 'stage' in cuco else ""
            print(f"{stagetxt}Error during the compilation of {cuco['from']} to {cuco['to']}")
        print_with_backtrace(sys.exc_info(), cuco['from'] if cuco else "(no compiler_common file)", args['p4dbg'])
        sys.exit(1)

    global errors
    if len(errors) > 0:
        sys.exit(1)

if __name__ == '__main__':
    main()


text:
from news.store import NewsDB

class NewsPipeline(object):
    def process_item(self, item, spider):
        # return item
        if spider.name != "news":  return item
        if item.get("news_thread", None) is None: return item

        spec = { "news_thread": item["news_thread"] }
        NewsDB.news.update(spec, {'$set': dict(item)}, upsert=True)
        return None

redpajama_set_name: RedPajamaGithub


text:
package Google::Ads::GoogleAds::V12::Enums::CustomConversionGoalStatusEnum;

use strict;
use warnings;

use Const::Exporter enums => [
  UNSPECIFIED => "UNSPECIFIED",
  UNKNOWN     => "UNKNOWN",
  ENABLED     => "ENABLED",
  REMOVED     => "REMOVED"
];

1;


text:
var net = require('net')
  , EventEmitter = require('events').EventEmitter;

var Client = module.exports = function() {
  this._reset();
};

Client.prototype.__proto__ = EventEmitter.prototype;

Client.prototype.connect = function(address) {
  var that = this;

  this._socket = new net.Socket();

  this._socket.setEncoding('utf8');
  this._socket.setNoDelay(true);

  this._socket.on('data', function(data) {
    var tokens = that._tokenizer(data);
    for (var i = 0, len = tokens.length; i < len; i++) {
      that._process(tokens[i]);
    }
  });
  this._socket.on('connect', function() {
    that.emit('connect');
  });
  this._socket.on('error', function(e) {
    that.emit('error', e);
  });
  this._socket.on('close', function() {
    that._reset();
    that.emit('close');
  });
  this._socket.connect(address);
};

Client.prototype.close = function() {
  this._socket.end();
};

Client.prototype.message = function(subject, data, fn) {
  var msg = {
    subject: subject,
    data: data
  }

  if (fn) {
    msg.id = this._uniqueId();
    msg.reply = true;
    this._callbacks[msg.id] = fn;
  }

  this._socket.write(JSON.stringify(msg) + '\0');
};

Client.prototype._process = function(msg) {
  var that = this;

  try {
    msg = JSON.parse(msg);
    if (!this._callbacks[msg.id]) return;

    var err = msg.err || undefined;
    var data = msg.data || undefined;

    var fn = this._callbacks[msg.id];
    delete this._callbacks[msg.id];
    fn(err, data);
  } catch (e) {
    this.emit('error', e);
  }
};

Client.prototype._reset = function() {
  for (var key in this._callbacks) {
    var fn = this._callbacks[key];
    fn(new Error('connection lost'));
  }
  this._buffer = '';
  this._nextId = 0;
  this._callbacks = {};
  this._socket = null;
};

Client.prototype._uniqueId = function() {
  return this._nextId++;
};

Client.prototype._tokenizer = function(data) {
  this._buffer += data;

  var result = this._buffer.split('\0');
  if (result.length == 1) return [];

  var last = result.pop();
  if (last === '') {
    this._buffer = '';
    return result;
  } else {
    this._buffer = last;
    return result;
  }
};


text:
package com.xthena.hr.domain;
// default package

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * HrPzRy entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name="t_hr_px_ry"
    ,catalog="xhf"
)

public class HrPzRy  implements java.io.Serializable {

    // Fields

     private Long fid;
     private String fry;
     private Long frenyuan;
     private Date fpxdate;
     private Integer fksresult;
     private Integer fksfs;
     private String fmemo;

    // Constructors

    /** default constructor */
    public HrPzRy() {
    }

    /** full constructor */
    public HrPzRy(String fry, Long frenyuan, Date fpxdate, Integer fksresult, Integer fksfs, String fmemo) {
        this.fry = fry;
        this.frenyuan = frenyuan;
        this.fpxdate = fpxdate;
        this.fksresult = fksresult;
        this.fksfs = fksfs;
        this.fmemo = fmemo;
    }

    // Property accessors
    @Id @GeneratedValue(strategy=IDENTITY)

    @Column(name="fid", unique=true, nullable=false)

    public Long getFid() {
        return this.fid;
    }

    public void setFid(Long fid) {
        this.fid = fid;
    }

    @Column(name="fry", length=64)

    public String getFry() {
        return this.fry;
    }

    public void setFry(String fry) {
        this.fry = fry;
    }

    @Column(name="frenyuan")

    public Long getFrenyuan() {
        return this.frenyuan;
    }

    public void setFrenyuan(Long frenyuan) {
        this.frenyuan = frenyuan;
    }
    @Temporal(TemporalType.DATE)
    @Column(name="fpxdate", length=10)

    public Date getFpxdate() {
        return this.fpxdate;
    }

    public void setFpxdate(Date fpxdate) {
        this.fpxdate = fpxdate;
    }

    @Column(name="fksresult")

    public Integer getFksresult() {
        return this.fksresult;
    }

    public void setFksresult(Integer fksresult) {
        this.fksresult = fksresult;
    }

    @Column(name="fksfs")

    public Integer getFksfs() {
        return this.fksfs;
    }

    public void setFksfs(Integer fksfs) {
        this.fksfs = fksfs;
    }

    @Column(name="fmemo", length=512)

    public String getFmemo() {
        return this.fmemo;
    }

    public void setFmemo(String fmemo) {
        this.fmemo = fmemo;
    }

}


text:
import firebase from 'firebase'
import 'firebase/firestore'
import app from '@firebase/app'
import auth from 'firebase/auth'
import database from 'firebase/database'

// #1
const a1: firebase.app.App = firebase.initializeApp({
  apiKey: 'apiKey',
  databaseURL: 'databaseURL',
  projectId: '42',
})

// #2
// $ExpectError
const a2: firebase.app.App = firebase.initializeApp({
  storageBucker: 'storageBucket',
  projectId: '42',
})

// #3
const a3: app.App = app('DEFAULT')

// #4
firebase
  .auth()
  .createUserWithEmailAndPassword('email', 'password')
  .then()
  .catch()

// #5
firebase.auth().onAuthStateChanged(user => {
  if (user) {
    user.displayName
    user.email
    user.emailVerified
    user.photoURL
    user.isAnonymous
    user.uid
    user.providerData
    // $ExpectError
    user.foobar
  }
})

const currentUser = firebase.auth().currentUser

if (currentUser) {
  // #6
  currentUser.linkAndRetrieveDataWithCredential({
    providerId: 'providerId',
  })
  .then(userCredential => {
    userCredential.user
    // $ExpectError
    userCredential.foobar
  })

  // #7
  const provider = new firebase.auth.GithubAuthProvider()
  currentUser.linkWithPopup(provider)
    .then(result => {
      result.credential
      result.additionalUserInfo
      result.operationType
      result.user
      // $ExpectError
      result.foobar
    })

  // #8
  const provider2 = new firebase.auth.EmailAuthProvider()
  currentUser // $ExpectError
    .linkWithPopup(provider2)
    .then(result => {
      result.credential
      result.additionalUserInfo
      result.operationType
      result.user
      // $ExpectError
      result.foobar
    })
}

const prevUser = firebase.auth().currentUser
if (prevUser) {
  // #9
  const credential = { providerId: 'providerId' }
  firebase
    .auth()
    .signInWithCredential(credential)
    .then(user =>
      user.delete().then(() => prevUser.linkWithCredential(credential)),
    )
    .then(() => firebase.auth().signInWithCredential(credential))
}

// #10
firebase
  .database()
  .ref('users/42')
  .set({ username: 'foobar' })

// #11
firebase
  .database()
  .ref('users/42')
  .on('value', snp => {
    snp.val()
  })

// #12
firebase
  .database()
  .ref('users/42') // $ExpectError
  .on('foo', snp => {
    snp.val()
  })

// #13
firebase
  .database()
  .ref('users/42')
  .orderByKey()
  .limitToLast(17)
  .once('child_added')
  .then(snp => snp.forEach(_ => true))

// #14
firebase
  .database()
  .ref('users/42')
  .orderByKey() // $ExpectError
  .limitToLast('foo')

// #15
firebase
  .storage()
  .ref()
  .child('foo')
  .child('bar')

// #17
firebase
  .storage()
  .ref('/foo')
  .getMetadata()
  .then(metadata => {
    ;(metadata.bucket: string)
    // $ExpectError
    metadata.foo
  })
  .catch()

// #18
firebase
  .storage()
  .ref('/foo')
  .put(new File(['foo'], 'foo.txt'))
  .then(snp => {
    ;(snp.bytesTransferred: number)
    // $ExpectError
    snp.foo
  })
  .catch()

// #19
firebase
  .storage()
  .ref('/foo') // $ExpectError
  .put('foobar')

// #20
const task = firebase
  .storage()
  .ref('/foo')
  .put(new File(['foo'], 'foo.txt'))
const subscribe = task.on('state_changed')
const unsubscribe = subscribe(snp => {
  ;(snp.bytesTransferred: number)
  // $ExpectError
  snp.foo
})
;(unsubscribe(): void)

// #21
firebase
  .storage()
  .ref('/foo')
  .put(new File(['foo'], 'foo.txt'))
  .on('state_changed', snp => {
    ;(snp.bytesTransferred: number)
    // $ExpectError
    snp.foo
  })()

// #22
firebase
  .storage()
  .ref('/foo')
  .put(new File(['foo'], 'foo.txt'))
  .on('state_changed', {
    next: snp => {
      ;(snp.bytesTransferred: number)
      // $ExpectError
      snp.foo
    },
  })()

// #23
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
firebase.auth().setPersistence('local')

// $ExpectError
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.FOO)
// $ExpectError
firebase.auth().setPersistence('foo')

firebase
  .firestore()
  .doc('/foo/bar')
  .get()
  .then(snapshot => {
    ;(snapshot.id: string)
    // $ExpectError
    snapshot.foo
  })
  .catch()

// #24
firebase
  .firestore()
  .doc('/foo/bar')
  .get()
  .then(snapshot => {
    ;(snapshot.id: string)
    // $ExpectError
    snapshot.foo
    // $ExpectError
    snapshot.forEach(snapshot => {})
  })
  .catch()

// #25
;(firebase.firestore().doc('/foo/bar').id: string)

// #26
// $ExpectError
firebase
  .firestore()
  .doc('/foo/bar')
  .limit(4)

// #27
firebase
  .firestore()
  .collection('/foo/bar')
  .get()
  .then(snapshots => {
    snapshots.forEach(snapshot => {
      ;(snapshot.id: string)
    })
    // $ExpectError
    snapshots.foo
  })
  .catch()

// #28
firebase
  .firestore()
  .collection('/foo')
  .limit(4)
  .endAt({ foo: 4 })
  .endBefore({ bar: 5 })
  .startAt({ foo: 1 })
  .startAfter({ bar: 2 })
  .orderBy(new firebase.firestore.FieldPath('foo', 'bar'), 'asc')
  .get()
  .then(snapshots => {
    snapshots.forEach(snapshot => {
      ;(snapshot.id: string)
    })
    // $ExpectError
    snapshots.foo
  })
  .catch()

// #29
firebase
  .firestore()
  .collection('/foo')
  .get({ source: 'cache' })

// #30
firebase
  .firestore()
  .getAll(
    firebase.firestore().doc('col/doc1'),
    firebase.firestore().doc('col/doc2'));

// #31
firebase
  .firestore()
  .collection('/foo')
  .where('id', '==', '5')
  .get({ source: 'cache' });

// #32
firebase
 .firestore()
 .collection('/foo')
 .where('id', 'array-contains', '5')
 .get({ source: 'cache' });

// #33
firebase
 .firestore()
 .collection('/foo')
 // $ExpectError
 .where('id', 'lte', '5')
 .get({ source: 'cache' });

// #34
firebase
  .firestore()
  .collection('/foo')
  .add({foo: 'bar'})
  .then(document => {
    const id = document.id
  })

// #35
firebase
  .firestore()
  .collection('/foo')
  .add({foo: 'bar'})
  .then(document => {
    // $ExpectError
    const foo = document.foo
  })

// #36
firebase
  .firestore()
  .runTransaction((transaction) => Promise.resolve({foo: 'bar'}))
  .then(object => {
    const foo = object.foo
  })


text:
package edu.stanford.math.plex4.streams.multi;

import edu.stanford.math.plex4.streams.interfaces.AbstractFilteredStream;

public interface AbstractStreamFlattener<T> {
	AbstractFilteredStream<T> collapse(AbstractMultifilteredStream<T> multifilteredStream);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  The ASF licenses this file to You
  under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License.
  You may obtain a copy of the License at

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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.  For additional information regarding
  copyright in this work, please see the NOTICE file in the top level
  directory of this distribution. -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <parent>
        <groupId>org.trianacode</groupId>
        <artifactId>triana</artifactId>
        <version>4.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>triana-gui</artifactId>
    <packaging>jar</packaging>
    <name>Triana GUI</name>
    <version>4.0.1-SNAPSHOT</version>
    <url>http://www.trianacode.org</url>

    <dependencies>
        <dependency>
            <groupId>org.trianacode</groupId>
            <artifactId>triana-core</artifactId>
            <version>${project.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.trianacode</groupId>
            <artifactId>triana-types</artifactId>
            <version>${project.version}</version>
            <scope>compile</scope>
        </dependency>
        <!--<dependency>-->
        <!--<groupId>jgraph</groupId>-->
        <!--<artifactId>jgraph</artifactId>-->
        <!--<version>5.13.0.0</version>-->
        <!--</dependency>-->
    </dependencies>

</project>


text:
@interface GDNet_ImageOfTheDayAppDelegate : NSObject <UIApplicationDelegate>
{
    UIWindow *window;
    UITabBarController *tabBarController;
    UINavigationController *imagesNavigationController;
    UINavigationController *favouritesNavigationController;
    UINavigationController *devMasterNavigationController;

@private
    NSManagedObjectContext *managedObjectContext_;
    NSManagedObjectModel *managedObjectModel_;
    NSPersistentStoreCoordinator *persistentStoreCoordinator_;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (NSString *)applicationDocumentsDirectory;

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
	<meta content="2013-12-25 10:18:47 -0700" http-equiv="change-date" />
	<title>HB 5</title>

	<link rel="stylesheet" href='../css/bpi.css' >

Hebreus 5

1Porque todo sumo sacerdote tomado dentre os homens é constituído a favor dos homens nas coisas concernentes a Deus, para que ofereça dons e sacrifícios pelos pecados,

2podendo ele compadecer-se devidamente dos ignorantes e errados, porquanto também ele mesmo está rodeado de fraqueza.

3E por esta razão deve ele, tanto pelo povo como também por si mesmo, oferecer sacrifício pelos pecados.

4Ora, ninguém toma para si esta honra, senão quando é chamado por Deus, como o foi Arão.

5assim também Cristo não se glorificou a si mesmo, para se fazer sumo sacerdote, mas o glorificou aquele que lhe disse: Tu és meu Filho, hoje te gerei;

6como também em outro lugar diz: Tu és sacerdote para sempre, segundo a ordem de Melquisedeque.

7O qual nos dias da sua carne, tendo oferecido, com grande clamor e lágrimas, orações e súplicas ao que podia livrar da morte, e tendo sido ouvido por causa da sua reverência,

8ainda que era Filho, aprendeu a obediência por meio daquilo que sofreu;

9e, tendo sido aperfeiçoado, veio a ser autor de eterna salvação para todos os que lhe obedecem,

10sendo por Deus chamado sumo sacerdote, segundo a ordem de Melquisedeque.

11Sobre isso temos muito que dizer, mas de difícil interpretação, porquanto vos tornastes tardios em ouvir.

12Porque, desde a infância sabes as sagradas letras, que podem necessitais de que se vos torne a ensinar os princípios elementares dos oráculos de Deus, e vos haveis feito tais que precisais de leite, e não de alimento sólido.

13Ora, qualquer que se alimenta de leite é inexperiente na palavra da justiça, pois é criança;

14mas o alimento sólido é para os adultos, os quais têm, pela prática, as faculdades exercitadas para discernir tanto o bem como o mal.

Almeida Revista e Atualizada© Copyright © 1993 Sociedade Bíblica do Brasil. Todos os direitos reservados. Texto bíblico utilizado com autorização. Saiba mais sobre a Sociedade Bíblica do Brasil. A Sociedade Bíblica do Brasil trabalha para que a Bíblia esteja, efetivamente, ao alcance de todos e seja lida por todos. A SBB é uma entidade sem fins lucrativos, dedicada a promover o desenvolvimento integral do ser humano.


text:
require 'spec_helper'

describe RunSqlWorkfileTask do
  # job and workfile in public workspace fixture
  let(:job) { jobs(:default) }
  let(:workfile) { workfiles(:'sql.sql') }

  describe 'assemble!' do
    let(:params) do
      {
          :action => 'run_sql_workfile',
          :workfile_id => workfile.id
      }
    end

    context 'when the workfile is in the same workspace as the job' do
      it 'creates a RunSqlWorkfileTask' do
        expect {
          JobTask.assemble!(params, job)
        }.to change(RunSqlWorkfileTask, :count).by(1)
      end

      it 'associates the task with the job' do
        expect {
          JobTask.assemble!(params, job)
        }.to change(job.job_tasks, :count).by(1)

      end

      it 'should have a reference to the workflow as payload' do
        JobTask.assemble!(params, job).reload.payload.should == workfile
      end

      context 'when the workfile is not a sql workfile' do
        let(:workfile) { FactoryGirl.create(:chorus_workfile, :file_name => 'other.not_sql', :workspace => job.workspace) }

        it 'raises' do
          expect {
            JobTask.assemble!(params, job)
          }.to raise_error(ActiveRecord::RecordNotFound)
        end
      end
    end

    context 'when the workfile is not in the same workspace as the job' do
      let(:workfile) { FactoryGirl.create(:chorus_workfile, :file_name => 'other.sql') }

      it 'raises' do
        expect {
          JobTask.assemble!(params, job)
        }.to raise_error(ActiveRecord::RecordNotFound)
      end
    end
  end

  describe '#perform' do
    let(:task) { job_tasks(:rswt) }
    let(:runner) { task.job.owner }
    let(:sql_result) { SqlResult.new }

    before do
      mock(CancelableQuery).new(is_a(DataSourceConnection), anything, runner) do
        query = Object.new
        mock(query).execute(anything, :limit => 0, :include_public_schema_in_search_path => true) {
          sql_result
        }
        query
      end
    end

    it 'executes the sql workfile' do
      task.perform
    end

    context 'when execution is successful' do
      let(:sql_result) { SqlResult.new }

      it 'returns a successful job task result' do
        result = task.perform
        result.status.should == JobTaskResult::SUCCESS
      end
    end

    context 'when execution fails' do
      let(:sql_result) { raise DataSourceConnection::QueryError.new 'query exe failure message' }

      it 'returns a failure job task result' do
        result = task.perform
        result.status.should == JobTaskResult::FAILURE
        result.message.should == 'query exe failure message'
      end
    end
  end

  describe '#derived_name' do
    let(:task) { job_tasks(:rswt) }
    it 'includes the file_name' do
      task.derived_name.should include(task.payload.file_name)
    end

    context 'when the payload has been deleted' do
      before do
        task.payload.destroy
        task.reload
      end

      it 'is [invalid]' do
        task.derived_name.should == '[invalid task]'
      end
    end
  end
end


text:
<?php

namespace AreaPhoto\AppBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\Form;
use AreaPhoto\AppBundle\Controller\MediaController;
use AreaPhoto\AppBundle\Tests\Schema;

class MediaControllerTest extends WebTestCase
{
    public function setUp()
    {
        $this->client = static::createClient();
        $this->csrf_provider = $this->client->getContainer()->get('form.csrf_provider');
        $token = $this->csrf_provider->generateCsrfToken('default');
        $this->header = ['HTTP_X-CSRF-Token' => $token];
        $this->storage = $this->client->getContainer()->get('snc_redis.default');
    }

    public function testLocationActionSuccess()
    {
        $query = ['lat' => '35.79390245637972', 'lng' => '139.80063915252686', 'distance' => '100'];
        $request = new Request($query);

        $location = $this->getLocationMock();
        $location->expects($this->once())
            ->method('getLat')
            ->will($this->returnValue('35.79390245637972'));
        $location->expects($this->once())
            ->method('getLng')
            ->will($this->returnValue('139.80063915252686'));
        $location->expects($this->once())
            ->method('getDistance')
            ->will($this->returnValue('100'));

        $form = $this->getFormMock();
        $form->expects($this->once())
            ->method('isValid')
            ->will($this->returnValue(true));

        $location_form = $this->getLocationFormMock($request, $form, $location);

        $service = $this->getMediaServiceMock();
        $media[] = Schema::media();
        $service->expects($this->once())
            ->method('execute')
            ->will($this->returnValue(json_encode($media)));

        $controller = new MediaController($location_form, $service);
        $response = $controller->getLocationAction($request);
        $data = json_decode($response->getData(), true);

        $this->assertInstanceOf('FOS\RestBundle\View\View', $response);
        $this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
        $this->assertTrue($response->getHeaders() === ['cache-control' => ['public, s-maxage=30']]);
        $this->assertTrue($data[0] === Schema::media());
    }

    public function testLocationActionValidError()
    {
        $query = ['lat' => '35.7939024563797a', 'lng' => '139.800639152526b', 'distance' => '100'];
        $crawler = $this->client->request(
            'GET',
            '/media/location',
            $query,
            [],
            $this->header
        );
        $response = $this->client->getResponse();
        $content = $response->getContent();
        $json = json_decode($content, true);
        $this->assertEquals(Response::HTTP_BAD_REQUEST, $response->getStatusCode());
        $this->assertTrue($response->headers->contains('Content-Type', 'application/json'));
        $this->assertEquals($json['message'], 'Validation Failed');
    }

    public function testLocationActionCsrfTokenValid()
    {
        $query = ['lat' => '35.79390245637970', 'lng' => '139.800639152526b', 'distance' => '100'];
        $this->header['HTTP_X-CSRF-Token'] = '0000000001';
        $crawler = $this->client->request(
            'GET',
            '/media/location',
            $query,
            [],
            $this->header
        );
        $response = $this->client->getResponse();
        $content = $response->getContent();
        $json = json_decode($content, true);
        $this->assertEquals(Response::HTTP_FORBIDDEN, $response->getStatusCode());
        $this->assertTrue($response->headers->contains('Content-Type', 'application/json'));
        $this->assertEquals($json['error']['exception'][0]['message'], 'CSRF token is invalid.');
        $this->assertEquals($json['error']['exception'][0]['class'], 'Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException');
    }

    public function testLocationActionNotFound()
    {
        $query = ['lat' => '35.79995912279198', 'lng' => '139.7947597503662', 'distance' => '100'];
        $request = new Request($query);

        $location = $this->getLocationMock();
        $location->expects($this->exactly(2))
            ->method('getLat')
            ->will($this->returnValue('35.79995912279198'));
        $location->expects($this->exactly(2))
            ->method('getLng')
            ->will($this->returnValue('139.7947597503662'));
        $location->expects($this->once())
            ->method('getDistance')
            ->will($this->returnValue('100'));

        $form = $this->getFormMock();
        $form->expects($this->once())
            ->method('isValid')
            ->will($this->returnValue(true));

        $location_form = $this->getLocationFormMock($request, $form, $location);

        $service = $this->getMediaServiceMock();
        $media = [];
        $service->expects($this->once())
            ->method('execute')
            ->will($this->returnValue($media));

        try {
            $controller = new MediaController($location_form, $service);
            $response = $controller->getLocationAction($request);
            $this->fail();
        } catch (\Exception $e) {
            $this->assertEquals(Response::HTTP_NOT_FOUND, $e->getStatusCode());
            $this->assertInstanceOf('Symfony\Component\HttpKernel\Exception\NotFoundHttpException', $e);
            $this->assertEquals($e->getMessage(), "The resource lat:'35.79995912279198' lng:'139.7947597503662' was not found.");
        }
    }

    private function getLocationMock()
    {
        $location = $this->getMockBuilder('AreaPhoto\AppBundle\Entity\Location')->disableOriginalConstructor()->getMock();

        return $location;
    }

    private function getLocationFormMock(Request $request, $form, $location)
    {
        $location_form = $this->getMockBuilder('AreaPhoto\AppBundle\Form\MediaFormInterface')->disableOriginalConstructor()->getMock();
        $location_form->expects($this->once())
            ->method('process')
            ->with($request)
            ->will($this->returnValue($form));
        $location_form->expects($this->once())
            ->method('getData')
            ->will($this->returnValue($location));

        return $location_form;
    }

    private function getFormMock()
    {
        return $this->getMockBuilder('Symfony\Component\Form\Form')->disableOriginalConstructor()->getMock();
    }

    private function getMediaServiceMock()
    {
        return $this->getMockBuilder('AreaPhoto\AppBundle\Services\Location')->disableOriginalConstructor()->getMock();
    }
}


text:
package org.hipparchus.stat.descriptive.vector;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import org.hipparchus.UnitTestUtils;
import org.hipparchus.exception.MathIllegalArgumentException;
import org.hipparchus.stat.descriptive.moment.Mean;
import org.junit.Test;

public class VectorialStorelessStatisticTest {
    private double[][] points;

    public VectorialStorelessStatisticTest() {
        points = new double[][] {
            { 1.2, 2.3,  4.5},
            {-0.7, 2.3,  5.0},
            { 3.1, 0.0, -3.1},
            { 6.0, 1.2,  4.2},
            {-0.7, 2.3,  5.0}
        };
    }

    protected VectorialStorelessStatistic createStatistic(int dimension) {
        return new VectorialStorelessStatistic(dimension, new Mean());
    }

    @Test
    public void testMismatch() {
        try {
            createStatistic(8).increment(new double[5]);
            fail("an exception should have been thrown");
        } catch (MathIllegalArgumentException dme) {
            assertEquals(5, ((Integer) dme.getParts()[0]).intValue());
            assertEquals(8, ((Integer) dme.getParts()[1]).intValue());
        }
    }

    @Test
    public void testSimplistic() {
        VectorialStorelessStatistic stat = createStatistic(2);
        stat.increment(new double[] {-1.0,  1.0});
        stat.increment(new double[] { 1.0, -1.0});
        double[] mean = stat.getResult();
        assertEquals(0.0, mean[0], 1.0e-12);
        assertEquals(0.0, mean[1], 1.0e-12);
    }

    @Test
    public void testBasicStats() {

        VectorialStorelessStatistic stat = createStatistic(points[0].length);
        for (int i = 0; i < points.length; ++i) {
            stat.increment(points[i]);
        }

        assertEquals(points.length, stat.getN());

        double[] mean = stat.getResult();
        double[]   refMean = new double[] { 1.78, 1.62,  3.12};

        for (int i = 0; i < mean.length; ++i) {
            assertEquals(refMean[i], mean[i], 1.0e-12);
        }
    }

    @Test
    public void testSerial() {
        VectorialStorelessStatistic stat = createStatistic(points[0].length);
        for (int i = 0; i < points.length; ++i) {
            stat.increment(points[i]);
        }
        assertEquals(stat, UnitTestUtils.serializeAndRecover(stat));
    }
}


text:
import exec from '../../exec.js';

export const run = async () => {
    try {
        await exec('service proftpd status', {}, null, {
            SYSTEMD_PAGER: ''
        });
        return 'Service is running';
    } catch (e) {
        throw new Error('Service is unavailable');
    }
};


text:
"""Binary to run Stable Baselines 3 agents on meltingpot substrates."""

import gym
import stable_baselines3
from stable_baselines3.common import callbacks
from stable_baselines3.common import torch_layers
from stable_baselines3.common import vec_env
import supersuit as ss
import torch
from torch import nn
import torch.nn.functional as F

from examples.pettingzoo import utils
from meltingpot.python import substrate

device = torch.device("cuda") if torch.cuda.is_available() else torch.device(
    "cpu")

# Use this with lambda wrapper returning observations only
class CustomCNN(torch_layers.BaseFeaturesExtractor):
  """Class describing a custom feature extractor."""

  def __init__(
      self,
      observation_space: gym.spaces.Box,
      features_dim=128,
      num_frames=6,
      fcnet_hiddens=(1024, 128),
  ):
    """Construct a custom CNN feature extractor.

    Args:
      observation_space: the observation space as a gym.Space
      features_dim: Number of features extracted. This corresponds to the number
        of unit for the last layer.
      num_frames: The number of (consecutive) frames to feed into the network.
      fcnet_hiddens: Sizes of hidden layers.
    """
    super(CustomCNN, self).__init__(observation_space, features_dim)
    # We assume CxHxW images (channels first)
    # Re-ordering will be done by pre-preprocessing or wrapper

    self.conv = nn.Sequential(
        nn.Conv2d(
            num_frames * 3, num_frames * 3, kernel_size=8, stride=4, padding=0),
        nn.ReLU(),  # 18 * 21 * 21
        nn.Conv2d(
            num_frames * 3, num_frames * 6, kernel_size=5, stride=2, padding=0),
        nn.ReLU(),  # 36 * 9 * 9
        nn.Conv2d(
            num_frames * 6, num_frames * 6, kernel_size=3, stride=1, padding=0),
        nn.ReLU(),  # 36 * 7 * 7
        nn.Flatten(),
    )
    flat_out = num_frames * 6 * 7 * 7
    self.fc1 = nn.Linear(in_features=flat_out, out_features=fcnet_hiddens[0])
    self.fc2 = nn.Linear(
        in_features=fcnet_hiddens[0], out_features=fcnet_hiddens[1])

  def forward(self, observations) -> torch.Tensor:
    # Convert to tensor, rescale to [0, 1], and convert from
    #   B x H x W x C to B x C x H x W
    observations = observations.permute(0, 3, 1, 2)
    features = self.conv(observations)
    features = F.relu(self.fc1(features))
    features = F.relu(self.fc2(features))
    return features

def main():
  # Config
  env_name = "commons_harvest_open"
  env_config = substrate.get_config(env_name)
  env = utils.parallel_env(env_config)
  rollout_len = 1000
  total_timesteps = 2000000
  num_agents = env.max_num_agents

  # Training
  num_cpus = 1  # number of cpus
  num_envs = 1  # number of parallel multi-agent environments
  # number of frames to stack together; use >4 to avoid automatic
  # VecTransposeImage
  num_frames = 4
  # output layer of cnn extractor AND shared layer for policy and value
  # functions
  features_dim = 128
  fcnet_hiddens = [1024, 128]  # Two hidden layers for cnn extractor
  ent_coef = 0.001  # entropy coefficient in loss
  batch_size = (rollout_len * num_envs // 2
               )  # This is from the rllib baseline implementation
  lr = 0.0001
  n_epochs = 30
  gae_lambda = 1.0
  gamma = 0.99
  target_kl = 0.01
  grad_clip = 40
  verbose = 3
  model_path = None  # Replace this with a saved model

  env = utils.parallel_env(
      max_cycles=rollout_len,
      env_config=env_config,
  )
  env = ss.observation_lambda_v0(env, lambda x, _: x["RGB"], lambda s: s["RGB"])
  env = ss.frame_stack_v1(env, num_frames)
  env = ss.pettingzoo_env_to_vec_env_v1(env)
  env = ss.concat_vec_envs_v1(
      env,
      num_vec_envs=num_envs,
      num_cpus=num_cpus,
      base_class="stable_baselines3")
  env = vec_env.VecMonitor(env)
  env = vec_env.VecTransposeImage(env, True)

  eval_env = utils.parallel_env(
      max_cycles=rollout_len,
      env_config=env_config,
  )
  eval_env = ss.observation_lambda_v0(eval_env, lambda x, _: x["RGB"],
                                      lambda s: s["RGB"])
  eval_env = ss.frame_stack_v1(eval_env, num_frames)
  eval_env = ss.pettingzoo_env_to_vec_env_v1(eval_env)
  eval_env = ss.concat_vec_envs_v1(
      eval_env, num_vec_envs=1, num_cpus=1, base_class="stable_baselines3")
  eval_env = vec_env.VecMonitor(eval_env)
  eval_env = vec_env.VecTransposeImage(eval_env, True)
  eval_freq = 100000 // (num_envs * num_agents)

  policy_kwargs = dict(
      features_extractor_class=CustomCNN,
      features_extractor_kwargs=dict(
          features_dim=features_dim,
          num_frames=num_frames,
          fcnet_hiddens=fcnet_hiddens,
      ),
      net_arch=[features_dim],
  )

  tensorboard_log = "./results/sb3/harvest_open_ppo_paramsharing"

  model = stable_baselines3.PPO(
      "CnnPolicy",
      env=env,
      learning_rate=lr,
      n_steps=rollout_len,
      batch_size=batch_size,
      n_epochs=n_epochs,
      gamma=gamma,
      gae_lambda=gae_lambda,
      ent_coef=ent_coef,
      max_grad_norm=grad_clip,
      target_kl=target_kl,
      policy_kwargs=policy_kwargs,
      tensorboard_log=tensorboard_log,
      verbose=verbose,
  )
  if model_path is not None:
    model = stable_baselines3.PPO.load(model_path, env=env)
  eval_callback = callbacks.EvalCallback(
      eval_env, eval_freq=eval_freq, best_model_save_path=tensorboard_log)
  model.learn(total_timesteps=total_timesteps, callback=eval_callback)

  logdir = model.logger.dir
  model.save(logdir + "/model")
  del model
  model = stable_baselines3.PPO.load(logdir + "/model")  # noqa: F841

if __name__ == "__main__":
  main()


text:
from django.apps import apps
from django.conf import settings
from taiga.base.utils.db import to_tsquery

MAX_RESULTS = getattr(settings, "SEARCHES_MAX_RESULTS", 150)

def search_user_stories(project, text):
    model_cls = apps.get_model("userstories", "UserStory")
    where_clause = ("to_tsvector('english_nostop', coalesce(userstories_userstory.subject) || ' ' || "
                                "coalesce(userstories_userstory.ref) || ' ' || "
                                "coalesce(userstories_userstory.description, '')) "
                    "@@ to_tsquery('english_nostop', %s)")

    if text:
        return (model_cls.objects.extra(where=[where_clause], params=[to_tsquery(text)])
                                 .filter(project_id=project.pk)[:MAX_RESULTS])

    return model_cls.objects.filter(project_id=project.pk)[:MAX_RESULTS]

def search_tasks(project, text):
    model_cls = apps.get_model("tasks", "Task")
    where_clause = ("to_tsvector('english_nostop', coalesce(tasks_task.subject, '') || ' ' || "
                    "coalesce(tasks_task.ref) || ' ' || "
                    "coalesce(tasks_task.description, '')) @@ to_tsquery('english_nostop', %s)")

    if text:
        return (model_cls.objects.extra(where=[where_clause], params=[to_tsquery(text)])
                                 .filter(project_id=project.pk)[:MAX_RESULTS])

    return model_cls.objects.filter(project_id=project.pk)[:MAX_RESULTS]

def search_issues(project, text):
    model_cls = apps.get_model("issues", "Issue")
    where_clause = ("to_tsvector('english_nostop', coalesce(issues_issue.subject) || ' ' || "
                    "coalesce(issues_issue.ref) || ' ' || "
                    "coalesce(issues_issue.description, '')) @@ to_tsquery('english_nostop', %s)")

    if text:
        return (model_cls.objects.extra(where=[where_clause], params=[to_tsquery(text)])
                                 .filter(project_id=project.pk)[:MAX_RESULTS])

    return model_cls.objects.filter(project_id=project.pk)[:MAX_RESULTS]

def search_wiki_pages(project, text):
    model_cls = apps.get_model("wiki", "WikiPage")
    where_clause = ("to_tsvector('english_nostop', coalesce(wiki_wikipage.slug) || ' ' || "
                                "coalesce(wiki_wikipage.content, '')) "
                    "@@ to_tsquery('english_nostop', %s)")

    if text:
        return (model_cls.objects.extra(where=[where_clause], params=[to_tsquery(text)])
                                 .filter(project_id=project.pk)[:MAX_RESULTS])

    return model_cls.objects.filter(project_id=project.pk)[:MAX_RESULTS]


text:
CREATE DATABASE  IF NOT EXISTS `simulados` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `simulados`;
-- MySQL dump 10.13  Distrib 5.6.13, for Win32 (x86)
--
-- Host: localhost    Database: simulados
-- ------------------------------------------------------
-- Server version	5.5.23

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `user`
--

DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user` (
  `id_user` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  `email` varchar(45) NOT NULL,
  `photo` varchar(45) DEFAULT 'default',
  `id_credential` int(11) NOT NULL,
  PRIMARY KEY (`id_user`),
  KEY `user.credential` (`id_credential`),
  CONSTRAINT `user.credential` FOREIGN KEY (`id_credential`) REFERENCES `credential` (`id_credential`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `user`
--

LOCK TABLES `user` WRITE;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` VALUES (1,'Daniel Ventura Costa','danielventura.90@gmail.com',NULL,19),(13,'Teste','teste@teste.com.br',NULL,21);
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2014-06-20 21:51:10


text: UPDATE t2_segments SET block = b2 WHERE rowid = rowid


text:
/*
 * Project:Easy Web Framework
 * Description:
 * EasyFK stands for Easy Web Framework.It's an open source product for E-Business / E-Commerce.It
 * was launched by a chinese Hezhiping(QQ:110476592) in 2015.The goal of EasyFK is to  provide a
 * foundation and starting point for reliable, secure , simple-to-use ,cost-effective ,scalable
 * and suitable-for-Chinese E-Business / E-Commerce solutions. With EasyFK, you can get started
 * right away without the huge deployment and maintenance costs of E-Business / E-Commerce systems.
 * Of course, you can customize it or use it as a framework to implement your most challenging business needs.
 * EasyFk is licensed under the Apache License Version 2.0.  You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Author:hezhiping   Email:110476592@qq.com
 */
package cn.gorun8.easyfk.webapp.taglib;

public enum ThemePart {
	//登录页面模板
	VT_LOGIN_TMPLT_LOC,
	//错误页面
	VT_ERR_PAGE_LOC,
	//消息样式模板文件,用于显示各类消息:如提示、警告,错误信息等
	VT_MSG_TMPLT_LOC,
	//导航模板文件
	VT_NAV_BAR_LOC,
	//上下文件菜单模板文件
	VT_CONTEXT_MENU_LOC,
	//分页栏模板
	VT_PAGE_BAR_LOC,
	//页头文件
	VT_HDR_TMPLT_LOC,
	//TOP模板文件
	VT_TOP_PANEL_LOC,
	//LEFT模板文件
	VT_LEFT_PANEL_LOC,
	//RIGHT模板文件
	VT_RIGHT_PANEL_LOC,
	//页脚文件模板文件
	VT_FTR_TMPLT_LOC;

    public String toString() {
        return name();
    }
}


text:
<?php
/**
 * CTypeValidatorTest
 */
class CTypeValidatorTest extends CTestCase
{

    public function testInteger()
    {

        $validator       = new CTypeValidator();
        $validator->type = 'integer';
        $this->assertTrue($validator->validateValue(42));
        $this->assertTrue($validator->validateValue(+42));
        $this->assertTrue($validator->validateValue(-42));
        $this->assertTrue($validator->validateValue('42'));
        $this->assertTrue($validator->validateValue('+42'));
        $this->assertTrue($validator->validateValue('-42'));
        $this->assertFalse($validator->validateValue('42 is a good number!'));
        $this->assertFalse($validator->validateValue(3.1415926));
        $this->assertFalse($validator->validateValue(array(13)));

        $this->assertFalse($validator->validateValue(true));
        $this->assertFalse($validator->validateValue(false));
        $this->assertFalse($validator->validateValue(new stdClass()));
    }

    public function testIntegerStrict()
    {

        $validator         = new CTypeValidator();
        $validator->type   = 'integer';
        $validator->strict = true;
        $this->assertTrue($validator->validateValue(42));
        $this->assertTrue($validator->validateValue(+42));
        $this->assertTrue($validator->validateValue(-42));
        $this->assertFalse($validator->validateValue('42'));
        $this->assertFalse($validator->validateValue('+42'));
        $this->assertFalse($validator->validateValue('-42'));
        $this->assertFalse($validator->validateValue('42 is a good number!'));
        $this->assertFalse($validator->validateValue(3.1415926));
        $this->assertFalse($validator->validateValue(array(13)));

        $this->assertFalse($validator->validateValue(true));
        $this->assertFalse($validator->validateValue(false));
        $this->assertFalse($validator->validateValue(new stdClass()));
    }

    public function testFloat()
    {

        $validator       = new CTypeValidator();
        $validator->type = 'float';
        $this->assertTrue($validator->validateValue(42));
        $this->assertTrue($validator->validateValue(42.0));
        $this->assertTrue($validator->validateValue(+42.1));
        $this->assertTrue($validator->validateValue(-42.2));
        $this->assertTrue($validator->validateValue('42'));
        $this->assertTrue($validator->validateValue('42.1'));
        $this->assertTrue($validator->validateValue('+42.2'));
        $this->assertTrue($validator->validateValue('-42.3'));
        $this->assertFalse($validator->validateValue('42.3 is a good number!'));
        $this->assertFalse($validator->validateValue(array(13)));

        $this->assertFalse($validator->validateValue(true));
        $this->assertFalse($validator->validateValue(false));
        $this->assertFalse($validator->validateValue(new stdClass()));
    }

    public function testFloatStrict()
    {

        $validator         = new CTypeValidator();
        $validator->type   = 'float';
        $validator->strict = true;
        $this->assertFalse($validator->validateValue(42));
        $this->assertTrue($validator->validateValue(42.0));
        $this->assertTrue($validator->validateValue(+42.1));
        $this->assertTrue($validator->validateValue(-42.2));
        $this->assertFalse($validator->validateValue('42'));
        $this->assertFalse($validator->validateValue('42.1'));
        $this->assertFalse($validator->validateValue('+42.2'));
        $this->assertFalse($validator->validateValue('-42.3'));
        $this->assertFalse($validator->validateValue('42.3 is a good number!'));
        $this->assertFalse($validator->validateValue(array(13)));

        $this->assertFalse($validator->validateValue(true));
        $this->assertFalse($validator->validateValue(false));
        $this->assertFalse($validator->validateValue(new stdClass()));
    }

    public function testString()
    {

        $validator       = new CTypeValidator();
        $validator->type = 'string';
        $this->assertFalse($validator->validateValue(42));
        $this->assertFalse($validator->validateValue(42.0));
        $this->assertTrue($validator->validateValue('42'));
        $this->assertTrue($validator->validateValue('42.3 is a good number!'));
        $this->assertFalse($validator->validateValue(array(13)));

        $this->assertFalse($validator->validateValue(true));
        $this->assertFalse($validator->validateValue(false));
        $this->assertFalse($validator->validateValue(new stdClass()));
    }

    public function testArray()
    {

        $validator       = new CTypeValidator();
        $validator->type = 'array';
        $this->assertFalse($validator->validateValue(42));
        $this->assertFalse($validator->validateValue(42.0));
        $this->assertFalse($validator->validateValue('42.3 is a good number!'));
        $this->assertTrue($validator->validateValue(array(13)));

        $this->assertFalse($validator->validateValue(true));
        $this->assertFalse($validator->validateValue(false));
        $this->assertFalse($validator->validateValue(new stdClass()));
    }

    // TODO: the following three should be tested for actual pattern matching

    public function testDate()
    {

        $validator       = new CTypeValidator();
        $validator->type = 'date';
        $this->assertFalse($validator->validateValue(array(13)));

        $this->assertFalse($validator->validateValue(42));
        $this->assertFalse($validator->validateValue(true));
        $this->assertFalse($validator->validateValue(false));
        $this->assertFalse($validator->validateValue(new stdClass()));
    }

    public function testTime()
    {

        $validator       = new CTypeValidator();
        $validator->type = 'time';
        $this->assertFalse($validator->validateValue(array(13)));

        $this->assertFalse($validator->validateValue(42));
        $this->assertFalse($validator->validateValue(true));
        $this->assertFalse($validator->validateValue(false));
        $this->assertFalse($validator->validateValue(new stdClass()));
    }

    public function testDateTime()
    {

        $validator       = new CTypeValidator();
        $validator->type = 'datetime';
        $this->assertFalse($validator->validateValue(array(13)));

        $this->assertFalse($validator->validateValue(42));
        $this->assertFalse($validator->validateValue(true));
        $this->assertFalse($validator->validateValue(false));
        $this->assertFalse($validator->validateValue(new stdClass()));
    }
}


text:
using NUnit.Framework;

namespace IronAHK.Tests
{
    partial class Scripting
    {
        [Test]
        public void SimplePass()
        {
            Assert.IsTrue(TestScript("pass"));
        }

        [Test]
        public void If()
        {
            Assert.IsTrue(TestScript("if"));
        }

        [Test]
        public void Functions()
        {
            Assert.IsTrue(TestScript("functions"));
        }

        [Test]
        public void Comments()
        {
            Assert.IsTrue(TestScript("comments"));
        }

        [Test]
        public void Directive()
        {
            Assert.IsTrue(TestScript("directive"));
        }

        [Test]
        public void Expressions()
        {
            Assert.IsTrue(TestScript("expressions"));
        }

        [Test]
        public void Command()
        {
            Assert.IsTrue(TestScript("command"));
        }

        [Test]
        public void Line()
        {
            Assert.IsTrue(TestScript("line"));
        }

        [Test]
        public void Loop()
        {
            Assert.IsTrue(TestScript("loop"));
        }

        [Test]
        public void Objects()
        {
            Assert.IsTrue(TestScript("objects"));
        }

        [Test]
        public void Assign()
        {
            Assert.IsTrue(TestScript("assign"));
        }

        [Test]
        public void Goto()
        {
            Assert.IsTrue(TestScript("goto"));
        }

        [Test]
        public void Hotkey()
        {
            Assert.IsTrue(ValidateScript("hotkey"));
        }

        [Test]
        public void VanillaExpressions()
        {
            Assert.IsTrue(ValidateScript("vanilla-Expressions"));
        }

        [Test]
        public void VanillaContinuation()
        {
            Assert.IsTrue(ValidateScript("vanilla-Line Continuation"));
        }

        [Test]
        public void VanillaMain()
        {
            Assert.IsTrue(ValidateScript("vanilla-MAIN"));
        }

        [Test]
        public void VanillaRegex()
        {
            Assert.IsTrue(ValidateScript("vanilla-RegExMatch & RegExReplace"));
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 26: 256 (1928)

#### Original name
Meliola peruviana var. irregularis F. Stevens

### Remarks
null


text:
"""
    EauDouce.main
    ~~~~~~~~~~~~~~

    This is a blog program based on Flask:
    This is an entry files, main applications, and some initialization operations.

    Docstring conventions:
    http://flask.pocoo.org/docs/0.10/styleguide/#docstrings

    Comments:
    http://flask.pocoo.org/docs/0.10/styleguide/#comments

    :copyright: (c) 2017 by Mr.tao.
    :license: BSD 3-Clause, see LICENSE for more details.
"""

__author__  = "Mr.tao"
__email__   = "staugur@saintic.com"
__doc__     = "A flask+mysql+bootstrap blog based on personal interests and hobbies."
__date__    = "2017-03-26"
__version__ = "0.1.0"
__license__ = "BSD 3-Clause License"

import time, os.path, jinja2, sys, rq_dashboard
from flask import request, g, render_template, redirect, make_response, url_for
from flask_pluginkit import PluginManager, Flask
from config import GLOBAL, SSO, PLUGINS, RQREDIS
from utils.tool import logger, ChoiceColor, TagRandomColor, timestamp_to_timestring
from utils.web import verify_sessionId, analysis_sessionId, get_redirect_url
from urllib import urlencode
from libs.api import ApiManager
from views import api_blueprint, front_blueprint, admin_blueprint, upload_blueprint
reload(sys)
sys.setdefaultencoding('utf-8')

#初始化定义application
app = Flask(__name__)
app.config.update(
    REDIS_URL = RQREDIS,
    RQ_POLL_INTERVAL = 2500,
    ISSO_API = PLUGINS["ISSO"]["api"],
)

#初始化插件管理器(自动扫描并加载运行)
plugin_packages = []
if PLUGINS["Valine"]["enable"] in ("true", True, "True"):
    plugin_packages.append("flask_pluginkit_valine")
if PLUGINS["ISSO"]["enable"] in ("true", True, "True"):
    plugin_packages.append("flask_pluginkit_isso")
plugin = PluginManager(app, logger=logger.plugin, stpl=True, plugin_packages=plugin_packages)

#初始化接口管理器
api = ApiManager()

#注册蓝图路由,可以修改前缀
app.register_blueprint(front_blueprint)
app.register_blueprint(api_blueprint, url_prefix="/api")
app.register_blueprint(admin_blueprint, url_prefix="/admin")
app.register_blueprint(upload_blueprint, url_prefix="/upload")
app.register_blueprint(rq_dashboard.blueprint, url_prefix="/rqdashboard")

@app.context_processor
def GlobalTemplateVariables():
    data = {"Version": __version__, "Author": __author__, "Email": __email__, "Doc": __doc__, "ChoiceColor": ChoiceColor, "TagRandomColor": TagRandomColor, "timestamp_to_timestring": timestamp_to_timestring, "PLUGINS": PLUGINS}
    return data

@app.before_request_top
def before_request():
    g.startTime = time.time()
    g.signin    = verify_sessionId(request.cookies.get("sessionId"))
    g.sid,g.uid = analysis_sessionId(request.cookies.get("sessionId"), "tuple") if g.signin else (None, None)
    g.username  = g.uid
    g.api       = api
    g.plugins   = PLUGINS
    g.userinfo  = api.sso_get_userinfo(g.uid)
    g.config = api.get_sys_config()['data']
    # 仅是重定向页面快捷定义
    g.redirect_uri = get_redirect_url()
    logger.access.debug("sid: {}, uid: {}, userinfo: {}".format(g.sid, g.uid, g.userinfo))

@app.after_request
def after_request(response):
    data = {
        "status_code": response.status_code,
        "method": request.method,
        "ip": request.headers.get('X-Real-Ip', request.remote_addr),
        "url": request.url,
        "referer": request.headers.get('Referer'),
        "agent": request.headers.get("User-Agent"),
        "TimeInterval": "%0.2fs" %float(time.time() - g.startTime)
    }
    logger.access.info(data)
    response.headers["X-Frame-Options"] = "SAMEORIGIN"
    response.headers["Access-Control-Allow-Origin"] = "*"
    return response

@app.errorhandler(404)
def not_found(error=None):
    return render_template('public/404.html'),404

@app.errorhandler(500)
def server_error(error=None):
    if error:
        logger.err.error(error, exc_info=True)
    return render_template('public/500.html'),500

@app.route('/login/')
def login():
    if g.signin:
        return redirect(url_for("front.index"))
    else:
        ReturnUrl = request.args.get("NextUrl") or request.args.get("ReturnUrl")
        SSOLoginURL = url_for("sso.Login", ReturnUrl=ReturnUrl) if ReturnUrl else url_for("sso.Login")
        return redirect(SSOLoginURL)

@app.route('/logout/')
def logout():
    # 注销
    if g.signin:
        return redirect(url_for("sso.Logout"))
    else:
        return redirect(url_for("sso.Login"))

@app.route('/SignUp')
def signup():
    regUrl = SSO.get("sso_server").strip("/") + "/signUp"
    return redirect(regUrl)

if __name__ == '__main__':
    app.run(host=GLOBAL.get('Host'), port=int(GLOBAL.get('Port')), debug=True)


text:
"""
The MIT License (MIT)

Copyright (c) 2015 Robin Jespersen

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import sys, os, shutil, unittest, urllib2
sys.path[0:0] = [os.path.join(os.path.dirname(__file__), ".."),]

from wunderpython import stupidcache
from wunderpython import wunderground

class TestStupidCache(unittest.TestCase):
    cacheFolder = './cache/folder/'
    cacheBaseFolder = './cache/'
    url = 'http://autocomplete.wunderground.com/aq'

    def test_not_cached_content(self):
        self.assertFalse(os.path.exists(self.cacheFolder))
        self.assertEqual(stupidcache.urlopen(self.url), urllib2.urlopen(self.url).read())
        self.assertFalse(os.path.exists(self.cacheFolder))

    def test_folder_creation(self):
        self.assertFalse(os.path.exists(self.cacheFolder))
        stupidcache.urlopen(self.url, self.cacheFolder)
        self.assertTrue(os.path.exists(self.cacheFolder))

    def test_cached_content(self):
        self.assertEqual(stupidcache.urlopen(self.url, self.cacheFolder), urllib2.urlopen(self.url).read())

    def tearDown(self):
        if os.path.exists(self.cacheFolder):
            shutil.rmtree(self.cacheBaseFolder)

class TestWunderground(unittest.TestCase):
    wg = wunderground.Wunderground('no_valid_key')

    def test_search(self):
        self.assertTrue(len(self.wg.search('')) == 20)
        self.assertTrue(type(self.wg.search(''))==list)
        self.assertTrue(len(self.wg.search('not a name of a place')) == 0)
        self.assertTrue(len(self.wg.search('Munich, Germany')) == 1)

    def test_location(self):
        self.assertEqual(self.wg['Munich, Germany'].name, 'Munich, Germany')
        self.assertEqual(type(self.wg['Munich, Germany', 'Berlin, Germany', 'Hamburg, Germany']), list)
        self.assertEqual(self.wg['Munich, Germany'].ll, '48.130001 11.700000')

    def test_features(self):
        for feature in ['almanac', 'astronomy', 'conditions', 'forecast', 'forecast10day', 'rawtide', 'satellite', 'tide']:
            self.assertEqual(type(getattr(self.wg['Munich, Germany'], feature)), dict)

        for feature in ['alerts', 'hourly', 'hourly10day', 'webcams']:
            self.assertEqual(type(getattr(self.wg['Munich, Germany'], feature)), list)

    def test_history_feature(self):
        self.assertEqual(type(self.wg['Munich, Germany'].history['2015.01.01']), dict)
        self.assertEqual(type(self.wg['Munich, Germany'].history['2015.01.01', '2015.01.03', '2015.01.05']), list)
        self.assertEqual(self.wg['Munich, Germany'].history['2015.01.01'], self.wg['Munich, Germany'].history['2015.01.01', '2015.01.03', '2015.01.05'][0])
        self.assertEqual(self.wg['Munich, Germany'].history['2015.01.01'], self.wg['Munich, Germany'].history['2014.12.31':'2015.01.02'][1])

if __name__ == '__main__':
    unittest.main()


text:
'use strict';

/**
 * @ngdoc function
 * @name vizApp.controller:PanelCtrl
 * @description
 * # PanelCtrl
 * Controller of the vizApp
 */
angular.module('vizApp')
  .controller('PanelCtrl', function ($scope) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];
  });


text:
import { get } from 'axios';
import {
    SAVED_JSON_FETCH_IN_PROGRESS,
    SAVED_JSON_FETCH_SUCCESS,
    SAVED_JSON_FETCH_ERROR,
    EDITED_JSON_LOAD
} from '../constants';

export const fetchData = url => dispatch => {
    dispatch({ type: SAVED_JSON_FETCH_IN_PROGRESS });

    let requestUrl = url;
    if (process.env.NODE_ENV === 'production') {
        requestUrl = `${document.location.protocol}//${document.location.host}/api/${encodeURIComponent(url)}`;
    }

    get(requestUrl).then((response) => {
        try {
            dispatch({
                type: SAVED_JSON_FETCH_SUCCESS,
                payload: response.data,
            });
            dispatch({
                type: EDITED_JSON_LOAD,
                payload: response.data,
            });
        } catch(e) {
            dispatch({
                type: SAVED_JSON_FETCH_ERROR,
                error: e.message,
            });
        }
    })
    .catch((error) => {
        dispatch({
            type: SAVED_JSON_FETCH_ERROR,
            error: `Request error: ${error.message}`,
        });
    });
};

export const loadData = json => dispatch => {
    dispatch({
        type: SAVED_JSON_FETCH_SUCCESS,
        payload: json,
    });
    dispatch({
        type: EDITED_JSON_LOAD,
        payload: json,
    });
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateSocialitesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('socialites', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('social_type');//登录类型
            $table->string('social_name')->default('');//第三方的姓名
            $table->string('social_id')->nullable();//第三方登录的id
            $table->foreign('user_id')
                  ->references('id')
                  ->on('users')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('socialites');
    }
}


text:
//
//  OLKHand.h
//  OpenLeapKit
//
//  Created by Tyler Zetterstrom on 2013-08-16.
//

#import <Foundation/Foundation.h>
#import "LeapObjectiveC.h"

@class OLKHand;

@protocol OLKHandFactory <NSObject>
- (OLKHand *)manufactureHand:(LeapHand *)leapHand;
@end

@protocol OLKHandContainer <NSObject, NSCopying>

@property (nonatomic) OLKHand *hand;
@property (nonatomic) NSView *spaceView;
@property (nonatomic) BOOL enabled;

@end

static NSString * const OLKHandBestLeftGuessKey = @"BestLeftGuess";
static NSString * const OLKHandBestRightGuessKey = @"BestRightGuess";
static NSString * const OLKHandLeftHandsKey = @"LeftHands";
static NSString * const OLKHandRightHandsKey = @"RightHands";
static NSString * const OLKHandUnknownHandednessKey = @"UnknownHandednessHands";

typedef enum {
    OLKHandednessAlgorithmHandPos = 1,
    OLKHandednessAlgorithmThumbBasePos = 2,
    OLKHandednessAlgorithmThumbTipAndBase = 3,
    OLKHandednessAlgorithmThumbShortest = 4
}OLKHandednessAlgorithm;

typedef enum {
    OLKHandednessUnknown=0,
    OLKLeftHand=1,
    OLKRightHand=2
}OLKHandedness;

@interface OLKHand : NSObject <NSCopying>

+ (BOOL)isLeapHandFist:(LeapHand *)leapHand;
+ (LeapMatrix *)transformForHandReference:(LeapHand *)hand;

+ (LeapPointable *)furthestFingerOrPointableTipFromPalm:(LeapHand *)hand;
+ (NSDictionary *)leftRightHandSearch:(NSArray *)hands ignoreHands:(NSSet *)ignoreHands handednessAlgorithm:(OLKHandednessAlgorithm)handednesAlgorithm factory:(NSObject<OLKHandFactory>*)factory;
+ (NSArray *)simpleLeftRightHandSearch:(NSArray *)hands;

+ (OLKHandedness)handednessByThumbTipDistFromPalm:(LeapHand *)hand thumb:(LeapFinger **)pThumb;
+ (OLKHandedness)handednessByThumbBasePosToPalm:(LeapHand *)hand thumb:(LeapFinger **)pThumb;
+ (OLKHandedness)handednessByThumbTipAndBaseCombo:(LeapHand *)hand thumb:(LeapFinger **)pThumb;
+ (OLKHandedness)handednessByShortestFinger:(LeapHand *)hand thumb:(LeapFinger **)pThumb;

- (BOOL)isLeapHand:(LeapHand *)leapHand;
- (void)updateLeapHand:(LeapHand *)leapHand;
- (OLKHandedness)updateHandedness;

- (BOOL)isFist;

- (OLKHandedness)updateHandednessByThumbTipDistFromPalm;
- (OLKHandedness)updateHandednessByThumbBasePosToPalm;
- (OLKHandedness)updateHandednessByShortestFinger;
- (OLKHandedness)updateHandednessByThumbTipAndBaseCombo;

- (LeapVector *)palmPosition;
- (LeapVector *)direction;
- (LeapVector *)palmNormal;

@property (nonatomic) LeapHand *leapHand;
@property (nonatomic) LeapFrame *leapFrame;
@property (nonatomic, readonly) LeapFinger *thumb;
@property (nonatomic) OLKHandedness handedness;
@property (nonatomic, readonly) NSUInteger numFramesExist;
@property (nonatomic) OLKHandedness simHandedness;
@property (nonatomic) OLKHandednessAlgorithm handednessAlgorithm;
@property (nonatomic) BOOL usesStabilized;

@end


text:
#include <aws/dms/model/SslSecurityProtocolValue.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace DatabaseMigrationService
  {
    namespace Model
    {
      namespace SslSecurityProtocolValueMapper
      {

        static const int plaintext_HASH = HashingUtils::HashString("plaintext");
        static const int ssl_encryption_HASH = HashingUtils::HashString("ssl-encryption");

        SslSecurityProtocolValue GetSslSecurityProtocolValueForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == plaintext_HASH)
          {
            return SslSecurityProtocolValue::plaintext;
          }
          else if (hashCode == ssl_encryption_HASH)
          {
            return SslSecurityProtocolValue::ssl_encryption;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<SslSecurityProtocolValue>(hashCode);
          }

          return SslSecurityProtocolValue::NOT_SET;
        }

        Aws::String GetNameForSslSecurityProtocolValue(SslSecurityProtocolValue enumValue)
        {
          switch(enumValue)
          {
          case SslSecurityProtocolValue::plaintext:
            return "plaintext";
          case SslSecurityProtocolValue::ssl_encryption:
            return "ssl-encryption";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace SslSecurityProtocolValueMapper
    } // namespace Model
  } // namespace DatabaseMigrationService
} // namespace Aws


text:
CKEDITOR.plugins.setLang("a11yhelp", "af", {
    title: "Toeganglikheid instruksies",
    contents: "Hulp inhoud. Druk ESC om toe te maak.",
    legend: [{
        name: "Algemeen",
        items: [{
            name: "Bewerker balk",
            legend: "Druk ${toolbarFocus} om op die werkbalk te land. Beweeg na die volgende en voorige wekrbalkgroep met TAB and SHIFT+TAB. Beweeg na die volgende en voorige werkbalkknop met die regter of linker pyl. Druk SPASIE of ENTER om die knop te bevestig."
        }, {
            name: "Bewerker dialoog",
            legend: "Inside a dialog, press TAB to navigate to the next dialog element, press SHIFT+TAB to move to the previous dialog element, press ENTER to submit the dialog, press ESC to cancel the dialog. When a dialog has multiple tabs, the tab list can be reached either with ALT+F10 or with TAB as part of the dialog tabbing order. With tab list focused, move to the next and previous tab with RIGHT and LEFT ARROW, respectively."
        },
            {
                name: "Bewerkerinhoudmenu",
                legend: "Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option with SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC."
            }, {
                name: "Editor List Box",
                legend: "Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box."
            },
            {
                name: "Editor Element Path Bar",
                legend: "Press ${elementsPathFocus} to navigate to the elements path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor."
            }]
    }, {
        name: "Commands",
        items: [{name: " Undo command", legend: "Press ${undo}"}, {
            name: " Redo command",
            legend: "Press ${redo}"
        }, {name: " Bold command", legend: "Press ${bold}"}, {name: " Italic command", legend: "Press ${italic}"}, {
            name: " Underline command",
            legend: "Press ${underline}"
        }, {name: " Link command", legend: "Press ${link}"}, {
            name: " Toolbar Collapse command",
            legend: "Press ${toolbarCollapse}"
        }, {
            name: " Access previous focus space command",
            legend: "Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."
        }, {
            name: " Access next focus space command",
            legend: "Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."
        },
            {name: " Accessibility Help", legend: "Press ${a11yHelp}"}]
    }],
    backspace: "Backspace",
    tab: "Tab",
    enter: "Enter",
    shift: "Shift",
    ctrl: "Ctrl",
    alt: "Alt",
    pause: "Pouse",
    capslock: "Hoofletterslot",
    escape: "Ontsnap",
    pageUp: "Blaaiop",
    pageDown: "Blaaiaf",
    end: "Einde",
    home: "Tuis",
    leftArrow: "Linkspyl",
    upArrow: "Oppyl",
    rightArrow: "Regterpyl",
    downArrow: "Afpyl",
    insert: "Toevoeg",
    "delete": "Verwyder",
    leftWindowKey: "Left Windows key",
    rightWindowKey: "Right Windows key",
    selectKey: "Select key",
    numpad0: "Nommerblok 0",
    numpad1: "Nommerblok 1",
    numpad2: "Nommerblok 2",
    numpad3: "Nommerblok 3",
    numpad4: "Nommerblok 4",
    numpad5: "Nommerblok 5",
    numpad6: "Nommerblok 6",
    numpad7: "Nommerblok 7",
    numpad8: "Nommerblok 8",
    numpad9: "Nommerblok 9",
    multiply: "Maal",
    add: "Plus",
    subtract: "Minus",
    decimalPoint: "Desimaalepunt",
    divide: "Gedeeldeur",
    f1: "F1",
    f2: "F2",
    f3: "F3",
    f4: "F4",
    f5: "F5",
    f6: "F6",
    f7: "F7",
    f8: "F8",
    f9: "F9",
    f10: "F10",
    f11: "F11",
    f12: "F12",
    numLock: "Nommervergrendel",
    scrollLock: "Rolvergrendel",
    semiColon: "Kommapunt",
    equalSign: "Isgelykaan",
    comma: "Komma",
    dash: "Koppelteken",
    period: "Punt",
    forwardSlash: "Skuinsstreep",
    graveAccent: "Aksentteken",
    openBracket: "Oopblokhakkie",
    backSlash: "Trustreep",
    closeBracket: "Toeblokhakkie",
    singleQuote: "Enkelaanhaalingsteken"
});


text:
<?php

namespace Flex\Code\Html\Tag;

use Flex\Code\Html\Tag\Attribute\GlobalAttributeAwareInterface;
use Flex\Code\Html\Tag\Attribute\GlobalAttributeAwareTrait;
use Flex\Code\Html\Tag\Model\AbstractTag;

/**
 * The <meta> tag provides metadata about the HTML document. Metadata will not be
 * displayed on the page, but will be machine parsable.
 *
 * Meta elements are typically used to specify page description, keywords, author
 * of the document, last modified, and other metadata. The metadata can be used by
 * browsers (how to display content or reload page), search engines (keywords), or
 * other web services.
 *
 * @author elnebuloso/flex-code-html-generator
 * @link http://www.w3schools.com/tags/tag_meta.asp
 */
class Meta extends AbstractTag implements GlobalAttributeAwareInterface
{
    use GlobalAttributeAwareTrait;

    /**
     * @var string
     */
    protected $name = 'meta';

    /**
     * @var string
     */
    protected $doctype = 'html5';

    /**
     * @var bool
     */
    protected $isVoid = true;

    /**
     * @var array
     */
    protected $attributes = [

    ];

    /**
     * @var array
     */
    protected $flags = [

    ];

    /**
     * Specifies the character encoding for the HTML document
     *
     * @var string
     * @return $this
     */
    public function setCharset($v)
    {
        $this->attributes['charset'] = $v;

        return $this;
    }

    /**
     * Gives the value associated with the http-equiv or name attribute
     *
     * @var string
     * @return $this
     */
    public function setContent($v)
    {
        $this->attributes['content'] = $v;

        return $this;
    }

    /**
     * Provides an HTTP header for the information/value of the content attribute
     *
     * @var string
     * @return $this
     */
    public function setHttpEquiv($v)
    {
        $this->attributes['http-equiv'] = $v;

        return $this;
    }

    /**
     * Specifies a name for the metadata
     *
     * @var string
     * @return $this
     */
    public function setName($v)
    {
        $this->attributes['name'] = $v;

        return $this;
    }

    /**
     * NOT VALID in HTML5, only with correct doctype
     *
     * <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
     * "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
     *
     * @var string
     * @return $this
     */
    public function setProperty($v)
    {
        $this->attributes['property'] = $v;

        return $this;
    }

    /**
     * Not supported in HTML5. Specifies a scheme to be used to interpret the value of
     * the content attribute
     *
     * @var string
     * @return $this
     */
    public function setScheme($v)
    {
        $this->attributes['scheme'] = $v;

        return $this;
    }
}


text:
package org.wildfly.swarm.datasources;

import org.wildfly.swarm.config.Datasources;
import org.wildfly.swarm.config.datasources.DataSource;
import org.wildfly.swarm.config.datasources.JDBCDriverConfigurator;
import org.wildfly.swarm.container.Fraction;

/**
 * @author Bob McWhirter
 */
public class DatasourcesFraction extends Datasources<DatasourcesFraction> implements Fraction {
    @Override
    public DatasourcesFraction dataSource(DataSource value) {
        if (value.jndiName() == null) value.jndiName("java:jboss/datasources/" + value.getKey());
        return super.dataSource(value);
    }

    public DatasourcesFraction jdbcDriver(String childKey, EnhancedJDBCDriverConfigurator config) {
        JDBCDriver driver = new JDBCDriver(childKey);
        config.configure(driver);
        jdbcDriver( driver );
        return this;
    }

    public interface EnhancedJDBCDriverConfigurator extends JDBCDriverConfigurator {

    }
}