text:
using System;
using System.Collections.Generic;
using System.Linq;
using DotVVM.Framework.Binding;
using DotVVM.Framework.Compilation.Parser.Dothtml.Parser;
using DotVVM.Framework.Compilation.Parser.Dothtml.Tokenizer;
using DotVVM.Framework.Controls;
using DotVVM.Framework.Tools.SeleniumGenerator.Helpers;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using DotVVM.Framework.Tools.SeleniumGenerator.Modifications;

namespace DotVVM.Framework.Tools.SeleniumGenerator
{
    public abstract class SeleniumGenerator<TControl> : ISeleniumGenerator where TControl : DotvvmBindableObject
    {
        /// <summary>
        /// Gets a list of properties that can be used to determine the control name.
        /// </summary>
        public abstract DotvvmProperty[] NameProperties { get; }

        /// <summary>
        /// Gets a value indicating whether the content of the control can be used to generate the control name.
        /// </summary>
        public abstract bool CanUseControlContentForName { get; }

        public Type ControlType => typeof(TControl);

        /// <summary>
        /// Gets a list of declarations emitted by the control.
        /// </summary>
        public void AddDeclarations(PageObjectDefinition pageObject, SeleniumGeneratorContext context)
        {
            string propertyName;

            var htmlName = SelectorStringHelper.TryGetNameFromProperty(context.Control, UITests.NameProperty);
            if (htmlName == null)
            {
                // determine the name
                propertyName = DetermineName(pageObject, context);
            }
            else
            {
                propertyName = htmlName;
            }

            // normalize name
            var normalizedName = SelectorStringHelper.RemoveNonIdentifierCharacters(propertyName);
            // make the name unique
            var uniqueName = MakePropertyNameUnique(context.UsedNames, normalizedName);

            context.UsedNames.Add(uniqueName);
            context.UniqueName = uniqueName;

            // determine the selector
            if (htmlName == null)
            {
                context.Selector = uniqueName;
                AddUITestNameProperty(pageObject, context, uniqueName);
            }
            else
            {
                context.Selector = htmlName;
            }

            context.UsedNames.Add(propertyName);

            AddDeclarationsCore(pageObject, context);
        }

        internal string MakePropertyNameUnique(ICollection<string> usedNames, string selector)
        {
            if (usedNames.Contains(selector))
            {
                var index = 1;
                while (usedNames.Contains(selector + index))
                {
                    index++;
                }

                selector += index;
            }

            return selector;
        }

        public virtual bool CanAddDeclarations(PageObjectDefinition pageObject, SeleniumGeneratorContext context)
        {
            return true;
        }

        private void AddUITestNameProperty(PageObjectDefinition pageObject, SeleniumGeneratorContext context, string uniqueName)
        {
            // find end of the tag
            var token = context.Control.DothtmlNode.Tokens.First(t => t.Type == DothtmlTokenType.CloseTag || t.Type == DothtmlTokenType.Slash);
            if (!pageObject.MarkupFileModifications.OfType<UITestNameMarkupFileInsertText>().Any())
            {
                pageObject.MarkupFileModifications.Add(new UITestNameMarkupFileInsertText() {
                    UniqueName = uniqueName,
                    Position = token.StartPosition
                });
            }

        }

        protected virtual string DetermineName(PageObjectDefinition pageObject, SeleniumGeneratorContext context)
        {
            // if selector is set, just read it and don't add data context prefixes
            //var shouldAddDataContextPrefixes = uniqueName == null;
            var shouldAddDataContextPrefixes = true;

            // if not found, use the name properties to determine the name

            string uniqueName = null;
            foreach (var nameProperty in NameProperties)
            {
                uniqueName = SelectorStringHelper.TryGetNameFromProperty(context.Control, nameProperty);
                if (uniqueName != null)
                {
                    uniqueName = SelectorStringHelper.NormalizeUniqueName(uniqueName);
                    break;
                }
            }

            // if not found, try to use the content of the control to determine the name
            if (uniqueName == null && CanUseControlContentForName)
            {
                uniqueName = SelectorStringHelper.GetTextFromContent(context.Control.Content);
            }

            // check if control is userControl and assign control's name as unique name
            if (uniqueName == null && context.Control.DothtmlNode is DothtmlElementNode htmlNode)
            {
                uniqueName = htmlNode.TagName;

                // not add DataContext when generating page object for user control
                shouldAddDataContextPrefixes = false;
            }

            // if not found, use control name
            if (uniqueName == null)
            {
                uniqueName = typeof(TControl).Name;
            }

            if (shouldAddDataContextPrefixes)
            {
                uniqueName = SelectorStringHelper.AddDataContextPrefixesToName(pageObject.DataContextPrefixes, uniqueName);
            }

            return uniqueName;
        }

        protected void AddPageObjectProperties(PageObjectDefinition pageObject, SeleniumGeneratorContext context, string type)
        {
            pageObject.Members.Add(GeneratePropertyForProxy(context.UniqueName, type));
            pageObject.ConstructorStatements.Add(GenerateInitializerForProxy(context, type));
        }

        protected void AddGenericPageObjectProperties(PageObjectDefinition pageObject,
            SeleniumGeneratorContext context,
            string type,
            string itemHelperName)
        {
            pageObject.Members.Add(GeneratePropertyForProxy(context.UniqueName, type, itemHelperName));
            pageObject.ConstructorStatements.Add(GenerateInitializerForProxy(context, type, itemHelperName));
        }

        protected void AddControlPageObjectProperty(PageObjectDefinition pageObject, SeleniumGeneratorContext context, string type)
        {
            pageObject.Members.Add(GeneratePropertyForProxy(context.UniqueName, type));
            pageObject.ConstructorStatements.Add(GenerateInitializerForControl(context.UniqueName, context.Selector, type));
        }

        protected MemberDeclarationSyntax GeneratePropertyForProxy(string uniqueName, string typeName, params string[] genericTypeNames)
        {
            return SyntaxFactory.PropertyDeclaration(
                    RoslynHelper.ParseTypeName(typeName, genericTypeNames),
                    uniqueName
                )
                .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
                .AddAccessorListAccessors(
                    SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                        .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
                );
        }

        protected StatementSyntax GenerateInitializerForProxy(SeleniumGeneratorContext context, string typeName, params string[] genericTypeNames)
        {
            return SyntaxFactory.ExpressionStatement(
                SyntaxFactory.AssignmentExpression(
                    SyntaxKind.SimpleAssignmentExpression,
                    SyntaxFactory.IdentifierName(context.UniqueName),
                    SyntaxFactory.ObjectCreationExpression(RoslynHelper.ParseTypeName(typeName, genericTypeNames))
                        .WithArgumentList(
                            SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new[]
                            {
                                SyntaxFactory.Argument(SyntaxFactory.ThisExpression()),
                                SyntaxFactory.Argument(RoslynHelper.GetPathSelectorObjectInitialization(context.Selector))
                            }))
                        )
                )
            );
        }

        protected StatementSyntax GenerateInitializerForControl(string propertyName, string selector, string typeName)
        {
            return SyntaxFactory.ExpressionStatement(
                SyntaxFactory.AssignmentExpression(
                    SyntaxKind.SimpleAssignmentExpression,
                    SyntaxFactory.IdentifierName(propertyName),
                    SyntaxFactory.ObjectCreationExpression(SyntaxFactory.ParseTypeName(typeName))
                        .WithArgumentList(SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new[]
                        {
                            SyntaxFactory.Argument(SyntaxFactory.IdentifierName("webDriver")),
                            SyntaxFactory.Argument(SyntaxFactory.ThisExpression()),
                            SyntaxFactory.Argument(RoslynHelper.GetPathSelectorObjectInitialization(selector))
                        })))
                )
            );
        }

        protected StatementSyntax GenerateInitializerForTemplate(string propertyName, string typeName)
        {
            return SyntaxFactory.ExpressionStatement(
                SyntaxFactory.AssignmentExpression(
                    SyntaxKind.SimpleAssignmentExpression,
                    SyntaxFactory.IdentifierName(propertyName),
                    SyntaxFactory.ObjectCreationExpression(SyntaxFactory.ParseTypeName(typeName))
                        .WithArgumentList(SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new[]
                        {
                            SyntaxFactory.Argument(SyntaxFactory.IdentifierName("webDriver")),
                            SyntaxFactory.Argument(SyntaxFactory.ThisExpression()),
                            SyntaxFactory.Argument(SyntaxFactory.IdentifierName("parentSelector"))
                        })))
                )
            );
        }

        protected abstract void AddDeclarationsCore(PageObjectDefinition pageObject, SeleniumGeneratorContext context);

    }
}


text:
"Tests for the `btclib.script.taproot` module."

import json
from os import path

import pytest

from btclib.ecc.curve import mult
from btclib.exceptions import BTClibValueError
from btclib.script.script import serialize
from btclib.script.script_pub_key import is_p2tr, type_and_payload
from btclib.script.taproot import (
    check_output_pubkey,
    input_script_sig,
    output_prvkey,
    output_pubkey,
)
from btclib.script.witness import Witness
from btclib.tx.tx_out import TxOut

def test_valid_script_path() -> None:
    fname = "tapscript_test_vector.json"
    filename = path.join(path.dirname(__file__), "_data", fname)
    with open(filename, "r", encoding="ascii") as file_:
        data = json.load(file_)

    for x in data:

        prevouts = [TxOut.parse(prevout) for prevout in x["prevouts"]]
        index = x["index"]

        if not is_p2tr(prevouts[index].script_pub_key.script):
            continue

        script_sig = x["success"]["scriptSig"]
        assert not script_sig

        witness = Witness(x["success"]["witness"])
        if len(witness.stack) >= 2 and witness.stack[-1][0] == 0x50:
            witness.stack = witness.stack[:-1]

        # check script paths
        if len(witness.stack) < 2:
            continue

        Q = type_and_payload(prevouts[index].script_pub_key.script)[1]

        script = witness.stack[-2]
        control = witness.stack[-1]

        assert check_output_pubkey(Q, script, control)

def test_taproot_key_tweaking() -> None:
    prvkey = 123456
    pubkey = mult(prvkey)

    script_trees = [
        None,
        [(0xC0, ["OP_1"])],
        [[(0xC0, ["OP_2"])], [(0xC0, ["OP_3"])]],
    ]

    for script_tree in script_trees:
        tweaked_prvkey = output_prvkey(prvkey, script_tree)
        tweaked_pubkey = output_pubkey(pubkey, script_tree)[0]

        assert tweaked_pubkey == mult(tweaked_prvkey)[0].to_bytes(32, "big")

