text:
from .shell import RED_B, RESET, GREEN_B, BLUE_B, BLACK_B, YELLOW_B, GREEN, RED

def get_types(thing):
    try:
        import types
        _all_types = types.__all__

        thing_type = type(thing)
        return [t for t in _all_types if thing_type is getattr(types, t)]
    except:
        pass

def dse(*args, **kwargs):
    import ipdb
    try:
        ds(*args, **kwargs)
    except Exception as e:
        ipdb.post_mortem()

def ds(dictlike, searchstring, case_insensitive=True):
    if isinstance(dictlike, list):
        _list_search(dictlike, searchstring, case_insensitive=case_insensitive)
    elif isinstance(dictlike, dict):
        _dict_search(dictlike, searchstring, case_insensitive=case_insensitive)

def _dict_search(somedict, string, case_insensitive=True, path='', done=None):
    dictid = id(somedict)

    if done is None:
        done = set([dictid])
    elif not dictid in done:
        done.add(dictid)

    if isinstance(somedict, list):
        _list_search(somedict, string, done=done)
        return

    for key, value in somedict.items():
        if (
            case_insensitive and (key.lower().find(string.lower()) != -1) or
            not case_insensitive and (key.find(string) != -1)
        ):
            # print path, 'KEY:', key
            print("{path} {col2}{key}{col0}:{rst} {value}".format(
                col0=BLACK_B,
                # col1=YELLOW_B,
                col2=RED_B,
                rst=RESET,
                key=key,
                value=repr(value),
                path=path + BLACK_B + " >" + RESET if path else ''
            ))
            # print YELLOW_B + path, RED_B + 'KEY:' + RESET, repr(value)

        if isinstance(value, str) or isinstance(value, str):
            if (
                case_insensitive and (value.lower().find(string.lower()) != -1) or
                not case_insensitive and (value.find(string) != -1)
            ):
                print("{path} {col2}{key} {col0}:{rst} {value}".format(
                    col0=BLACK_B,
                    col1=YELLOW_B,
                    col2=RED_B,
                    rst=RESET,
                    key=key,
                    value=repr(value),
                    path=path + BLACK_B + " >" + RESET if path else ''
                ))
                # print BLACK_B + path, BLUE_B + 'VALUE:' + RESET, repr(value)

        elif isinstance(value, dict):
            valueid = id(value)
            if valueid in done:
                continue
            # print '+', valueid
            done.add(valueid)
            new_path = "{path} {col0}> {col2}{key}{rst}".format(col2=RED_B, col0=BLACK_B, rst=RESET, path=path, key=key) if path else RED_B + key + RESET
            _dict_search(value, string, case_insensitive=case_insensitive, path=new_path, done=done)
        elif isinstance(value, list):
            valueid = id(value)
            if valueid in done:
                continue
            # print '-', valueid
            done.add(valueid)
            new_path = "{path} {col0}> {col2}{key}{rst}".format(col2=RED_B, col0=BLACK_B, rst=RESET, path=path, key=key) if path else RED_B + key + RESET
            _list_search(value, string, case_insensitive=case_insensitive, path=new_path, done=done)

def _list_search(somelist, string, case_insensitive=True, path='', done=None):
    listid = id(somelist)

    if done is None:
        done = set([listid])
    elif not listid in done:
        done.add(listid)

    if isinstance(somelist, dict):
        _dict_search(somelist, string, case_insensitive=case_insensitive, done=done)
        return

    for i, value in enumerate(somelist):
        if isinstance(value, str) or isinstance(value, str):
            if (
                case_insensitive and (value.lower().find(string.lower()) != -1) or
                not case_insensitive and (value.find(string) != -1)
            ):
                print("{path} {col2}{key}{rst} {col0}:{rst} {value}".format(
                    col0=BLACK_B,
                    col1=YELLOW_B,
                    col2=BLUE_B,
                    rst=RESET,
                    key=i,
                    value=repr(value),
                    path=path + BLACK_B + ' >' + RESET if path else ''
                ))
                # print BLACK_B + path, i, BLUE_B + 'VALUE:' + RESET, value
        elif isinstance(value, dict):
            valueid = id(value)
            if valueid in done:
                continue
            # print '+', valueid
            done.add(valueid)
            new_path = "{path} {col0}> {col2}{key}{rst}".format(col2=BLUE_B, col0=BLACK_B, rst=RESET, path=path, key=i) if path else BLUE_B + i + RESET
            _dict_search(value, string, case_insensitive=case_insensitive, path=new_path, done=done)
        elif isinstance(value, list):
            valueid = id(value)
            if valueid in done:
                continue
            # print '-', valueid
            done.add(valueid)
            new_path = "{path} {col0}> {col2}{key}{rst}".format(col2=BLUE_B, col0=BLACK_B, rst=RESET, path=path, key=i) if path else BLUE_B + i + RESET
            _list_search(value, string, case_insensitive=case_insensitive, path=new_path, done=done)

def ruler(length=71, pad=0, start_from_zero=True):
    rulermrks = "|._._:_._.|._._:_._.|._._:_._.|._._:_._.|._._:_._.|._._:_._.|._._:_._.|._._:_._.|._._:_._.|._._:_._.|._._:_._.|._._:_._.|._._:_._.|._._:_._.|._._:_._.|"
    rulerdata = "0        10        20        30        40        50        60        70        80        90        100       110       120       130       140       150"

    if start_from_zero:
        return "{}\n{}".format(
            ''.join([' ' for _ in range(pad)]) + rulermrks[:length],
            ''.join([' ' for _ in range(pad)]) + rulerdata[:length]
        )

    return "{}\n{}".format(
        ''.join([' ' for _ in range(pad)]) + rulermrks[1:(length + 1)],
        ''.join([' ' for _ in range(pad)]) + rulerdata[1:(length + 1)]
    )

_encodings = [
    'utf-8',
    'latin1',
    'ascii',
    'ISO-8859-1',
    'ISO-8859-15',
]

def ascfix(input_text):
    if isinstance(input_text, bytes):
        print(input_text)
        # print type(input_text),
        print('bytes', end=' ')
        print("-decode-> unicode", end=' ')
        try:
            import chardet
            res = chardet.detect(input_text)
            print("({en} at ~{con})".format(en=res.get('encoding'), con=res.get('confidence')))
        except:
            print()

        for enc in _encodings:
            print("{}: ".format(enc))

            try:
                data = input_text.decode(enc, 'replace')
                # print "-> OK"

                for enc2 in _encodings:
                    print("  -> {}:".format(enc2), end=' ')
                    try:
                        data2 = str(data.encode(enc2, 'replace'))
                        print(data2)
                    except Exception as e:
                        print('Error')
                print()

            except Exception as e:
                print("-> Error")

    elif isinstance(input_text, str):
        print(input_text)
        # print type(input_text),
        print('str')
        print("-encode-> bytes")

        for enc in _encodings:
            print("{}: ".format(enc))
            print("  e: ", end=' ')
            try:
                data = str(input_text.encode(enc, 'replace'))
                print(data, input_text.encode(enc, 'replace'))
            except Exception as e:
                print("Error", e, end=' ')
                try:
                    data = input_text.encode(enc, 'replace')
                    print("-> OK")
                except Exception as e:
                    print("-> Error")

    else:
        print("-> not string")
        return
import logging
log = logging.getLogger(__name__)
import chardet
def uni(thing):
    if thing is None:
        return None

    if isinstance(thing, str):
        # log.debug(u'unicode: {}'.format(thing))
        # log.debug('is unicode')
        return thing

    if isinstance(thing, bytes):
        # log.debug('str {}'.format(thing))
        # log.debug('is str')
        try:
            return thing.decode('utf-8')
        except UnicodeDecodeError as e:
            # log.debug(' not utf-8')
            result = chardet.detect(thing)
            charenc = result['encoding']
            if charenc:
                return thing.decode(charenc, 'replace')
            else:
                return '<undecodable bytes>'

    if isinstance(thing, (int, float)):
        # log.debug(u'number: {}'.format(thing))
        # log.debug('is number')
        return '{}'.format(thing)

    if hasattr(thing, '__unicode__'):
        try:
            # log.debug('__unicode__ {} -> {}'.format(repr(thing), thing.__unicode__()))
            # log.debug('has __unicode__()')
            return thing.__unicode__()
        except:
            # log.debug('  could not __unicode__()')
            pass
    if hasattr(thing, '__str__') and not isinstance(thing, type):
        # log.debug('__str__() {} -> {}'.format(repr(thing), uni(thing.__str__())))

        return uni(thing.__str__())

    return repr(thing)

def get_subqueus_req(elements, first=True):
    if not elements:
        # print '-'
        yield None
    elif len(elements) == 1:
        # print ' .', [elements]
        yield [elements]
    else:
        for w in range(1, len(elements)):
            for rest in get_subqueus_req(elements[w:], first=False):
                # if first:
                #     print '=> ', [elements[:w]], '+', rest
                # else:
                #     print '  <-', [elements[:w]], '+', rest
                yield [elements[:w]] + rest if rest else [elements]
        # yield [elements] if first else [elements]
        # if first:
        #     print '=> ', elements
        # else:
        #     print ' <=', [elements]
        yield [elements]

class _dict2props(object):
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

cols = _dict2props(**{
    'black'         : (30, 40),
    'red'           : (31, 41),
    'green'         : (32, 42),
    'yellow'        : (33, 43),
    'blue'          : (34, 44),
    'magenta'       : (35, 45),
    'cyan'          : (36, 46),
    'white'         : (37, 47),
    'bright_black'  : (90, 100),
    'bright_red'    : (91, 101),
    'bright_green'  : (92, 102),
    'bright_yellow' : (93, 103),
    'bright_blue'   : (94, 104),
    'bright_magenta': (95, 105),
    'bright_cyan'   : (96, 106),
    'bright_white'  : (97, 107 ),
})

# 0	Reset / Normal
# 1	Bold or increased intensity
# 2	Faint (decreased intensity)
# 3	Italic
# 4	Underline
# 5	Slow Blink
# 6	Rapid Blink
# 7	reverse video
# 8	Conceal
# 9	Crossed-out
# 10	Primary(default) font
# 11–19	Alternative font

def shc(fg=None, bg=None, rev=None, under=None, bold=None, faint=None, italic=None, blinks=None, blinkr=None, con=None, cross=None):
    '''
Colors:
- [bright_]black
- [bright_]red
- [bright_]green
- [bright_]yellow
- [bright_]blue
- [bright_]magenta
- [bright_]cyan
- [bright_]white
    '''
    esc = '\x1b['
    sep = ';'
    end = 'm'
    command = []
    if bold is not None and bold: command.append('1')
    if bold is not None and not bold: command.append('22')
    if faint is not None and faint: command.append('2')
    if faint is not None and not faint: command.append('22')
    if italic is not None and italic: command.append('3')
    if italic is not None and not italic: command.append('23')
    if under is not None and under: command.append('4')
    if under is not None and not under: command.append('24')
    # if blinks: command.append('5')
    # if blinkr: command.append('6')
    if rev is not None and rev: command.append('7')
    if rev is not None and not rev: command.append('27')
    # if con: command.append('8')
    # if cross: command.append('9')

    if fg:
        command.append(str(getattr(cols, fg)[0]))

    if bg:
        command.append(str(getattr(cols, bg)[1]))

    if not command:
        command.append('0')

    return esc + sep.join(command) + end

