text:
<bill session="110" type="s" number="2495" updated="2009-01-09T17:03:29-05:00">
	<status><introduced date="1197954000" datetime="2007-12-18"/></status>

	<introduced date="1197954000" datetime="2007-12-18"/>
	<titles>
		<title type="short" as="introduced">Bail Bond Fairness Act of 2007</title>
		<title type="official" as="introduced">A bill to amend title 18, United States Code, and the Federal Rules of Criminal Procedure with respect to bail bond forfeitures.</title>
	</titles>
	<sponsor id="300008"/>
	<cosponsors>
		<cosponsor id="300029" joined="2008-04-29"/>
		<cosponsor id="400064" joined="2007-12-18"/>
		<cosponsor id="300030" joined="2008-05-14"/>
		<cosponsor id="300047" joined="2007-12-18"/>
		<cosponsor id="400621" joined="2008-06-27"/>
		<cosponsor id="300092" joined="2007-12-18"/>
		<cosponsor id="300078" joined="2008-04-10"/>
	</cosponsors>
	<actions>
		<action date="1197954000" datetime="2007-12-18"><text>Sponsor introductory remarks on measure. (CR S15913-15914)</text></action>
		<action date="1197954000" datetime="2007-12-18"><text>Read twice and referred to the Committee on the Judiciary.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	12/18/2007--Introduced.
Bail Bond Fairness Act of 2007 - Amends the federal criminal code to prohibit a judicial officer from declaring forfeited a bail bond for violation of specified collateral release conditions other than failing to appear in court. Makes forfeiture of a bail bond for violation of such collateral release conditions unavailable as a sanction.
Amends the Federal Rules of Criminal Procedure to provide that if a defendant fails to appear physically before the court (currently, if there is a breach of a condition of a bond), the court shall declare a forfeiture of the bail.

</bill>


text:
<?xml version="1.0"?>

<role xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
	  xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3"
	  xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3"
		oid="a19ede0a-94ff-4edd-990b-699b3ad7ab94">
	<name>k23</name>
	<inducement>
		<policyRule>
			<policyConstraints>
				<minAssignees>
					<multiplicity>1</multiplicity>
				</minAssignees>
			</policyConstraints>
			<policyActions>
				<enforcement>
					<condition>

					</condition>
				</enforcement>
				<approval>
					<condition>

					</condition>
					<approvalSchema>
						<stage>
							<approverExpression>

							</approverExpression>
						</stage>
					</approvalSchema>
				</approval>
			</policyActions>
			<evaluationTarget>assignment</evaluationTarget>
		</policyRule>
		<order>2</order>
	</inducement>
</role>

redpajama_set_name: RedPajamaGithub


text:
package cheesegame.entities;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;

public abstract class Entity {

	public Vector2 position;
	public Rectangle hitbox;
	public Texture texture;

	public Entity(final Vector2 position, final Rectangle hitbox, final String texFilename) {
		this.position = position;
		this.hitbox = hitbox;
		texture = new Texture(Gdx.files.internal(texFilename));
	}

	public abstract void update(float delta);
}


text:
from virtualisation.clock.abstractclock import AbstractClock

__author__ = 'Marten Fischer (m.fischer@hs-osnabrueck.de)'

from virtualisation.wrapper.parser.abstractparser import AbstractParser
from virtualisation.misc.jsonobject import JSONObject as JOb
from virtualisation.misc.utils import unicode2ascii as u, str2Type
import datetime as dt

class JSONParser(AbstractParser):
    """
    Maps a list of values read by a CSVReader with a given naming list
    """

    def __init__(self, wrapper):
        super(JSONParser, self).__init__(wrapper)
        self.timestampfield = None
        if self.wrapper.getSensorDescription().isTimestampedStream():
            self.timestampfield = self.wrapper.getSensorDescription().timestamp.inField
            self.timestampformat = self.wrapper.getSensorDescription().timestamp.format

    def parse(self, data, clock):
        if not data:  # nothing received or nothing in the history -> nothing to parse
            return None

        if isinstance(data, str) or isinstance(data, unicode):
            data = JOb(u(data))

        result = JOb()
        sd = self.wrapper.getSensorDescription()
        result.fields = sd.fields
        for fieldname in sd.fields:
            result[fieldname] = JOb()
            result[fieldname].propertyName = sd.field[fieldname].propertyName
            result[fieldname].propertyURI = sd.field[fieldname].propertyURI
            if "unit" in sd.field[fieldname]:
                result[fieldname].unit = sd.field[fieldname].unit
            result[fieldname].sensorID = sd.fullSensorID
            result[fieldname].observationSamplingTime = clock.timeAsString()
            if self.timestampfield and self.timestampfield in data:
                result[fieldname].observationResultTime = sd.parseTimestamp(data[self.timestampfield]).strftime(AbstractClock.format)
            else:
                result[fieldname].observationResultTime = result[fieldname].observationSamplingTime

            if sd.field[fieldname].dataType == "datetime.datetime":
                if sd.field[fieldname].format.startswith("UNIX"):
                    result[fieldname].value = sd.parseTimestamp(data[fieldname]) if fieldname in data else None
                else:
                    result[fieldname].value = dt.datetime.strptime(data[fieldname], sd.field[fieldname].format) if fieldname in data else None
            else:
                result[fieldname].value = str2Type(u(data[fieldname]), sd.field[fieldname].dataType) if fieldname in data else None

        return result


text:
/*
 * Blackjack Simulator calculates the odds of drawing blackjack
 * from a fair deck of 52 shuffled cards by simulating trials.
 */
package com.comp110.lecture10; // A "package" is a grouping of functionality

import com.comp110.cards.Deck; // We're importing some functionality from
import com.comp110.cards.Card; // another package written for this class.

class BlackjackSimulator {

  public static void main(String[] args) {

      Deck deck = new Deck(); // Initialize a new Deck variable

      Card card0, card1;      // Declare 2 card variables
      card0 = deck.draw();    // Draw cards from deck
      card1 = deck.draw();

      System.out.println("You drew: " + card0 + " " + card1);

  }

}


text:
package com.commercetools.sunrise.common.reverserouter;

import play.mvc.Call;

public interface AddressBookReverseRouter {

    Call addressBookCall(final String languageTag);

    Call addAddressToAddressBookCall(final String languageTag);

    Call addAddressToAddressBookProcessFormCall(final String languageTag);

    Call changeAddressInAddressBookCall(final String languageTag, final String addressId);

    Call changeAddressInAddressBookProcessFormCall(final String languageTag, final String addressId);

    Call removeAddressFromAddressBookProcessFormCall(final String languageTag, final String addressId);

}


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

<title>com.hourglassapps.serialise Class Hierarchy</title>
<meta name="date" content="2015-04-26">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.hourglassapps.serialise

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

com.hourglassapps.serialise.AbstractDeserialiser<T> (implements com.hourglassapps.serialise.Deserialiser<T>)

com.hourglassapps.serialise.AbstractSerialiser<T> (implements com.hourglassapps.serialise.Serialiser<T>)

com.hourglassapps.serialise.Buffer

com.hourglassapps.serialise.JSONParser<I,C,R> (implements java.lang.AutoCloseable, com.hourglassapps.util.ThrowingIterable<T>)

com.hourglassapps.serialise.PoemRecordXMLParser (implements java.lang.AutoCloseable, com.hourglassapps.util.ThrowingIterable<T>)

java.io.Reader (implements java.io.Closeable, java.lang.Readable)

com.hourglassapps.serialise.RemoveUnescapesReader

com.hourglassapps.serialise.ReGroupHandler

java.lang.Throwable (implements java.io.Serializable)

java.lang.Exception

com.hourglassapps.serialise.SerialiseException

com.hourglassapps.serialise.ParseException

Interface Hierarchy

com.hourglassapps.serialise.Deserialiser<T>

com.hourglassapps.serialise.SearchAndReplacer

com.hourglassapps.serialise.Serialiser<T>

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
@class DBSHARINGAccessLevel;
@class DBSHARINGAudienceRestrictingSharedFolder;
@class DBSHARINGLinkAudience;
@class DBSHARINGLinkPermission;
@class DBSHARINGSharedContentLinkMetadata;

NS_ASSUME_NONNULL_BEGIN

#pragma mark - API Object

///
/// The `SharedContentLinkMetadata` struct.
///
/// Metadata of a shared link for a file or folder.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBSHARINGSharedContentLinkMetadata : DBSHARINGSharedContentLinkMetadataBase <DBSerializable, NSCopying>

#pragma mark - Instance fields

/// The URL of the link.
@property (nonatomic, readonly, copy) NSString *url;

#pragma mark - Constructors

///
/// Full constructor for the struct (exposes all instance variables).
///
/// @param audienceOptions The audience options that are available for the
/// content. Some audience options may be unavailable. For example, team_only
/// may be unavailable if the content is not owned by a user on a team. The
/// 'default' audience option is always available if the user can modify link
/// settings.
/// @param currentAudience The current audience of the link.
/// @param linkPermissions A list of permissions for actions you can perform on
/// the link.
/// @param passwordProtected Whether the link is protected by a password.
/// @param url The URL of the link.
/// @param accessLevel The access level on the link for this file.
/// @param audienceRestrictingSharedFolder The shared folder that prevents the
/// link audience for this link from being more restrictive.
/// @param expiry Whether the link has an expiry set on it. A link with an
/// expiry will have its  audience changed to members when the expiry is
/// reached.
///
/// @return An initialized instance.
///
- (instancetype)initWithAudienceOptions:(NSArray<DBSHARINGLinkAudience *> *)audienceOptions
                        currentAudience:(DBSHARINGLinkAudience *)currentAudience
                        linkPermissions:(NSArray<DBSHARINGLinkPermission *> *)linkPermissions
                      passwordProtected:(NSNumber *)passwordProtected
                                    url:(NSString *)url
                            accessLevel:(nullable DBSHARINGAccessLevel *)accessLevel
        audienceRestrictingSharedFolder:
            (nullable DBSHARINGAudienceRestrictingSharedFolder *)audienceRestrictingSharedFolder
                                 expiry:(nullable NSDate *)expiry;

///
/// Convenience constructor (exposes only non-nullable instance variables with
/// no default value).
///
/// @param audienceOptions The audience options that are available for the
/// content. Some audience options may be unavailable. For example, team_only
/// may be unavailable if the content is not owned by a user on a team. The
/// 'default' audience option is always available if the user can modify link
/// settings.
/// @param currentAudience The current audience of the link.
/// @param linkPermissions A list of permissions for actions you can perform on
/// the link.
/// @param passwordProtected Whether the link is protected by a password.
/// @param url The URL of the link.
///
/// @return An initialized instance.
///
- (instancetype)initWithAudienceOptions:(NSArray<DBSHARINGLinkAudience *> *)audienceOptions
                        currentAudience:(DBSHARINGLinkAudience *)currentAudience
                        linkPermissions:(NSArray<DBSHARINGLinkPermission *> *)linkPermissions
                      passwordProtected:(NSNumber *)passwordProtected
                                    url:(NSString *)url;

@end

#pragma mark - Serializer Object

///
/// The serialization class for the `SharedContentLinkMetadata` struct.
///
@interface DBSHARINGSharedContentLinkMetadataSerializer : NSObject

///
/// Serializes `DBSHARINGSharedContentLinkMetadata` instances.
///
/// @param instance An instance of the `DBSHARINGSharedContentLinkMetadata` API
/// object.
///
/// @return A json-compatible dictionary representation of the
/// `DBSHARINGSharedContentLinkMetadata` API object.
///
+ (NSDictionary *)serialize:(DBSHARINGSharedContentLinkMetadata *)instance;