def test_invalid_control_block() -> None:

    err_msg = "Control block too long"
    with pytest.raises(BTClibValueError, match=err_msg):
        check_output_pubkey(b"\x00" * 32, b"\x00", b"\x00" * 4130)

    err_msg = "Invalid control block length"
    with pytest.raises(BTClibValueError, match=err_msg):
        check_output_pubkey(b"\x00" * 32, b"\x00", b"\x00" * 100)

def test_unspendable_script() -> None:
    err_msg = "Missing data"
    with pytest.raises(BTClibValueError, match=err_msg):
        output_pubkey()

def test_control_block() -> None:

    script_tree = [[(0xC0, ["OP_2"])], [(0xC0, ["OP_3"])]]
    pubkey = output_pubkey(None, script_tree)[0]
    script, control = input_script_sig(None, script_tree, 0)
    assert check_output_pubkey(pubkey, serialize(script), control)

    prvkey = 123456
    internal_pubkey = mult(prvkey)
    script_tree = [[(0xC0, ["OP_2"])], [(0xC0, ["OP_3"])]]
    pubkey = output_pubkey(internal_pubkey, script_tree)[0]
    script, control = input_script_sig(internal_pubkey, script_tree, 0)
    assert check_output_pubkey(pubkey, serialize(script), control)

redpajama_set_name: RedPajamaGithub


text:
declare module 'timezonecomplete' {
    import basics = require("__timezonecomplete/basics");
    export import TimeUnit = basics.TimeUnit;
}

declare module '__timezonecomplete/basics' {
    export enum TimeUnit {
        Second = 0,
        Minute = 1,
        Hour = 2,
        Day = 3,
        Week = 4,
        Month = 5,
        Year = 6,
    }
}

//// [externalModuleReferenceDoubleUnderscore1.js]


text:
{% if page.author %}
  {% assign author = site.data.authors[page.author] %}{% else %}{% assign author = site.owner %}
{% endif %}

  {% if author.avatar %}

  {% endif %}

    {{ author.name | downcase }}
    {{ author.bio }}

        {% for page in site.pages %} {% if page.title %}

          {{ page.title }}{% unless forloop.last %} /{% endunless %}

        {% endif %} {% endfor %}

    {% include social-links.html %}


text:
from horizon.test.settings import *  # noqa: F403,H303
from openstack_dashboard.test.settings import *  # noqa: F403,H303

INSTALLED_APPS = list(INSTALLED_APPS)
INSTALLED_APPS.append('senlin_dashboard.cluster')

# NOTE(shu-mutou): For Django-based panels. This should be remove when
# deprecated Django-based panels are removed.
ANGULAR_FEATURES.update({
    'profiles_panel': False,
    'nodes_panel': False,
    'clusters_panel': False,
    'policies_panel': False,
    'receivers_panel': False
})


text:
ReflectionObject::isInstance() - invalid params
--FILE--
<?php
class X {}
$instance = new X;
$ro = new ReflectionObject(new X);

var_dump($ro->isInstance());
var_dump($ro->isInstance($instance, $instance));
var_dump($ro->isInstance(1));
var_dump($ro->isInstance(1.5));
var_dump($ro->isInstance(true));
var_dump($ro->isInstance('X'));
var_dump($ro->isInstance(null));

?>
--EXPECTF--
Warning: ReflectionClass::isInstance() expects exactly 1 parameter, 0 given in %s on line 6
NULL

Warning: ReflectionClass::isInstance() expects exactly 1 parameter, 2 given in %s on line 7
NULL

Warning: ReflectionClass::isInstance() expects parameter 1 to be object, integer given in %s on line 8
NULL

Warning: ReflectionClass::isInstance() expects parameter 1 to be object, double given in %s on line 9
NULL

Warning: ReflectionClass::isInstance() expects parameter 1 to be object, boolean given in %s on line 10
NULL

Warning: ReflectionClass::isInstance() expects parameter 1 to be object, string given in %s on line 11
NULL

Warning: ReflectionClass::isInstance() expects parameter 1 to be object, null given in %s on line 12
NULL


text:
<resources>
    <string name="app_name">3D打印姬</string>
    <string name="title_activity_main">首页</string>

    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>

    <string name="action_settings">设置</string>
    <string name="ok">确定</string>
    <string name="cancel">取消</string>

    <string name="bottom_nav_favorite">收藏</string>
    <string name="bottom_nav_model">模型</string>
    <string name="bottom_nav_print">打印</string>

    <!-- Show STL -->
    <string name="stl_load_progress_message">请等一会.</string>
    <string name="stl_load_progress_title">STL 文件加载中…</string>
    <string name="error_fetch_data">STL 文件解析失败.</string>
    <string name="error_outbig"> 文件过大,解析失败!</string>
    <string name="close_dialog">关闭对话框</string>
    <string name="parent_directory">父目录</string>
    <string name="choose_stl_file">选择STL文件</string>

    <!-- toggle button -->
    <string name="toggleButtonMove">移动</string>
    <string name="toggleButtonRotate">旋转</string>

    <!-- Strings related to Settings -->
    <string name="title_activity_settings">设置</string>
    <string name="default_cache">256</string>
    <string name="version_name">1.0.0</string>

</resources>


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>PacketTypeFilter (smack-core 4.2.0-beta3-SNAPSHOT API)</title>
<meta name="date" content="2016-08-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.jivesoftware.smack.filter

Class PacketTypeFilter

java.lang.Object

org.jivesoftware.smack.filter.PacketTypeFilter

All Implemented Interfaces:

StanzaFilter

Deprecated.

use StanzaTypeFilter instead.

@Deprecated
public class PacketTypeFilter
extends java.lang.Object
implements StanzaFilter

Filters for packets of a particular type. The type is given as a Class object, so
 example types would:

<tt>Message.class</tt>

<tt>IQ.class</tt>

<tt>Presence.class</tt>

Field Summary

Fields

Modifier and Type
Field and Description

static PacketTypeFilter
MESSAGE

Deprecated.

static PacketTypeFilter
PRESENCE

Deprecated.

Constructor Summary

Constructors

Constructor and Description

PacketTypeFilter(java.lang.Class<? extends Stanza> packetType)

Deprecated.

Creates a new stanza(/packet) type filter that will filter for packets that are the
 same type as <tt>packetType</tt>.

Method Summary

All Methods Instance Methods Concrete Methods Deprecated Methods

Modifier and Type
Method and Description

boolean
accept(Stanza packet)

Deprecated.

Tests whether or not the specified stanza should pass the filter.

java.lang.String
toString()

Deprecated.

Methods inherited from class java.lang.Object

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

Field Detail

PRESENCE

public static final PacketTypeFilter PRESENCE

Deprecated.

MESSAGE

public static final PacketTypeFilter MESSAGE

Deprecated.

Constructor Detail

PacketTypeFilter

public PacketTypeFilter(java.lang.Class<? extends Stanza> packetType)

Deprecated.

Creates a new stanza(/packet) type filter that will filter for packets that are the
 same type as <tt>packetType</tt>.

Parameters:

packetType - the Class type.

Method Detail

accept

public boolean accept(Stanza packet)

Deprecated.

Description copied from interface: StanzaFilter

Tests whether or not the specified stanza should pass the filter.

Specified by:

accept in interface StanzaFilter

Parameters:

packet - the stanza(/packet) to test.

Returns:

true if and only if <tt>stanza</tt> passes the filter.

toString

public java.lang.String toString()

Deprecated.

Overrides:

toString in class java.lang.Object

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
"use strict";

var callable    = require("../../../object/valid-callable")
  , ensureValue = require("../../../object/valid-value")
  , some        = Array.prototype.some
  , apply       = Function.prototype.apply;

module.exports = function (predicate /*, thisArg*/) {
	var k, self;
	self = Object(ensureValue(this));
	callable(predicate);

	return some.call(
		self,
		function (value, index) {
			if (apply.call(predicate, this, arguments)) {
				k = index;
				return true;
			}
			return false;
		},
		arguments[1]
	)
		? k
		: -1;
};


text:
package org.blinkenlights.jid3.v2;

import java.io.*;

import org.blinkenlights.jid3.*;
import org.blinkenlights.jid3.io.*;
import org.blinkenlights.jid3.util.*;

/**
 * @author paul
 *
 * Text frame containing the language(s) used in this track.  Although this requirement is
 * not enforced, languages should be specified using ISO-639-2 three letter language codes.
 */
public class TLANTextInformationID3V2Frame extends TextInformationID3V2Frame
{
    private String m_sLanguages = null;

    /** Constructor.
     *
     * @param sLanguages the language(s) used in this track
     */
    public TLANTextInformationID3V2Frame(String sLanguages)
    {
        // We could try to check to see if the language codes are valid... but in Sun's
        // documentation of the getLanguage method of the Locale class in jdk1.4, it is
        // claimed that ISO639 is not a stable standard.
        super(sLanguages);

        m_sLanguages = sLanguages;
    }

    public TLANTextInformationID3V2Frame(InputStream oIS)
        throws ID3Exception
    {
        super(oIS);

        m_sLanguages = m_sInformation;
    }

    public void accept(ID3Visitor oID3Visitor)
    {
        oID3Visitor.visitTLANTextInformationID3V2Frame(this);
    }

    /** Set the language(s) used in this track.
     *
     * @param sLanguages the language(s) used in this track
     */
    public void setLanguages(String sLanguages)
    {
        m_sLanguages = sLanguages;
        m_oTextEncoding = TextEncoding.getDefaultTextEncoding();
        m_sInformation = sLanguages;
    }

    /** Get the language(s) used in this track.
     *
     * @return the language(s) used in this track
     */
    public String getLanguages()
    {
        return m_sLanguages;
    }

    protected byte[] getFrameId()
    {
        return "TLAN".getBytes();
    }

    public String toString()
    {
        return "Language(s): [" + m_sInformation + "]";
    }

    public boolean equals(Object oOther)
    {
        if ((oOther == null) || (!(oOther instanceof TLANTextInformationID3V2Frame)))
        {
            return false;
        }

        TLANTextInformationID3V2Frame oOtherTLAN = (TLANTextInformationID3V2Frame)oOther;

        return (m_sLanguages.equals(oOtherTLAN.m_sLanguages) &&
                m_oTextEncoding.equals(oOtherTLAN.m_oTextEncoding) &&
                m_sInformation.equals(oOtherTLAN.m_sInformation));
    }
}