def print_colors():
    colornames = [
        'black',
        'red',
        'green',
        'yellow',
        'blue',
        'magenta',
        'cyan',
        'white',
    ]

    print('RESET    ' + \
          'NORMAL   ' + \
          'BOLD     ' + \
          'BRIGHT   ' + \
          'FAINT    ' + \
          'REVERSE  ')
    for c in colornames:
        print('{name:9}{norm}{name:9}{rst}{bold}{name:9}{rst}{bright}{name:9}{rst}{faint}{name:9}{rst}{rev}{name:9}{rst}'.format(
            name=c,
            rst=shc(),
            norm=shc(c),
            bold=shc(c, bold=True),
            bright=shc('bright_'+c),
            faint=shc(c, faint=True),
            rev=shc(c, rev=True),
        ))

def color_bool(value):
    if value:
        return '{}{}{}'.format(GREEN, value, RESET)
    return '{}{}{}'.format(RED, value, RESET)

def ddiff(da, db, annotate=None):
    from collections import OrderedDict
    ka = set(da.keys())
    kb = set(db.keys())

    path = '[{}]'.format(annotate) if annotate else ''

    for k in ka.union(kb):
        if k not in ka:
            print('{} + {}'.format(path, k))
            continue

        if k not in kb:
            print('{} - {}'.format(path, k))
            continue

        va = da[k]
        vb = db[k]

        if type(va) != type(vb):
            if isinstance(va, (dict, OrderedDict)) and isinstance(vb, (dict, OrderedDict)):
                pass
            elif isinstance(va, str) and isinstance(vb, str):
                pass
            else:
                print('{}: MOD  {} - {}'.format(k, type(va),type(vb)))
                continue

        if isinstance(va, (tuple, list)):
            ldiff(va, vb)
            continue

        if isinstance(va, (dict, OrderedDict)):
            ddiff(va, vb, k)
            continue

        if isinstance(va, str) and isinstance(vb, str):
            from django.utils.encoding import smart_text
            va = smart_text(va)
            vb = smart_text(vb)

        if va != vb:
            print('{}: MOD  {} - {}'.format(k, va, vb))

def ldiff(la, lb, annotate=None):
    if len(la) != len(lb):
        print('{}: LEN  {} - {}'.format(annotate, len(la), len(lb)))
        return

    for i, (va, vb) in enumerate(zip(la, lb)):
        if va != vb:
            print('{} DIFF  {} - {}'.format('[{}][{}]'.format(annotate, i), va, vb))


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="Cache-Control" content="no-siteapp">
    <meta http-equiv="Cache-Control" content="no-transform">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1">
    <meta name="renderer" content="webkit">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>vue-upload-component- Upload Component - Uploader</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0-beta/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release/build/styles/atom-one-light.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/cropperjs/dist/cropper.css" rel="stylesheet" />

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Created by PhpStorm.
 * User: dashi
 * Date: 16/9/5
 * Time: 下午11:23
 */
namespace Foldy\Validators;

class JsonArrayValidator extends JsonValidator
{

    public $valueValidator;
    public $options;
    const OPTIONS_LENGTH_MIN = 'lengthMin';
    const OPTIONS_LENGTH_MAX = 'lengthMax';

    public function __construct(Validator $value_validator, array $options = [])
    {
        parent::__construct(self::TYPE_JSON_ARRAY);
        $this->valueValidator = $value_validator;
        $this->options = $options;
    }

    public function validate($value, bool &$is_validate)
    {
        $array = parent::validate($value, $is_validate);
        if (!$is_validate) {
            return null;
        }
        if (isset($this->options[self::OPTIONS_LENGTH_MIN]) && count($array) < $this->options[self::OPTIONS_LENGTH_MIN]) {
            return false;
        }
        if (isset($this->options[self::OPTIONS_LENGTH_MAX]) && count($array) >= $this->options[self::OPTIONS_LENGTH_MAX]) {
            return false;
        }

        $result = [];
        foreach ($array as $o) {
            $filtered = $this->valueValidator->validate($o, $is_validate);
            if (!$is_validate) {
                return null;
            }
            $result [] = $filtered;
        }
        return $result;
    }
}


text:
<TITLE>Review for Xiangnu xiaoxiao (1986)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Xiangnu xiaoxiao (1986)

reviewed by
Thomas E. Billings

                          A GIRL FROM HUNAN
                  A film review by Thomas E. Billings
                   Copyright 1989 Thomas E. Billings

Synopsis:
In pre-revolutionary China, a 12 year old girl is married to a 2 year old boy,
following the ancient tradition of child marriage.  Four years later the girl
is a young woman, experiencing her sexual awakening.  She has an affair and
gets pregnant.  This is very serious, for the penalty for adultery is death -
by drowning.  An interesting and surprisingly funny film.

China (English subtitles), color, 1986 (released in US: 1988), 110 minutes.
Directors: Xie Fei, U Lan

     Set in the recent past in pre-revolutionary China, this is the story of
Xiao Xiao, a young woman who is married, at age twelve, to a two year old boy.
This is the ancient tradition of (arranged) child marriage.  Both Xiao Xiao and
her husband are peasants, and live with her husband's family in a rural
village, where they are farmers.  Xiao Xiao's husband, as he grows up, refers
to her as "sister"!

     Four years later, she is maturing and awakening sexually.  Xiao Xiao's
mother-in-law is critical of her, for being lazy, and, even worse, for not
binding her feet and breasts (a common practice of the day).

     Shortly thereafter, Xiao Xiao is raped by a neighbor.  Rather than report
it, she takes the man as a lover, for it seems that she really likes sex.  Soon
she realizes that she is pregnant, and she starts gaining weight.

     The next day a couple in the village are caught in adultery.  As
punishment they injure the man and drown the woman.  This terrifies Xiao Xiao
and her lover.  Soon, her lover flees, leaving Xiao Xiao to face her fate
alone.  Is she drowned, the standard punishment for adulterous women?  What is
her fate?  See the film to find out.

     This is a very interesting film.  It illustrates some of the customs of
old China: arranged child marriages, infanticide of female infants, and the low
status of women (lower than cattle, it seems) in that society.  Although a bit
slow at times, it holds your interest very well.

     One surprising thing about this film is its humor.  I don't think any of
it is intended to be funny, but there are many times when you cannot help but
laugh.  For instance, at Xiao Xiao's wedding, her husband (being only 2 years
old) decides it's a great time to cry.  Later, Xiao Xiao's "uncle" (father-in-
law) reports seeing "girl students" on a trip to the city.  These people find
it funny and strange; what do women need education for?  Besides that, the
"girl students" are shameless, exposing their arms and part of their legs for
all to see!

     There is one quote from the film that neatly summarizes it.  At a critical
time, an older woman tells Xiao Xiao that "women are born to suffer."  This
film perfectly illustrates their suffering in old China.  It is interesting and
reasonably well made.  Overall, a very good film - definitely worth seeing.

Distribution.  No information available; suspect that you might find it
screened at repertory theaters and/or art houses.  Print Source: New Yorker
Films.

Reviewer:  Thomas E. Billings, Department of Statistics
           University of California, Berkeley
Reviewer contact:  teb@stat.Berkeley.EDU

.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
/**
 * Created by sheldon on 2016/3/21.
 */