///
/// Deserializes `DBSHARINGSharedContentLinkMetadata` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBSHARINGSharedContentLinkMetadata` API object.
///
/// @return An instantiation of the `DBSHARINGSharedContentLinkMetadata` object.
///
+ (DBSHARINGSharedContentLinkMetadata *)deserialize:(NSDictionary *)dict;

@end

NS_ASSUME_NONNULL_END


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hedwigia 74: 76 (1934)

#### Original name
Tuberculina rosae Petr.

### Remarks
null


text:
package pl.edu.agh.mplt.parser.declaration.constraint

import scala.util.parsing.combinator.JavaTokenParsers
import pl.edu.agh.mplt.parser.phrase.expression.Expression

trait ConstraintExpressionAMPLParser extends JavaTokenParsers {
   def expr: Parser[Expression]

   def constraintExpression: Parser[ConstraintExpression] =
      complementary | boundedConstraint

   private def boundedConstraint = dualBounds | singleBound

   private def complementary = dualBounds ~ ("complements" ~> expr) ^? {
      case cexpr ~ expr => MixedComplementarity(expr, cexpr)
   } | expr ~ ("complements" ~> dualBounds) ^? {
      case expr ~ cexpr => MixedComplementarity(expr, cexpr)
   } | singleBound ~ ("complements" ~> singleBound) ^? {
      case leftBound ~ rightBound => SimpleComplementarity(leftBound, rightBound)
   }

   private def singleBound = <= | == | >=

   private def <= = expr ~ ("<=" ~> expr) ^^ {
      case vexpr ~ cexpr => BoundedConstraint(expr = vexpr, rightExpression = Some(Constraint.<=(cexpr)))
   }

   private def == = expr ~ ("=" ~> expr) ^^ {
      case vexpr ~ cexpr => BoundedConstraint(expr = vexpr, rightExpression = Some(Constraint.==(cexpr)))
   }

   private def >= = expr ~ (">=" ~> expr) ^^ {
      case vexpr ~ cexpr => BoundedConstraint(expr = vexpr, rightExpression = Some(Constraint.>=(cexpr)))
   }

   private def dualBounds = <=<= | >=>=

   private def <=<= = expr ~ ("<=" ~> expr <~ "<=") ~ expr ^^ {
      case cexpr1 ~ vexpr ~ cexpr2 => BoundedConstraint(Some(Constraint.<=(cexpr1)), vexpr, Some(Constraint.<=(cexpr2)))
   }

   private def >=>= = expr ~ (">=" ~> expr <~ ">=") ~ expr ^^ {
      case cexpr1 ~ vexpr ~ cexpr2 => BoundedConstraint(Some(Constraint.>=(cexpr1)), vexpr, Some(Constraint.>=(cexpr2)))
   }

}


text:
CoreAPI Readme
==============

Requirements
------------
 - PHP Version => 5.3.15 (or later).