text:
"""
@author: Shreyas <shreyas@ischool.berkeley.edu>
@author:  Luis Aguilar <luis@ischool.berkeley.edu>

CheckApps
=========
Given an input of fair apps, create a csv file
"""

from __future__ import division
from optparse import OptionParser
import time
import datetime
import requests
import MySQLdb
import pandas as pd
import pandas.io.sql as psql

def getUserInput():
    """
    Get User Input
    """
    optionparser = OptionParser()

    optionparser.add_option('-f', '--file', dest='file')
    optionparser.add_option('-d', '--db', dest='db')
    optionparser.add_option('-s', '--server', dest='server')
    optionparser.add_option('-u', '--username', dest='un')
    optionparser.add_option('-p', '--password', dest='pw')
    optionparser.add_option('-o', '--output', dest='output')

    (option, args) = optionparser.parse_args()

    #if not option.file:
    #    return optionparser.error('Data File path not provided.\n Usage: --file="path.to.appData"')
    #elif not option

    return {
        'file': option.file,
        'db': option.db,
        'server': option.server,
        'username': option.un,
        'password': option.pw,
        'output': option.output
    }

def getDataframeFromDatabase(host, db, un, pw):
    query = "SELECT pkgname from fair_apps;"
    conn = MySQLdb.connect(host = host, user = un, passwd = pw, db = db)
    fair_apps_df = psql.frame_query(query, conn)
    return fair_apps_df

def pushDataframeToCSV(df, f_csv):
    df.to_csv(f_csv, index=False, header=False, encoding='utf-8')

def main():
    userInput = getUserInput()
    df = getDataframeFromDatabase(userInput['server'], userInput['db'],
        userInput['username'], userInput['password'])
    pushDataframeToCSV(df, userInput['output'])

if __name__ == '__main__':
    main()


text:
"""Functions for smooshing images. Given a background mask (a foreground
selection), these functions move pixels in an image around to create
various "crash" effects. Images can have their foregrounds crashed into
the center of the image, the side of the image, and so on."""

from __future__ import print_function, division
from collections import namedtuple
from itertools import repeat
import os
import sys
import time
import numpy as np
from six.moves import zip, range
from crash_kiss import util, foreground
from crash_kiss.config import WHITE
#from crash_kiss import smoosh
from crash_kiss.omp_smoosh import smoosh

# _MID_FG is a placeholder value for foreground data that is at the center
# of the image. It's used to distinguish the fg-at-center case from
# the no-fg-at-all case. This is because `np.argmax` returns 0 if the max
# value has index 0 (whether that max value is 0 or 1 or anything else!).
_MID_FG = 0xFFFF  # placeholder index for foreground data at the center
_crash_data = namedtuple(
    "sdata", "start stop fg_mid max_depth fg_l fg_r "
             "mid_left center mid_right side_len")
_row_data = namedtuple("row", "irow ls rs frow")

def center_crash(img, fg, bounds, background_value):
    start, stop, fg_mid, depth = bounds
    foreground = np.zeros(img.shape[:2], dtype=np.uint8)
    foreground[:, start: stop] = fg
    smoosh(img, foreground, depth, background_value)
    return img

def _old_center_crash(img, fg, bounds):
    """Move the rows of each subject together until they touch.
    Write over the vacated space with whatever the row's negative space
    is (probably white or transparent pixels)."""
    start, stop, fg_mid, depth = bounds
    fg_l = fg_mid - depth
    fg_r = fg_mid + depth
    mid_left = start + depth
    center = start +  2 * depth
    mid_right = center + depth
    side_len = fg.shape[1] // 2

    lfg = fg[:, :bounds.fg_mid]
    lfg = util.invert_horizontal(lfg)
    rfg = fg[:, bounds.fg_mid:]
    lstart = np.argmax(lfg, axis=1)
    rstart = np.argmax(rfg, axis=1)
    overlap = np.logical_or(rfg[:, 0], lfg[:, 0])
    foreground = np.zeros(img.shape[:2], dtype=np.uint8)
    foreground[:, start: stop] = fg
    lnil = np.logical_and(lstart == 0, ~overlap)
    rnil = np.logical_and(rstart == 0, ~overlap)

    rows_empty = np.logical_and(lnil, rnil)
    for chunk, _ in _contiguous_chunks(rows_empty, img):
        cpy = chunk.copy()
        chunk[:, mid_left: -depth] = chunk[:, center:]
        chunk[:, depth: mid_right] = cpy[:, :center]
        chunk[:, :depth] = WHITE
        chunk[:, -depth:] = WHITE

    # Move rows with subject only on left side OR no subject at all
    rows_left = np.logical_and(~lnil, rnil)
    for chunk, _ in _contiguous_chunks(rows_left, img):
        cpy = chunk.copy()
        chunk[:, mid_left: -depth] = chunk[:, center:]
        chunk[:, depth: mid_right] = cpy[:, :center]
        chunk[:, :depth] = WHITE
        chunk[:, -depth:] = WHITE

    # Move rows with subject only on right side
    rows_right = np.logical_and(~rnil, lnil)
    for chunk, _ in _contiguous_chunks(rows_right, img):
        cpy = chunk.copy()
        chunk[:, depth: mid_right] = chunk[:, :center]
        chunk[:, mid_left: -depth] = cpy[:, center:]
        chunk[:, :depth] = WHITE
        chunk[:, -depth:] = WHITE

    # Move rows with foreground overlapping the center
    chunks = _contiguous_chunks(overlap, img, foreground, lfg, rfg)
    for chunk, (f, _lfg, _rfg) in chunks:
        l = np.argmin(_lfg, axis=1)
        r = np.argmin(_rfg, axis=1)
        left_overlaps = (l > r).astype(np.uint8)
        smoosh.smoosh_overlap(chunk, f, left_overlaps, depth)

    # Move rows with subjects that are close together
    rows_close = np.logical_and(~rnil, ~lnil)
    rows_close[overlap] = 0
    chunks = _contiguous_chunks(
        rows_close, img, lstart, rstart, foreground)
    for chunk, (l, r, f) in chunks:
        smoosh.smoosh(chunk, l, r, f, depth)

    return img

def _contiguous_chunks(mask, img, *masks):
    idx = 0
    while idx <= mask.size - 1:
        start = np.argmax(mask[idx:]) + idx
        if start == idx and not mask[idx]:
            break
        stop = np.argmin(mask[start:]) + start
        if start == mask.size - 1:
            yield img[start: start + 1], (m[start: start + 1] for m in masks)
            break
        elif stop == start:
            if mask[start + 1]:
                yield img[start:], (m[start:] for m in masks)
            else:
                yield img[start: start + 1], (m[start: start + 1] for m in masks)
            break
        else:
            yield img[start: stop], (m[start: stop] for m in masks)
        idx = stop + 1

class CrashParams(object):
    """A **picklable** container of values that can be sent to
    a `multiprocessing.Process` object. Usually a `namedtuple` or some
    other simple container would be better, but `namedtuple` is not
    picklable!"""
    _params = "max_depth threshold bg_value rgb_select".split()

    def __init__(self, *args, **kwargs):
        given_args = dict(zip(self._params, repeat(None)))
        for name, value in zip(self._params, args):
            given_args[name] = value
        for name, value in kwargs.items():
            given_args[name] = value
        self.__dict__.update(given_args)

    def __iter__(self):
        for param_name in self._params:
            yield self.__dict__[param_name]

class SequenceParams(CrashParams):
    """A picklable record to pass to `parallel_crash` for running a
    crash over multiple processes"""
    _params = ("target working_dir output_suffix crash_params "
               "counter depths".split())

def sequence_crash(params):
    """Given an input filename `target`, a `CrashParams` instance,
    and an iterable of `depths`, write a crashed version of the target
    image to the disk for each depth."""
    # The images are *written* and not returned or yielded because it's not
    # efficient to pass huge n-dimensional arrays between processes. Each
    # process reads its own copy of the target image from the disk and writes
    # its own crashed output files to the disk. In my tests, the program is
    # mostly limited by disk IO (even on SSDs). While each additional process
    # below cpu_count() improves performance, it's usually not by huge amounts.
    start = time.time()  # keep track of duration to show how cool we are

    loc, name, suffix, ext = util.get_filename_hints(
        params.target, params.working_dir, params.output_suffix)
    tail = "{0}_{1}_{2}.{3}".format(name, suffix, "{0:04d}", ext)
    template = os.path.join(loc, tail)
    img = util.read_img(params.target)
    fg, bounds = foreground.find_foreground(img, params.crash_params)
    max_depth = params.depths[0]
    first_img = center_crash(img.copy(), fg, bounds)
    util.save_img(template.format(max_depth), first_img)
    _print_count(params.counter)

    # We'll create a background mask (i.e. the foreground selection) with
    # the same shape as the image. This lets us calculate the entire
    # foreground just once and slice it down to size for each iteration
    # of the crash. Not having to recalculate the foreground each time
    # saves lots of CPU cycles.
    total_fg = np.zeros(shape=img.shape[:2], dtype=bool)  # a 2D mask
    total_fg[:, bounds.start: bounds.stop] = fg
    for depth in params.depths[1:]:
        if depth == 0:
            crashed = img
        else:
            crashed = _crash_at_depth(img, total_fg, depth)
        util.save_img(template.format(depth), crashed)
        _print_count(params.counter)

def _print_count(counter):
    counter.value -= 1
    print("Remaining: {0:04d}\r".format(counter.value), end="")
    sys.stdout.flush()

def _crash_at_depth(img, total_fg, depth):
    """Select a subset of the complete background mask (the foreground)
    and crash that subset of pixels by `depth`"""
    fg, bounds = foreground.get_foreground_area(total_fg, depth)
    crashed_img = center_crash(img.copy(), fg, bounds)
    return crashed_img


text:
{% extends "transport/base.html" %}{% load molly_utils %}{% load i18n %}

{% block content %}
{{ block.super }}

{% trans "Routes" %}

        {% for route in routes %}

{{ route }}
            {% if route.nearest %}
{% trans "Closest stop:" %} {{ route.nearest.title }}
                {% if route.nearest_distance and route.nearest_bearing %}{% blocktrans with route.nearest_distance|humanise_distance as distance and route.nearest_bearing as bearing %}(about {{ distance }} {{ bearing }}){% endblocktrans %}{% endif %}
            {% endif %}

        {% endfor %}

{% endblock %}


text:
from django.conf.urls.defaults import *
from django.conf import settings

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^admin/', include(admin.site.urls)),
    (r'^blogs/', include('dogood.urls')),
    (r'^site_media/(?P<path>.*)$',
     'django.views.static.serve',
     {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}
    ),
)