//console.log('route中');
define(function(require, exports, module) {
    "use strict";
    module.exports = function(app) {
        app.config(['$routeProvider', '$httpProvider', '$locationProvider',
            function($routeProvider, $httpProvider, $locationProvider) {

                $locationProvider.hashPrefix('?');

                $routeProvider.
                    //Demo
                when('/phones/list', {
                    templateUrl: 'modules/demo/phone-list.html',
                    controller: 'PhoneListCtrl',
                    controllerUrl: './modules/demo/phone-controller.js'
                }).

                //login
                when('/login/fast', {
                    templateUrl: 'modules/login/loginFast.html',
                    controller: 'LoginFastCtrl',
                    controllerUrl: './modules/login/controller/loginFastCtrl.js'
                }).when('/login/password', {
                    templateUrl: 'modules/login/loginPassword.html',
                    controller: 'LoginPasswordCtrl',
                    controllerUrl: './modules/login/controller/loginPasswordCtrl.js'
                }).when('/login/telephone', {
                    templateUrl: 'modules/login/loginTelephone.html',
                    controller: 'LoginTelephoneCtrl',
                    controllerUrl: './modules/login/controller/loginTelephoneCtrl.js'
                }).when('/login/reset', {
                    templateUrl: 'modules/login/resetPassword.html',
                    controller: 'ResetPasswordCtrl',
                    controllerUrl: './modules/login/controller/resetPasswordCtrl.js'
                }).when('/login/signUp', {
                    templateUrl: 'modules/login/signUp.html',
                    controller: 'SignUpCtrl',
                    controllerUrl: './modules/login/controller/signUpCtrl.js'
                }).

                //实名认证提额
                when('/verify/index', {
                    templateUrl: 'modules/verify/index.html',
                    controller: 'VerifyIndexCtrl',
                    controllerUrl: './modules/verify/controller/verifyIndexCtrl.js'
                }).when('/verify/bank', {
                    templateUrl: 'modules/verify/bank-verify.html',
                    controller: 'VerifyBankCtrl',
                    controllerUrl: './modules/verify/controller/verifyBankCtrl.js'
                }).when('/verify/real-name', {
                    templateUrl: 'modules/verify/real-name.html',
                    controller: 'VerifyRealNameCtrl',
                    controllerUrl: './modules/verify/controller/verifyRealNameCtrl.js'
                }).when('/verify/taobao', {
                    templateUrl: 'modules/verify/taobao-verify.html',
                    controller: 'VerifyTaobaoCtrl',
                    controllerUrl: './modules/verify/controller/verifyTaobaoCtrl.js'
                }).when('/verify/fast', {
                    templateUrl: 'modules/verify/fast-verify.html',
                    controller: 'VerifyFastCtrl',
                    controllerUrl: './modules/verify/controller/verifyFastCtrl.js'
                }).when('/verify/fast-student', {
                    templateUrl: 'modules/verify/fast-verify-student.html',
                    controller: 'VerifyFastStudentCtrl',
                    controllerUrl: './modules/verify/controller/verifyFastStudentCtrl.js'
                }).when('/verify/how-to-register', {
                    templateUrl: 'modules/verify/how-to-register.html'
                }).

                //首页
                when('/index', {
                    templateUrl: 'modules/index/index.html',
                    controller: 'IndexCtrl',
                    controllerUrl: './modules/index/controller/indexCtrl.js'
                }).when('/mine/setting', {
                    templateUrl: 'modules/mine/setting.html',
                    controller: 'SettingCtrl',
                    controllerUrl: './modules/mine/controller/settingCtrl.js'
                }).

                //分类页面
                when('/categories', {
                    templateUrl: 'modules/categories/categories.html',
                    controller: 'CategoriesCtrl',
                    controllerUrl: './modules/categories/controller/categoriesCtrl.js'
                }).

                //分类页面
                when('/phones', {
                    templateUrl: 'modules/demo/phone-list.html',
                    controller: 'PhoneListCtrl',
                    controllerUrl: './modules/demo/phone-controller.js'
                }).

                //订单列表
                when('/order/list', {
                    templateUrl: 'modules/orderList/orderList.html',
                    controller: 'OrderListCtrl',
                    controllerUrl: './modules/orderList/controller/orderListCtrl.js'
                }).

                //订单详情
                when('/order/detail', {
                    templateUrl: 'modules/orderList/orderDetail.html',
                    controller: 'OrderDetailCtrl',
                    controllerUrl: './modules/orderList/controller/orderDetailCtrl.js'
                }).

                //知情同意书
                when('/order/inform', {
                    templateUrl: 'modules/orderList/orderDetailInform.html',
                    controller: 'OrderDetailInformCtrl',
                    controllerUrl: './modules/orderList/controller/orderDetailInformCtrl.js'
                }).

                //保险详情
                when('/insurance/details', {
                    templateUrl: 'modules/insurance/insurance.html',
                    controller: 'InsuranceCtrl',
                    controllerUrl: './modules/insurance/controller/insuranceCtrl.js'
                }).

                //账单模块
                when('/bill/list', {
                    templateUrl: 'modules/bill/billList.html',
                    controller: 'BillListCtrl',
                    controllerUrl: './modules/bill/controller/billListCtrl.js'
                }).when('/bill/detail', {
                    templateUrl: 'modules/bill/billDetail.html',
                    controller: 'BillDetailCtrl',
                    controllerUrl: './modules/bill/controller/billDetailCtrl.js'
                }).when('/bill/pay', {
                    templateUrl: 'modules/bill/billPay.html',
                    controller: 'BillPayCtrl',
                    controllerUrl: './modules/bill/controller/billPayCtrl.js'
                }).when('/bill/record', {
                    templateUrl: 'modules/bill/billRecord.html',
                    controller: 'BillRecordCtrl',
                    controllerUrl: './modules/bill/controller/billRecordCtrl.js'
                }).when('/bill/paySuccess', {
                    templateUrl: 'modules/bill/billPaySuccess.html',
                    controller: 'BillPaySuccessCtrl',
                    controllerUrl: './modules/bill/controller/billPaySuccessCtrl.js'
                }).when('/bill/bankCard', {
                    templateUrl: 'modules/bill/bindBankCard.html',
                    controller: 'BillBankCardCtrl',
                    controllerUrl: './modules/bill/controller/billBankCardCtrl.js'
                }).when('/bill/bindSuccess', {
                    templateUrl: 'modules/bill/bindSuccess.html',
                    controller: 'BillBankCardCtrl',
                    controllerUrl: './modules/bill/controller/billBankCardCtrl.js'
                }).when('/bill/manageBankCard', {
                    templateUrl: 'modules/bill/manageBankCard.html',
                    controller: 'BillBankCardCtrl',
                    controllerUrl: './modules/bill/controller/billBankCardCtrl.js'
                }).

                    //收藏模块
                when('/collection', {
                    templateUrl: 'modules/collection/collection.html',
                    controller: 'CollectionCtrl',
                    controllerUrl: './modules/collection/controller/collectionCtrl.js'
                }).

                //活动页面
                when('/activities', {
                    templateUrl: 'modules/activities/common/activity.html',
                    controller: 'ActivityCtrl',
                    controllerUrl: './modules/activities/common/controller/activity.js'
                }).
                when('/activities/graduation', {
                    templateUrl: 'modules/activities/graduation/graduation.html',
                    controller: 'GraduationCtrl',
                    controllerUrl: './modules/activities/graduation/controller/graduation.js'
                }).
                when('/activities/wanghong', {
                    templateUrl: 'modules/activities/wanghong/wanghong.html',
                    controller: 'WanghongCtrl',
                    controllerUrl: './modules/activities/wanghong/controller/wanghong.js'
                }).
                when('/activities/president', {
                    templateUrl: 'modules/activities/president/president.html',
                    controller: 'PresidentCtrl',
                    controllerUrl: './modules/activities/president/controller/president.js'
                }).
                when('/activities/seckilling', {
                    templateUrl: 'modules/activities/seckilling/seckilling.html',
                    controller: 'SeckillingCtrl',
                    controllerUrl: './modules/activities/seckilling/controller/seckilling.js'
                }).

                //商品列表
                when('/list', {
                    templateUrl: './modules/list/list.html',
                    controller: 'ListCtrl',
                    controllerUrl: './modules/list/controller/listCtrl.js'
                }).

                //产品详情
                when('/goods', {
                    templateUrl: './modules/goods/goods.html',
                    controller: 'GoodsCtrl',
                    controllerUrl: './modules/goods/controller/goodsCtrl.js'
                }).

                //医院自定义商品
                when('/diy/goods', {
                    templateUrl: './modules/diyGoods/diyGoods.html',
                    controller: 'DiyGoodsCtrl',
                    controllerUrl: './modules/diyGoods/controller/diyGoodsCtrl.js'
                }).

                //下订单
                when('/order', {
                    templateUrl: './modules/order/order.html',
                    controller: 'OrderCtrl',
                    controllerUrl: './modules/order/controller/orderCtrl.js'
                }).

                //精品推荐
                when('/recommend', {
                    templateUrl: 'modules/recommend/recommend.html',
                    controller: 'RecommendCtrl',
                    controllerUrl: './modules/recommend/controller/recommendCtrl.js'
                }).

                //0首付验证码
                when('/pay/allCredit', {
                    templateUrl: 'modules/pay/allCredit.html',
                    controller: 'AllCreditCtrl',
                    controllerUrl: './modules/pay/controller/allCreditCtrl.js'
                }).

                //支付首付
                when('/pay/firstPay', {
                    templateUrl: 'modules/pay/firstPay.html',
                    controller: 'FirstPayCtrl',
                    controllerUrl: './modules/pay/controller/firstPayCtrl.js'
                }).

                //保险说明静态页
                when('/insurance/introduce', {
                        templateUrl: 'modules/static/insuranceIntroduce.html'
                    }).
                    //保险条款静态页
                when('/insurance/contact', {
                        templateUrl: 'modules/static/insurance.html'
                    }).
                    //服务合同静态页
                when('/contact/service', {
                        templateUrl: 'modules/static/serviceContact.html'
                    }).
                    //借款合同静态页
                when('/contact/loan', {
                        templateUrl: 'modules/static/loanContact.html'
                    }).
                    //芝麻信用回调
                when('/zmxy/callback', {
                        templateUrl: 'modules/static/zmVerifyCallback.html',
                        controller: 'ZmVerifyCallbackCtrl',
                        controllerUrl: './modules/static/controller/zmVerifyCallbackCtrl.js'
                    }).
                    //优惠券
                when('/coupon', {
                    templateUrl: 'modules/coupon/coupon.html',
                    controller: 'CouponCtrl',
                    controllerUrl: './modules/coupon/controller/couponCtrl.js'
                }).

                //一元夺宝
                when('/treasure', {
                    templateUrl: 'modules/treasure/index.html',
                    controller: 'TreasureCtrl',
                    controllerUrl: './modules/treasure/controller/treasureCtrl.js'
                }).when('/treasure/detail', {
                    templateUrl: 'modules/treasure/detail.html',
                    controller: 'TreasureDetailCtrl',
                    controllerUrl: './modules/treasure/controller/treasureDetailCtrl.js'
                }).when('/treasure/record/detail', {
                    templateUrl: 'modules/treasure/recordDetail.html',
                    controller: 'TreasureRecordDetailCtrl',
                    controllerUrl: './modules/treasure/controller/treasureRecordDetailCtrl.js'
                }).when('/treasure/recharge', {
                    templateUrl: 'modules/treasure/recharge.html',
                    controller: 'TreasureRechargeCtrl',
                    controllerUrl: './modules/treasure/controller/treasureRechargeCtrl.js'
                }).when('/treasure/my-share', {
                    templateUrl: 'modules/treasure/myShare.html',
                    controller: 'TreasureMyShareCtrl',
                    controllerUrl: './modules/treasure/controller/treasureMyShareCtrl.js'
                }).when('/treasure/share', {
                    templateUrl: 'modules/treasure/share.html',
                    controller: 'TreasureShareCtrl',
                    controllerUrl: './modules/treasure/controller/treasureShareCtrl.js'
                }).when('/treasure/share/list', {
                    templateUrl: 'modules/treasure/shareList.html',
                    controller: 'TreasureShareListCtrl',
                    controllerUrl: './modules/treasure/controller/treasureShareListCtrl.js'
                }).when('/treasure/address', {
                    templateUrl: 'modules/treasure/address.html',
                    controller: 'TreasureAddressCtrl',
                    controllerUrl: './modules/treasure/controller/treasureAddressCtrl.js'
                }).when('/treasure/prize-record', {
                    templateUrl: 'modules/treasure/prizeRecord.html',
                    controller: 'TreasurePrizeRecordCtrl',
                    controllerUrl: './modules/treasure/controller/treasurePrizeRecordCtrl.js'
                }).when('/treasure/treasure-record', {
                    templateUrl: 'modules/treasure/treasureRecord.html',
                    controller: 'TreasureTreasureRecordCtrl',
                    controllerUrl: './modules/treasure/controller/treasureTreasureRecordCtrl.js'
                }).when('/treasure/invite', {
                    templateUrl: 'modules/treasure/invite.html',
                    controller: 'TreasureInviteCtrl',
                    controllerUrl: './modules/treasure/controller/treasureInviteCtrl.js'
                }).when('/treasure/pay-way', {
                    templateUrl: 'modules/treasure/payWay.html',
                    controller: 'TreasurePayWayCtrl',
                    controllerUrl: './modules/treasure/controller/treasurePayWayCtrl.js'
                }).

                //拼团
                when('/groupbuy/detail', {
                    templateUrl: 'modules/groupbuy/detail.html',
                    controller: 'GroupBuyDetailCtrl',
                    controllerUrl: './modules/groupbuy/controller/groupBuyDetailCtrl.js'
                }).when('/groupbuy/list', {
                    templateUrl: 'modules/groupbuy/list.html',
                    controller: 'GroupBuyListCtrl',
                    controllerUrl: './modules/groupbuy/controller/groupBuyListCtrl.js'
                }).when('/groupbuy/mine', {
                    templateUrl: 'modules/groupbuy/mine.html',
                    controller: 'GroupBuyMineCtrl',
                    controllerUrl: './modules/groupbuy/controller/groupBuyMineCtrl.js'
                }).when('/groupbuy/join', {
                    templateUrl: 'modules/groupbuy/join.html',
                    controller: 'GroupBuyJoinCtrl',
                    controllerUrl: './modules/groupbuy/controller/groupBuyJoinCtrl.js'
                }).when('/groupbuy/pay', {
                    templateUrl: 'modules/groupbuy/pay.html',
                    controller: 'GroupBuyPayCtrl',
                    controllerUrl: './modules/groupbuy/controller/groupBuyPayCtrl.js'
                }).

                //首页
                when('/', {
                    templateUrl: 'modules/app/app.html',
                    controller: 'AppCtrl',
                    controllerUrl: './modules/app/controller/appCtrl.js'
                }).

                //默认首页
                otherwise({
                    redirectTo: '/'
                });
                //$locationProvider.html5Mode(true);

                // Use x-www-form-urlencoded Content-Type
                $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

                /**
                 * The workhorse; converts an object to x-www-form-urlencoded serialization.
                 * @param {Object} obj
                 * @return {String}
                 */
                var param = function(obj) {
                    var query = '',
                        name, value, fullSubName, subName, subValue, innerObj, i;

                    for (name in obj) {
                        value = obj[name];

                        if (value instanceof Array) {
                            for (i = 0; i < value.length; ++i) {
                                subValue = value[i];
                                fullSubName = name + '[' + i + ']';
                                innerObj = {};
                                innerObj[fullSubName] = subValue;
                                query += param(innerObj) + '&';
                            }
                        } else if (value instanceof Object) {
                            for (subName in value) {
                                subValue = value[subName];
                                fullSubName = name + '[' + subName + ']';
                                innerObj = {};
                                innerObj[fullSubName] = subValue;
                                query += param(innerObj) + '&';
                            }
                        } else if (value !== undefined && value !== null)
                            query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
                    }

                    return query.length ? query.substr(0, query.length - 1) : query;
                };

                // Override $http service's default transformRequest
                $httpProvider.defaults.transformRequest = [function(data) {
                    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
                }];

            }
        ]);
    }

});