**Build Script**

 -  PHP CLI SAPI
 - [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer)
 - [CakePHP Code Sniffer](https://github.com/cakephp/cakephp-codesniffer)*
 - [PHPUnit](https://github.com/sebastianbergmann/phpunit)
 - [ApiGen](http://apigen.org)

*Default coding standard


text:
package com.github.jjYBdx4IL.utils.math;

//CHECKSTYLE:OFF
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import static org.junit.Assert.*;

import com.github.jjYBdx4IL.utils.math.DigestFormatter;

import org.junit.Test;

/**
 *
 * @author Github jjYBdx4IL Projects
 */
public class DigestFormatterTest {

    public static final String TEST_INPUT = "abc";

    @Test
    public void testMd5() throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        assertNotNull(md);
        byte[] digest = md.digest(TEST_INPUT.getBytes("ASCII"));

        assertEquals("900150983cd24fb0d6963f7d28e17f72", DigestFormatter.md5(digest));
    }

    @Test
    public void testSha1() throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        assertNotNull(md);
        byte[] digest = md.digest(TEST_INPUT.getBytes("ASCII"));

        assertEquals("a9993e364706816aba3e25717850c26c9cd0d89d", DigestFormatter.sha1(digest));
    }

}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>IFixingRequired.GetFixedObject Method</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0

IFixingRequired.GetFixedObject Method

 Get a portable version of this object

        [Visual Basic]

Function GetFixedObject() As Object

        [C#]

        object GetFixedObject();

Return Value

the portable instance of this object

Remarks

 Get a portable instance object that represents the current state of this object. The portable object can be stored and logged from any thread with identical results.

See Also

IFixingRequired Interface | log4net.Core Namespace
<object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;"><param name="Keyword" value="GetFixedObject method"></param><param name="Keyword" value="GetFixedObject method, IFixingRequired interface"></param><param name="Keyword" value="IFixingRequired.GetFixedObject method"></param></object>

Copyright 2004-2013 The Apache Software Foundation.

Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.


text:
import Ember from 'ember';
import Family from 'web/models/family';
import FamilyMember from 'web/models/familyMember';
import ListResult from 'web/models/listResult';

export default Ember.Service.extend({
  client: Ember.inject.service('client'),
  searchFamilies:function(){
    const client = this.get('client');
    let results = ListResult.create({childType:Family});

    let searchUrl = '/auditioner/families';

    client.getResource(searchUrl,results);

    return results;
  },
  loadFamilyById:function(familyId)
  {
    const client = this.get('client');
    const url = '/auditioner/families/' + familyId;

    const family = Family.create();

    family.set('client',client);
    family.set('path',url);

    client.getResource(url,family);

    return family;
  },
  saveFamily:function(family)
  {
    const client = this.get('client');
    if(family.get('location')) {
      return client.putResource(family);
    }
    else {
      return client.postResource("/auditioner/families", family);
    }
  },
  reloadFamily:function(family)
  {
    const client = this.get('client');

    client.getResource(family.get('location'),family);

    return family;
  },
  deleteFamily:function(family)
  {
    const client = this.get('client');

    return client.deleteResource(family);
  },
  createFamily:function()
  {
    const client = this.get('client');
    const family = Family.create();
    family.set('client',client);
    return family;
  },
  loadFamilyMemberById:function(familyId,familyMemberId)
  {
    const client = this.get('client');
    const url = '/auditioner/families/' + familyId + '/family_member/' + familyMemberId;

    const familyMember = FamilyMember.create();

    familyMember.set('client',client);
    familyMember.set('path',url);

    client.getResource(url,familyMember);

    return familyMember;
  },
  loadFamilyMembersByFamilyId: function(familyId) {
    const client = this.get('client');
    let results = ListResult.create({childType:FamilyMember});

    let searchUrl = '/auditioner/families/' + familyId + '/family_member/';

    client.getResource(searchUrl,results);

    return results;
  },
  deleteFamilyMember:function(familyMember)
  {
    const client = this.get('client');

    return client.deleteResource(familyMember);
  },
  createFamilyMember:function()
  {
    const client = this.get('client');
    const familyMember = FamilyMember.create();
    familyMember.set('client',client);
    return familyMember;
  },
  saveFamilyMember:function(familyId,saveFamilyMember)
  {
    const client = this.get('client');

    if (saveFamilyMember.get("location")) {
      return client.putResource(saveFamilyMember);
    }
    else {
      return client.postResource("/auditioner/families/" + familyId + "/family_member",saveFamilyMember);
    }
  },

});


text:
$(document).ready(function(){

    /* --- dropdown menu */
    $(function(){
        $("ul.dropdown li").hover(function(){
            $(this).addClass("hover");
            $('ul:first',this).css('visibility', 'visible');
        }, function(){
            $(this).removeClass("hover");
            $('ul:first',this).css('visibility', 'hidden');
        });
        $("ul.dropdown li ul li:has(ul)").find("a:first").append(" » ");
    });

    /* -----  random gutter image ----- */
    var classes = ['bodybg1', 'bodybg2', 'bodybg3', 'bodybg4', 'bodybg5', 'bodybg6', 'bodybg7'];
    var numRand = Math.floor(Math.random()*7);
    $('body').addClass(classes[numRand]);

    /* ------exp leaderboard 660x150 banner   */
    var $popban = $(document).find('#expleaderboard');
    $(function(){
        $popban.delay(10000).animate({ height:18, bottom:0}, function(){
            //show hide funx
            $popban.mouseover(function(){
                $popban.stop().animate({ height:150, bottom:150});
            });
            $popban.mouseout(function(){
                $popban.stop().animate({ height:18, bottom:0});
            });
        });
    });

    /* ------page takeover header shrink from 250 to 100   */
    var $tkohdr = $(document).find('.takeover-hdr');
    $(function(){
        $tkohdr.delay(10000).animate({ height:100, bottom:0, marginTop:0}, function(){
            //show hide funx
            $tkohdr.mouseover(function(){
                $tkohdr.stop().animate({ height:250, bottom:250, marginTop:0});
            });
            $tkohdr.mouseout(function(){
                $tkohdr.stop().animate({ height:100, bottom:0, marginTop:0});
            });
        });
    });

});


text:
require 'helper'

describe 'find_in_batches' do
  after do
    Post.destroy_all
  end

  it 'accepts finder options' do
    foo = Post.create title: 'foo'
    Post.create title: 'bar'

    assert_deprecated do
      Post.find_in_batches(conditions: "title = 'foo'") do |records|
        records.must_equal [foo]
      end
    end
  end
end


text:
'''
Test 1 preaccept callback (without delay) two times
'''
#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you under the Apache License, Version 2.0 (the
#  "License"); you may not use this file except in compliance
#  with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os
import re

Test.Summary = '''
Test different combinations of TLS handshake hooks to ensure they are applied consistently.
'''

Test.SkipUnless(Condition.HasProgram("grep", "grep needs to be installed on system for this test to work"))

ts = Test.MakeATSProcess("ts", select_ports=False)
server = Test.MakeOriginServer("server")
request_header = {"headers": "GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
# desired response form the origin server
response_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
server.addResponse("sessionlog.json", request_header, response_header)

ts.addSSLfile("ssl/server.pem")
ts.addSSLfile("ssl/server.key")

ts.Variables.ssl_port = 4443
ts.Disk.records_config.update({
    'proxy.config.diags.debug.enabled': 1,
    'proxy.config.diags.debug.tags': 'ssl_hook_test',
    'proxy.config.ssl.server.cert.path': '{0}'.format(ts.Variables.SSLDir),
    'proxy.config.ssl.server.private_key.path': '{0}'.format(ts.Variables.SSLDir),
    # enable ssl port
    'proxy.config.http.server_ports': '{0}:ssl'.format(ts.Variables.ssl_port),
    'proxy.config.ssl.client.verify.server':  0,
    'proxy.config.ssl.server.cipher_suite': 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:AES128-GCM-SHA256:AES256-GCM-SHA384:ECDHE-RSA-RC4-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:RC4-SHA:RC4-MD5:AES128-SHA:AES256-SHA:DES-CBC3-SHA!SRP:!DSS:!PSK:!aNULL:!eNULL:!SSLv2',
})

ts.Disk.ssl_multicert_config.AddLine(
    'dest_ip=* ssl_cert_name=server.pem ssl_key_name=server.key'
)

ts.Disk.remap_config.AddLine(
    'map https://example.com:4443 http://127.0.0.1:{0}'.format(server.Variables.Port)
)

Test.PreparePlugin(os.path.join(Test.Variables.AtsTestToolsDir, 'plugins', 'ssl_hook_test.cc'), ts, '-preaccept=2')

tr = Test.AddTestRun("Test two preaccept hooks")
tr.Processes.Default.StartBefore(server)
tr.Processes.Default.StartBefore(Test.Processes.ts, ready=When.PortOpen(ts.Variables.ssl_port))
tr.StillRunningAfter = ts
tr.StillRunningAfter = server
tr.Processes.Default.Command = 'curl -k -H \'host:example.com:{0}\' https://127.0.0.1:{0}'.format(ts.Variables.ssl_port)
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Streams.stdout = "gold/preaccept-1.gold"

ts.Streams.stderr = "gold/ts-preaccept-2.gold"

# the preaccept may get triggered twice because the test framework creates a TCP connection before handing off to traffic_server
preacceptstring0 = "Pre accept callback 0"
preacceptstring1 = "Pre accept callback 1"
ts.Streams.All = Testers.ContainsExpression(
    "\A(?:(?!{0}).)*{0}.*({0})?(?!.*{0}).*\Z".format(preacceptstring0), "Pre accept message appears only once or twice", reflags=re.S | re.M)
ts.Streams.All = Testers.ContainsExpression(
    "\A(?:(?!{0}).)*{0}.*({0})?(?!.*{0}).*\Z".format(preacceptstring1), "Pre accept message appears only once or twice", reflags=re.S | re.M)

tr.Processes.Default.TimeOut = 5
tr.TimeOut = 5


text:
package com.hibegin.http.server.util;

import com.hibegin.common.util.LoggerUtil;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ServerInfo {

    private static final Logger LOGGER = LoggerUtil.getLogger(FreeMarkerUtil.class);
    private static String name;
    private static String version;
    private static Date time;

    static {
        Properties properties = new Properties();
        InputStream inputStream = ServerInfo.class.getResourceAsStream("/ServerInfo.properties");
        if (inputStream != null) {
            try {
                properties.load(inputStream);
                name = properties.get("server.name").toString();
                if (properties.get("server.version") != null && !"".equals(properties.get("server.version"))) {
                    version = properties.get("server.version").toString();
                }
                if (properties.get("server.buildTime") != null && !"".equals(properties.get("server.buildTime"))) {
                    time = new SimpleDateFormat("yyyy-MM-dd hh:mm").parse(properties.get("server.buildTime").toString());
                }
            } catch (IOException | ParseException e) {
                LOGGER.log(Level.SEVERE, "", e);
            }
        }
        if (name == null) {
            name = "SimpleWebServer";
        }
        if (version == null) {
            version = "0.1";
        }
        if (time == null) {
            time = new Date();
        }

    }

    public static String getName() {
        return name;
    }

    public static String getVersion() {
        return version;
    }

    public static Date getTime() {
        return time;
    }

    public static void main(String[] args) {
        System.out.println("name = " + name);
        System.out.println("version = " + version);
        System.out.println("time = " + time);
    }
}


text:
package org.apache.flink.api.scala.runtime

import java.util
import java.util.Random

import org.apache.flink.api.common.ExecutionConfig
import org.apache.flink.api.common.typeinfo.TypeInformation
import org.apache.flink.api.java.typeutils.TupleTypeInfoBase
import org.apache.flink.api.java.typeutils.runtime.AbstractGenericTypeSerializerTest._
import org.apache.flink.api.scala._
import org.apache.flink.api.scala.typeutils.CaseClassSerializer
import org.apache.flink.util.StringUtils
import org.joda.time.LocalDate
import org.junit.Assert._
import org.junit.{Assert, Test}

import scala.collection.JavaConverters._

class TupleSerializerTest {

  @Test
  def testProperDeepCopy(): Unit = {
    val tpe = createTypeInformation[((String, Int), (Int, String))]

    val originalSerializer =
      tpe.createSerializer(new ExecutionConfig)
        .asInstanceOf[CaseClassSerializer[((String, Int), (Int, String))]]
    val duplicateSerializer = originalSerializer.duplicate()

    duplicateSerializer.getFieldSerializers

    // the list of child serializers must be duplicated
    assertTrue(duplicateSerializer.getFieldSerializers ne originalSerializer.getFieldSerializers)

    // each of the child serializers (which are themselves CaseClassSerializers) must be duplicated
    assertTrue(
      duplicateSerializer.getFieldSerializers()(0) ne originalSerializer.getFieldSerializers()(0))

    assertTrue(
      duplicateSerializer.getFieldSerializers()(1) ne originalSerializer.getFieldSerializers()(1))
  }

  @Test
  def testTuple1Int(): Unit = {
    val testTuples = Array(Tuple1(42), Tuple1(1), Tuple1(0), Tuple1(-1), Tuple1(Int.MaxValue),
      Tuple1(Int.MinValue))
    runTests(testTuples, 4)
  }

  @Test
  def testTuple1String(): Unit = {
    val rnd: Random = new Random(68761564135413L)
    val testTuples = Array(
      Tuple1(StringUtils.getRandomString(rnd, 10, 100)),
      Tuple1("abc"),
      Tuple1(""),
      Tuple1(StringUtils.getRandomString(rnd, 30, 170)),
      Tuple1(StringUtils.getRandomString(rnd, 15, 50)),
      Tuple1(""))
    runTests(testTuples, -1)
  }

  @Test
  def testTuple1StringArray(): Unit = {
    val rnd: Random = new Random(289347567856686223L)

    val arr1 = Array(
      "abc",
      "",
      StringUtils.getRandomString(rnd, 10, 100),
      StringUtils.getRandomString(rnd, 15, 50),
      StringUtils.getRandomString(rnd, 30, 170),
      StringUtils.getRandomString(rnd, 14, 15),
      "")
    val arr2 = Array(
      "foo",
      "",
      StringUtils.getRandomString(rnd, 10, 100),
      StringUtils.getRandomString(rnd, 1000, 5000),
      StringUtils.getRandomString(rnd, 30000, 35000),
      StringUtils.getRandomString(rnd, 100 * 1024, 105 * 1024),
      "bar")
    val testTuples = Array(Tuple1(arr1), Tuple1(arr2))
    runTests(testTuples, -1)
  }

  @Test
  def testTuple2StringDouble(): Unit = {
    val rnd: Random = new Random(807346528946L)

    val testTuples = Array(
      (StringUtils.getRandomString(rnd, 10, 100), rnd.nextDouble),
      (StringUtils.getRandomString(rnd, 10, 100), rnd.nextDouble),
      (StringUtils.getRandomString(rnd, 10, 100), rnd.nextDouble),
      ("", rnd.nextDouble),
      (StringUtils.getRandomString(rnd, 10, 100), rnd.nextDouble),
      (StringUtils.getRandomString(rnd, 10, 100), rnd.nextDouble))
    runTests(testTuples, -1)
  }

  @Test
  def testTuple2StringJodaTime(): Unit = {
    val rnd: Random = new Random(807346528946L)

    val testTuples = Array(
      (StringUtils.getRandomString(rnd, 10, 100), new LocalDate(rnd.nextInt)),
      (StringUtils.getRandomString(rnd, 10, 100), new LocalDate(rnd.nextInt)),
      (StringUtils.getRandomString(rnd, 10, 100), new LocalDate(rnd.nextInt)),
      ("", rnd.nextDouble),
      (StringUtils.getRandomString(rnd, 10, 100), new LocalDate(rnd.nextInt)),
      (StringUtils.getRandomString(rnd, 10, 100), new LocalDate(rnd.nextInt)))

    runTests(testTuples, -1)
  }

  @Test
  def testTuple2StringStringArray(): Unit = {
    val rnd: Random = new Random(289347567856686223L)

    val arr1 = Array(
      "abc",
      "",
      StringUtils.getRandomString(rnd, 10, 100),
      StringUtils.getRandomString(rnd, 15, 50),
      StringUtils.getRandomString(rnd, 30, 170),
      StringUtils.getRandomString(rnd, 14, 15), "")
    val arr2 = Array(
      "foo",
      "",
      StringUtils.getRandomString(rnd, 10, 100),
      StringUtils.getRandomString(rnd, 1000, 5000),
      StringUtils.getRandomString(rnd, 30000, 35000),
      StringUtils.getRandomString(rnd, 100 * 1024, 105 * 1024),
      "bar")
    val testTuples = Array(
      (StringUtils.getRandomString(rnd, 30, 170), arr1),
      (StringUtils.getRandomString(rnd, 30, 170), arr2),
      (StringUtils.getRandomString(rnd, 30, 170), arr1),
      (StringUtils.getRandomString(rnd, 30, 170), arr2),
      (StringUtils.getRandomString(rnd, 30, 170), arr2))
    runTests(testTuples, -1)
  }

  @Test
  def testTuple5CustomObjects(): Unit = {
    val rnd: Random = new Random(807346528946L)

    val a = new SimpleTypes
    val b =  new SimpleTypes(rnd.nextInt, rnd.nextLong, rnd.nextInt.asInstanceOf[Byte],
        StringUtils.getRandomString(rnd, 10, 100), rnd.nextInt.asInstanceOf[Short], rnd.nextDouble)
    val c = new SimpleTypes(rnd.nextInt, rnd.nextLong, rnd.nextInt.asInstanceOf[Byte],
        StringUtils.getRandomString(rnd, 10, 100), rnd.nextInt.asInstanceOf[Short], rnd.nextDouble)
    val d = new SimpleTypes(rnd.nextInt, rnd.nextLong, rnd.nextInt.asInstanceOf[Byte],
        StringUtils.getRandomString(rnd, 10, 100), rnd.nextInt.asInstanceOf[Short], rnd.nextDouble)
    val e = new SimpleTypes(rnd.nextInt, rnd.nextLong, rnd.nextInt.asInstanceOf[Byte],
        StringUtils.getRandomString(rnd, 10, 100), rnd.nextInt.asInstanceOf[Short], rnd.nextDouble)
    val f = new SimpleTypes(rnd.nextInt, rnd.nextLong, rnd.nextInt.asInstanceOf[Byte],
        StringUtils.getRandomString(rnd, 10, 100), rnd.nextInt.asInstanceOf[Short], rnd.nextDouble)
    val g = new SimpleTypes(rnd.nextInt, rnd.nextLong, rnd.nextInt.asInstanceOf[Byte],
        StringUtils.getRandomString(rnd, 10, 100), rnd.nextInt.asInstanceOf[Short], rnd.nextDouble)

    val o1 = new ComplexNestedObject1(5626435)
    val o2 = new ComplexNestedObject1(76923)
    val o3 = new ComplexNestedObject1(-1100)
    val o4 = new ComplexNestedObject1(0)
    val o5 = new ComplexNestedObject1(44)

    val co1 = new ComplexNestedObject2(rnd)
    val co2 = new ComplexNestedObject2
    val co3 = new ComplexNestedObject2(rnd)
    val co4 = new ComplexNestedObject2(rnd)

    val b1 = new Book(976243875L, "The Serialization Odysse", 42)
    val b2 = new Book(0L, "Debugging byte streams", 1337)
    val b3 = new Book(-1L, "Low level interfaces", 0xC0FFEE)
    val b4 = new Book(Long.MaxValue, "The joy of bits and bytes", 0xDEADBEEF)
    val b5 = new Book(Long.MaxValue, "Winnign a prize for creative test strings", 0xBADF00)
    val b6 = new Book(-2L, "Distributed Systems", 0xABCDEF0123456789L)

    // We need to use actual java Lists here, to make them serializable by the GenericSerializer
    val list = new util.LinkedList[String]()
    list.addAll(List("A", "B", "C", "D", "E").asJava)
    val ba1 = new BookAuthor(976243875L, list, "Arno Nym")

    val list2 = new util.LinkedList[String]()
    val ba2 = new BookAuthor(987654321L, list2, "The Saurus")

    val testTuples = Array(
      (a, b1, o1, ba1, co1),
      (b, b2, o2, ba2, co2),
      (c, b3, o3, ba1, co3),
      (d, b2, o4, ba1, co4),
      (e, b4, o5, ba2, co4),
      (f, b5, o1, ba2, co4),
      (g, b6, o4, ba1, co2))
    runTests(testTuples, -1)
  }

  private final def runTests[T <: Product : TypeInformation](instances: Array[T], length: Int) {
    try {
      // Register the custom Kryo Serializer
      val conf = new ExecutionConfig()
      conf.registerTypeWithKryoSerializer(classOf[LocalDate], classOf[LocalDateSerializer])

      val tupleTypeInfo = implicitly[TypeInformation[T]].asInstanceOf[TupleTypeInfoBase[T]]
      val serializer = tupleTypeInfo.createSerializer(conf)
      val tupleClass = tupleTypeInfo.getTypeClass
      val test = new TupleSerializerTestInstance[T](serializer, tupleClass, length, instances)
      test.testAll()
    } catch {
      case e: Exception => {
        System.err.println(e.getMessage)
        e.printStackTrace()
        Assert.fail(e.getMessage)
      }
    }
  }
}


text:
package com.eleith.calchoochoo.data;

import org.parceler.Parcel;

@Parcel(analyze = Routes.class)
public class Routes {
  public String route_id;
  public String route_short_name;
  public String route_long_name;
  public int route_type;
  public String route_color;
}


text:
import DS from 'ember-data';

var belongsTo = DS.belongsTo;

export default DS.Model.extend({
  comments: belongsTo(App.PostComment, {async: true})
});


text:
id: layout-and-style
title: Layout and Style
layout: docs
category: The Basics
permalink: docs/layout-and-style.html
next: events-and-links
previous: reactnative
---

React VR makes use of a Flexbox style layout algorithm to automatically position components and their children.

The library we use, [CSSLayout](https://github.com/facebook/css-layout), tries to follows the web implementation of flexbox as much as possible. CSSLayout does make changes to the default properties, and [these changes](http://jsfiddle.net/vjeux/y11txxv9/) can be forked to allow testing in a browser environment.

#### Layout Sample

In most cases, children are arranged vertically in a `'column'` or horizontally in a `'row'`. This arrangement behavior, as well as size and alignment, are controlled through style properties of the component.

Here are some of the more common attributes:

* `flexDirection` - Can be `column` or `row`.
* `justifyContent` - Can be `flex-start`, `space-around` or `space-between`.
* `itemAlign` - `stretch`, `flex-start`, `center` or `flex-end`.
* `margin` - specifies space around the item.

The behavior of these and other layout attributes is demonstrated by the *LayoutSample* included
with React VR. This sample displays the following scene, with buttons arranged vertically:

![](img/layoutsample.jpg)

Colored buttons with text can be generated by the following code within a component:

```
render() {
  // <View> below creates a view that is 2 meters wide and is positioned
  // 5 meters in front of the user (z = -5). Its child items are laid out
  // in a 'column' and marked to 'stretch' to the width of the view container.
  // This causes call child view to have the same width.
  return (
    <View>
      <Pano source={{uri: 'office_lobby.jpg'}} />
      <View style={{
        flex: 1,
        flexDirection: 'column',
        width: 2,
        alignItems: 'stretch',
        transform: [{translate: [-1, 1, -5]}],
      }}>

      <View style={{ margin: 0.1, height: 0.3, backgroundColor: 'red'}}>
        <Text style={{fontSize: 0.2, textAlign: 'center'}}>Red</Text>
      </View>
      <View style={{ margin: 0.1, height: 0.3, backgroundColor: 'orange'}}>
        <Text style={{fontSize: 0.2, textAlign: 'center'}}>Orange</Text>
      </View>
      <View style={{ margin: 0.1, height: 0.3, backgroundColor: 'yellow'}}>
        <Text style={{fontSize: 0.2, textAlign: 'center'}}>Yellow</Text>
      </View>
      <View style={{ margin: 0.1, height: 0.3, backgroundColor: 'green'}}>
        <Text style={{fontSize: 0.2, textAlign: 'center'}}>Green</Text>
      </View>
      <View style={{ margin: 0.1, height: 0.3, backgroundColor: 'blue'}}>
        <Text style={{fontSize: 0.2, textAlign: 'center'}}>Blue</Text>
      </View>

    </View>
    </View>
  );
}
```

For more information about layout, see [Layout with Flexbox](https://facebook.github.io/react-native/docs/flexbox.html) in the React Native docs.

#### Style

React VR doesn't use a special language or syntax for defining styles. All of the core and VR components accept a prop named `style`. You just style your application using JavaScript. Here is an example of a view with style applied to it:

```
<View style={{
          flex: 1, flexDirection: 'column',
          width: 2,
          alignItems: 'stretch',
          transform: [{translate: [-1, 1, -5]}]
}}>
```

The style names and values usually match how CSS works on the web, except names are written like `backgroundColor` instead of `background-color`.

The style prop can be a plain old JavaScript object. In the above example, we declared an inline object with attributes `flex`, `width`, and so on.  This direct inline approach is simple and is what we usually do for sample code.

As a component grows in complexity, it is often cleaner to use `StyleSheet.create` to define several styles in one place.

```
const styles = StyleSheet.create({
  bigblue: {
    color: 'blue',
    fontSize: 0.4
  },
  red: {
    color: 'red',
  },
});
```

Such styles can be used directly inside of the style property. The shorter syntax encourages style reuse.

```
<Text style={styles.bigblue}>bigblue colored text</Text>
```

You can also pass an array of styles:

```
<Text style={[styles.bigblue, styles.red]}>red text</Text>
<Text style={[styles.bigblue, {color:'green'}]}>green text</Text>
```

In style arrays, the styles are merged and the members of the last array element take precedence. This means we can use this approach to help inherit styles or override their elements.

#### Width and Height

A component's width and height style properties determine its size in the world and during layout.

React VR uses meters as its units unlike React Native, which uses pixels. Using meters is important, as it gives meaningful physical size to the object in the VR world. Meter units are also used by the WebVR APIs.

### Units

The distance and dimensional units for the Web version of React VR are meters.


text:
<?php

// No direct access.
defined('_JEXEC') or die;

/**
 * Cache component helper.
 *
 * @package		Joomla.Administrator
 * @subpackage	com_cache
 * @since		1.6
 */
class CacheHelper
{

	/**
	 * Get a list of filter options for the application clients.
	 *
	 * @return	array	An array of JHtmlOption elements.
	 */
	static function getClientOptions()
	{
		// Build the filter options.
		$options	= array();
		$options[]	= JHtml::_('select.option', '0', JText::_('JSITE'));
		$options[]	= JHtml::_('select.option', '1', JText::_('JADMINISTRATOR'));
		return $options;
	}

	/**
	 * Configure the Linkbar.
	 *
	 * @param	string	The name of the active view.
	 *
	 * @return	void
	 * @since	1.6
	 */
	public static function addSubmenu($vName)
	{
		JSubMenuHelper::addEntry(
			JText::_('JGLOBAL_SUBMENU_CHECKIN'),
			'index.php?option=com_checkin',
			$vName == 'com_checkin'
		);

		JSubMenuHelper::addEntry(
			JText::_('JGLOBAL_SUBMENU_CLEAR_CACHE'),
			'index.php?option=com_cache',
			$vName == 'cache'
		);
		JSubMenuHelper::addEntry(
			JText::_('JGLOBAL_SUBMENU_PURGE_EXPIRED_CACHE'),
			'index.php?option=com_cache&view=purge',
			$vName == 'purge'
		);
	}
}


text:
(function(angular){
    'use strict';

    angular.module('gitlabKBApp.board').factory('CardPriority', [
        'priority_regexp',
        function(priority_regexp) {
            function CardPriority(label) {
                if (_.isEmpty(label)) {
                    return {
                        index: 0,
                        color: '#fffff'
                    }
                }
                var priority = priority_regexp.exec(label.name);
                return {
                    id: label.name,
                    name: label.name,
                    index: parseInt(priority[1]),
                    color: label.color,
                    viewName: priority[2]
                };
            }

            return CardPriority;
        }
    ]);

}(window.angular));


text:
package tpl

import (
	"fmt"

	"github.com/nicksnyder/go-i18n/i18n/bundle"
	jww "github.com/spf13/jwalterweatherman"
)

var i18nTfunc bundle.TranslateFunc

func SetI18nTfunc(lang string, bndl *bundle.Bundle) {
	tFunc, err := bndl.Tfunc(lang)
	if err == nil {
		i18nTfunc = tFunc
		return
	}

	jww.WARN.Printf("could not load translations for language %q (%s), will not translate!\n", lang, err.Error())
	i18nTfunc = bundle.TranslateFunc(func(id string, args ...interface{}) string {
		// TODO: depending on the site mode, we might want to fall back on the default
		// language's translation.
		// TODO: eventually, we could add --i18n-warnings and print something when
		// such things happen.
		return fmt.Sprintf("[i18n: %s]", id)
	})
}

func I18nTranslate(id string, args ...interface{}) (string, error) {
	if i18nTfunc == nil {
		return "", fmt.Errorf("i18n not initialized, have you configured everything properly?")
	}
	return i18nTfunc(id, args...), nil
}


text:
The Go project's development process is design-driven.
Significant changes to the language, libraries, or tools must be first
discussed, and sometimes formally documented, before they can be implemented.

This document describes the process for proposing, documenting, and
implementing changes to the Go project.

To learn more about Go's origins and development process, see the talks
[How Go Was Made](http://talks.golang.org/2015/how-go-was-made.slide),
[The Evolution of Go](http://talks.golang.org/2015/gophercon-goevolution.slide),
and [Go, Open Source, Community](http://blog.golang.org/open-source)
from GopherCon 2015.

## The Proposal Process

### Goals

- Make sure that proposals get a proper, fair, timely, recorded evaluation with
  a clear answer.
- Make past proposals easy to find, to avoid duplicated effort.
- If a design doc is needed, make sure contributors know how to write a good one.

### Definitions

- A **proposal** is a suggestion filed as a GitHub issue, identified by having
  the Proposal label.
- A **design doc** is the expanded form of a proposal, written when the
  proposal needs more careful explanation and consideration.

### Scope

The proposal process should be used for any notable change or addition to the
language, libraries and tools.
Since proposals begin (and will often end) with the filing of an issue, even
small changes can go through the proposal process if appropriate.
Deciding what is appropriate is matter of judgment we will refine through
experience.
If in doubt, file a proposal.

#### Compatibility

Programs written for Go version 1.x must continue to compile and work with
future versions of Go 1.
The [Go 1 compatibility document](http://golang.org/doc/go1compat) describes
the promise we have made to Go users for the future of Go 1.x.
Any proposed change must not break this promise.

#### Language changes

Go is a mature language and, as such, significant language changes are unlikely
to be accepted.
A "language change" in this context means a change to the
[Go language specification](https://golang.org/ref/spec).
(See the [release notes](https://golang.org/doc/devel/release.html) for
examples of recent language changes.)

### Process

- [Create an issue](https://golang.org/issue/new) describing the proposal.

- Like any GitHub issue, a Proposal issue is followed by an initial discussion
  about the suggestion. For Proposal issues:
	- The goal of the initial discussion is to reach agreement on the next step:
		(1) accept, (2) decline, or (3) ask for a design doc.
	- The discussion is expected to be resolved in a timely manner.
	- If the author wants to write a design doc, then they can write one.
	- In Go development historically, a lack of agreement means the
	  author should write a design doc.
	- If there is disagreement about whether there is agreement,
	  [adg@](mailto:adg@golang.org) is the arbiter.

- It's always fine to label a suggestion issue with Proposal to opt in to this process.

- It's always fine not to label a suggestion issue with Proposal.
  (If the suggestion needs a design doc or is declined but worth remembering,
  it is trivial to add the label later.)

- If a Proposal issue leads to a design doc:
	- The design doc should be checked in to [the proposal repository](https://github.com/golang/proposal/) as `design/NNNN-shortname.md`,
	  where `NNNN` is the GitHub issue number and `shortname` is a short name
	  (a few dash-separated words at most).
	- The design doc should follow [the template](design/TEMPLATE.md).
	- The design doc should address any specific issues asked for during the
	  initial discussion.
	- It is expected that the design doc may go through multiple checked-in revisions.
	- New design doc authors may be paired with a design doc "shepherd" to help work
	  on the doc.
	- If the author is a committer, each revision can be self-+2'ed.
	- Comments by others can be made on the Gerrit CLs or on the GitHub issue,
	  whatever makes sense.

- Once comments and revisions on the design doc wind down, there is a final
  discussion about the proposal.
	- The goal of the final discussion is to reach agreement on the next step:
		(1) accept or (2) decline.
	- The discussion is expected to be resolved in a timely manner.
	- In Go development historically, a lack of agreement means decline.
	- If there is disagreement about whether there is agreement,
	  [adg@](mailto:adg@golang.org) is the arbiter.

- The author (and/or other contributors) do the work as described by the
  "Implementation" section of the proposal.

#### Quick start for committers

If you're already familiar with writing design docs for the Go project,
the process has not changed much.
The main thing that has changed is where the proposal is published.

In the situation where you'd write and circulate a design doc as a Google doc
before, now you:

- Create a GitHub issue labeled Proposal, to get a number NNNN.
- Check in the Markdown-formatted design doc to
  [the proposal repository](https://github.com/golang/proposal/)
  as `design/NNNN-shortname.md`.
- Mail [golang-dev](https://groups.google.com/group/golang-dev/) as usual.

Worst case, by bypassing the initial discussion you've possibly written an
unnecessary design doc. Not a big deal.

## Help

If you need help with this process, please contact the Go contributors by posting
to the [golang-dev mailing list](https://groups.google.com/group/golang-dev).
(Note that the list is moderated, and that first-time posters should expect a
delay while their message is held for moderation.)

If you want to talk to someone off-list, contact Andrew Gerrand at <adg@golang.org>.

To learn about contributing to Go in general, see the
[contribution guidelines](https://golang.org/doc/contribute.html).


text:
package com.manusunny.pinlock.sample;

import android.content.SharedPreferences;

import com.manusunny.pinlock.SetPinActivity;

public class SetPinActivitySample extends SetPinActivity {

    @Override
    public void onPinSet(String pin) {
        SharedPreferences.Editor edit = MainActivity.pinLockPrefs.edit();
        edit.putString("pin", pin);
        edit.commit();
        setResult(SUCCESS);
        finish();
    }
}


text:
package br.com.catbag.gifreduxsample.reducers.middlewares;

import com.umaplay.fluxxan.Action;
import com.umaplay.fluxxan.Fluxxan;
import com.umaplay.fluxxan.Middleware;
import com.umaplay.fluxxan.impl.BaseMiddleware;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import br.com.catbag.gifreduxsample.BuildConfig;
import br.com.catbag.gifreduxsample.actions.PayloadParams;
import br.com.catbag.gifreduxsample.asyncs.data.DataManager;
import br.com.catbag.gifreduxsample.asyncs.data.net.downloader.FileDownloader;
import br.com.catbag.gifreduxsample.middlewares.RestMiddleware;
import br.com.catbag.gifreduxsample.models.AppState;
import br.com.catbag.gifreduxsample.models.Gif;
import br.com.catbag.gifreduxsample.models.ImmutableAppState;
import shared.ReduxBaseTest;
import shared.TestHelper;

import static br.com.catbag.gifreduxsample.actions.GifActionCreator.GIF_DOWNLOAD_FAILURE;
import static br.com.catbag.gifreduxsample.actions.GifActionCreator.GIF_DOWNLOAD_START;
import static br.com.catbag.gifreduxsample.actions.GifActionCreator.GIF_DOWNLOAD_SUCCESS;
import static br.com.catbag.gifreduxsample.actions.GifListActionCreator.GIF_LIST_FETCHING;
import static br.com.catbag.gifreduxsample.actions.GifListActionCreator.GIF_LIST_UPDATED;
import static br.com.catbag.gifreduxsample.asyncs.data.DataManager.GifListLoadListener;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.robolectric.RuntimeEnvironment.application;
import static shared.TestHelper.buildGif;

// Roboeletric still not supports API 24 stuffs
@Config(sdk = 23, constants = BuildConfig.class)
@RunWith(RobolectricTestRunner.class)
public class RestMiddlewareTest extends ReduxBaseTest {

    private static final boolean EXPECTED_HAS_MORE = false;
    private static final Map EXPECTED_GIFS = new LinkedHashMap<>();

    private Fluxxan<AppState> mFluxxan;
    private CountDownLatch mSignal;
    private Action mLastAction;

    private Middleware mInterceptMiddleware = new BaseMiddleware() {
        @Override
        public void intercept(Object o, Action action) throws Exception {
            mLastAction = action;
            mSignal.countDown();
        }
    };

    public RestMiddlewareTest() {
        mFluxxan = new Fluxxan<>(ImmutableAppState.builder().build());
        mHelper = new TestHelper(mFluxxan);
        mFluxxan.start();
    }

    @Before
    public void setup() {
        mSignal = new CountDownLatch(1);
        mFluxxan.getDispatcher().registerMiddleware(mInterceptMiddleware);
    }

    @After
    @Override
    public void cleanup() {
        super.cleanup();
        mFluxxan.stop();
        mFluxxan.getDispatcher().unregisterMiddleware(mInterceptMiddleware.getClass());
    }

    @Test
    public void whenInterceptListFetching() throws Exception {
        RestMiddleware middleware = new RestMiddleware(application,
                mHelper.mockDataManagerFetch(EXPECTED_GIFS, EXPECTED_HAS_MORE),
                any(FileDownloader.class));
        middleware.setDispatcher(mFluxxan.getDispatcher());
        middleware.intercept(mFluxxan.getState(), new Action(GIF_LIST_FETCHING));
        mSignal.await();

        assertEquals(GIF_LIST_UPDATED, mLastAction.Type);
        assertEquals(mLastAction.Payload.getClass(), HashMap.class);
        Map params = (Map) mLastAction.Payload;
        assertEquals(params.get(PayloadParams.PARAM_HAS_MORE), EXPECTED_HAS_MORE);
        Map<String, Gif> gotGifs = (Map) params.get(PayloadParams.PARAM_GIFS);
        assertEquals(gotGifs.size(), EXPECTED_GIFS.size());
    }

    @Test
    public void whenInterceptListFetchingAndDontHasMoreGifs() throws Exception {
        AppState state = ImmutableAppState.builder().hasMoreGifs(false).build();
        DataManager dataManager = mHelper.mockDataManagerFetch(EXPECTED_GIFS, EXPECTED_HAS_MORE);
        RestMiddleware middleware = new RestMiddleware(application, dataManager, null);
        middleware.setDispatcher(mFluxxan.getDispatcher());
        middleware.intercept(state, new Action(GIF_LIST_FETCHING));

        verify(dataManager, never()).fetchGifs(any(GifListLoadListener.class));
    }

    @Test
    public void whenInterceptNonUsefulActions() throws Exception {
        AppState state = ImmutableAppState.builder().hasMoreGifs(false).build();
        DataManager dataManager = mHelper.mockDataManagerFetch(EXPECTED_GIFS, EXPECTED_HAS_MORE);
        FileDownloader fileDownloader = mock(FileDownloader.class);
        RestMiddleware middleware = new RestMiddleware(application,
                dataManager, fileDownloader);
        middleware.setDispatcher(mFluxxan.getDispatcher());
        middleware.intercept(state, new Action("RANDOM_ACTION"));

        verify(dataManager, never()).fetchGifs(any(GifListLoadListener.class));
        verify(fileDownloader, never()).download(anyString(), anyString(),
                any(FileDownloader.SuccessDownloadListener.class),
                any(FileDownloader.FailureDownloadListener.class));
    }

    @Test
    public void whenInterceptGifDownloadStartWithSuccess() throws Exception {
        Gif gif = buildGif();
        AppState state = TestHelper.buildAppState(gif);
        RestMiddleware middleware = new RestMiddleware(application,
                mHelper.mockDataManagerFetch(EXPECTED_GIFS, EXPECTED_HAS_MORE),
                mockFileDownloaderWithSuccess());
        middleware.setDispatcher(mFluxxan.getDispatcher());
        middleware.intercept(state, new Action(GIF_DOWNLOAD_START, gif.getUuid()));
        mSignal.await();

        assertEquals(GIF_DOWNLOAD_SUCCESS, mLastAction.Type);
        assertEquals(mLastAction.Payload.getClass(), HashMap.class);
        Map params = (Map) mLastAction.Payload;
        assertTrue(params.containsKey(PayloadParams.PARAM_PATH));
        assertTrue(params.containsKey(PayloadParams.PARAM_UUID));
    }

    @Test
    public void whenInterceptGifDownloadStartWithFailure() throws Exception {
        Gif gif = buildGif();
        AppState state = TestHelper.buildAppState(gif);
        Middleware middleware = new RestMiddleware(application,
                mHelper.mockDataManagerFetch(EXPECTED_GIFS, EXPECTED_HAS_MORE),
                mockFileDownloaderFailure());
        middleware.setDispatcher(mFluxxan.getDispatcher());

        middleware.intercept(state, new Action(GIF_DOWNLOAD_START, gif.getUuid()));
        mSignal.await();

        assertEquals(GIF_DOWNLOAD_FAILURE, mLastAction.Type);
        assertEquals(mLastAction.Payload, gif.getUuid());
    }

    private FileDownloader mockFileDownloaderWithSuccess() {
        FileDownloader downloader = mock(FileDownloader.class);
        ArgumentCaptor<FileDownloader.SuccessDownloadListener> successCaptor
                = ArgumentCaptor.forClass(FileDownloader.SuccessDownloadListener.class);
        doAnswer(invocation -> {
            successCaptor.getValue().onSuccess();
            return null;
        }).when(downloader).download(anyString(), anyString(), successCaptor.capture(),
                any(FileDownloader.FailureDownloadListener.class));
        return downloader;
    }

    private FileDownloader mockFileDownloaderFailure() {
        FileDownloader downloader = mock(FileDownloader.class);
        ArgumentCaptor<FileDownloader.FailureDownloadListener> failureCaptor
                = ArgumentCaptor.forClass(FileDownloader.FailureDownloadListener.class);
        doAnswer(invocation -> {
            failureCaptor.getValue().onFailure(any(Exception.class));
            return null;
        }).when(downloader).download(anyString(), anyString(),
                any(FileDownloader.SuccessDownloadListener.class),
                failureCaptor.capture());
        return downloader;
    }

}


text:
module ApplicationHelper
  def active_nav_item(tgt_controller)
    (tgt_controller == controller_name ? "active" : "")
  end

  def formatted_owner(user)
    text = if user.first_name.blank? && user.last_name.blank?
      user.username
    else
      [user.first_name, user.last_name].join(' ')
    end

    text += " (#{user.organization_name})"
    text
  end
end


text:
(function () {
    /**
     * mllib linalg distributed module.
     * @example
     * var mllibDistrib = require('eclairjs/mllib/linalg/distributed');
     * var rm = new mllibDistrib.RowMatrix(...);
     * @module eclairjs/mllib/linalg/distributed
     */
    module.exports = {
        DistributedMatrix: require(EclairJS_Globals.NAMESPACE + '/mllib/linalg/distributed/DistributedMatrix'),
        RowMatrix: require(EclairJS_Globals.NAMESPACE + '/mllib/linalg/distributed/RowMatrix')
    }
})();


text:
package org.neo4j.ogm.typeconversion;

/**
 * Proxy implementation of {@link AttributeConverter} backed by an index to which custom generic converters
 * can be added after the object-graph mapping framework has been initialised.
 *
 * @author Adam George
 */
public final class ProxyAttributeConverter implements AttributeConverter<Object, Object> {

    private final ConversionCallbackRegistry converterCallbackRegistry;
    private final Class<?> entityAttributeType;
    private final Class<?> targetGraphType;

    /**
     * Constructs a new {@link ProxyAttributeConverter} based on the given arguments.
     *
     * @param entityAttributeType       The type of the attribute in the entity to convert
     * @param targetGraphType           The target type to which the value from the entity should be converted for saving into the graph
     * @param converterCallbackRegistry The {@link ConversionCallbackRegistry} from which to look up the converters
     */
    public ProxyAttributeConverter(Class<?> entityAttributeType, Class<?> targetGraphType,
        ConversionCallbackRegistry converterCallbackRegistry) {
        this.entityAttributeType = entityAttributeType;
        this.targetGraphType = targetGraphType;
        this.converterCallbackRegistry = converterCallbackRegistry;
    }

    @Override
    public Object toEntityAttribute(Object valueFromGraph) {
        ConversionCallback conversionCallback = this.converterCallbackRegistry.lookUpConverter();
        return conversionCallback.convert(this.entityAttributeType, valueFromGraph);
    }

    @Override
    public Object toGraphProperty(Object valueFromEntity) {
        ConversionCallback conversionCallback = this.converterCallbackRegistry.lookUpConverter();
        return conversionCallback.convert(this.targetGraphType, valueFromEntity);
    }
}


text:
<?php

namespace Rofil\BootstrapTemplate\Libraries;

class Menu
{
    protected $menu;

    public function setMenu(array $menu)
    {
        $this->menu = $menu;
        return $this;
    }

    public function render()
    {
        return $this->_render($this->menu);
    }

    public function _render($menus)
    {
        $ulAttrs = isset($menus['attributes']) ? ' '.$this->parseAttributes($menus['attributes']) : "";
        $menuHTML = "
";
        foreach($menus['items'] as $menu){
            $options = isset($menu['options']) ? ' '.$this->parseAttributes($menu['options']) : "";
            $attributes = isset($menu['attributes']) ? ' '.$this->parseAttributes($menu['attributes']) : "";
            $menuHTML .= "
";
            $menuHTML .= "". $menu['label'] .'';
            if(isset($menu['childs']) && count($menu['childs'])>0){
                $menuHTML .= $this->_render($menu['childs']);
            }
            $menuHTML .= "
";
        }

        $menuHTML .= "
";
        return $menuHTML;
    }

    public function parseAttributes(array $attributes)
    {
        $attributesMap = array_map(function($item, $key){
            return $key."=\"".$item."\"";
        }, $attributes, array_keys($attributes));
        return implode(" ", $attributesMap);
    }
}


text:
package org.eminmamedov.smscenter.common;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.JdbcType;

/**
 * TypeHandler implementation that is used to store enum values in database.
 * Uses {@link DBValue} annotation to specify concrete database values for each
 * enum value.
 *
 * @author Emin Mamedov
 *
 */
public class EnumAnnotatedTypeHandler<E extends Enum<E>> extends TypedTypeHandler<E> {

    public EnumAnnotatedTypeHandler(Class<E> type) {
        super(type);
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        Object dbValue = DbValueUtils.getDbValue(parameter);
        if (dbValue instanceof String) {
            ps.setString(i, (String) dbValue);
        } else if (dbValue instanceof Integer) {
            ps.setInt(i, (Integer) dbValue);
        }
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String s = rs.getString(columnName);
        return convertStringToEnum(s);
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String s = rs.getString(columnIndex);
        return convertStringToEnum(s);
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String s = cs.getString(columnIndex);
        return convertStringToEnum(s);
    }

    private E convertStringToEnum(String s) {
        return s == null ? null : DbValueUtils.getEnumValueByDbValue(getJavaType(), s);
    }

}


text:
CREATE TABLE IF NOT EXISTS product_roots (
    "id" bigserial,
    "name" text NOT NULL,
    "primary_image_id" bigint,
    "subtitle" text NOT NULL DEFAULT '',
    "description" text NOT NULL DEFAULT '',
    "sku_prefix" text NOT NULL,
    "manufacturer" text NOT NULL DEFAULT '',
    "brand" text NOT NULL DEFAULT '',
    "taxable" boolean NOT NULL DEFAULT 'false',
    "cost" numeric(15, 2) NOT NULL DEFAULT 0,
    "product_weight" numeric(15, 2) NOT NULL DEFAULT 0,
    "product_height" numeric(15, 2) NOT NULL DEFAULT 0,
    "product_width" numeric(15, 2) NOT NULL DEFAULT 0,
    "product_length" numeric(15, 2) NOT NULL DEFAULT 0,
    "package_weight" numeric(15, 2) NOT NULL DEFAULT 0,
    "package_height" numeric(15, 2) NOT NULL DEFAULT 0,
    "package_width" numeric(15, 2) NOT NULL DEFAULT 0,
    "package_length" numeric(15, 2) NOT NULL DEFAULT 0,
    "quantity_per_package" integer NOT NULL DEFAULT 1,
    "available_on" timestamp NOT NULL DEFAULT NOW(),
    "created_on" timestamp NOT NULL DEFAULT NOW(),
    "updated_on" timestamp,
    "archived_on" timestamp,
    UNIQUE ("sku_prefix", "archived_on"),
    PRIMARY KEY ("id")
);

CREATE TABLE IF NOT EXISTS products (
    "id" bigserial,
    "product_root_id" bigint NOT NULL,
    "primary_image_id" bigint,
    "name" text NOT NULL,
    "subtitle" text NOT NULL DEFAULT '',
    "description" text NOT NULL DEFAULT '',
    "option_summary" text NOT NULL DEFAULT '',
    "sku" text NOT NULL,
    "upc" text NOT NULL DEFAULT '',
    "manufacturer" text NOT NULL DEFAULT '',
    "brand" text NOT NULL DEFAULT '',
    "quantity" integer NOT NULL DEFAULT 0,
    "taxable" boolean NOT NULL DEFAULT 'false',
    "price" numeric(15, 2) NOT NULL,
    "on_sale" boolean NOT NULL DEFAULT 'false',
    "sale_price" numeric(15, 2) NOT NULL DEFAULT 0 CONSTRAINT sale_price_must_not_be_zero CHECK(
        (sale_price != 0 AND on_sale IS TRUE)
                         OR
        (sale_price  = 0 AND on_sale IS FALSE)
    ),
    "cost" numeric(15, 2) NOT NULL DEFAULT 0,
    "product_weight" numeric(15, 2) NOT NULL DEFAULT 0,
    "product_height" numeric(15, 2) NOT NULL DEFAULT 0,
    "product_width" numeric(15, 2) NOT NULL DEFAULT 0,
    "product_length" numeric(15, 2) NOT NULL DEFAULT 0,
    "package_weight" numeric(15, 2) NOT NULL DEFAULT 0,
    "package_height" numeric(15, 2) NOT NULL DEFAULT 0,
    "package_width" numeric(15, 2) NOT NULL DEFAULT 0,
    "package_length" numeric(15, 2) NOT NULL DEFAULT 0,
    "quantity_per_package" integer NOT NULL DEFAULT 1,
    "available_on" timestamp NOT NULL DEFAULT NOW(),
    "created_on" timestamp NOT NULL DEFAULT NOW(),
    "updated_on" timestamp,
    "archived_on" timestamp,
    UNIQUE ("sku", "archived_on"),
    PRIMARY KEY ("id"),
    FOREIGN KEY ("product_root_id") REFERENCES "product_roots"("id")
);
CREATE UNIQUE INDEX products_upc_empty_but_not_null_idx ON products (upc) WHERE upc != '';

CREATE TABLE IF NOT EXISTS product_images (
    "id" bigserial,
    "product_root_id" bigint NOT NULL,
    "thumbnail_url" text NOT NULL,
    "main_url" text NOT NULL,
    "original_url" text NOT NULL,
    "source_url" text NOT NULL DEFAULT '',
    "created_on" timestamp NOT NULL DEFAULT NOW(),
    "updated_on" timestamp,
    "archived_on" timestamp,
    PRIMARY KEY ("id"),
    FOREIGN KEY ("product_root_id") REFERENCES "product_roots"("id")
);

ALTER TABLE IF EXISTS "product_roots"
    ADD FOREIGN KEY ("primary_image_id") REFERENCES "product_images"("id");

ALTER TABLE IF EXISTS "products"
    ADD FOREIGN KEY ("primary_image_id") REFERENCES "product_images"("id");

CREATE TABLE IF NOT EXISTS product_image_bridge (
    "id" bigserial,
    "product_id" bigint NOT NULL,
    "product_image_id" bigint NOT NULL,
    UNIQUE ("product_id", "product_image_id"),
    PRIMARY KEY ("id"),
    FOREIGN KEY ("product_id") REFERENCES "products"("id"),
    FOREIGN KEY ("product_image_id") REFERENCES "product_images"("id")
);

CREATE TABLE IF NOT EXISTS product_options (
    "id" bigserial,
    "name" text NOT NULL,
    "product_root_id" bigint NOT NULL,
    "created_on" timestamp NOT NULL DEFAULT NOW(),
    "updated_on" timestamp,
    "archived_on" timestamp,
    UNIQUE ("product_root_id", "name"),
    UNIQUE ("name", "archived_on"),
    PRIMARY KEY ("id"),
    FOREIGN KEY ("product_root_id") REFERENCES "product_roots"("id")
);

CREATE TABLE IF NOT EXISTS product_option_values (
    "id" bigserial,
    "product_option_id" bigint NOT NULL,
    "value" text NOT NULL,
    "created_on" timestamp NOT NULL DEFAULT NOW(),
    "updated_on" timestamp,
    "archived_on" timestamp,
    UNIQUE ("product_option_id", "value"),
    UNIQUE ("value", "archived_on"),
    PRIMARY KEY ("id"),
    FOREIGN KEY ("product_option_id") REFERENCES "product_options"("id")
);

CREATE TABLE IF NOT EXISTS product_variant_bridge (
    "id" bigserial,
    "product_id" bigint NOT NULL,
    "product_option_value_id" bigint NOT NULL,
    "created_on" timestamp NOT NULL DEFAULT NOW(),
    "archived_on" timestamp,
    FOREIGN KEY ("product_id") REFERENCES "products"("id"),
    FOREIGN KEY ("product_option_value_id") REFERENCES "product_option_values"("id")
);


text:
/**
 * @fileoverview Navigation of events in graphics replay.
 *
 * @author chizeng@google.com (Chi Zeng)
 */

goog.provide('wtf.replay.graphics.ui.EventNavigator');

goog.require('goog.soy');
goog.require('wtf.replay.graphics.Playback');
goog.require('wtf.replay.graphics.ui.EventNavigatorTableSource');
goog.require('wtf.replay.graphics.ui.EventNavigatorToolbar');
goog.require('wtf.replay.graphics.ui.eventNavigator');
goog.require('wtf.ui.Control');
goog.require('wtf.ui.VirtualTable');

/**
 * Navigation of events control.
 *
 * @param {!wtf.replay.graphics.Playback} playback The playback.
 * @param {!wtf.db.EventList} eventList Event list for an entire animation.
 * @param {!Element} parentElement Element to display in.
 * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper.
 * @constructor
 * @extends {wtf.ui.Control}
 */
wtf.replay.graphics.ui.EventNavigator = function(
    playback, eventList, parentElement, opt_domHelper) {
  goog.base(this, parentElement, opt_domHelper);

  /**
   * Source of table.
   * @type {!wtf.replay.graphics.ui.EventNavigatorTableSource}
   * @private
   */
  this.tableSource_ =
      new wtf.replay.graphics.ui.EventNavigatorTableSource(
          playback, eventList, this.getDom());
  this.registerDisposable(this.tableSource_);

  /**
   * Toolbar for navigating within a step.
   * @type {!wtf.replay.graphics.ui.EventNavigatorToolbar}
   * @private
   */
  this.toolbar_ = new wtf.replay.graphics.ui.EventNavigatorToolbar(
      this.getChildElement(goog.getCssName('toolbarContainer')),
      playback, this.getDom());
  this.registerDisposable(this.toolbar_);

  /**
   * Results table.
   * @type {!wtf.ui.VirtualTable}
   * @private
   */
  this.table_ = new wtf.ui.VirtualTable(
      this.getChildElement(goog.getCssName('tableOuter')),
      this.getDom());
  this.registerDisposable(this.table_);

  /**
   * The playback.
   * @type {!wtf.replay.graphics.Playback}
   * @private
   */
  this.playback_ = playback;

  // Listen to changes in step.
  this.listenToStepUpdates_(playback);

  // Stop listening to changes in step after playing begins. Start listening
  // again when playing stops.
  this.listenToPlayUpdates_(playback);

  // Listen to the toolbar to determine when to scroll the table.
  this.listenToToolbarUpdates_(playback);
};
goog.inherits(wtf.replay.graphics.ui.EventNavigator, wtf.ui.Control);

/**
 * @override
 */
wtf.replay.graphics.ui.EventNavigator.prototype.createDom = function(dom) {
  return /** @type {!Element} */ (goog.soy.renderAsFragment(
      wtf.replay.graphics.ui.eventNavigator.controller,
      undefined, undefined, dom));
};

/**
 * Specifies that the event navigator is ready for interaction.
 */
wtf.replay.graphics.ui.EventNavigator.prototype.setReady = function() {
  this.table_.setSource(this.tableSource_);
  this.toolbar_.setReady();
};

/**
 * Changes the layout of elements to fit the container.
 */
wtf.replay.graphics.ui.EventNavigator.prototype.layout = function() {
  this.table_.layout();
  if (this.table_.getSource()) {
    this.updateScrolling(this.playback_);
  }
};

/**
 * Listens to updates from the toolbar.
 * @param {!wtf.replay.graphics.Playback} playback The playback.
 * @private
 */
wtf.replay.graphics.ui.EventNavigator.prototype.listenToToolbarUpdates_ =
    function(playback) {
  // If the user selects an event within a step, go to it.
  this.toolbar_.addListener(
      wtf.replay.graphics.ui.EventNavigatorToolbar.EventType
          .MANUAL_SUB_STEP_SEEK,
      function() {
        this.updateScrolling(playback);
      }, this);

  // If the user changes the search value, update the events displayed.
  this.toolbar_.addListener(
      wtf.replay.graphics.ui.EventNavigatorToolbar.EventType
          .SEARCH_VALUE_CHANGED,
      this.setSearchValue_, this);
};

/**
 * Listens to play updates to determine if the event navigator should update
 * if the step changes.
 * @param {!wtf.replay.graphics.Playback} playback The playback.
 * @private
 */
wtf.replay.graphics.ui.EventNavigator.prototype.listenToPlayUpdates_ =
    function(playback) {
  // After playing begins, do not update the table events upon step change.
  playback.addListener(
      wtf.replay.graphics.Playback.EventType.PLAY_BEGAN,
      function() {
        this.unListenToStepUpdates_(playback);
        this.table_.setSource(null);
      }, this);

  // After playing stops, update the table events upon step change.
  playback.addListener(
      wtf.replay.graphics.Playback.EventType.PLAY_STOPPED,
      function() {
        this.listenToStepUpdates_(playback);
        this.table_.setSource(this.tableSource_);
      }, this);
};

/**
 * Ensures that the event table updates when the step changes.
 * @param {!wtf.replay.graphics.Playback} playback The playback.
 * @private
 */
wtf.replay.graphics.ui.EventNavigator.prototype.listenToStepUpdates_ =
    function(playback) {
  playback.addListener(
      wtf.replay.graphics.Playback.EventType.STEP_CHANGED,
      this.tableSource_.invalidate, this.tableSource_);
  playback.addListener(
      wtf.replay.graphics.Playback.EventType.SUB_STEP_EVENT_CHANGED,
      this.tableSource_.invalidate, this.tableSource_);
};

/**
 * Stops updating the event table based on changes in step.
 * @param {!wtf.replay.graphics.Playback} playback The playback.
 * @private
 */
wtf.replay.graphics.ui.EventNavigator.prototype.unListenToStepUpdates_ =
    function(playback) {
  playback.removeListener(
      wtf.replay.graphics.Playback.EventType.STEP_CHANGED,
      this.tableSource_.invalidate, this.tableSource_);
};

/**
 * Updates the token used to search within the events table.
 * @param {string} value The new value.
 * @private
 */
wtf.replay.graphics.ui.EventNavigator.prototype.setSearchValue_ = function(
    value) {
  this.tableSource_.setSearchValue(value);
};

/**
 * Updates the scrolling of the virtual table.
 * @param {!wtf.replay.graphics.Playback} playback The playback.
 */
wtf.replay.graphics.ui.EventNavigator.prototype.updateScrolling = function(
    playback) {
  var rowToScrollTo = playback.getSubStepEventIndex() + 1;
  this.table_.scrollToRow(
      rowToScrollTo, wtf.ui.VirtualTable.Alignment.MIDDLE);
};


text:
package com.ccjeng.news.controler.rss;

import android.util.Log;

import com.ccjeng.news.utils.DateTimeFormater;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class RSSItem {

	private static final String TAG = "RSSItem";
	public static final String TITLE = "title";
	public static final String PUBDATE = "pubDate";

	private String title = null;
	private String link = null;
	private String pubDate = null;
	private String description = null;
	private String category = null;
	private String img = null;

	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getLink() {
		return link;
	}
	public void setLink(String link) {
		this.link = link;
	}

	public String getPubDate() {
		return DateTimeFormater.parse(pubDate);
	}
	public void setPubDate(String pubDate) {
		this.pubDate = pubDate;
	}

	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {

		int maxDescrLength = 100;
		Document doc = Jsoup.parse(description);
		Element image = doc.select("img").first();
		String descr = doc.text().trim();

		if (descr.length()>0) {
			descr = descr.replace("-- Delivered by Feed43 service","");
			if (descr.length() > maxDescrLength) {
				descr = descr.substring(0, maxDescrLength);
			}
		}

		String imgURL = "";
		if (image != null) {
			imgURL = image.absUrl("src");
			//Log.d(TAG, imgURL);
			if (imgURL.contains("rsscna") || imgURL.contains("cnaFirstNews")) {
				setImg("");
			} else {
				setImg(image.absUrl("src"));
			}
		} else {
			setImg("");
		}

		//Log.d(TAG, descr);

		this.description = descr;
	}

	public String getCategory() {
		return category;
	}
	public void setCategory(String category) {
		this.category = category;
	}

	public String getImg() {
		return img;
	}
	public void setImg(String img) {
		this.img = img;
	}

	public String toString()
	{
		// limit how much text we display
		/*if (title.length() > 42)
		{
			return title.substring(0, 42) + "...";
		}*/

		return getTitle();
	}
}


text:
const optional = true,
      required = true

module.exports = [
  {
    name: "Vec2",
    doc: "A two-item vector.",
    properties: {
      x: {
        isa: "number(sequencable)",
        type: "float",
        default: 0,
        doc: "The x mmember of the vector."
      },
      y: {
        isa: "number(sequencable)",
        type: "float",
        default: 0,
        doc: "The y mmember of the vector."
      },
    }
  },
  {
    name: "Vec3",
    doc: "A three-item vector.",
    properties: {
      x: {
        isa: "number(sequencable)",
        type: "float",
        default: 0,
        doc: "The x mmember of the vector."
      },
      y: {
        isa: "number(sequencable)",
        type: "float",
        default: 0,
        doc: "The y mmember of the vector."
      },
      z: {
        isa: "number(sequencable)",
        type: "float",
        default: 0,
        doc: "The z mmember of the vector."
      },
    }
  },
  {
    name: "Vec4",
    doc: "A four-item vector.",
    properties: {
      x: {
        isa: "number(sequencable)",
        type: "float",
        default: 0,
        doc: "The x mmember of the vector."
      },
      y: {
        isa: "number(sequencable)",
        type: "float",
        default: 0,
        doc: "The y mmember of the vector."
      },
      z: {
        isa: "number(sequencable)",
        type: "float",
        default: 0,
        doc: "The z member of the vector."
      },
      w: {
        isa: "number(sequencable)",
        type: "float",
        default: 0,
        doc: "The w member of the vector."
      },
    }
  },
  {
    name: "Material",
    doc: "This determines aspects of a geometry such as color and reflectance.",
    properties: {
      mode: {
        type: "string",
        default: 'global',
        doc: "The lighting model employed by the material. Possible options include 'global', 'phong', 'orenn', and 'normal'."
      },
      ambient: {
        type: "vec3",
        default: '(.1,.1,.1)',
        doc: "This color is applied to every pixel in the geometry equally, regardless of how light strikes the geometry."
      },
      diffuse: {
        type: "vec3",
        default: '(0,0,1)',
        doc: "This color is applied to every pixel in proportion to how much light is striking each pixel."
      },
      specular: {
        type: "vec3",
        default: '(1,1,1)',
        doc: "This color is applied to the geometry in spots where light reflects directly off the geometry into the camera, creating a glare."
      },
      shininess: {
        type: "float",
        default: 0,
        doc: "This determines how soft or hard the edges of specular highlights are. More 'shiny' surfaces will have harder edges and are indicated by higher values."
      },
      fresnel: {
        type: "vec3",
        default: '(0,1,2)',
        doc: "he Fresnel effect changes the color of a geometry based upon the angle it is viewed at. This vector contains three values: x is bias, or an offset for the effect; y is scale, or a multiplier for the effect; z an coefficient that exponentially controls the effect of reflectance."
      },
    }
  },
  {
    name: "Texture",
    doc: "A texture can be applied to a geometry in order to pattern its surface; it can also be used as a lookup table for bump mapping. Unlike materials, every texture has a relatively unique set of properties depending on the algorithm used for the texture. However, the majority of texture will have a 'scale' property which determines the resolution of the texture; many will also have a 'strength' property that scales the effect of the texture on the final color of the geometry (lighting and material also affect this).",
    properties: {
      scale: {
        isa: "number(sequencable)",
        type: "float",
        default: 1,
        doc: "The scale property determines the size, or resolution, of the texture. For example, when 'dots' texture is assigned to a cube with a scale of 10 there will be 10x10 dots on each side of the cube. A scale value of 1 will yiled a single dot centered on each side."
      }
    }
  },
]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using Abp.Domain.Uow;
using Abp.Web.Models;
using AutoMapper;
using isriding.School;
using isriding.TbTroubleFeedback;
using isriding.Web.Extension.Fliter;
using isriding.Web.Models.Common;
using isriding.Web.Models.SchoolManage;

namespace isriding.Web.Controllers.SchoolManage
{
    public class TroubleController : isridingControllerBase
    {

        private readonly ITbTroubleFeedbackReadRepository _tbTroubleFeedbackReadRepository;
        private readonly ITbTroubleFeedbackWriteRepository _tbTroubleFeedbackWriteRepository;
        private readonly ISchoolReadRepository _schoolReadRepository;

        public TroubleController(ITbTroubleFeedbackReadRepository tbTroubleFeedbackReadRepository
            , ITbTroubleFeedbackWriteRepository tbTroubleFeedbackWriteRepository
            , ISchoolReadRepository schoolReadRepository)
        {
            _tbTroubleFeedbackReadRepository = tbTroubleFeedbackReadRepository;
            _tbTroubleFeedbackWriteRepository = tbTroubleFeedbackWriteRepository;
            _schoolReadRepository = schoolReadRepository;
        }

        public ActionResult Index()
        {
            return RedirectToAction("List");
        }
        [AdminLayout]
        //[AdminPermission(PermissionCustomMode.Enforce)]
        public ActionResult List()
        {
            var model = new TroubleModel();
            PrepareAllUserModel(model);
            return View(model);
        }

        [DontWrapResult, UnitOfWork]
        public virtual ActionResult InitDataTable(DataTableParameter param)
        {
            var expr = BuildSearchCriteria();
            var temp = _tbTroubleFeedbackReadRepository.GetAll();
            if (expr != null)
            {
                temp = temp.Where(expr);
            }
            var query = temp.OrderBy(s => s.Id).Skip(param.iDisplayStart).Take(param.iDisplayLength);
            var total = temp.Count();
            var filterResult = query.Select(t => new TroubleModel
            {
                Id = t.Id,
                create_by = t.create_by,
                update_by = t.update_by,
                bike_number = t.bike_number,
                trouble1 = t.trouble1,
                trouble2 = t.trouble2,
                trouble3 = t.trouble3,
                comments = t.comments,
                img_url = t.img_url,
                verify_status = t.verify_status,
                deal_status = t.deal_status,
                create_time = t.create_time,
                update_time = t.update_time,
                schoolname = t.User.School.Name,
                username = t.User.Name,
                phone = t.User.Phone
            }).ToList();
            int sortId = param.iDisplayStart + 1;
            var result = from t in filterResult
                         select new[]
                             {
                                sortId++.ToString(),
                                t.Id.ToString(),
                                t.create_time.ToString(),
                                t.username,
                                t.schoolname,
                                t.phone,
                                t.bike_number,
                                t.trouble1,
                                t.trouble2,
                                t.trouble3,
                                t.comments,
                                t.img_url,
                                t.verify_status.ToString(),
                                t.deal_status.ToString(),
                                t.Id.ToString()
                            };

            return DataTableJsonResult(param.sEcho, param.iDisplayStart, total, total, result);
        }

        //public ActionResult Create()
        //{
        //    var model = new TroubleModel();
        //    PrepareAllUserModel(model);
        //    return PartialView(model);
        //}

        //[HttpPost, UnitOfWork]
        //public virtual ActionResult Create(TroubleModel model)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        Mapper.Initialize(t => t.CreateMap<TroubleModel, Entities.Tb_trouble_feedback>());
        //        var user = Mapper.Map<Entities.Tb_trouble_feedback>(model);
        //        user = _tbTroubleFeedbackWriteRepository.Insert(user);

        //        //SuccessNotification("添加成功");
        //        return Json(model);
        //    }
        //    return Json(null);
        //}
        [UnitOfWork]
        public virtual ActionResult Edit(int id)
        {
            Mapper.Initialize(t => t.CreateMap<Entities.Tb_trouble_feedback, TroubleModel>());
            var model = Mapper.Map<TroubleModel>(_tbTroubleFeedbackReadRepository.Get(id));
            //var model = role.ToModel();
            PrepareAllUserModel(model);
            return PartialView(model);
        }

        [HttpPost, UnitOfWork]
        public virtual ActionResult Edit(TroubleModel model)
        {
            var trouble = _tbTroubleFeedbackWriteRepository.Get(model.Id);

            if (ModelState.IsValid)
            {
                trouble.verify_status = model.verify_status;
                trouble.deal_status = model.deal_status;

                _tbTroubleFeedbackWriteRepository.Update(trouble);
                //role = model.ToEntity(role);
                //_roleService.UpdateRole(role);

                //SuccessNotification("更新成功");
                return Json(model);
            }
            return Json(null);
        }

        [HttpPost, UnitOfWork]
        public virtual ActionResult Delete(int id)
        {
            _tbTroubleFeedbackWriteRepository.Delete(s => s.Id == id);
            //var role = _roleService.GetRoleById(id);
            //_roleService.DeleteRole(role);

            return Json(new { success = true });
        }

        #region 公共方法
        [NonAction, UnitOfWork]
        protected virtual void PrepareAllUserModel(TroubleModel model)
        {
            if (model == null)
                throw new ArgumentNullException("model");
            var list = _schoolReadRepository.GetAll();

            var sessionschoolids = Session["SchoolIds"] as List<int>;
            if (sessionschoolids != null && sessionschoolids.Count > 0)
            {
                list = list.Where(t => sessionschoolids.Contains(t.Id));
            }
            var schoollist = list.Select(b => new SelectListItem { Text = b.Name, Value = b.Id.ToString() });
            model.Search.SchoolList.AddRange(schoollist);
            model.Search.SchoolList.Insert(0, new SelectListItem { Text = "---请选择---", Value = "0" });
        }
        #region 构建查询表达式
        /// <summary>
        /// 构建查询表达式
        /// </summary>
        /// <returns></returns>
        private Expression<Func<Entities.Tb_trouble_feedback, Boolean>> BuildSearchCriteria()
        {
            DynamicLambda<Entities.Tb_trouble_feedback> bulider = new DynamicLambda<Entities.Tb_trouble_feedback>();
            Expression<Func<Entities.Tb_trouble_feedback, Boolean>> expr = null;
            if (!string.IsNullOrEmpty(Request["verify_status"]) && Request["verify_status"].Trim() != "0")
            {
                var data = Convert.ToInt32(Request["verify_status"].Trim());
                Expression<Func<Entities.Tb_trouble_feedback, Boolean>> tmp = t => t.verify_status == data;
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["deal_status"]) && Request["deal_status"].Trim() != "0")
            {
                var data = Convert.ToInt32(Request["deal_status"].Trim());
                Expression<Func<Entities.Tb_trouble_feedback, Boolean>> tmp = t => t.deal_status == data;
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["StartDate"]))
            {
                var data = DateTime.Parse(Request["StartDate"].Trim());
                Expression<Func<Entities.Tb_trouble_feedback, Boolean>> tmp = t => t.create_time.Value >= data;
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["EndDate"]))
            {
                var data = DateTime.Parse(Request["EndDate"].Trim());
                Expression<Func<Entities.Tb_trouble_feedback, Boolean>> tmp = t => t.create_time.Value <= data;
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["School_id"]))
            {
                var data = Convert.ToInt32(Request["School_id"].Trim());
                if (data > 0)
                {
                    Expression<Func<Entities.Tb_trouble_feedback, Boolean>> tmp = t => t.User.School_id == data;
                    expr = bulider.BuildQueryAnd(expr, tmp);
                }
                else
                {
                    var sessionschoolids = Session["SchoolIds"] as List<int>;
                    if (sessionschoolids != null && sessionschoolids.Count > 0)
                    {
                        Expression<Func<Entities.Tb_trouble_feedback, Boolean>> tmp = t => sessionschoolids.Contains((int)t.User.School_id);
                        expr = bulider.BuildQueryAnd(expr, tmp);
                    }
                }
            }
            else
            {
                var sessionschoolids = Session["SchoolIds"] as List<int>;
                if (sessionschoolids != null && sessionschoolids.Count > 0)
                {
                    Expression<Func<Entities.Tb_trouble_feedback, Boolean>> tmp = t => sessionschoolids.Contains((int)t.User.School_id);
                    expr = bulider.BuildQueryAnd(expr, tmp);
                }
            }
            //var id = CommonHelper.GetSchoolId();
            //if (id > 1)
            //{
            //    Expression<Func<Entities.User, Boolean>> tmpSolid = t => t.School_id == id;
            //    expr = bulider.BuildQueryAnd(expr, tmpSolid);
            //}
            return expr;
        }
        #endregion
        #endregion
    }
}


text:
<?php

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity;

use ApiPlatform\Metadata\ApiResource;
use DateTime;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;

#[ApiResource(graphQlOperations: [], normalizationContext: ['groups' => ['inspection_read']], denormalizationContext: ['groups' => ['inspection_write']])]
#[ORM\Entity]
class VoDummyInspection
{
    use VoDummyIdAwareTrait;

    #[ORM\Column(type: 'boolean')]
    #[Groups(['car_read', 'car_write', 'inspection_read', 'inspection_write'])]
    private bool $accepted;

    #[ORM\ManyToOne(targetEntity: VoDummyCar::class, inversedBy: 'inspections')]
    #[Groups(['inspection_read', 'inspection_write'])]
    private ?VoDummyCar $car;

    #[ORM\Column(type: 'datetime')]
    #[Groups(['car_read', 'car_write', 'inspection_read', 'inspection_write'])]
    private \DateTime $performed;

    private $attributeWithoutConstructorEquivalent;

    public function __construct(bool $accepted, VoDummyCar $car, DateTime $performed = null, string $parameterWhichIsNotClassAttribute = '')
    {
        $this->accepted = $accepted;
        $this->car = $car;
        $this->performed = $performed ?: new DateTime();
        $this->attributeWithoutConstructorEquivalent = $parameterWhichIsNotClassAttribute;
    }

    public function isAccepted()
    {
        return $this->accepted;
    }

    public function getCar()
    {
        return $this->car;
    }

    public function getPerformed()
    {
        return $this->performed;
    }

    public function setPerformed(DateTime $performed)
    {
        $this->performed = $performed;

        return $this;
    }
}


text:
namespace peachy {

  IStreamScriptSource::IStreamScriptSource(Log * logger,
    std::istream * stream) {
    logger->debug("IStreamScriptSource constructor");
    this->logger = logger;
    this->stream = stream;
  }

  IStreamScriptSource::~IStreamScriptSource() {
    logger->debug("IStreamScriptSource destructor");
    delete stream;
  }

  std::string IStreamScriptSource::getLine() {
    logger->debug("IStreamScriptSource::getLine()");
    std::getline(*stream, currentLine);
    return currentLine;
  }

  bool IStreamScriptSource::hasMoreLines() {
    logger->debug("IStreamScriptSource::hasMoreLines()");
    return !stream->eof();
  }
}