text:
Based on the summary given above, the main result is negative: No useful
clusters can be found in the majority of the dataset by this algorithm.
From this, we can conclude that a simple Hamming metric is probably too
coarse. The lowest non-zero distance it can create is 1, and this has
been taken as the maximum distance to relate two otherwise unrelated
sequences. No stricter criterion is possible, yet it is not strict
enough to not absorb the vast majority of the data into a single cluster
per sequence length.

What this says about the dataset is that, using this metric, we can walk
within sequences in the dataset from almost any point to almost any
other point without ever having a step distance greater than 1.
Intuitively, this seems to indicate that if any real clusters exist,
those clusters all touch, which gives a rather "fuzzy" view.

Alternatively, the dataset might just be too noisy. However, if this is
the case, the majority of the dataset is under the noise floor, based on
trial and error with the minimum occurence count setting: any setting
which eliminates the "all" cluster leaves only a few scattered peaks,
with no or nearly no actual clustering occurring.

Note that this is a property of the dataset equipped with this metric:
Other metrics might produce a clearer view, and indeed this is likely if
they have more possible values and are chosen sensibly.

The problem, however, might very well be the MST algorithm itself: it
cannot distinguish overlapping clusters at all, and such overlap is not
impossible or even unlikely given the subject matter. If clusters
overlap, a more sophisticated algorithm will be required, likely
designed specifically with this problem in mind, rather than this most
generic of clustering algorithms.

##Conclusion for Biologists
The approach used in this thesis did not yield any directly useful
results, beyond the suspicion that motifs should not be assumed to only
cover sequences of a single size.

However, the manner in which it failed does provide some insight into
the shape of the dataset, the shape of the noise, and the amount of
noise. This should prove useful in formulating any alternative
approaches.

Additionally, while our primitive clustering algorithm turned out to be
mostly useless, the underlying model is likely fine, and can be used for
other algorithms without substantial biological knowledge, said
knowledge being contained in the model.

An exception is the process of taking the "join" of a cluster to extract
a motif, if the cluster contains sequences of differing lengths. The
model does not define any way to do so, and it is not easily defined
without some biological knowledge. In this case, a biologist would need
to be available to answer questions, and provide some examples of the
"right" motifs for some clusters with varying sequence lengths.

In summary, while providing no direct results, this thesis can hopefully
allow data scientists without much biological background to develop more
sophisticated algorithms, using only this thesis for background
knowledge.

##Other considerations
###Singleton clusters
The tails of singletons noted in the summary are very unlikely to
actually exist as proper motifs belonging to transcription factors,
especially considering their low occurence numbers. They are almost
certainly noise, and should be ignored.

However, their existence also indicates the amount of noise in the
entire dataset, including where it might interfere with clustering
algorithms. Any succesful clustering algorithm will have to handle such
noise correctly. A filter capable of removing such noise before clustering
might work, but ideally, clustering algorithms should be made inherently
robust against this type of noise.

###Similarity across lengths
In designing both the distance function and the join function, it had
been assumed that all sequences within a motif should be of the same
length. Several sequences in the result seem to contradict this
assumption, including some non-trivial pairs with a length difference of 1.
Therefore, future algorithms should *not* make this assumption, and
instead find some way to interpret and represent similarity between
sequences of different lengths.

##Potential improvements
###Distance functions
The distance function used was a simple Hamming metric, which is
relatively coarse. Several refinements are imaginable:

####Sequence-based refinement
Not all distances between two nucleotides are equal: each nucleotide has
spatial and chemical features which are closer to or further from
those of each other nucleotide. Incorporating such differences into the
distance function could increase point-wise resolution, if based on
biochemical knowledge. This would in turn increase resolution on the
sequence level.

Additionally and alternatively, some features recognized by
transcription factors are known to be based not on individual
nucleotides, but by the transition between them in a sequence. Thus, the
metric could be enriched by adding some similarity score if certain
properties on sequential pairs of nucleotides are equal, rather than the
nucleotides themselves.

####Frequency-based refinement
There is a possibility that motifs have properly disjoint "cores" which
are most often seen, but also contain less commonly seen "peripheries",
which can overlap. If so, clusters might be distinguishable by having
distances between sequences seen with low frequency be penalized
(increased) compared to distances between high-frequency sequences. This
would, under the assumptions given, keep cluster cores together while
pushing the confounding peripheries apart.

###Alternative algorithms
Constructing an MST doesn't really leave any choices or tuning variables,
so it is hard to improve it except by choosing a better distance
function. Alternative algorithms are thinkable however, so long as one
keeps in mind that the sequence space does not have meaningful averages,
and so it's not possible to use averaging-based clustering algorithms.

####Convexity-based
One very plausible hypothesis is that true clusters are (mostly) convex.
This requires a generalisation of the concept of convexity:

A subset $A$ of a metric space $X$ is considered convex iff
$\forall x, y \in A \, \forall z \in X \, d(x,z) + d(z,y) = d(x,y) \Rightarrow z \in A$.

In other words, if two points are in a convex set, that set must also
include all points "between" them for which the triangle inequality is
an equality. This is consistent with the notion of convexity in spaces
with weighted averages such as real and complex numbers and vector
spaces.

Given such a notion of convexity, it might be possible and useful to
define an algorithm based on trying to split non-convex clusters,
ideally such that as many points in the cluster but not in the dataset
are excluded from the union of the two new clusters (intuitively, split
along the plane of maximum missing datapoints in the cluster). Given an
algorithm to perform such a step, apply this iteratively to the most
non-convex cluster after each step, starting with a universal cluster.

No attempt has been made here to write such an algorithm beyond
formulating the concept, but further work could include making such an
attempt.

####Co-occurrence based
Another possibility is to look not only at what sequences are found, but
also where they are found. Transcription factors form complexes, so
often, the same motifs will always occur together, with similar relative
positioning. It is possible to base a statistical algorithm on this,
with the chance of two sequences belonging to the same motif increasing
as they occur next to the same other motif. This is a very different
approach, and only vaguely sketched here, but it might detect patterns
which pure sequence-based algorithms would miss.

###Dealing with different sequence lengths
While it is relatively easy to adapt distance functions to enable
comparisons on sequences of unequal length, by replacing Hamming
distances by edit distances, doing the same for joins is a greater
challenge, and we will make no attempt at a solution here.


text:
import React, { Component, ReactNode } from 'react';
import PopupWindow from '../../util/PopupWindow';
import { toQuery } from '../../util/url';

const defaultProps = {
  autoLogin: false,
  buttonText: 'Login',
  scope: '',
  state: '',
  className: '',
  children: undefined as ReactNode,
  onRequest: () => {}
};

type DefaultProps = Readonly<typeof defaultProps>;

export type OAuth2LoginProps = {
  autoLogin?: boolean;
  authorizationUrl: string;
  clientId: string;
  redirectUri: string;
  responseType: 'code' | 'token';
  onSuccess: (data: any) => any;
  onFailure: (error: any) => any;
} & DefaultProps;

interface Payload {
  client_id: string;
  scope: string;
  redirect_uri: string;
  response_type: 'code' | 'token';
  state?: string;
  nonce?: string;
}

const responseTypeLocationKeys = {
  code: 'search',
  token: 'hash'
};

const responseTypeDataKeys = {
  code: 'code',
  token: 'access_token'
};

export class OAuth2Login extends Component<OAuth2LoginProps> {
  popup?: PopupWindow;
  static defaultProps = defaultProps;

  constructor(props: OAuth2LoginProps) {
    super(props);
    this.onBtnClick = this.onBtnClick.bind(this);
    this.onRequest = this.onRequest.bind(this);
    this.onSuccess = this.onSuccess.bind(this);
    this.onFailure = this.onFailure.bind(this);
  }

  onBtnClick() {
    const { buttonText, authorizationUrl, clientId, scope, redirectUri, state, responseType } = this.props;
    const payload: Payload = {
      client_id: clientId,
      scope,
      redirect_uri: redirectUri,
      response_type: responseType,
      nonce: 'fixme'
    };
    if (state) {
      payload.state = state;
    }
    const search = toQuery(payload);
    const width = 680;
    const height = 440;
    const left = window.screenX + (window.outerWidth - width) / 2;
    const top = window.screenY + (window.outerHeight - height) / 2.5;
    const locationKey = responseTypeLocationKeys[responseType];
    console.log(`opening popup window: ${authorizationUrl}?${search}`);
    const popup = PopupWindow.open(
      buttonText,
      `${authorizationUrl}?${search}`,
      {
        height,
        width,
        top,
        left
      },
      {
        locationKey
      }
    );
    this.popup = popup;

    this.onRequest();
    popup.then(this.onSuccess)?.catch(this.onFailure);
  }

  componentDidMount() {
    if (this.props.autoLogin) {
      this.onBtnClick();
    }
  }

  onRequest() {
    const { onRequest } = this.props;
    onRequest();
  }

  onSuccess(data: any) {
    const { responseType, onSuccess } = this.props;
    const responseKey = responseTypeDataKeys[responseType];
    if (!data[responseKey]) {
      console.error('received data', data);
      return this.onFailure(new Error(`'${responseKey}' not found in received data`));
    }

    return onSuccess(data);
  }

  onFailure(error: any) {
    const { onFailure } = this.props;
    onFailure(error);
  }

  render() {
    const { className, buttonText, children } = this.props;
    const attrs = { onClick: this.onBtnClick, className: '' };

    if (className) {
      attrs.className = className;
    }

    // eslint-disable-next-line react/jsx-props-no-spreading
    return (
      <button type="button" {...attrs}>
        {children || buttonText}
      </button>
    );
  }
}


text:
Interface = {
	functions = {}
}

function Interface.functions.basicOnClick(self, interfaceState)
	Console.info("clicked on entity " .. self:getOf():getId() .. ", facet " .. self:getId())
end

function Interface.functions.basicDragMove(self, interfaceState)
	if interfaceState.pickedUpThisTick then
		local position = self:getOf():getPosition()
		self.dragDelta = Util.subtractPositions(position,interfaceState.clickPosition)
		local dimensions = self:getOf():getDimensions()
		self.dragDelta[3] = position[3]
		self.dragDelta[4] = dimensions[1]
		self.dragDelta[5] = dimensions[2]
	else
		local newPosition = Util.addPositions(interfaceState.currentPosition, self.dragDelta)
		newPosition[3] = self.dragDelta[3]
		newPosition[1] = Util.bounds(newPosition[1], 0, Config.window[1] - self.dragDelta[4])
		newPosition[2] = Util.bounds(newPosition[2], 0, Config.window[2] - self.dragDelta[5])
		self:getOf():setPosition(newPosition)
	end

	for i, v in pairs(self:getOf():getChildren()) do
		local childOnDrag = v.facets.interface:getOnDrag()
		childOnDrag(interfaceState)
	end