text:
A class based utility library for building modular and scalable web platform applications. Features opt-in classes and utilities which provide a solid foundation and toolset to build your next project.

Developers accustomed to ActionScript will immediately find themselves at home.

## Documentation
* [Documentation](http://codebelt.github.io/StructureJS/docs/)

## Install

With [Node.js](http://nodejs.org):

    $ npm install structure-js

With [Bower](http://bower.io):

    $ bower install structurejs

## IDE Snippets
* [Webstorm JS](https://github.com/codebelt/StructureJS/tree/master/ide-snippets/webstorm/js)
* [Webstorm TS](https://github.com/codebelt/StructureJS/tree/master/ide-snippets/webstorm/ts)
* [Sublime](https://github.com/codebelt/StructureJS/tree/master/ide-snippets/sublimetext)
* [Atom](https://github.com/codebelt/StructureJS/tree/master/ide-snippets/atom)

## Boilerplate
[StructureJS Boilerplate (Babel - ES6)](https://github.com/codeBelt/StructureJS-Boilerplate/tree/babel)

[StructureJS Boilerplate (TypeScript - ES6 Modules)](https://github.com/codeBelt/StructureJS-Boilerplate/tree/typescript-es6)

[StructureJS Boilerplate (TypeScript - CommonJS Modules)](https://github.com/codeBelt/StructureJS-Boilerplate/tree/typescript-commonjs)

[StructureJS Boilerplate (Browserify - ES5)](https://github.com/codeBelt/StructureJS-Boilerplate/tree/browserify)

[StructureJS Boilerplate (RequireJS - ES5)](https://github.com/codeBelt/StructureJS-Boilerplate/tree/requirejs)

## Examples
* Event Bubbling [Demo](http://codebelt.github.io/StructureJS/examples/EventBubbling/web/) [Code](https://github.com/codeBelt/StructureJS/tree/master/examples/EventBubbling)
* Movie Collection [Demo](http://codebelt.github.io/StructureJS/examples/MovieCollection/web/) [Code](https://github.com/codeBelt/StructureJS/tree/master/examples/MovieCollection)
* Single Page Application [Demo](http://codebelt.github.io/StructureJS/examples/SinglePageWebsite/web/) [Code](https://github.com/codeBelt/StructureJS/tree/master/examples/SinglePageWebsite)
* TodoMVC [Demo](http://codebelt.github.io/StructureJS/examples/TodoMVC/web/) [Code](https://github.com/codeBelt/StructureJS/tree/master/examples/TodoMVC)
* Simon Game [Demo](http://codebelt.github.io/StructureJS/examples/SimonGame/web/) [Code](https://github.com/codeBelt/StructureJS/tree/master/examples/SimonGame)

## Core Classes

### `DOMElement`

All view classes will extend the `DOMElement` class. Here is an example how you would setup your main application class.

```js
import FooView from './views/FooView';
import BarView from './views/BarView';
import ExampleView from './views/ExampleView';

class App extends DOMElement {

    _exampleView = null;

    constructor() {
        super()
    }

    create() {
        super.create();

        // single instance of a component
        const $exampleView = this.$element.find('#js-ExampleView');

		this._exampleView = new ExampleView($exampleView);
		this.addChild(this._exampleView);

		// multiple instances of a component
		this.createComponents([
			{ selector: '.js-FooView', component: FooView },
			{ selector: '.js-BarView', component: BarView }
		]);
    }

}

export default App;
```

To start the application you would use ```appendTo``` method on the main application class to attach it to the DOM. Only use ```appendTo``` once per application. After that you will use the ```addChild``` methed for child views like in the above example. Example of using ```appendTo```:

```js
const app = new App();
app.appendTo('body');
```

`DOMElement` provides helper methods and adds the following lifecycle to your class, these methods get called in this order:
* `create()`
* `enable()`
* `layout()`

```js
class ExampleView extends DOMElement {

    constructor($element) {
        super($element);
    }

    create() {
        super.create();
        // Create or setup child objects in this parent class.
    }

    enable() {
        if (this.isEnabled === true) { return; }
        // Add any event listeners and/or enable the child objects.
        super.enable();
    }

    disable() {
        if (this.isEnabled === false) { return; }
        // Remove any event listeners and/or disable the child objects.
        super.disable();
    }

    layout() {
        // Layout or update the objects in this parent class.
    }

    destroy() {
        this.disable();
        // Call destroy on any child objects.
        // This super method will also null out your properties for garbage collection.
        super.destroy();
    }

}

export default ExampleView;
```

[Example `DOMElement` View](https://github.com/codeBelt/StructureJS/blob/master/examples/MovieCollection/src/assets/scripts/views/ListView.js)

[Read more about `DOMElement`](http://codebelt.github.io/StructureJS/docs/classes/DOMElement.html)

### `EventDispatcher`

A base event bus class for managing prioritized queues of event listeners and dispatched events.

```js
this.dispatchEvent('change');

// Send data object with the event:
this.dispatchEvent('change', { some: 'data' });

// Example with an event object
// (event type, bubbling set to true, cancelable set to true, and passing data)
let event = new BaseEvent(BaseEvent.CHANGE, true, true, { some: 'data' });
this.dispatchEvent(event);

// Dispatching an inline event object
this.dispatchEvent(new BaseEvent(BaseEvent.CHANGE));
```

[Read more about `EventDispatcher`](http://codebelt.github.io/StructureJS/docs/classes/EventDispatcher.html)

[Read more about `BaseEvent`](http://codebelt.github.io/StructureJS/docs/classes/BaseEvent.html)

### `EventBroker`

A pub/sub static class for dispatching and listening for events.

```js
EventBroker.addEventListener('change', this._handlerMethod, this);

// Using a constant event type
EventBroker.addEventListener(BaseEvent.CHANGE, this._handlerMethod, this);

// Event passed to the method will always be a BaseEvent object.
_handlerMethod(event) {
     console.log(event);
}
```

[Read more about `EventBroker`](http://codebelt.github.io/StructureJS/docs/classes/EventBroker.html)

[Read more about `BaseEvent`](http://codebelt.github.io/StructureJS/docs/classes/BaseEvent.html)

### `Router`

A static class for managing route patterns for single page applications.

* {required}
* :optional:
* \* (all)

```js
// A route listener with an event handler
Router.add('/games/{gameName}/:level:/', this._onRouteHandler, this);
Router.start();

// The above route would match the string below:
// '/games/asteroids/2/'

// The Call back receives a RouterEvent object.
_onRouteHandler(routerEvent) {
    console.log(routerEvent.params);
}
```
[Example `Router`](https://github.com/codeBelt/StructureJS/blob/master/examples/SinglePageWebsite/assets/scripts/view/RootView.js)

[Read more about `Router`](http://codebelt.github.io/StructureJS/docs/classes/Router.html)

[Read more about `Route`](http://codebelt.github.io/StructureJS/docs/classes/Route.html)

[Read more about `RouteEvent`](http://codebelt.github.io/StructureJS/docs/classes/RouterEvent.html)

### `jQueryEventListener`

Similar to the `.on()` & `.off()` jQuery methods, this plugin allows you to bind your function calls and assign them to a property on the class avoiding something like setupHandlers or bindAll methods.

* eventType
* delegation (optional)
* eventHandler
* scope

```js
enable() {
    if (this.isEnabled === true) { return; }

    this.$element.addEventListener('click', this._onClickHandler, this);
    this.$element.addEventListener('click', 'button', this._onClickHandler, this); // event delegation

    super.enable();
}

disable() {
    if (this.isEnabled === false) { return; }

    this.$element.removeEventListener('click', this._onClickHandler, this);
    this.$element.removeEventListener('click', 'button', this._onClickHandler, this);

    super.disable();
}

_onClickHandler(event) {
    console.log('click', event);
}
```

[Read more about `jQueryEventListener`](https://github.com/codeBelt/jquery-eventListener)

## Release History

 * 2017-02-15 v0.15.4 BaseModel - remove logic that was cloning children BaseModel's.

 * 2017-02-08 v0.15.3 BaseModel - Wasn't really fixed. Now it is fixed. Fingers crossed!

 * 2017-02-08 v0.15.2 BaseModel - Fixed issue with arrays having the same data for every item in the array when instantiated directly on the property. Fixed issue with child models not actually being cloned into new objects when .clone() is called on the parent model.

 * 2017-01-19 v0.15.1 Add missing Interface *.d.ts files.

 * 2017-01-19 v0.15.0 Add *.d.ts files and update TypeScript compiler version.

 * 2016-12-27 v0.14.9 Fix TypeScript file issues.

 * 2016-12-16 v0.14.8 Util - Fix issue with deletePropertyFromObject.

 * 2016-12-15 v0.14.7 BaseModel - Add the ability to pass options in as a second parameter. Supports { expand: true } so nested base model class will be instantiated instead of nulled out.

 * 2016-11-18 v0.14.6 BaseModel - Fix issue with properties having a function as it data.

 * 2016-10-26 v0.14.5 ValidationUtil - Update isValidEmailAddress regex. BrowserUtil - fix issue with event listener name.

 * 2016-10-26 v0.14.4 MerchantUtil - Update getCreditCardProvider method to work with only a few numbers.

 * 2016-10-26 v0.14.3 LocalStorageService - add an in memory fallback if window.localStorage is not available.

 * 2016-10-06 v0.14.2 EventDispatcher - add printEventListeners method and now getEventListeners returns the object of event listeners.

 * 2016-09-26 v0.14.1 LocalStorageService - rename method names.

 * 2016-09-17 v0.14.0 StringUtil - added toQueryString. Router - remove _toQueryString and fix buildRoute to remove extra back slashes.

 * 2016-09-16 v0.13.3 StringUtil - fix toSentence issue with grouped numbers. LocalStorageService - Allow namespace to be set in the constructor and add removeItemsWithNamespace method.

 * 2016-08-26 v0.13.2 Fix Router class where on load it would not navigate to the proper history route.

 * 2016-08-26 v0.13.1 Fix npm index class path issues.

 * 2016-08-26 v0.13.0 Rename ApplicationCacheController to ApplicationCacheService and move to service directory. Rename LocalStorageController to LocalStorageService and move to service directory. Move Router to service directory.

 * 2016-08-20 v0.12.8 Router - Add Router to npm index file.

 * 2016-08-19 v0.12.7 Router - Add HTML History API to the Router Class.

 * 2016-07-13 v0.12.6 BaseModel - Fix EventDispatcher.dispatchEvent issue Needed to cache current listener objects to prevent the edge case were another listener is added during the dispatch loop.

 * 2016-06-24 v0.12.5 BaseModel - fix issue if object was passed in with messing property and the property was assigned a BaseModel class it would keep reference to the class. Now it sets it to null.
                      Router - validate method to allow validation checks before the Router class triggers the next route.
                      LocalStorageController - Add example comments.

 * 2016-05-17 v0.12.4 Remove break; to stop TypeScript warning in ApplicationCacheController.getStatus method. Fix issue with Router.buildRoute method putting '/' in front of '?'. Rename snippet extensions.

 * 2016-05-11 v0.12.3 Remove jquery import and make it global for the eventListener plugin.

 * 2016-05-11 v0.12.2 Allow passing of arguments to the layout method. Fix Router.getCurrentRoute being null right after callback.

 * 2016-04-23 v0.12.0 Deprecated Stage class and the appendTo method. Copied the appendTo method to the DOMElement class.

 * 2016-02-29 v0.11.1 Update Router.buildRoute to turn an object passed in to query string.

 * 2016-02-06 v0.11.0 Prevent Collection.add from allowing null and undefined. Remove onEnabled and onDisabled methods.

 * 2016-01-22 v0.10.5 Change examples and IDE snippets back to the show the enable and disable way rather than the onEnabled or onDisabled way.

 * 2016-01-19 v0.10.4 Add maxConnections to BulkLoader to set the maximum number of simultaneous connections.

 * 2016-01-06 v0.10.3 Add onEnabled and onDisabled methods. Removed enable and disable methods from Examples and IDE Snippets.

 * 2015-12-30 v0.10.2 Publishing to NPM https://www.npmjs.com/package/structure-js

 * 2015-12-30 v0.10.1 EventDispatcher - Fix currentTarget when event is bubbling. Update IDE Snippets.

 * 2015-12-21 v0.10.0 Change TypeScript from CommonJS to ES6 modules.

 * 2015-12-20 v0.9.3 Add third optional parameter to EventBroker so you can pass the scope of the object that dispatched the event. Update EventDispatcher to always update the currentTarget property. Add EventBroker.waitFor, EventBroker.waitForOnce, EventBroker.removeWaitFor. Collection.get() remove clamping if index is out of bounds.

 * 2015-12-05 v0.9.2 Allow a custom indicator with StringUtil.truncate(). Update ide-snippets. Made the start method private in NetworkMonitor.

 * 2015-11-25 v0.9.1 Add Router.getCurrentRoute, Add Util.unique, Fix BrowserUtil.getBrowser and make public. Update docs to ES6/Typescript. Rename all private and protected method to have an underscore in front.

 * 2015-10-24 v0.9.0 Remove unnecessary classes. DisplayObject - rename update to renderCanvas. Util - add applyMixins static method. Updated BulkLoader and created BulkLoaderEvent. Update interface files.

 * 2015-10-03 v0.8.0 Rename ValueObject to BaseModel and update all classes using it. Added addEventListenerOnce to EventDispatcher and EventBroker. Fixed Collection assign it a type in the constructor causes issues if data was already that type.

 * 2015-09-04 v0.7.9 Remove Util.getClassName, Util.getFunctionName and add Util.getName. Fix issue with getQualifiedClassName now working when code was uglified (Now need to have mangle set as false). Remove jQuery dependency from TemplateFactory. Change private methods and properties to protected.

 * 2015-08-22 v0.7.8 Fix issue with disable not being called when the destroy method is called on a DisplayObject. Add import for DisplayObjectContainer on CanvasElement. Allow ComponentFactory.create to be called multiple times with the same selector names and not overwrite active components. Update addClientSideId and add removeClientSideId. Add BulkLoader, ImageLoader ...

 * 2015-07-20 v0.7.7 Fixed ValueObject - Allow data passed in that is an array to get assigned to the property even if it is not of type of an array. Fix for phone number validation.

 * 2015-06-23 v0.7.6 DOMElement createComponents rename componentClass to component.

 * 2015-06-18 v0.7.5 Add groupBy method on Collection. Change ValidationUtil.isPostalCode to be case insensitive.

 * 2015-06-10 v0.7.4 Add pluck method to Collection. Move removeChild destroy functionality from DisplayObjectContainer to DOMElement.

 * 2015-05-26 v0.7.3 Corrects string replacement on getBreakpoint

 * 2015-05-21 v0.7.2 Add showHours flag to NumberUtil.convertToHHMMSS to display as 00:05:23 or 05:23

 * 2015-05-12 v0.7.1 DOMElement have createComponents return the list of children it created. Fix small bugs. Update comments. Add some unit tests.

 * 2015-04-26 v0.7.0 Breaking changes: Rename createChildren to create. Rename layoutChildren to layout. Create DisplayObject class and have DisplayObjectContainer extend it. Add Canvas specific classes. Rename namespace StructureTS to StructureJS in TypeScript files. Change namespace from structurejs to StructureJS in JavaScript classes. Rename folder src to js.

 * 2015-04-15 v0.6.17 Previous version before I started doing this release history.


text: Yeoman Generator em desenvolvimento.


text:
<?php

namespace Drupal\block_content\Form;

use Drupal\Core\Entity\EntityDeleteForm;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a confirmation form for deleting a custom block type entity.
 *
 * @internal
 */
class BlockContentTypeDeleteForm extends EntityDeleteForm {

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $blocks = $this->entityTypeManager->getStorage('block_content')->getQuery()
      ->condition('type', $this->entity->id())
      ->execute();
    if (!empty($blocks)) {
      $caption = '<p>' . $this->formatPlural(count($blocks), '%label is used by 1 custom block on your site. You can not remove this block type until you have removed all of the %label blocks.', '%label is used by @count custom blocks on your site. You may not remove %label until you have removed all of the %label custom blocks.', ['%label' => $this->entity->label()]) . '</p>';
      $form['description'] = ['#markup' => $caption];
      return $form;
    }
    else {
      return parent::buildForm($form, $form_state);
    }
  }

}


text:
package org.sosy_lab.java_smt.solvers.cvc4;

import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import de.uni_freiburg.informatik.ultimate.logic.PrintTerm;
import edu.stanford.CVC4.Expr;
import edu.stanford.CVC4.ExprManager;
import edu.stanford.CVC4.Type;
import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedHashMap;
import java.util.Map;
import org.sosy_lab.common.Appender;
import org.sosy_lab.common.Appenders;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.basicimpl.AbstractFormulaManager;

class CVC4FormulaManager extends AbstractFormulaManager<Expr, Type, ExprManager, Expr> {

  private final CVC4FormulaCreator creator;

  @SuppressWarnings("checkstyle:parameternumber")
  CVC4FormulaManager(
      CVC4FormulaCreator pFormulaCreator,
      CVC4UFManager pFfmgr,
      CVC4BooleanFormulaManager pBfmgr,
      CVC4IntegerFormulaManager pIfmgr,
      CVC4RationalFormulaManager pRfmgr,
      CVC4BitvectorFormulaManager pBvfmgr,
      CVC4FloatingPointFormulaManager pFpfmgr,
      CVC4QuantifiedFormulaManager pQfmgr,
      CVC4ArrayFormulaManager pAfmgr,
      CVC4SLFormulaManager pSLfmgr,
      CVC4StringFormulaManager pStrmgr) {
    super(
        pFormulaCreator,
        pFfmgr,
        pBfmgr,
        pIfmgr,
        pRfmgr,
        pBvfmgr,
        pFpfmgr,
        pQfmgr,
        pAfmgr,
        pSLfmgr,
        pStrmgr);
    creator = pFormulaCreator;
  }

  static Expr getCVC4Expr(Formula pT) {
    if (pT instanceof CVC4Formula) {
      return ((CVC4Formula) pT).getTerm();
    }
    throw new IllegalArgumentException(
        "Cannot get the formula info of type " + pT.getClass().getSimpleName() + " in the Solver!");
  }

  @Override
  public BooleanFormula parse(String pS) throws IllegalArgumentException {
    throw new UnsupportedOperationException();
  }

  @Override
  public Appender dumpFormula(Expr f) {
    assert getFormulaCreator().getFormulaType(f) == FormulaType.BooleanType
        : "Only BooleanFormulas may be dumped";

    return new Appenders.AbstractAppender() {

      @Override
      public void appendTo(Appendable out) throws IOException {

        // get all symbols
        final Map<String, Expr> allVars = new LinkedHashMap<>();
        creator.extractVariablesAndUFs(f, true, allVars::put);

        // print all symbols
        for (Map.Entry<String, Expr> entry : allVars.entrySet()) {
          String name = entry.getKey();
          Expr var = entry.getValue();

          // escaping is stolen from SMTInterpol, lets hope this remains consistent
          out.append("(declare-fun ").append(PrintTerm.quoteIdentifier(name)).append(" (");

          // add function parameters
          Iterable<Type> childrenTypes = Iterables.transform(var, Expr::getType);
          out.append(Joiner.on(" ").join(childrenTypes));

          // and return type
          out.append(") ").append(var.getType().toString()).append(")\n");
        }

        // now add the final assert
        out.append("(assert ");
        // f.toString() does expand all nested sub-expressions and causes exponential overhead.
        // f.toStream() uses LET-expressions and is exactly what we want.
        try (OutputStream stream =
            new OutputStream() {

              @Override
              public void write(int chr) throws IOException {
                out.append((char) chr);
              }
            }) {
          f.toStream(stream);
        }
        out.append(')');
      }
    };
  }
}


text:
package org.apache.fineract.infrastructure.core.exceptionmapper;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.apache.fineract.infrastructure.core.data.ApiGlobalErrorResponse;
import org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * An {@link ExceptionMapper} to map {@link PlatformApiDataValidationException}
 * thrown by platform into a HTTP API friendly format.
 *
 * The {@link PlatformApiDataValidationException} is typically thrown in data
 * validation of the parameters passed in with an api request.
 */
@Provider
@Component
@Scope("singleton")
public class PlatformApiDataValidationExceptionMapper implements ExceptionMapper<PlatformApiDataValidationException> {

    @Override
    public Response toResponse(final PlatformApiDataValidationException exception) {

        final ApiGlobalErrorResponse dataValidationErrorResponse = ApiGlobalErrorResponse.badClientRequest(
                exception.getGlobalisationMessageCode(), exception.getDefaultUserMessage(), exception.getErrors());

        return Response.status(Status.BAD_REQUEST).entity(dataValidationErrorResponse).type(MediaType.APPLICATION_JSON).build();
    }
}


text:
<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "{{%comment}}".
 *
 * @property integer $id
 * @property string $author
 * @property string $email
 * @property string $content
 * @property integer $status
 */
class Comment extends \yii\db\ActiveRecord
{

    public static function tableName()
    {
        return '{{%comment}}';
    }

    public function rules()
    {
        return [
            [['author', 'email', 'content', 'comment_post', 'status'], 'required'],
            [['content'], 'string'],
            [['status','comment_post', 'created_at'], 'integer'],
            [['author', 'email'], 'string', 'max' => 255],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'author' => 'Автор',
            'email' => 'Email',
            'content' => 'Комментарий',
            'comment_post' => 'Заголовок',
            'created_at' => 'Создан',
            'status' => 'Статус',
        ];
    }
    public function behaviors()
    {
        return [
            [
                'class' => 'yii\behaviors\TimestampBehavior',
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
                ],
            ],
        ];
    }

    public function getPost()
    {
        return $this->hasOne(Post::className(), ['id' => 'comment_post']); //id - ключ. comment_post - значения.
    }

}


text:
package spaceinvaders.command;

import com.google.gson.JsonSyntaxException;
import spaceinvaders.exceptions.CommandNotFoundException;

/**
 * Used to convert JSON data into {@link spaceinvaders.command.Command}.
 *
 * @see spaceinvaders.command.CommandBuilder
 */
public class CommandDirector {
  private final CommandBuilder builder;

  /**
   * Constrct a director that uses the {@code builder} to make commands.
   *
   * @throws NullPointerException if builder is {@code null}.
   */
  public CommandDirector(CommandBuilder builder) {
    if (builder == null) {
      throw new NullPointerException();
    }
    this.builder = builder;
  }

  /**
   * Convert the {@code json} into a {@link spaceinvaders.command.Command}.
   *
   * @throws JsonSyntaxException if the specified JSON is invalid.
   * @throws CommandNotFoundException if the command could not be recognized.
   * @throws NullPointerException if argument is {@code null}.
   */
  public void makeCommand(String json) throws JsonSyntaxException, CommandNotFoundException {
    if (json == null) {
      throw new NullPointerException();
    }
    builder.buildCommand(json);
  }

  /**
   * Get the last succesfully built command.
   *
   * @return last command, or {@code null} if there was no such command.
   */
  public Command getCommand() {
    return builder.getCommand();
  }
}


text:
"""
This is the App Engine Console auto-executing module.  When you start a console session, it will
execute "from autoexec import *".  So you may place anything in here which you find useful.
"""

# Examples:  Uncomment these if you want them in your console by default.
#
#from google.appengine.ext import db
#from google.appengine.api import users
#import logging

# This allows you to run help(...) just like the standard console has.
import site
help = site._Helper()
del site


text: Trying to create Flask App that will dynamically generate and render a plot in PNG format


text:
from django import template
register = template.Library()

def paginator(context, adjacent_pages=2):
    """
    To be used in conjunction with the object_list generic view.

    Adds pagination context variables for use in displaying first, adjacent and
    last page links in addition to those created by the object_list generic
    view.

    """
    startPage = max(context['page'].number - adjacent_pages, 1)
    if startPage <= 3: startPage = 1
    endPage = context['page'].number + adjacent_pages + 1
    if endPage >= context['page'].paginator.num_pages - 1: endPage = context['page'].paginator.num_pages + 1
    page_numbers = [n for n in range(startPage, endPage) \
            if n > 0 and n <= context['page'].paginator.num_pages]
    page = context['page']
    paginator = context['page'].paginator
    context.dicts[0]['page_numbers'] = page_numbers
    context.dicts[0]['page_current'] = context['page'].number
    context.dicts[0]['pages'] = context['page'].paginator.num_pages
    context.dicts[0]['page_numbers'] = page_numbers
    context.dicts[0]['page_current'] = context['page'].number
    context.dicts[0]['next'] = context['page'].next_page_number
    context.dicts[0]['previous'] = context['page'].previous_page_number
    context.dicts[0]['has_next'] = context['page'].has_next
    context.dicts[0]['has_previous'] = context['page'].has_previous
    context.dicts[0]['show_first'] = 1 not in page_numbers
    context.dicts[0]['show_last'] = context['page'].paginator.num_pages not in page_numbers
    return ''

register.simple_tag(takes_context=True)(paginator)


text:
require('dotenv').load();
var environment = 'development';
var config = require('../knexfile')[environment];
var knex = require('knex')(config);
module.exports = knex;


text:
sap.ui.define([
	"sap/ui/core/sample/common/Helper",
	"sap/ui/test/opaQunit"
], function (Helper, opaTest) {
	"use strict";

	Helper.qUnitModule("sap.ui.core.internal.samples.odata.v2.SalesOrders - ODataListBinding#create"
		+ ": Test Case 3: Create new sales orders with inline creation rows");

	//*****************************************************************************
	opaTest("Test Case 3: Create new sales orders with inline creation rows",
		function (Given, When, Then) {
			Given.iStartMyUIComponent({
				componentConfig : {
					name : "sap.ui.core.internal.samples.odata.v2.SalesOrders",
					settings : {inlineCreationRows : 1}
				}
			});

			// Start the sales orders application with 1 inline creation row
			// Step 1 - start application with inlineCreationRows=1
			// Step 2
			When.onMainPage.pressUseTableButton();
			Then.onMainPage.checkSalesOrderAtRow(0, "", "", "", "Inactive");
			Then.onMainPage.checkSalesOrderAtRow(1, "205", "SAP", "Inline Creation Rows 205",
				"From Server");
			// Step 3
			When.onMainPage.rememberSalesOrdersCount();
			Then.onMainPage.checkSalesOrdersTableLengthDiffersBy(1);

			// Edit inactive rows
			// Step 1
			When.onMainPage.changeSalesOrderNoteOfRow(0, "A");
			Then.onMainPage.checkSalesOrderAtRow(0, "", "", "A", "Transient");
			Then.onMainPage.checkSalesOrderAtRow(1, "", "", "", "Inactive");
			Then.onMainPage.checkSalesOrderAtRow(2, "205", "SAP", "Inline Creation Rows 205",
				"From Server");
			Then.onMainPage.checkSalesOrdersCountChangedBy(1);
			Then.onMainPage.checkSalesOrdersTableLengthDiffersBy(1);
			// Step 2
			When.onMainPage.changeSalesOrderNoteOfRow(1, "B");
			Then.onMainPage.checkSalesOrderAtRow(0, "", "", "A", "Transient");
			Then.onMainPage.checkSalesOrderAtRow(1, "", "", "B", "Transient");
			Then.onMainPage.checkSalesOrderAtRow(2, "", "", "", "Inactive");
			Then.onMainPage.checkSalesOrderAtRow(3, "205", "SAP", "Inline Creation Rows 205",
				"From Server");
			Then.onMainPage.checkSalesOrdersCountChangedBy(1);
			Then.onMainPage.checkSalesOrdersTableLengthDiffersBy(1);

			// Reset changes removes only transient entries
			// Step 1
			When.onMainPage.pressResetChangesButton();
			Then.onMainPage.checkSalesOrderAtRow(0, "", "", "", "Inactive");
			Then.onMainPage.checkSalesOrderAtRow(1, "205", "SAP", "Inline Creation Rows 205",
				"From Server");
			Then.onMainPage.checkSalesOrdersCountChangedBy(-2);
			Then.onMainPage.checkSalesOrdersTableLengthDiffersBy(1);

			// Modify inactive entry in the object page
			// Step 1
			When.onMainPage.selectSalesOrderAtRow(0);
			Then.onMainPage.checkSalesOrderItemsTableIsEmpty();
			// Step 2
			When.onMainPage.changeSalesOrderNoteOnObjectPage("C");
			Then.onMainPage.checkSalesOrderAtRow(0, "", "", "C", "Transient");
			Then.onMainPage.checkSalesOrderAtRow(1, "", "", "", "Inactive");
			Then.onMainPage.checkSalesOrderAtRow(2, "205", "SAP", "Inline Creation Rows 205",
				"From Server");
			Then.onMainPage.checkSalesOrdersCountChangedBy(1);
			Then.onMainPage.checkSalesOrdersTableLengthDiffersBy(1);
			// Step 3
			When.onMainPage.selectSalesOrderAtRow(1);
			Then.onMainPage.checkSalesOrderItemsTableIsEmpty();
			// Step 4
			When.onMainPage.pressSalesOrderSaveButton();
			Then.onMainPage.checkSalesOrderAtRow(0, "240", "SAP", "C", "Persisted");
			Then.onMainPage.checkSalesOrderAtRow(1, "", "", "", "Inactive");
			// Step 5
			When.onMainPage.changeSalesOrderNoteOfRow(1, "D");
			Then.onMainPage.checkSalesOrderAtRow(0, "240", "SAP", "C", "Persisted");
			Then.onMainPage.checkSalesOrderAtRow(1, "", "", "D", "Transient");
			Then.onMainPage.checkSalesOrderAtRow(2, "", "", "", "Inactive");
			Then.onMainPage.checkSalesOrderAtRow(3, "205", "SAP", "Inline Creation Rows 205",
				"From Server");
			Then.onMainPage.checkSalesOrdersCountChangedBy(1);
			Then.onMainPage.checkSalesOrdersTableLengthDiffersBy(1);

			// Empty sales order items table for inactive and transient sales orders
			// Step 1
			When.onMainPage.selectSalesOrderAtRow(2);
			Then.onMainPage.checkSalesOrderItemsTableIsEmpty();
			// Step 2
			When.onMainPage.selectSalesOrderAtRow(1);
			Then.onMainPage.checkSalesOrderItemsTableIsEmpty();
			// Step 3
			When.onMainPage.selectSalesOrderAtRow(3);
			Then.onMainPage.checkItemAtRow(0, {
				Currency : "EUR",
				GrossAmount : "1,137.64",
				ItemPosition : "010",
				Note : "Item 010",
				ProductID : "HT-1000",
				Quantity : "1",
				SalesOrderID : "205",
				Status : "From Server"
			});
			Then.onMainPage.checkItemAtRow(1, {
				Currency : "",
				GrossAmount : "",
				ItemPosition : "",
				Note : "",
				ProductID : "",
				Quantity : "",
				SalesOrderID : "205",
				Status : "Inactive",
				Unit : ""
			});
			// Step 4
			When.onMainPage.selectSalesOrderAtRow(0);
			Then.onMainPage.checkItemAtRow(0, {
				Currency : "",
				GrossAmount : "",
				ItemPosition : "",
				Note : "",
				ProductID : "",
				Quantity : "",
				SalesOrderID : "240",
				Status : "Inactive",
				Unit : ""
			});

			Given.iTeardownMyApp();
		});
});


text:
@(account: Account)(title: String)(content: Html)

<!DOCTYPE html>

        <title>@title</title>
        <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")">

        logout

        @content


text:
from django.db.models import Q
from rest_framework import generics, permissions as drf_permissions
from rest_framework.exceptions import NotFound

from api.actions.serializers import SchemaResponseActionSerializer
from api.base import permissions as base_permissions
from api.base.exceptions import Conflict
from api.base.filters import ListFilterMixin
from api.base.parsers import (
    JSONSchemaParser,
    JSONAPIParser,
    JSONAPIMultipleRelationshipsParser,
    JSONAPIMultipleRelationshipsParserForRegularJSON,
)
from api.base.utils import get_object_or_error
from api.base.views import JSONAPIBaseView
from api.schema_responses import annotations
from api.schema_responses.permissions import (
    SchemaResponseDetailPermission,
    SchemaResponseListPermission,
    SchemaResponseActionDetailPermission,
    SchemaResponseActionListPermission,
)
from api.schema_responses.schemas import create_schema_response_payload
from api.schema_responses.serializers import (
    RegistrationSchemaResponseSerializer,
)

from framework.auth.oauth_scopes import CoreScopes

from osf.exceptions import SchemaResponseStateError
from osf.models import SchemaResponse, SchemaResponseAction, Registration
from osf.utils.workflows import ApprovalStates

class SchemaResponseList(JSONAPIBaseView, ListFilterMixin, generics.ListCreateAPIView):
    permission_classes = (
        SchemaResponseListPermission,
        drf_permissions.IsAuthenticatedOrReadOnly,
        base_permissions.TokenHasScope,
    )

    required_read_scopes = [CoreScopes.READ_SCHEMA_RESPONSES]
    required_write_scopes = [CoreScopes.WRITE_SCHEMA_RESPONSES]

    parser_classes = (JSONAPIParser, JSONSchemaParser)

    serializer_class = RegistrationSchemaResponseSerializer
    view_category = 'schema_responses'
    view_name = 'schema-responses-list'
    create_payload_schema = create_schema_response_payload

    def get_queryset(self):
        '''Retrieve the list of SchemaResponses visible to the user.

        This should be the union of all APPROVED SchemaResponses on Public registrations
        and all SchemaResponses for registrations on which the caller is a contributor
        (excluding any SchemaResponses on WITHDRAWN or deleted registrations).
        '''
        user = self.request.user
        return SchemaResponse.objects.annotate(
            user_is_contributor=annotations.user_is_contributor(user),
            parent_is_public=annotations.PARENT_IS_PUBLIC,
        ).exclude(
            Q(parent_is_public__isnull=True),  # Withdrawn or deleted parent, always exclude
        ).filter(
            Q(user_is_contributor=True) |
            (Q(parent_is_public=True) & Q(reviews_state=ApprovalStates.APPROVED.db_name)),
        ).annotate(
            is_pending_current_user_approval=annotations.is_pending_current_user_approval(user),
            is_original_response=annotations.IS_ORIGINAL_RESPONSE,
        )

    def get_parser_context(self, http_request):
        """
        Tells parser what json schema we are checking againest.
        """
        res = super().get_parser_context(http_request)
        res['json_schema'] = self.create_payload_schema
        return res

class SchemaResponseDetail(JSONAPIBaseView, generics.RetrieveUpdateDestroyAPIView):

    permission_classes = (
        SchemaResponseDetailPermission,
        drf_permissions.IsAuthenticatedOrReadOnly,
        base_permissions.TokenHasScope,
    )

    required_read_scopes = [CoreScopes.READ_SCHEMA_RESPONSES]
    required_write_scopes = [CoreScopes.WRITE_SCHEMA_RESPONSES]

    view_category = 'schema_responses'
    view_name = 'schema-responses-detail'

    def get_serializer_class(self):
        parent = self.get_object().parent

        if isinstance(parent, Registration):
            return RegistrationSchemaResponseSerializer
        else:
            raise NotImplementedError()

    def get_object(self):
        user = self.request.user
        annotated_schema_response = SchemaResponse.objects.filter(
            _id=self.kwargs['schema_response_id'],
        ).annotate(
            is_pending_current_user_approval=annotations.is_pending_current_user_approval(user),
            is_original_response=annotations.IS_ORIGINAL_RESPONSE,
        )

        try:
            return annotated_schema_response.get()
        except SchemaResponse.DoesNotExist:
            raise NotFound

    def perform_destroy(self, instance):
        try:
            instance.delete()
        except SchemaResponseStateError as e:
            raise Conflict(str(e))

class SchemaResponseActionList(JSONAPIBaseView, ListFilterMixin, generics.ListCreateAPIView):
    permission_classes = (
        SchemaResponseActionListPermission,
        drf_permissions.IsAuthenticatedOrReadOnly,
        base_permissions.TokenHasScope,
    )

    required_read_scopes = [CoreScopes.READ_SCHEMA_RESPONSES]
    required_write_scopes = [CoreScopes.WRITE_SCHEMA_RESPONSES]

    parser_classes = (JSONAPIMultipleRelationshipsParser, JSONAPIMultipleRelationshipsParserForRegularJSON)

    view_category = 'schema_responses'
    view_name = 'schema-response-action-list'
    serializer_class = SchemaResponseActionSerializer

    def get_queryset(self):
        return self.get_object().actions.all().order_by('created')

    def get_object(self):
        return get_object_or_error(
            model_or_qs=SchemaResponse,
            query_or_pk=self.kwargs['schema_response_id'],
            request=self.request,
            check_deleted=False,
        )

class SchemaResponseActionDetail(JSONAPIBaseView, generics.RetrieveAPIView):
    permission_classes = (
        SchemaResponseActionDetailPermission,
        drf_permissions.IsAuthenticatedOrReadOnly,
        base_permissions.TokenHasScope,
    )

    required_read_scopes = [CoreScopes.READ_SCHEMA_RESPONSES]
    required_write_scopes = [CoreScopes.WRITE_SCHEMA_RESPONSES]

    view_category = 'schema_responses'
    view_name = 'schema-responses-detail'

    serializer_class = SchemaResponseActionSerializer

    def get_object(self):
        return get_object_or_error(
            SchemaResponseAction,
            query_or_pk=self.kwargs['schema_response_action_id'],
            request=self.request,
        )


text:
import { VALIDATE_UPDATE } from '../const'
import util, { empty, each, trigger, isPromise, toggleClasses } from '../util'

/**
 * BaseValidation class
 */

export default class BaseValidation {

  constructor (field, model, vm, el, scope, validator, filters, detectBlur, detectChange) {
    this.field = field
    this.touched = false
    this.dirty = false
    this.modified = false

    this._modified = false
    this._model = model
    this._filters = filters
    this._validator = validator
    this._vm = vm
    this._el = el
    this._forScope = scope
    this._init = this._getValue(el)
    this._validators = {}
    this._detectBlur = detectBlur
    this._detectChange = detectChange
    this._classes = {}
  }

  get vm () { return this._vm }

  get el () { return this._el }

  get detectChange () { return this._detectChange }
  set detectChange (val) { this._detectChange = val }

  get detectBlur () { return this._detectBlur }
  set detectBlur (val) { this._detectBlur = val }

  manageElement (el, initial) {
    const scope = this._getScope()
    const model = this._model

    this._initial = initial

    const classIds = el.getAttribute(VALIDATE_UPDATE)
    if (classIds) {
      el.removeAttribute(VALIDATE_UPDATE)
      this._classIds = classIds.split(',')
    }

    if (model) {
      el.value = this._evalModel(model, this._filters)
      this._unwatch = scope.$watch(model, (val, old) => {
        if (val !== old) {
          if (this.guardValidate(el, 'input')) {
            return
          }

          this.handleValidate(el, { noopable: this._initial })
          if (this._initial) {
            this._initial = null
          }
        }
      }, { deep: true })
    }
  }

  unmanageElement (el) {
    this._unwatch && this._unwatch()
  }

  setValidation (name, arg, msg, initial) {
    let validator = this._validators[name]
    if (!validator) {
      validator = this._validators[name] = {}
      validator.name = name
    }

    validator.arg = arg
    if (msg) {
      validator.msg = msg
    }

    if (initial) {
      validator.initial = initial
      validator._isNoopable = true
    }
  }

  setValidationClasses (classes) {
    each(classes, (value, key) => {
      this._classes[key] = value
    })
  }

  willUpdateFlags (touched = false) {
    touched && this.willUpdateTouched(this._el, 'blur')
    this.willUpdateDirty(this._el)
    this.willUpdateModified(this._el)
  }

  willUpdateTouched (el, type) {
    if (type && type === 'blur') {
      this.touched = true
      this._fireEvent(el, 'touched')
    }
  }

  willUpdateDirty (el) {
    if (!this.dirty && this._checkModified(el)) {
      this.dirty = true
      this._fireEvent(el, 'dirty')
    }
  }

  willUpdateModified (el) {
    this.modified = this._checkModified(el)
    if (this._modified !== this.modified) {
      this._fireEvent(el, 'modified', { modified: this.modified })
      this._modified = this.modified
    }
  }

  listener (e) {
    if (this.guardValidate(e.target, e.type)) {
      return
    }

    this.handleValidate(e.target, { type: e.type })
  }

  handleValidate (el, { type = null, noopable = false } = {}) {
    this.willUpdateTouched(el, type)
    this.willUpdateDirty(el)
    this.willUpdateModified(el)

    this._validator.validate({ field: this.field, el: el, noopable: noopable })
  }

  validate (cb, noopable = false, el = null) {
    const _ = util.Vue.util

    let results = {}
    let errors = []
    let valid = true

    this._runValidators((descriptor, name, done) => {
      let asset = this._resolveValidator(name)
      let validator = null
      let msg = null

      if (_.isPlainObject(asset)) {
        if (asset.check && typeof asset.check === 'function') {
          validator = asset.check
        }
        if (asset.message) {
          msg = asset.message
        }
      } else if (typeof asset === 'function') {
        validator = asset
      }

      if (descriptor.msg) {
        msg = descriptor.msg
      }

      if (noopable) {
        results[name] = false
        return done()
      }

      if (descriptor._isNoopable) {
        results[name] = false
        descriptor._isNoopable = null
        return done()
      }

      if (validator) {
        let value = this._getValue(this._el)
        this._invokeValidator(this._vm, validator, value, descriptor.arg, (ret, err) => {
          if (!ret) {
            valid = false
            if (err) { // async error message
              errors.push({ validator: name, message: err })
              results[name] = err
            } else if (msg) {
              let error = { validator: name }
              error.message = typeof msg === 'function'
                ? msg.call(this._vm, this.field, descriptor.arg)
                : msg
              errors.push(error)
              results[name] = error.message
            } else {
              results[name] = !ret
            }
          } else {
            results[name] = !ret
          }

          done()
        })
      } else {
        done()
      }
    }, () => { // finished
      this._fireEvent(this._el, valid ? 'valid' : 'invalid')

      let props = {
        valid: valid,
        invalid: !valid,
        touched: this.touched,
        untouched: !this.touched,
        dirty: this.dirty,
        pristine: !this.dirty,
        modified: this.modified
      }
      if (!empty(errors)) {
        props.errors = errors
      }
      _.extend(results, props)

      this.willUpdateClasses(results, el)

      cb(results)
    })
  }

  resetFlags () {
    this.touched = false
    this.dirty = false
    this.modified = false
    this._modified = false
  }

  reset () {
    each(this._validators, (descriptor, key) => {
      if (descriptor.initial && !descriptor._isNoopable) {
        descriptor._isNoopable = true
      }
    })
    this.resetFlags()
    this._init = this._getValue(this._el)
  }

  willUpdateClasses (results, el = null) {
    if (this._checkClassIds(el)) {
      const classIds = this._getClassIds(el)
      this.vm.$nextTick(() => {
        this.vm.$emit(VALIDATE_UPDATE, classIds, this, results)
      })
    } else {
      this.updateClasses(results)
    }
  }

  updateClasses (results, el = null) {
    this._updateClasses(el || this._el, results)
  }

  guardValidate (el, type) {
    if (type && type === 'blur' && !this.detectBlur) {
      return true
    }

    if (type && type === 'input' && !this.detectChange) {
      return true
    }

    if (type && type === 'change' && !this.detectChange) {
      return true
    }

    if (type && type === 'click' && !this.detectChange) {
      return true
    }

    return false
  }

  _getValue (el) {
    return el.value
  }

  _getScope () {
    return this._forScope || this._vm
  }

  _getClassIds (el) {
    return this._classIds
  }

  _checkModified (target) {
    return this._init !== this._getValue(target)
  }

  _checkClassIds (el) {
    return this._getClassIds(el)
  }

  _fireEvent (el, type, args) {
    trigger(el, type, args)
  }

  _evalModel (model, filters) {
    const scope = this._getScope()

    let val = null
    if (filters) {
      val = scope.$get(model)
      return filters ? this._applyFilters(val, null, filters) : val
    } else {
      val = scope.$get(model)
      return val === undefined || val === null ? '' : val
    }
  }

  _updateClasses (el, results) {
    this._toggleValid(el, results.valid)
    this._toggleTouched(el, results.touched)
    this._togglePristine(el, results.pristine)
    this._toggleModfied(el, results.modified)
  }

  _toggleValid (el, valid) {
    const { addClass, removeClass } = util.Vue.util
    const validClass = this._classes.valid || 'valid'
    const invalidClass = this._classes.invalid || 'invalid'

    if (valid) {
      toggleClasses(el, validClass, addClass)
      toggleClasses(el, invalidClass, removeClass)
    } else {
      toggleClasses(el, validClass, removeClass)
      toggleClasses(el, invalidClass, addClass)
    }
  }

  _toggleTouched (el, touched) {
    const { addClass, removeClass } = util.Vue.util
    const touchedClass = this._classes.touched || 'touched'
    const untouchedClass = this._classes.untouched || 'untouched'

    if (touched) {
      toggleClasses(el, touchedClass, addClass)
      toggleClasses(el, untouchedClass, removeClass)
    } else {
      toggleClasses(el, touchedClass, removeClass)
      toggleClasses(el, untouchedClass, addClass)
    }
  }

  _togglePristine (el, pristine) {
    const { addClass, removeClass } = util.Vue.util
    const pristineClass = this._classes.pristine || 'pristine'
    const dirtyClass = this._classes.dirty || 'dirty'

    if (pristine) {
      toggleClasses(el, pristineClass, addClass)
      toggleClasses(el, dirtyClass, removeClass)
    } else {
      toggleClasses(el, pristineClass, removeClass)
      toggleClasses(el, dirtyClass, addClass)
    }
  }

  _toggleModfied (el, modified) {
    const { addClass, removeClass } = util.Vue.util
    const modifiedClass = this._classes.modified || 'modified'

    if (modified) {
      toggleClasses(el, modifiedClass, addClass)
    } else {
      toggleClasses(el, modifiedClass, removeClass)
    }
  }

  _applyFilters (value, oldValue, filters, write) {
    const resolveAsset = util.Vue.util.resolveAsset
    const scope = this._getScope()

    let filter, fn, args, arg, offset, i, l, j, k
    for (i = 0, l = filters.length; i < l; i++) {
      filter = filters[i]
      fn = resolveAsset(this._vm.$options, 'filters', filter.name)
      if (!fn) { continue }

      fn = write ? fn.write : (fn.read || fn)
      if (typeof fn !== 'function') { continue }

      args = write ? [value, oldValue] : [value]
      offset = write ? 2 : 1
      if (filter.args) {
        for (j = 0, k = filter.args.length; j < k; j++) {
          arg = filter.args[j]
          args[j + offset] = arg.dynamic ? scope.$get(arg.value) : arg.value
        }
      }

      value = fn.apply(this._vm, args)
    }

    return value
  }

  _runValidators (fn, cb) {
    const validators = this._validators
    const length = Object.keys(validators).length

    let count = 0
    each(validators, (descriptor, name) => {
      fn(descriptor, name, () => {
        ++count
        count >= length && cb()
      })
    })
  }

  _invokeValidator (vm, validator, val, arg, cb) {
    let future = validator.call(this, val, arg)
    if (typeof future === 'function') { // function
      future(() => { // resolve
        cb(true)
      }, (msg) => { // reject
        cb(false, msg)
      })
    } else if (isPromise(future)) { // promise
      future.then(() => { // resolve
        cb(true)
      }, (msg) => { // reject
        cb(false, msg)
      }).catch((err) => {
        cb(false, err.message)
      })
    } else { // sync
      cb(future)
    }
  }

  _resolveValidator (name) {
    const resolveAsset = util.Vue.util.resolveAsset
    return resolveAsset(this._vm.$options, 'validators', name)
  }
}


text:
__author__ = 'Robin Quetin, Shamal Faily'

import logging
import os
import sys
if (sys.version_info > (3,)):
  import http.client
else:
  import httplib
from flask import Flask
from flask_security import Security, SQLAlchemyUserDatastore
from flask_cors import CORS
from cairis.core.Borg import Borg
from cairis.daemon.WebConfig import *
from .cdb import db
from .models import User, Role

def create_app():
  options = {
    'port' : 0,
    'unitTesting': False
  }
  WebConfig.config(options)

  b = Borg()
  app = Flask(__name__)
  app.config['DEBUG'] = True
  app.config['SECRET_KEY'] = b.secretKey
  app.config['SECURITY_PASSWORD_HASH'] = b.passwordHash
  app.config['SECURITY_PASSWORD_SALT'] = b.passwordSalt
  app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:' + b.rPasswd + '@' + b.dbHost + '/cairis_user'
  b.logger.setLevel(b.logLevel)
  b.logger.debug('Error handlers: {0}'.format(app.error_handler_spec))
  app.secret_key = os.urandom(24)
  logger = logging.getLogger('werkzeug')
  logger.setLevel(b.logLevel)
  enable_debug = b.logLevel = logging.DEBUG

  cors = CORS(app)
  db.init_app(app)
  user_datastore = SQLAlchemyUserDatastore(db,User, Role)
  security = Security(app, user_datastore)

  from .main import main as main_blueprint
  app.register_blueprint(main_blueprint)

  with app.app_context():
    db.create_all()
  return app


text:
(function() {
  var hasInputBox, matchFilter, matchNumber, matchText, setupFilters, setupTable, updateFilters, updateTable, zip;

  hasInputBox = function(elem) {
    return $(elem).children('input').length > 0;
  };

  zip = function(a, b) {
    var i, results;
    i = 0;
    results = [];
    while (i < a.length) {
      results.push([a[i], b[i]]);
      i++;
    }
    return results;
  };

  setupFilters = function() {
    return $('table[filterable-table]').each(function(i, table) {
      return setupTable(table);
    });
  };

  setupTable = function(t) {
    $(t).find('thead').append('

');
    $(t).find('thead tr[filterable-header-row] th').each(function(i, elem) {
      if ($(elem).is('[filterable-column]')) {
        return $(t).find('thead tr[filterable-column-inputs]').append('<input filterable-logic=\'' + $(elem).attr('filterable-logic') + '\'></input>	');
      } else {
        return $(t).find('thead tr[filterable-column-inputs]').append('	');
      }
    });
    return $('table[filterable-table] thead tr th input').change(function() {
      return updateFilters();
    });
  };

  updateFilters = function() {
    return $('table[filterable-table]').each(function(i, table) {
      return updateTable(table);
    });
  };

  updateTable = function(table) {
    var cellsWithPatterns, patterns;
    cellsWithPatterns = $(table).find('thead tr[filterable-column-inputs] th');
    patterns = cellsWithPatterns.map(function(idx, cell) {
      if (hasInputBox(cell)) {
        return {
          pattern: $(cell).children('input').val(),
          logic: $(cell).children('input').attr('filterable-logic')
        };
      } else {
        return {
          pattern: null,
          logic: null
        };
      }
    });
    patterns = patterns.toArray();
    $(table).find('tbody tr').show();
    return $(table).find('tbody tr').each(function(j, row) {
      var filterMatches, i, results1, values;
      values = $(row).find('td').map(function(i, x) {
        return $(x).text();
      });
      filterMatches = zip(patterns, values).map(function(x) {
        return matchFilter(x[0], x[1]);
      });
      i = 0;
      results1 = [];
      while (i < filterMatches.length) {
        if (!filterMatches[i]) {
          $(row).hide();
        }
        results1.push(i++);
      }
      return results1;
    });
  };

  matchText = function(pattern, value) {
    return value.toLowerCase().includes(pattern.toLowerCase());
  };

  matchNumber = function(pattern, value) {
    value = value.replace(",", "");
    if (/^\d/.test(pattern)) {
      return value.includes(pattern);
    }
    return eval(value + pattern);
  };

  matchFilter = function(filter, value) {
    var logic, pattern;
    pattern = filter['pattern'];
    logic = filter['logic'];
    if ((logic === null) || (pattern.length === 0)) {
      return true;
    }
    if (logic === 'text') {
      return matchText(pattern, value);
    } else if (logic === 'numeric') {
      return matchNumber(pattern, value);
    }
    return true;
  };

  $(document).ready(setupFilters);

}).call(this);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

    class Task03EnglishNameOfLastDigit
    {
        static void Main(string[] args)
        {

        long number = long.Parse(Console.ReadLine());

        string numberInLetters = FindTheLastDigitInLetters(number);

        Console.WriteLine(numberInLetters);
        }

    private static string FindTheLastDigitInLetters(long number)
    {
        long lastDigit = long.Parse(number.ToString().Last().ToString());

        switch (lastDigit)
        {
            case 0:
                {
                    return "zero";
                    break;
                }
            case 1:
                {
                    return "one";
                    break;
                }
            case 2:
                {
                    return "two";
                    break;
                }
            case 3:
                {
                    return "three";
                    break;
                }
            case 4:
                {
                    return "four";
                    break;
                }
            case 5:
                {
                    return "five";
                    break;
                }
            case 6:
                {
                    return "six";
                    break;
                }
            case 7:
                {
                    return "seven";
                    break;
                }
            case 8:
                {
                    return "eight";
                    break;
                }
            case 9:
                {
                    return "nine";
                    break;
                }

            default:
                return string.Empty;
                break;
        }
    }
}


text:
layout: post
status: publish
published: true
title: Data Dude
author:
  display_name: Tomas Restrepo
  login: tomasr
  email: tomas@winterdom.com
  url: http://winterdom.com/
author_login: tomasr
author_email: tomas@winterdom.com
author_url: http://winterdom.com/
wordpress_id: 116
wordpress_url: http://winterdom.com/2007/08/datadude
date: '2007-08-06 18:32:00 +0000'
date_gmt: '2007-08-06 18:32:00 +0000'
categories:
- ".NET"
- Tools
tags: []
comments: []
---

I've been using a bit today some of the tools in Visual Studio 2005 Team Edition for Database Professionals today, and I gotta say, some of the features of the product are quite useful. Now I know why Jeff was always so enthusiastic about it :-). The schema comparison tool is quite useful, for example.

That said, I admit I was a bit baffled at first about how to get started with it; a few things aren't quite as intuitive as one could hope for.

Technorati tags: Visual Studio