end

function Interface.functions.gridDragMove(self, interfaceState)
	if interfaceState.pickedUpThisTick then
		self.dragDelta = Util.subtractPositions(interfaceState.pickedUpPosition,interfaceState.clickPosition)
		self.dragDelta[3] = interfaceState.pickedUpPosition[3] --just want to keep the current z so don't need too many "get position" calls
		local dimensions = self:getOf():getDimensions()
		self.dragDelta[4] = dimensions[1]
		self.dragDelta[5] = dimensions[2]
	else
		local newPosition = Util.addPositions(interfaceState.currentPosition, self.dragDelta)
			newPosition[1] = newPosition[1] - newPosition[1] % 50
			newPosition[2] = newPosition[2] - newPosition[2] % 50
			newPosition[1] = Util.bounds(newPosition[1], 0, Config.window[1] - self.dragDelta[4])
			newPosition[2] = Util.bounds(newPosition[2], 0, Config.window[2] - self.dragDelta[5])
			newPosition[3] = self.dragDelta[3]
		self:getOf():setPosition(newPosition)
	end
end

function Interface.functions.alphaFun(self, interfaceState)

	if interfaceState.pickedUpThisTick then
		self.alphaBase = self.newAlpha or 255
	else
		self.newAlpha = self.alphaBase - (interfaceState.clickPosition[2] - interfaceState.currentPosition[2])
		self.newAlpha = Util.bounds(self.newAlpha, 0, 255)
		self:getOf().facets.background:setColor({255,255,255,self.newAlpha})
	end
end

function Interface.setCursorTexture(cursorTexture)
	setCursorTexture_bind(cursorTexture)
end

function Interface.dragComposite(self, interfaceState)
	Interface.functions.alphaFun(self, interfaceState)
	Interface.functions.basicDragMove(self, interfaceState)
end


text:
layout: page-fullwidth
subheadline:  "Multi-Device Layouts in Color"
title:  "Grid & Colors"
teaser: "Create powerful multi-device layouts quickly and easily with the 12-column, nest-able Foundation grid. To optimize the size of your images, you find the correct dimensions beneath. Further below you find the colorscheme and colors used for Feeling Responsive and their color codes."
breadcrumb: true
categories:
    - design
permalink: /design/grid/
header:
    image_fullwidth: "unsplash_brooklyn-bridge_header.jpg"
image:
    thumb: "unsplash_brooklyn-bridge_thumb.jpg"
---
*Feeling Responsive* is built on Foundation. And of course, we make use of the wonderful grid system and so can you. Find out more about [constructing  beautiful layouts][1] in the foundation documentation.

Small Grid

Large Displays

Large Displays Two Columns

Large Displays Three Columns

Large Displays Four Columns

Color Scheme and Colors Codes

Feeling Responsive uses strong colors in combination with grey colors.

Colours

Grey Scale

      {% include next-previous-post-in-category.html %}

 [1]: http://foundation.zurb.com/docs/components/grid.html


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/banners/app_banner_manager.h"

#include <algorithm>

#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "base/time/time.h"
#include "chrome/browser/banners/app_banner_metrics.h"
#include "chrome/browser/banners/app_banner_settings_helper.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/engagement/site_engagement_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "components/rappor/rappor_utils.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/origin_util.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"

namespace {

int gCurrentRequestID = -1;
int gTimeDeltaInDaysForTesting = 0;

// Returns |size_in_px| in dp, i.e. divided by the current device scale factor.
int ConvertIconSizeFromPxToDp(int size_in_px) {
  return size_in_px /
      display::Screen::GetScreen()->GetPrimaryDisplay().device_scale_factor();
}

InstallableParams ParamsToGetManifest() {
  return InstallableParams();
}

// Returns an InstallableParams object that requests all checks necessary for
// a web app banner.
InstallableParams ParamsToPerformInstallableCheck(int ideal_icon_size_in_dp,
                                                  int minimum_icon_size_in_dp) {
  InstallableParams params;
  params.ideal_icon_size_in_dp = ideal_icon_size_in_dp;
  params.minimum_icon_size_in_dp = minimum_icon_size_in_dp;
  params.check_installable = true;
  params.fetch_valid_icon = true;

  return params;
}

}  // anonymous namespace

namespace banners {

// static
base::Time AppBannerManager::GetCurrentTime() {
  return base::Time::Now() +
         base::TimeDelta::FromDays(gTimeDeltaInDaysForTesting);
}

// static
void AppBannerManager::SetTimeDeltaForTesting(int days) {
  gTimeDeltaInDaysForTesting = days;
}

// static
void AppBannerManager::SetEngagementWeights(double direct_engagement,
                                            double indirect_engagement) {
  AppBannerSettingsHelper::SetEngagementWeights(direct_engagement,
                                                indirect_engagement);
}

// static
bool AppBannerManager::URLsAreForTheSamePage(const GURL& first,
                                             const GURL& second) {
  return first.GetWithEmptyPath() == second.GetWithEmptyPath() &&
         first.path_piece() == second.path_piece() &&
         first.query_piece() == second.query_piece();
}

void AppBannerManager::RequestAppBanner(const GURL& validated_url,
                                        bool is_debug_mode) {
  // Don't start a redundant banner request. Otherwise, if one is running,
  // invalidate our weak pointers so it terminates.
  content::WebContents* contents = web_contents();
  if (is_active_) {
    if (URLsAreForTheSamePage(validated_url, contents->GetLastCommittedURL()))
      return;
    else
      weak_factory_.InvalidateWeakPtrs();
  }

  is_active_ = true;
  is_debug_mode_ = is_debug_mode;

  // We only need to call ReportStatus if we aren't in debug mode (this avoids
  // skew from testing).
  DCHECK(!need_to_log_status_);
  need_to_log_status_ = !IsDebugMode();

  if (contents->GetMainFrame()->GetParent()) {
    ReportStatus(contents, NOT_IN_MAIN_FRAME);
    Stop();
    return;
  }

  // A secure origin is required to show banners, so exit early if we see the
  // URL is invalid.
  if (!content::IsOriginSecure(validated_url)) {
    ReportStatus(contents, NOT_FROM_SECURE_ORIGIN);
    Stop();
    return;
  }

  if (validated_url_.is_empty())
    validated_url_ = validated_url;

  // Any existing binding is invalid when we request a new banner.
  if (binding_.is_bound())
    binding_.Close();

  manager_->GetData(
      ParamsToGetManifest(),
      base::Bind(&AppBannerManager::OnDidGetManifest, GetWeakPtr()));
}

void AppBannerManager::SendBannerAccepted(int request_id) {
  if (request_id != gCurrentRequestID)
    return;

  DCHECK(event_.is_bound());
  event_->BannerAccepted(GetBannerType());
}

void AppBannerManager::SendBannerDismissed(int request_id) {
  if (request_id != gCurrentRequestID)
    return;

  DCHECK(event_.is_bound());
  event_->BannerDismissed();
}

base::Closure AppBannerManager::FetchWebappSplashScreenImageCallback(
    const std::string& webapp_id) {
  return base::Closure();
}

AppBannerManager::AppBannerManager(content::WebContents* web_contents)
    : content::WebContentsObserver(web_contents),
      SiteEngagementObserver(nullptr),
      manager_(nullptr),
      event_request_id_(-1),
      binding_(this),
      is_active_(false),
      banner_request_queued_(false),
      load_finished_(false),
      was_canceled_by_page_(false),
      page_requested_prompt_(false),
      is_debug_mode_(false),
      need_to_log_status_(false),
      weak_factory_(this) {
  // Ensure the InstallableManager exists since we have a hard dependency on it.
  InstallableManager::CreateForWebContents(web_contents);
  manager_ = InstallableManager::FromWebContents(web_contents);
  DCHECK(manager_);

  AppBannerSettingsHelper::UpdateFromFieldTrial();
}

AppBannerManager::~AppBannerManager() { }

std::string AppBannerManager::GetAppIdentifier() {
  DCHECK(!manifest_.IsEmpty());
  return manifest_.start_url.spec();
}

std::string AppBannerManager::GetBannerType() {
  return "web";
}

std::string AppBannerManager::GetStatusParam(InstallableStatusCode code) {
  if (code == NO_ACCEPTABLE_ICON || code == MANIFEST_MISSING_SUITABLE_ICON) {
    return base::IntToString(InstallableManager::GetMinimumIconSizeInPx());
  }

  return std::string();
}

int AppBannerManager::GetIdealIconSizeInDp() {
  return ConvertIconSizeFromPxToDp(
      InstallableManager::GetMinimumIconSizeInPx());
}

int AppBannerManager::GetMinimumIconSizeInDp() {
  return ConvertIconSizeFromPxToDp(
      InstallableManager::GetMinimumIconSizeInPx());
}

base::WeakPtr<AppBannerManager> AppBannerManager::GetWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

bool AppBannerManager::IsDebugMode() const {
  return is_debug_mode_ ||
         base::CommandLine::ForCurrentProcess()->HasSwitch(
             switches::kBypassAppBannerEngagementChecks);
}

bool AppBannerManager::IsWebAppInstalled(
    content::BrowserContext* browser_context,
    const GURL& start_url) {
  return false;
}

void AppBannerManager::OnDidGetManifest(const InstallableData& data) {
  if (data.error_code != NO_ERROR_DETECTED) {
    ReportStatus(web_contents(), data.error_code);
    Stop();
  }

  if (!is_active_)
    return;

  DCHECK(!data.manifest_url.is_empty());
  DCHECK(!data.manifest.IsEmpty());

  manifest_url_ = data.manifest_url;
  manifest_ = data.manifest;
  app_title_ = (manifest_.name.is_null()) ? manifest_.short_name.string()
                                          : manifest_.name.string();

  PerformInstallableCheck();
}

void AppBannerManager::PerformInstallableCheck() {
  if (IsWebAppInstalled(web_contents()->GetBrowserContext(),
                        manifest_.start_url) &&
      !IsDebugMode()) {
    ReportStatus(web_contents(), ALREADY_INSTALLED);
    Stop();
  }

  if (!is_active_)
    return;

  // Fetch and verify the other required information.
  manager_->GetData(ParamsToPerformInstallableCheck(GetIdealIconSizeInDp(),
                                                    GetMinimumIconSizeInDp()),
                    base::Bind(&AppBannerManager::OnDidPerformInstallableCheck,
                               GetWeakPtr()));
}

void AppBannerManager::OnDidPerformInstallableCheck(
    const InstallableData& data) {
  if (data.is_installable)
    TrackDisplayEvent(DISPLAY_EVENT_WEB_APP_BANNER_REQUESTED);

  if (data.error_code != NO_ERROR_DETECTED) {
    if (data.error_code == NO_MATCHING_SERVICE_WORKER)
      TrackDisplayEvent(DISPLAY_EVENT_LACKS_SERVICE_WORKER);

    ReportStatus(web_contents(), data.error_code);
    Stop();
  }

  if (!is_active_)
    return;

  DCHECK(data.is_installable);
  DCHECK(!data.icon_url.is_empty());
  DCHECK(data.icon);

  icon_url_ = data.icon_url;
  icon_.reset(new SkBitmap(*data.icon));

  SendBannerPromptRequest();
}

void AppBannerManager::RecordDidShowBanner(const std::string& event_name) {
  content::WebContents* contents = web_contents();
  DCHECK(contents);

  AppBannerSettingsHelper::RecordBannerEvent(
      contents, validated_url_, GetAppIdentifier(),
      AppBannerSettingsHelper::APP_BANNER_EVENT_DID_SHOW,
      GetCurrentTime());
  rappor::SampleDomainAndRegistryFromGURL(g_browser_process->rappor_service(),
                                          event_name,
                                          contents->GetLastCommittedURL());
}

void AppBannerManager::ReportStatus(content::WebContents* web_contents,
                                    InstallableStatusCode code) {
  if (IsDebugMode()) {
    LogErrorToConsole(web_contents, code, GetStatusParam(code));
  } else {
    // Ensure that we haven't yet logged a status code for this page.
    DCHECK(need_to_log_status_);
    TrackInstallableStatusCode(code);
    need_to_log_status_ = false;
  }
}

void AppBannerManager::Stop() {
  if (was_canceled_by_page_ && !page_requested_prompt_) {
    TrackBeforeInstallEvent(
        BEFORE_INSTALL_EVENT_PROMPT_NOT_CALLED_AFTER_PREVENT_DEFAULT);
    ReportStatus(web_contents(), RENDERER_CANCELLED);
  }

  // In every non-debug run through the banner pipeline, we should have called
  // ReportStatus() and set need_to_log_status_ to false. The only case where
  // we don't is if we're still active and waiting for a callback from the
  // InstallableManager (e.g. the renderer crashes or the browser is shutting
  // down). These situations are explicitly not logged.
  DCHECK(!need_to_log_status_ || is_active_);

  weak_factory_.InvalidateWeakPtrs();
  binding_.Close();
  controller_.reset();
  event_.reset();

  is_active_ = false;
  was_canceled_by_page_ = false;
  page_requested_prompt_ = false;
  need_to_log_status_ = false;
  validated_url_ = GURL();
  referrer_.erase();
}

void AppBannerManager::SendBannerPromptRequest() {
  RecordCouldShowBanner();

  // Given all of the other checks that have been made, the only possible reason
  // for stopping now is that the app has been added to the homescreen.
  if (!IsDebugMode() && !CheckIfShouldShowBanner()) {
    Stop();
    return;
  }

  TrackBeforeInstallEvent(BEFORE_INSTALL_EVENT_CREATED);
  event_request_id_ = ++gCurrentRequestID;

  web_contents()->GetMainFrame()->GetRemoteInterfaces()->GetInterface(
      mojo::GetProxy(&controller_));

  controller_->BannerPromptRequest(
      binding_.CreateInterfacePtrAndBind(), mojo::GetProxy(&event_),
      {GetBannerType()},
      base::Bind(&AppBannerManager::OnBannerPromptReply, GetWeakPtr()));
}

void AppBannerManager::DidStartNavigation(content::NavigationHandle* handle) {
  if (!handle->IsInMainFrame() || handle->IsSamePage())
    return;

  load_finished_ = false;
  if (AppBannerSettingsHelper::ShouldUseSiteEngagementScore() &&
      GetSiteEngagementService() == nullptr) {
    // Ensure that we are observing the site engagement service on navigation
    // start. This may be the first navigation, or we may have stopped
    // observing if the banner flow was triggered on the previous page.
    SiteEngagementObserver::Observe(SiteEngagementService::Get(
        Profile::FromBrowserContext(web_contents()->GetBrowserContext())));
  }
}

void AppBannerManager::DidFinishNavigation(content::NavigationHandle* handle) {
  if (handle->IsInMainFrame() && handle->HasCommitted() &&
      !handle->IsSamePage()) {
    last_transition_type_ = handle->GetPageTransition();
    active_media_players_.clear();
    if (is_active_)
      Stop();
  }
}

void AppBannerManager::DidFinishLoad(
    content::RenderFrameHost* render_frame_host,
    const GURL& validated_url) {
  // Don't start the banner flow unless the main frame has finished loading.
  if (render_frame_host->GetParent())
    return;

  load_finished_ = true;
  validated_url_ = validated_url;
  // Start the pipeline immediately if we aren't using engagement, or if 0
  // engagement is required.
  if (!AppBannerSettingsHelper::ShouldUseSiteEngagementScore() ||
      banner_request_queued_ ||
      AppBannerSettingsHelper::HasSufficientEngagement(0)) {
    SiteEngagementObserver::Observe(nullptr);
    banner_request_queued_ = false;

    RequestAppBanner(validated_url, false /* is_debug_mode */);
  }
}

void AppBannerManager::MediaStartedPlaying(const MediaPlayerInfo& media_info,
                                           const MediaPlayerId& id) {
  active_media_players_.push_back(id);
}

void AppBannerManager::MediaStoppedPlaying(const MediaPlayerInfo& media_info,
                                           const MediaPlayerId& id) {
  active_media_players_.erase(std::remove(active_media_players_.begin(),
                                          active_media_players_.end(), id),
                              active_media_players_.end());
}

void AppBannerManager::WebContentsDestroyed() {
  Stop();
}

void AppBannerManager::OnEngagementIncreased(content::WebContents* contents,
                                             const GURL& url,
                                             double score) {
  // Only trigger a banner using site engagement if:
  //  1. engagement increased for the web contents which we are attached to; and
  //  2. there are no currently active media players; and
  //  3. we have accumulated sufficient engagement.
  if (web_contents() == contents && active_media_players_.empty() &&
      AppBannerSettingsHelper::HasSufficientEngagement(score)) {
    // Stop observing so we don't double-trigger the banner.
    SiteEngagementObserver::Observe(nullptr);

    if (!load_finished_) {
      // Queue the banner request until the main frame finishes loading.
      banner_request_queued_ = true;
    } else {
      // A banner request performs some simple tests, creates a data fetcher,
      // and starts some asynchronous checks to test installability. It should
      // be safe to start this in response to user input.
      RequestAppBanner(url, false /* is_debug_mode */);
    }
  }
}

void AppBannerManager::RecordCouldShowBanner() {
  content::WebContents* contents = web_contents();
  DCHECK(contents);

  AppBannerSettingsHelper::RecordBannerCouldShowEvent(
      contents, validated_url_, GetAppIdentifier(),
      GetCurrentTime(), last_transition_type_);
}

bool AppBannerManager::CheckIfShouldShowBanner() {
  content::WebContents* contents = web_contents();
  DCHECK(contents);

  InstallableStatusCode code = AppBannerSettingsHelper::ShouldShowBanner(
      contents, validated_url_, GetAppIdentifier(), GetCurrentTime());
  if (code == NO_ERROR_DETECTED)
    return true;

  switch (code) {
    case ALREADY_INSTALLED:
      banners::TrackDisplayEvent(banners::DISPLAY_EVENT_INSTALLED_PREVIOUSLY);
      break;
    case PREVIOUSLY_BLOCKED:
      banners::TrackDisplayEvent(banners::DISPLAY_EVENT_BLOCKED_PREVIOUSLY);
      break;
    case PREVIOUSLY_IGNORED:
      banners::TrackDisplayEvent(banners::DISPLAY_EVENT_IGNORED_PREVIOUSLY);
      break;
    case INSUFFICIENT_ENGAGEMENT:
      banners::TrackDisplayEvent(banners::DISPLAY_EVENT_NOT_VISITED_ENOUGH);
      break;
    default:
      break;
  }

  // If we are in debug mode, AppBannerSettingsHelper::ShouldShowBanner must
  // return NO_ERROR_DETECTED (bypass flag is set) or we must not have entered
  // this method.
  DCHECK(!IsDebugMode());
  ReportStatus(web_contents(), code);
  return false;
}

void AppBannerManager::OnBannerPromptReply(
    blink::mojom::AppBannerPromptReply reply,
    const std::string& referrer) {
  // We don't need the controller any more, so reset it so the Blink-side object
  // is destroyed.
  controller_.reset();
  content::WebContents* contents = web_contents();

  // The renderer might have requested the prompt to be canceled.
  // They may request that it is redisplayed later, so don't Stop() here.
  // However, log that the cancelation was requested, so Stop() can be
  // called if a redisplay isn't asked for.
  //
  // We use the additional page_requested_prompt_ variable because the redisplay
  // request may be received *before* the Cancel prompt reply (e.g. if redisplay
  // is requested in the beforeinstallprompt event handler).
  referrer_ = referrer;
  if (reply == blink::mojom::AppBannerPromptReply::CANCEL &&
      !page_requested_prompt_) {
    TrackBeforeInstallEvent(BEFORE_INSTALL_EVENT_PREVENT_DEFAULT_CALLED);
    was_canceled_by_page_ = true;
    return;
  }

  // If we haven't yet returned, but either of |was_canceled_by_page_| or
  // |page_requested_prompt_| is true, the page has requested a delayed showing
  // of the prompt. Otherwise, the prompt was never canceled by the page.
  if (was_canceled_by_page_ || page_requested_prompt_) {
    TrackBeforeInstallEvent(
        BEFORE_INSTALL_EVENT_PROMPT_CALLED_AFTER_PREVENT_DEFAULT);
    was_canceled_by_page_ = false;
  } else {
    TrackBeforeInstallEvent(BEFORE_INSTALL_EVENT_NO_ACTION);
  }

  AppBannerSettingsHelper::RecordMinutesFromFirstVisitToShow(
      contents, validated_url_, GetAppIdentifier(), GetCurrentTime());

  DCHECK(!manifest_url_.is_empty());
  DCHECK(!manifest_.IsEmpty());
  DCHECK(!icon_url_.is_empty());
  DCHECK(icon_.get());

  TrackBeforeInstallEvent(BEFORE_INSTALL_EVENT_COMPLETE);
  ShowBanner();
  is_active_ = false;
}

void AppBannerManager::DisplayAppBanner() {
  if (was_canceled_by_page_) {
    // Simulate a non-canceled OnBannerPromptReply to show the delayed banner.
    // Don't reset |was_canceled_by_page_| yet for metrics purposes.
    OnBannerPromptReply(blink::mojom::AppBannerPromptReply::NONE, referrer_);
  } else {
    // Log that the prompt request was made for when we get the prompt reply.
    page_requested_prompt_ = true;
  }
}

}  // namespace banners


text:
package cz.pojd.security.hooks;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cz.pojd.homeautomation.model.rooms.Entry;
import cz.pojd.homeautomation.model.rooms.Room;
import cz.pojd.homeautomation.model.rooms.RoomsDAO;
import cz.pojd.security.controller.Controller;
import cz.pojd.security.event.Type;

/**
 * Hook for window/door reed switches - is responsible for making sure the reed switches are hooked up to the security system
 *
 * @author Lubos Housa
 * @since Dec 10, 2014 12:04:58 AM
 */
public class EntryReedSwitchSecurityHook {
    private static final Log LOG = LogFactory.getLog(EntryReedSwitchSecurityHook.class);

    public EntryReedSwitchSecurityHook(RoomsDAO roomsDAO, Controller controller) {
	LOG.info("Hooking up reed switches to the security system...");

	for (Room room : roomsDAO.queryRooms()) {
	    for (Entry entry : room.getEntries()) {
		setupReedSwitch(entry, controller);
	    }
	}

	LOG.info("Done");
    }

    private void setupReedSwitch(Entry entry, Controller controller) {
	LOG.info("Hooking up " + entry + " ...");
	Type type;
	switch (entry.getSpecification()) {
	case GARAGE_DOOR:
	    type = Type.garageOpened;
	    break;
	case MAIN_DOOR:
	    type = Type.doorOpened;
	    break;
	default:
	    type = Type.windowOpened;
	}
	entry.getReedSwitch().addObserver(
		new SensorSecurityObserver(entry, controller, type, false));
    }
}


text:
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                        Case Studies

                        How It Works

                        Features

                        Contact

                        News

                        Blog


text:
<?xml version="1.0" encoding="UTF-8"?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="apc_cache_twig" class="Kelu95\ApcBundle\Extension\ApcCacheExtension">
        	<argument type="service" id="service_container" />
            <tag name="twig.extension" />
        </service>
    </services>
</container>


text:
/*!
 * Angular Material Design
 * https://github.com/angular/material
 * @license MIT
 * v0.6.1-master-fcb9b2c
 */
md-divider.md-default-theme {
  border-top-color: rgba(0, 0, 0, 0.12); }


text:
package com.softwareaggov.messaging.libs.jms.processor.impl;

import com.softwareaggov.messaging.libs.jms.processor.MessageProcessor;
import com.softwareaggov.messaging.libs.jms.processor.ProcessorOutput;

import javax.jms.JMSException;
import javax.jms.Message;

/**
 * Created by fabien.sanglier on 6/23/16.
 */

public class NoopProcessor implements MessageProcessor {
    @Override
    public ProcessorOutput processMessage(Message msg) throws JMSException {
        String payload = String.format("Mock message processing - doing nothing");

        // Packaging the payload + properties into processorOutput object
        ProcessorOutput processingResult = new ProcessorOutputImpl(
                payload,
                null,
                null
        );

        return processingResult;
    }
}


text:
Many people have contributed to Cougar over the years at Betfair, we want to call out those who have made the greatest contributions internally before it was released since those contributions aren't visible on Github. Authors are those who made >50 individual commits. Names are in decreasing order of number of individual commits.

Where just initials are presented it's because we haven't been able to obtain permission from the individual to publish their name.

Authors
=======
* [Simon Matic Langford](http://eswdd.github.io)
* Michael Funnell
* Peter Lewin-Harris
* [Richard Mason](http://github.com/richardqd)
* S.F.
* Alexsei Makarenko
* Teresa Christianson
* [James Dodd ](https://github.com/dodderish)
* [Colin Pretorius](http://github.com/colinpretorius)
* Gary Fry
* [Manjunath Shivakumar](https://github.com/ManjunathShivakumar)

Contributors
============
* R.S.
* G.E.
* Hannah Kroukamp
* Harsha Aswath
* E.D.
* Mike Guyver
* Denys Zakhozhyy
* Tristan Lanfrey
* Leigh Anderson
* David Soroko
* Paul Reeks
* Maris Orbidans
* Caner Akpinar
* David Prime
* J.S.
* Simon Tackley


text:
export interface Pg {
  dataGroup: string;
  description: string;
  dataSets: string ;
}


text:
/* See license.txt for terms of usage */

require.def("domplate/tableView", [
    "domplate/domplate",
    "core/lib",
    "i18n!nls/tableView",
    "domplate/domTree", //xxxHonza: hack, registered reps should be a separate module
    "core/trace"
],

function(Domplate, Lib, Strings, DomTree, Trace) { with (Domplate) {

// ********************************************************************************************* //

var TableView = domplate(
{
    className: "table",

    tag:
        DIV({"class": "dataTableSizer", "tabindex": "-1" },
            TABLE({"class": "dataTable", cellspacing: 0, cellpadding: 0, width: "100%",
                "role": "grid"},
                THEAD({"class": "dataTableThead", "role": "presentation"},
                    TR({"class": "headerRow focusRow dataTableRow subFocusRow", "role": "row",
                        onclick: "$onClickHeader"},
                        FOR("column", "$object.columns",
                            TH({"class": "headerCell a11yFocus", "role": "columnheader",
                                $alphaValue: "$column.alphaValue"},
                                DIV({"class": "headerCellBox"},
                                    "$column.label"
                                )
                            )
                        )
                    )
                ),
                TBODY({"class": "dataTableTbody", "role": "presentation"},
                    FOR("row", "$object.data|getRows",
                        TR({"class": "focusRow dataTableRow subFocusRow", "role": "row"},
                            FOR("column", "$row|getColumns",
                                TD({"class": "a11yFocus dataTableCell", "role": "gridcell"},
                                    TAG("$column|getValueTag", {object: "$column"})
                                )
                            )
                        )
                    )
                )
            )
        ),

    getValueTag: function(object)
    {
        var type = typeof(object);

        // Display embedded tree for object in table-cells
        if (type == "object")
            return DomTree.Reps.Tree.tag;

        var rep = DomTree.Reps.getRep(object);
        return rep.shortTag || rep.tag;
    },

    getRows: function(data)
    {
        var props = this.getProps(data);
        if (!props.length)
            return [];
        return props;
    },

    getColumns: function(row)
    {
        if (typeof(row) != "object")
            return [row];

        var cols = [];
        for (var i=0; i<this.columns.length; i++)
        {
            var prop = this.columns[i].property;

            if (!prop)
            {
                value = row;
            }
            else if (typeof row[prop] === "undefined")
            {
                var props = (typeof(prop) == "string") ? prop.split(".") : [prop];

                var value = row;
                for (var p in props)
                    value = (value && value[props[p]]) || undefined;
            }
            else
            {
                value = row[prop];
            }

            cols.push(value);
        }
        return cols;
    },

    getProps: function(obj)
    {
        if (typeof(obj) != "object")
            return [obj];

        if (obj.length)
            return Lib.cloneArray(obj);

        var arr = [];
        for (var p in obj)
        {
            var value = obj[p];
            if (this.domFilter(value, p))
                arr.push(value);
        }
        return arr;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    // Sorting

    onClickHeader: function(event)
    {
        var table = Lib.getAncestorByClass(event.target, "dataTable");
        var header = Lib.getAncestorByClass(event.target, "headerCell");
        if (!header)
            return;

        var numerical = !Lib.hasClass(header, "alphaValue");

        var colIndex = 0;
        for (header = header.previousSibling; header; header = header.previousSibling)
            ++colIndex;

        this.sort(table, colIndex, numerical);
    },

    sort: function(table, colIndex, numerical)
    {
        var tbody = Lib.getChildByClass(table, "dataTableTbody");
        var thead = Lib.getChildByClass(table, "dataTableThead");

        var values = [];
        for (var row = tbody.childNodes[0]; row; row = row.nextSibling)
        {
            var cell = row.childNodes[colIndex];
            var value = numerical ? parseFloat(cell.textContent) : cell.textContent;
            values.push({row: row, value: value});
        }

        values.sort(function(a, b) { return a.value < b.value ? -1 : 1; });

        var headerRow = thead.firstChild;
        var headerSorted = Lib.getChildByClass(headerRow, "headerSorted");
        Lib.removeClass(headerSorted, "headerSorted");
        if (headerSorted)
            headerSorted.removeAttribute('aria-sort');

        var header = headerRow.childNodes[colIndex];
        Lib.setClass(header, "headerSorted");

        if (!header.sorted || header.sorted == 1)
        {
            Lib.removeClass(header, "sortedDescending");
            Lib.setClass(header, "sortedAscending");
            header.setAttribute("aria-sort", "ascending");

            header.sorted = -1;

            for (var i = 0; i < values.length; ++i)
                tbody.appendChild(values[i].row);
        }
        else
        {
            Lib.removeClass(header, "sortedAscending");
            Lib.setClass(header, "sortedDescending");
            header.setAttribute("aria-sort", "descending")

            header.sorted = 1;

            for (var i = values.length-1; i >= 0; --i)
                tbody.appendChild(values[i].row);
        }
    },

    /**
     * Analyse data and return dynamically created list of columns.
     * @param {Object} data
     */
    getHeaderColumns: function(data)
    {
        // Get the first row in the object.
        var firstRow;
        for (var p in data)
        {
            firstRow = data[p];
            break;
        }

        if (typeof(firstRow) != "object")
            return [{label: Strings.objectProperties}];

        // Put together a column property, label and type (type for default sorting logic).
        var header = [];
        for (var p in firstRow)
        {
            var value = firstRow[p];
            if (!this.domFilter(value, p))
                continue;

            header.push({
                property: p,
                label: p,
                alphaValue: (typeof(value) != "number")
            });
        }

        return header;
    },

    /**
     * Filtering based on options set in the DOM panel.
     * @param {Object} value - a property value under inspection.
     * @param {String} name - name of the property.
     * @returns true if the value should be displayed, otherwise false.
     */
    domFilter: function(object, name)
    {
        return true;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    // Public

    render: function(parentNode, data, cols)
    {
        // No arguments passed into console.table method, bail out for now,
        // but some error message could be displayed in the future.
        if (!data)
            return;

        // Get header info from passed argument (can be null).
        var columns = [];
        for (var i=0; cols && i<cols.length; i++)
        {
            var col = cols[i];
            var prop = (typeof(col.property) != "undefined") ? col.property : col;
            var label = (typeof(col.label) != "undefined") ? col.label : prop;

            columns.push({
                property: prop,
                label: label,
                alphaValue: true
            });
        }

        // Generate header info from the data dynamically.
        if (!columns.length)
            columns = this.getHeaderColumns(data);

        try
        {
            this.columns = columns;
            var object = {data: data, columns: columns};
            var element = this.tag.append({object: object, columns: columns}, parentNode);

            // Set vertical height for scroll bar.
            var tBody = Lib.getElementByClass(element, "dataTableTbody");
            var maxHeight = 200; // xxxHonza: a pref?
            if (maxHeight > 0 && tBody.clientHeight > maxHeight)
                tBody.style.height = maxHeight + "px";
        }
        catch (err)
        {
            Trace.exception("tableView.render; EXCEPTION " + err, err);
        }
        finally
        {
            delete this.columns;
        }
    }
});

// ********************************************************************************************* //

return TableView;

// ********************************************************************************************* //
}});


text:
module SolidusMailchimpSync
  class Error < StandardError
    attr_reader :type, :title, :status, :detail, :instance,
                :request_method, :request_url, :request_body,
                :response_body, :response_hash

    def initialize( type:nil, title:nil, status: nil, detail: nil, instance: nil,
                    request_method:nil, request_url: nil, request_body: nil,
                    response_body: nil, response_hash: nil)

      @type = type
      @title = title
      @status = status
      @detail = detail
      @instance = instance

      @request_method = request_method.to_s.upcase
      @request_url = request_url
      @request_body = request_body

      @response_body = response_body
      @response_hash = response_hash

      super(constructed_message)
    end

    def constructed_message
      errors = response_hash.try { |h| h["errors"] }.to_s.presence
      [status, title, detail, errors].compact.join(': ')
    end
  end
end


text:
<?php

namespace MoySklad\Entities\Products;

use MoySklad\Traits\RequiresOnlyNameForCreation;

class Service extends AbstractProduct {
    use RequiresOnlyNameForCreation;
    public static $entityName = 'service';
}


text:
using AutoMapper;
using Microsoft.AspNet.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ShapingAPI.Entities;
using ShapingAPI.Infrastructure.Core;
using ShapingAPI.Infrastructure.Data.Repositories;
using ShapingAPI.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace ShapingAPI.Controllers
{
    [Route("api/[controller]")]
    public class CustomersController : Controller
    {
        #region Properties
        private readonly ICustomerRepository _customerRepository;
        private const int maxSize = 50;
        #endregion

        #region Constructor
        public CustomersController(ICustomerRepository customerRepository)
        {
            _customerRepository = customerRepository;
        }
        #endregion

        #region Actions
        public ActionResult Get(string props = null, int page = 1, int pageSize = maxSize)
        {
            try
            {
                var _customers = _customerRepository.LoadAll().Skip((page - 1) * pageSize).Take(pageSize);

                var _customersVM = Mapper.Map<IEnumerable<Customer>, IEnumerable<CustomerViewModel>>(_customers);

                JToken _jtoken = TokenService.CreateJToken(_customersVM, props);

                return Ok(_jtoken);
            }
            catch (Exception ex)
            {
                return new HttpStatusCodeResult(500);
            }
        }

        [Route("{customerId}")]
        public ActionResult Get(int customerId, string props = null)
        {
            try
            {
                var _customer = _customerRepository.Load(customerId);

                if (_customer == null)
                {
                    return HttpNotFound();
                }

                var _customerVM = Mapper.Map<Customer, CustomerViewModel>(_customer);

                JToken _jtoken = TokenService.CreateJToken(_customerVM, props);

                return Ok(_jtoken);
            }
            catch (Exception ex)
            {
                return new HttpStatusCodeResult(500);
            }
        }
        #endregion
    }
}


text:
package lila.user

import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import java.nio.ByteBuffer
import org.apache.commons.codec.binary.Base32
import reactivemongo.api.bson._

import lila.common.SecureRandom

import User.TotpToken

case class TotpSecret(secret: Array[Byte]) extends AnyVal {
  import TotpSecret._

  override def toString = "TotpSecret(****)"

  def base32: String = new Base32().encodeAsString(secret)

  def currentTotp = totp(System.currentTimeMillis / 30000)

  def totp(period: Long): TotpToken =
    TotpToken {
      val msg = ByteBuffer.allocate(8).putLong(0, period).array

      val hmac = Mac.getInstance("HMACSHA1")
      hmac.init(new SecretKeySpec(secret, "RAW"))
      val hash = hmac.doFinal(msg)

      val offset = hash.last & 0xf
      otpString(ByteBuffer.wrap(hash).getInt(offset) & 0x7fffffff)
    }

  def verify(token: TotpToken): Boolean = {
    val period = System.currentTimeMillis / 30000
    skewList.exists(skew => totp(period + skew) == token)
  }
}

object TotpSecret {
  // clock skews in rough order of likelihood
  private val skewList = List(0, -1, 1, -2, 2, -3, 3)

  private def otpString(otp: Int) = {
    val s = (otp % 1000000).toString
    "0" * (6 - s.length) + s
  }

  def apply(base32: String) = new TotpSecret(new Base32().decode(base32))

  def random = TotpSecret(SecureRandom.nextBytes(20))

  private[user] val totpSecretBSONHandler = lila.db.dsl.quickHandler[TotpSecret](
    { case v: BSONBinary => TotpSecret(v.byteArray) },
    v => BSONBinary(v.secret, Subtype.GenericBinarySubtype)
  )
}


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Server collations page
 *
 * @package PhpMyAdmin
 */

/**
 * requirements
 */
require_once 'libraries/common.inc.php';

/**
 * Does the common work
 */
require_once 'libraries/server_common.inc.php';

require_once 'libraries/server_collations.lib.php';

/**
 * Includes the required charset library
 */
require_once 'libraries/mysql_charsets.inc.php';

$response = PMA_Response::getInstance();

$response->addHTML(PMA_getHtmlForSubPageHeader('collations'));
$response->addHTML(
    PMA_getHtmlForCharsets(
        $mysql_charsets,
        $mysql_collations,
        $mysql_charsets_descriptions,
        $mysql_default_collations,
        $mysql_collations_available
    )
);


text:
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
ROOT_DIR=${DIR}/..

${ROOT_DIR}/deploy/confluent/bin/kafka-console-producer \
              --broker-list localhost:9092 --topic shakespeare \
              --compression-codec lz4 --new-producer < ${ROOT_DIR}/data/shakespeare.json

${ROOT_DIR}/deploy/confluent/bin/kafka-console-producer \
              --broker-list localhost:9092 --topic embedded \
              --compression-codec lz4 --new-producer < ${ROOT_DIR}/data/embedded.json

${ROOT_DIR}/deploy/confluent/bin/kafka-console-producer \
              --broker-list localhost:9092 --topic jsonkey --property parse.key=true \
              --compression-codec lz4 --new-producer < ${ROOT_DIR}/data/jsonkey.json


text:
require 'twilio-ruby'

# Get your Account SID and Auth Token from twilio.com/console
# To set up environmental variables, see http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']

# Initialize Twilio Client
@client = Twilio::REST::Client.new(account_sid, auth_token)

app = @client.api.v2010.accounts(account_sid).applications.create(
  friendly_name: 'Phone Me',
  voice_url: 'http://demo.twilio.com/docs/voice.xml',
  voice_method: 'GET'
)

puts app.voice_url


text:
module.exports.parse = function (url) {
	return require('url').parse(url, true).query;
};


text:
package io.leopard.web.freemarker.template;

import java.io.IOException;
import java.util.Map;

import freemarker.core.Environment;
import freemarker.template.SimpleScalar;
import freemarker.template.Template;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import io.leopard.web.freemarker.TemplateVariable;

/**
 * 消息Tab.
 *
 * @author 阿海
 *
 */

public class BodyTemplateDirective implements TemplateDirectiveModel, TemplateVariable {

	private static ThreadLocal<Map<String, Object>> DATA = new ThreadLocal<Map<String, Object>>();

	public static void setData(Map<String, Object> data) {
		DATA.set(data);
	}

	@Override
	public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
		// String folder = ((SimpleScalar) params.get("template_folder")).getAsString();
		String templateName = ((SimpleScalar) params.get("template_name")).getAsString();
		// String templateName = (String) params.get("template_name");

		Template template = env.getConfiguration().getTemplate(templateName + ".ftl");
		template.process(DATA.get(), env.getOut());
	}

	@Override
	public String getKey() {
		return "templateBody";
	}

}


text:
const ms = require('ms')

function merge (...args) {
  const merged = Object.assign({}, ...args)
  if (typeof merged.ttl === 'string') {
    merged.ttl = ms(merged.ttl)
  }
  return merged
}

function create (cfg) {
  let config = cfg || {
    ttl: 60000,
    key: (ctx) => ctx && ctx.request && ctx.request.href,
    storage: null
  }

  function cache (opts) {
    const options = merge(config, opts || {})

    return async function middleware (ctx, next) {
      const key = options.key(ctx, 'use')
      const cached = await options.storage.get(key)

      if (cached) {
        ctx.response.body = cached
        return
      }

      await next()
      if (ctx && ctx.response && ctx.response.body) {
        await options.storage.set(key, ctx.response.body, options.ttl)
      }
    }
  }

  cache.use = cache

  cache.config = function (opts = {}) {
    config = merge(config, opts)
    return config
  }

  cache.remove = function (opts) {
    const options = merge(config, opts || {})

    return function middleware (ctx, next) {
      const key = options.key(ctx, 'remove')
      return next().then(() => options.storage.remove(key))
    }
  }

  cache.clear = function (opts) {
    const options = merge(config, opts || {})

    return async function middleware (ctx, next) {
      const key = options.key(ctx, 'clear') || ''
      return next().then(() => options.storage.clear(key))
    }
  }

  return cache
}

const cache = create()
module.exports = cache
module.exports.create = create
module.exports.default = module.exports