text:
/**
 * 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.
 */
package com.sun.org.apache.xml.internal.security.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecurityPermission;

/**
 * A collection of different, general-purpose methods for JAVA-specific things
 * @author Christian Geuer-Pollmann
 */
public class JavaUtils {

    /** {@link org.apache.commons.logging} logging facility */
    private static java.util.logging.Logger log =
        java.util.logging.Logger.getLogger(JavaUtils.class.getName());

    private static final SecurityPermission REGISTER_PERMISSION =
        new SecurityPermission(
            "com.sun.org.apache.xml.internal.security.register");

    private JavaUtils() {
        // we don't allow instantiation
    }

    /**
     * Method getBytesFromFile
     *
     * @param fileName
     * @return the bytes read from the file
     *
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static byte[] getBytesFromFile(String fileName)
        throws FileNotFoundException, IOException {

        byte refBytes[] = null;

        FileInputStream fisRef = null;
        UnsyncByteArrayOutputStream baos = null;
        try {
            fisRef = new FileInputStream(fileName);
            baos = new UnsyncByteArrayOutputStream();
            byte buf[] = new byte[1024];
            int len;

            while ((len = fisRef.read(buf)) > 0) {
                baos.write(buf, 0, len);
            }

            refBytes = baos.toByteArray();
        } finally {
            if (baos != null) {
                baos.close();
            }
            if (fisRef != null) {
                fisRef.close();
            }
        }

        return refBytes;
    }

    /**
     * Method writeBytesToFilename
     *
     * @param filename
     * @param bytes
     */
    public static void writeBytesToFilename(String filename, byte[] bytes) {
        FileOutputStream fos = null;
        try {
            if (filename != null && bytes != null) {
                File f = new File(filename);

                fos = new FileOutputStream(f);

                fos.write(bytes);
                fos.close();
            } else {
                if (log.isLoggable(java.util.logging.Level.FINE)) {
                    log.log(java.util.logging.Level.FINE, "writeBytesToFilename got null byte[] pointed");
                }
            }
        } catch (IOException ex) {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ioe) {
                    if (log.isLoggable(java.util.logging.Level.FINE)) {
                        log.log(java.util.logging.Level.FINE, ioe.getMessage(), ioe);
                    }
                }
            }
        }
    }

    /**
     * This method reads all bytes from the given InputStream till EOF and
     * returns them as a byte array.
     *
     * @param inputStream
     * @return the bytes read from the stream
     *
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static byte[] getBytesFromStream(InputStream inputStream) throws IOException {
        UnsyncByteArrayOutputStream baos = null;

        byte[] retBytes = null;
        try {
            baos = new UnsyncByteArrayOutputStream();
            byte buf[] = new byte[4 * 1024];
            int len;

            while ((len = inputStream.read(buf)) > 0) {
                baos.write(buf, 0, len);
            }
            retBytes = baos.toByteArray();
        } finally {
            baos.close();
        }

        return retBytes;
    }

    /**
     * Throws a {@code SecurityException} if a security manager is installed
     * and the caller is not allowed to register an implementation of an
     * algorithm, transform, or other security sensitive XML Signature function.
     *
     * @throws SecurityException if a security manager is installed and the
     *    caller has not been granted the
     *    {@literal "com.sun.org.apache.xml.internal.security.register"}
     *    {@code SecurityPermission}
     */
    public static void checkRegisterPermission() {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(REGISTER_PERMISSION);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
		 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<artifactId>spring-data-neo4j-examples</artifactId>
	<packaging>pom</packaging>

	<parent>
		<groupId>org.springframework.data.examples</groupId>
		<artifactId>spring-data-examples</artifactId>
		<version>2.0.0.BUILD-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>

	<name>Spring Data Neo4j 4 - Examples</name>
	<description>Sample projects for Spring Data Neo4j 4</description>

	<modules>
		<module>example</module>
	</modules>

</project>

redpajama_set_name: RedPajamaGithub


text:
use Observations
Select
  Phenomenon.Name Phenomenon, Offering.Name Offering, UnitOfMeasure.Unit Unit, Site.Name Site, Station.Name Station, /*Status.Name Status,*/ Observation.ValueYear Year, Count(*) Count
from
  Observation
  inner join PhenomenonOffering
    on (Observation.PhenomenonOfferingID = PhenomenonOffering.ID)
  inner join Phenomenon
    on (PhenomenonOffering.PhenomenonID = Phenomenon.ID)
  inner join Offering
    on (PhenomenonOffering.OfferingID = Offering.ID)
  inner join PhenomenonUOM
    on (Observation.PhenomenonUOMID = PhenomenonUOM.ID)
  inner join UnitOfMeasure
    on (PhenomenonUOM.UnitOfMeasureID = UnitOfMeasure.ID)
  inner join Sensor
    on (Observation.SensorID = Sensor.ID)
  inner join Instrument_Sensor
    on (Observation.SensorID = Instrument_Sensor.SensorID) and
	   ((Instrument_Sensor.StartDate is null) or (Observation.ValueDay >= Instrument_Sensor.StartDate)) and
	   ((Instrument_Sensor.EndDate is null) or (Observation.ValueDay <= Instrument_Sensor.EndDate))
  inner join Instrument
    on (Instrument_Sensor.InstrumentID = Instrument.ID) and
	   ((Instrument.StartDate is null) or (Observation.ValueDay >= Instrument.StartDate)) and
	   ((Instrument.EndDate is null) or (Observation.ValueDay <= Instrument.EndDate))
  inner join Station_Instrument
    on (Station_Instrument.InstrumentID = Instrument_Sensor.InstrumentID) and
	   ((Station_Instrument.StartDate is null) or (Observation.ValueDay >= Station_Instrument.StartDate)) and
	   ((Station_Instrument.EndDate is null) or (Observation.ValueDay <= Station_Instrument.EndDate))
  inner join Station
    on (Station_Instrument.StationID = Station.ID) and
	   ((Station.StartDate is null) or (Observation.ValueDay >= Station.StartDate))	and
	   ((Station.EndDate is null) or (Observation.ValueDay <= Station.EndDate))
  inner join Site
    on (Station.SiteID = Site.ID) and
	   ((Site.StartDate is null) or (Observation.ValueDay >= Site.StartDate)) and
	   ((Site.EndDate is null) or (Observation.ValueDay <= Site.EndDate))
  left join Status
    on (Observation.StatusID = Status.ID)
where
  (Phenomenon.Name not in ('Current Direction','Current speed','Depth')) --and
  --(Status.Name = 'Verified')
group by
  Phenomenon.Name, Offering.Name, UnitOfMeasure.Unit, Site.Name, Station.Name, /*Status.Name,*/ Observation.ValueYear
order by
  Phenomenon.Name, Offering.Name, UnitOfMeasure.Unit, Site.Name, Station.Name, /*Status.Name,*/ Observation.ValueYear


text:
package ca.sapon.jici.evaluator.value;

public class ShortValue implements Value {
    private static final ShortValue[] COMMON_VALUES = new ShortValue[256];
    private final short value;

    static {
        for (int i = 0; i < 256; i++) {
            COMMON_VALUES[i] = new ShortValue((short) (i - 128));
        }
    }

    private ShortValue(short value) {
        this.value = value;
    }

    @Override
    public boolean asBoolean() {
        throw new UnsupportedOperationException("Cannot convert a short to a boolean");
    }

    @Override
    public byte asByte() {
        return (byte) value;
    }

    @Override
    public short asShort() {
        return value;
    }

    @Override
    public char asChar() {
        return (char) value;
    }

    @Override
    public int asInt() {
        return value;
    }

    @Override
    public long asLong() {
        return value;
    }

    @Override
    public float asFloat() {
        return value;
    }

    @Override
    public double asDouble() {
        return value;
    }

    @Override
    public Short asObject() {
        return value;
    }

    @Override
    public String asString() {
        return Short.toString(value);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T as() {
        return (T) asObject();
    }

    @Override
    public ValueKind getKind() {
        return ValueKind.SHORT;
    }

    @Override
    public boolean isPrimitive() {
        return true;
    }

    @Override
    public Class<?> getTypeClass() {
        return short.class;
    }

    @Override
    public String toString() {
        return asString();
    }

    public static ShortValue of(short value) {
        final int offsetValue = value + 128;
        if ((offsetValue & ~0xFF) == 0) {
            return COMMON_VALUES[offsetValue];
        }
        return new ShortValue(value);
    }

    public static ShortValue defaultValue() {
        return COMMON_VALUES[128];
    }
}


text:
using Holoholona.Entities.Enums;
using System;
using static Holoholona.Entities.Enums.AnimalEnums;

namespace Holoholona.Web.Models
{
    public class Animal
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public int Level { get; set; }
        public int Experience { get; set; }
        public AnimalType Type { get; set; }
        public AnimalFamily Family { get; set; }
        public int MaxHealth { get; set; }
        public int Health { get; set; }
        public int Speed { get; set; }
        public int Defence { get; set; }
        public int Strength { get; set; }

        public int Attack(Attack attack, Animal opponent)
        {
            Random rand = new Random();

            //((((2 * Level / 5 + 2) * AttackStat * AttackPower / DefenseStat) / 50) + 2) * STAB * Weakness / Resistance * RandomNumber / 100
            return ((((2 * Level / 5 + 2) * Strength * attack.Damage / opponent.Defence) / 50) + 2) * rand.Next(100) / 100 * (rand.Next(100) <= attack.CriticalHitChance ? 2 : 1);
        }

        public void Hit(int dmg)
        {
            Health -= dmg;
            if (Health < 0)
                Health = 0;
            Console.WriteLine("Damage: " + dmg.ToString());
        }
    }
}


text:
package org.apache.sis.util.iso;

import org.opengis.util.Factory;
import org.opengis.metadata.citation.Citation;
import org.apache.sis.internal.simple.SimpleCitation;

/**
 * Base class of factories provided in the Apache SIS library.
 *
 * @author  Martin Desruisseaux (Geomatys)
 * @version 0.3
 * @since   0.3
 * @module
 */
public abstract class AbstractFactory implements Factory {
    /**
     * Creates a new factory.
     */
    protected AbstractFactory() {
    }

    /**
     * Returns the implementor of this factory, or {@code null} if unknown.
     * The default implementation tries to fetch this information from the
     * manifest associated to the package of {@code this.getClass()}.
     *
     * @return the vendor for this factory implementation, or {@code null} if unknown.
     *
     * @see Package#getImplementationVendor()
     */
    @Override
    public Citation getVendor() {
        final Package p = getClass().getPackage();
        if (p != null) {
            final String vendor = p.getImplementationVendor();
            if (vendor != null) {
                return new SimpleCitation(vendor);
            }
        }
        return null;
    }
}


text:
package javax.print.attribute;

import java.io.Serializable;

/**
 * HashDocAttributeSet provides an implementation of
 * {@link javax.print.attribute.DocAttributeSet}.
 */
public class HashDocAttributeSet extends HashAttributeSet
  implements DocAttributeSet, Serializable
{
  private static final long serialVersionUID = -1128534486061432528L;

  /**
   * Creates an empty HashDocAttributeSet object.
   */
  public HashDocAttributeSet()
  {
    super(DocAttribute.class);
  }

  /**
   * Creates a HashDocAttributeSet object with the given
   * attribute in it.
   *
   * @param attribute the attribute to put into the attribute set
   *
   * @exception NullPointerException if attribute is null
   */
  public HashDocAttributeSet(DocAttribute attribute)
  {
    super(attribute, DocAttribute.class);
  }

  /**
   * Creates a HashDocAttributeSet object with the given
   * attributes in it.
   *
   * @param attributes the array of attributes to put into the set. If
   * null an empty set is created.
   *
   * @exception NullPointerException if one of the attributes of the given
   * array is null.
   */
  public HashDocAttributeSet(DocAttribute[] attributes)
  {
    super(attributes, DocAttribute.class);
  }

  /**
   * Creates a HashDocAttributeSet object with the attributes
   * of the given attributes set in it.
   *
   * @param attributes the attributes set to put into the set. If
   * null an empty set is created.
   * @exception ClassCastException if any element of attributes is not
   * an instance of DocAttribute
   */
  public HashDocAttributeSet(DocAttributeSet attributes)
  {
    super(attributes, DocAttribute.class);
  }
}


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

namespace CSharpQuickReference.src
{
    class XMLReader
    {
        //http://csharp.net-tutorials.com/xml/working-with-the-xmlnode-class/
        //http://csharp.net-tutorials.com/xml/reading-xml-with-the-xmlreader-class/
        public static void loadFileDummy()
        {
            XmlReader xmlReader = XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
            while (xmlReader.Read())
            {
                if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "Cube"))
                {
                    if (xmlReader.HasAttributes)
                        Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));

                /*
                    XMLDocument - is more memory consuming and possibly a bit slower than xmlReader approach
                 *
                 * XMLDocument - reads entire xml content into memory - then we can navigate it as we please or even XPath query
                 *
                 * XMLReader - one content at a time

                 */

                }
            }
            Console.ReadKey();
        }

        public static void loadFileDummyXmlDocument()
        {
            // require less code - due to the fact we're not doing stuff manually

            //(http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml) - gesmes:Envelope - root element

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
            foreach(XmlNode xmlNode in xmlDoc.DocumentElement.ChildNodes[2].ChildNodes[0].ChildNodes) {
                console.WriteLine(xmlNode.Attributes["currency"].Value + ": " + xmlNode.Attributes["rate"].Value);
            }
        }

        public static void readNodes()
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml("<user name=\"John Doe\">A user node</user>");
            Console.WriteLine(xmlDoc.documentElement.Name);
            // XmlDocument.documentElement.<propertyName>
            // <node property=proeprtyString></node>
            // return -> propertyString

            // XmlDocument.documentElement.InnerText
            // <node>Text</node>
            // return Text

            //
            //
            //
        }

    }
}


text:
Converts the [Dojo](http://dojotoolkit.org/) API into a .d.ts definition files for use with TypeScript.

# How does it work?
This is fairly small TypeScript program which runs on modern node/iojs versions. It reads the `details.json` file output from [js-doc-parse](https://github.com/wkeese/js-doc-parse) and outputs a TypeScript definition file.

# Running it

* Have [iojs](https://iojs.org) installed. Nodejs >= 0.12 probably works too but I haven't tried it.
* After cloning this repo do a `npm install` to grab the needed modules.
* `npm run make` builds the software.
* `npm run run` runs the generator itself.
* The generated output is written to the `output` directory.
* `npm run test` runs the unit tests.

The `details.json` file for Dojo 1.10 is already included in the `data` directory.

# Goals
* Produce working definition files for Dojo. It remains yet to be proven whether this can be achieved in a practical way.
* No manual modifications to the output. All parts of the conversion process must be automated and fully repeatable.
* Hackable code base. It should be easy for people to get involved and improve it.

# Related work
* [DojoTypeDescriptionGenerator](https://github.com/vansimke/DojoTypeDescriptionGenerator) is also a converter which parses the API HTML documentation to extract the needed information. It is discontinued, but still has some useful code.
* [dojo-typescript-class](https://github.com/sedwards2009/dojo-typescript-class) is a related project which tries to integrate Dojo's classes with TypeScript's classes such that Dojo classes can be extended using TypeScript's class syntax and vice versa.

----
Simon Edwards

Email: simon@simonzone.com

github: https://github.com/sedwards2009


text:
The files in this directory define how we build our GCC cross-compiler that
targets Linux, using the musl libc.

### A note about `-rdynamic`

Do not pass `-rdynamic` to GCC when building an executable; it will cause the compiled executable to depend on a musl libc dynamic loader in `/lib` that probably doesn't exist, and defeats the point of static linking.  The `-static` option overrides `-rdynamic`, so adding`-static` to the linker flags of a project using `-rdynamic` is one way to fix the issue.

CMake will pass `-rdynamic` unless you set [CMP0065](https://cmake.org/cmake/help/v3.8/policy/CMP0065.html) to new as shown below, or set your [CMake policy version](https://cmake.org/cmake/help/v3.8/command/cmake_policy.html) to 3.4 or later.

    # Don't use -rdynamic since it causes Musl static linking to not work.
    cmake_policy(SET CMP0065 NEW)


text:
package com.google.gerrit.server.query.change;

import com.google.gerrit.index.SchemaFieldDefs.SchemaField;
import com.google.gerrit.index.query.Matchable;
import com.google.gerrit.index.query.RegexPredicate;

public abstract class ChangeRegexPredicate extends RegexPredicate<ChangeData>
    implements Matchable<ChangeData> {
  protected ChangeRegexPredicate(SchemaField<ChangeData, ?> def, String value) {
    super(def, value);
  }

  protected ChangeRegexPredicate(SchemaField<ChangeData, ?> def, String name, String value) {
    super(def, name, value);
  }
}


text:
#import <UIKit/UIImage.h>

#import "NSCoding-Protocol.h"

@class NSString;

// Not exported
@interface UIImageNibPlaceholder : UIImage <NSCoding>
{
    NSString *runtimeResourceName;
}

- (void)encodeWithCoder:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (void)dealloc;
- (id)initWithData:(id)arg1 andRuntimeResourceName:(id)arg2;
- (id)initWithContentsOfFile:(id)arg1 andRuntimeResourceName:(id)arg2;

@end


text:
'use strict';

const angular = require('angular');

module.exports = angular
  .module('spinnaker.instanceList.filter', [])
  .filter('instanceSearch', function () {
    return function (instanceList, query) {
      if (!query) {
        return instanceList;
      }
      if (instanceList && instanceList.length) {
        return instanceList.filter(function (instance) {
          if (query.match('^i-')) {
            if (instance.id.includes(query)) {
              return instance;
            }
          } else {
            return instance;
          }
        });
      }
    };
  });


text:
#pragma once

#include "modules/canbus/proto/chassis_detail.pb.h"
#include "modules/drivers/canbus/can_comm/protocol_data.h"

namespace apollo {
namespace canbus {
namespace gem {

class Hornrpt79 : public ::apollo::drivers::canbus::ProtocolData<
                      ::apollo::canbus::ChassisDetail> {
 public:
  static const int32_t ID;
  Hornrpt79();
  void Parse(const std::uint8_t* bytes, int32_t length,
             ChassisDetail* chassis) const override;

 private:
  // config detail: {'name': 'OUTPUT_VALUE', 'enum': {0: 'OUTPUT_VALUE_OFF', 1:
  // 'OUTPUT_VALUE_ON'}, 'precision': 1.0, 'len': 8, 'is_signed_var': False,
  // 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 23, 'type': 'enum',
  // 'order': 'motorola', 'physical_unit': ''}
  Horn_rpt_79::Output_valueType output_value(const std::uint8_t* bytes,
                                             const int32_t length) const;

  // config detail: {'name': 'COMMANDED_VALUE', 'enum': {0:
  // 'COMMANDED_VALUE_OFF', 1: 'COMMANDED_VALUE_ON'}, 'precision': 1.0, 'len':
  // 8, 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit':
  // 15, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''}
  Horn_rpt_79::Commanded_valueType commanded_value(const std::uint8_t* bytes,
                                                   const int32_t length) const;

  // config detail: {'name': 'MANUAL_INPUT', 'enum': {0: 'MANUAL_INPUT_OFF', 1:
  // 'MANUAL_INPUT_ON'}, 'precision': 1.0, 'len': 8, 'is_signed_var': False,
  // 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 7, 'type': 'enum',
  // 'order': 'motorola', 'physical_unit': ''}
  Horn_rpt_79::Manual_inputType manual_input(const std::uint8_t* bytes,
                                             const int32_t length) const;
};

}  // namespace gem
}  // namespace canbus
}  // namespace apollo


text:
@implementation NSAttributedString (BoookAdditions)
- (NSArray *)componentsSeperatedBySubString:(NSString *)subString {
	NSMutableArray *components = [NSMutableArray array];

	NSArray *wordStrings = [self.string componentsSeparatedByString:subString];
	[wordStrings enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
		NSString *wordString = (NSString *)obj;

		if ([self.string rangeOfString:wordString].location != NSNotFound) {
			NSMutableAttributedString *attributedWordString = [[NSMutableAttributedString alloc] initWithAttributedString:[self attributedSubstringFromRange:[self.string rangeOfString:wordString]]];
			[attributedWordString appendAttributedString:[[NSAttributedString alloc] initWithString:@" "]]; // add a space

			[components addObject:attributedWordString];
		}
	}];
	return components;
}

+ (NSDictionary *)attributesForParagraph {
	UIFont *font=[UIFont fontWithName:@"AmericanTypewriter" size:14];
	return [NSDictionary dictionaryWithObjectsAndKeys:
			font, NSFontAttributeName,
			nil];
}

+ (NSDictionary *)attributesForHeading{
	UIFont *font=[UIFont fontWithName:@"AmericanTypewriter" size:25];
	NSShadow *shadowDic=[[NSShadow alloc] init];
	[shadowDic setShadowBlurRadius:3.0];
	[shadowDic setShadowColor:[UIColor darkGrayColor]];
	[shadowDic setShadowOffset:CGSizeMake(0, 1)];
	return [NSDictionary dictionaryWithObjectsAndKeys:
			font, NSFontAttributeName,
			[UIColor blackColor], NSForegroundColorAttributeName,
			nil];
}

+ (NSDictionary *)attributesForSubHeading{
	UIFont *font=[UIFont fontWithName:@"Baskerville-Italic" size:20];
	return [NSDictionary dictionaryWithObjectsAndKeys:
			font, NSFontAttributeName,
			[UIColor blackColor], NSForegroundColorAttributeName,
			nil];
}

+ (NSDictionary *)attributesForFootNote {
	UIFont *font=[UIFont fontWithName:@"AmericanTypewriter" size:14];
	return [NSDictionary dictionaryWithObjectsAndKeys:
			font, NSFontAttributeName,
			[UIColor redColor], NSForegroundColorAttributeName,
			nil];
}

+ (NSDictionary *)attributesForFirstParagraphTitle {
	UIFont *font=[UIFont fontWithName:@"AmericanTypewriter" size:14];
	return [NSDictionary dictionaryWithObjectsAndKeys:
			font, NSFontAttributeName,
			[UIColor redColor], NSForegroundColorAttributeName,
			nil];
}

- (UIFont *) font {
	NSRange *effectiveRange = nil;
	return [self attribute:NSFontAttributeName atIndex:0 effectiveRange:effectiveRange];
}

@end


text:
package com.google.template.soy.parsepasses.contextautoesc;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.template.soy.soytree.RawTextNode;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;

/**
 * A raw text node divided into a slice for each context found by the inference engine so that later
 * parse passes can take action based on text and attribute boundaries.
 *
 */
public final class SlicedRawTextNode {

  /**
   * A substring of raw text that is exposed to parse passes.
   *
   *
This slice is not the entire substring with the same context. Such a thing cannot be
   * statically determined since in a portion of a template that stays in the same context like
   *
   *

   *   foo {if $cond}bar{else}baz{/if} boo
   *

   *
   * there might be two possible strings with the same context: {@code "foo bar boo"} and {@code
   * "foo baz boo"}.
   *
   *

   */
  public static final class RawTextSlice {

    /** The context of the slice. */
    public final Context context;

    /** The text node containing the slice. */
    public final SlicedRawTextNode slicedRawTextNode;

    /** The start offset (inclusive) into the text node's text. */
    private int startOffset;

    /** The end offset (exclusive) into the text node's text. */
    private int endOffset;

    RawTextSlice(
        Context context, SlicedRawTextNode slicedRawTextNode, int startOffset, int endOffset) {
      this.context = context;
      this.slicedRawTextNode = slicedRawTextNode;
      this.startOffset = startOffset;
      this.endOffset = endOffset;
    }

    /** The start offset (inclusive) into the text node's text. */
    public int getStartOffset() {
      return startOffset;
    }

    /** The length of the slice in {@code char}s. */
    public int getLength() {
      return endOffset - startOffset;
    }

    public SlicedRawTextNode getSlicedRawTextNode() {
      return slicedRawTextNode;
    }

    /**
     * Splits this slice in two at the given offset and returns the slice after the split.
     *
     * @param offset into the slice.
     */
    private RawTextSlice split(int offset) {
      int indexInParent = slicedRawTextNode.slices.indexOf(this);
      if (indexInParent < 0) {
        throw new AssertionError("slice is not in its parent");
      }
      Preconditions.checkElementIndex(offset, getLength(), "slice offset");
      RawTextSlice secondSlice = slicedRawTextNode.insertSlice(indexInParent + 1, context, 0);
      int wholeTextOffset = offset + startOffset;
      secondSlice.startOffset = wholeTextOffset;
      this.endOffset = wholeTextOffset;
      return secondSlice;
    }

    /**
     * Mutates the parse tree by replacing the sliced text node with a text node that includes the
     * given text at the given point within this slice.
     *
     * @param text A string in context context.
     * @param offset An offset between 0 (inclusive) and {@link #getLength()} (exclusive).
     * @param context the context of text.
     * @throws SoyAutoescapeException if inserting text would violate context assumptions made by
     *     the contextual autoescaper.
     */
    public void insertText(int offset, String text) throws SoyAutoescapeException {
      int indexInParent = slicedRawTextNode.slices.indexOf(this);
      if (indexInParent < 0) {
        throw new AssertionError("slice is not in its parent");
      }
      Preconditions.checkElementIndex(offset, getLength(), "slice offset");

      // Figure out at which character offset to insert text.
      int insertionIndex = -1;
      int insertionOffset = -1;

      // Split or recurse as necessary so that we are called at the boundary of a slice.
      if (offset == 0) {
        insertionIndex = indexInParent;
        insertionOffset = startOffset;
      } else if (offset == getLength()) {
        insertionIndex = indexInParent;
        insertionOffset = endOffset;
      } else {
        split(offset).insertText(0, text);
        return;
      }

      // Compute the new raw text and create a node to hold it.
      // We re-use the node ID since we're going to remove the old node and discard it.
      RawTextNode rawTextNode = slicedRawTextNode.getRawTextNode();
      String originalText = rawTextNode.getRawText();
      String replacementText =
          originalText.substring(0, insertionOffset)
              + text
              + originalText.substring(insertionOffset);
      RawTextNode replacementNode =
          new RawTextNode(rawTextNode.getId(), replacementText, rawTextNode.getSourceLocation());

      // Rerun the context update algo so that we can figure out the context of the inserted slices
      // and ensure that the inserted text does not invalidate any of the security assumptions made
      // by the auto-escaper.
      Context startContext = slicedRawTextNode.startContext;
      Context expectedEndContext = slicedRawTextNode.endContext;
      SlicedRawTextNode retyped =
          RawTextContextUpdater.processRawText(replacementNode, startContext);
      Context actualEndContext = retyped.getEndContext();

      if (!expectedEndContext.equals(actualEndContext)) {
        // Inserting the text would invalidate typing assumptions made earlier.
        throw SoyAutoescapeException.createWithNode(
            "Inserting `"
                + text
                + "` would cause text node to end in context "
                + actualEndContext
                + " instead of "
                + expectedEndContext,
            rawTextNode);
      }

      // Now that we know that it's valid to insert the text at that location, replace the text node
      // and insert slices for each of the slices in builder corresponding to characters in text.
      slicedRawTextNode.replaceNode(replacementNode);
      int insertionEndOffset = insertionOffset + text.length();
      for (RawTextSlice slice : retyped.slices) {
        if (slice.endOffset <= insertionOffset) {
          continue;
        }
        if (slice.startOffset >= insertionEndOffset) {
          break;
        }
        int length =
            Math.min(insertionEndOffset, slice.endOffset)
                - Math.max(insertionOffset, slice.startOffset);
        slicedRawTextNode.insertSlice(insertionIndex, slice.context, length);
        // Increment the insertion index to point past the slice just inserted so that
        // we're ready for the next one.
        ++insertionIndex;
      }
    }

    /** The raw text of the slice. */
    public String getRawText() {
      return slicedRawTextNode.rawTextNode.getRawText().substring(startOffset, endOffset);
    }

    /** Adjusts the start and end offsets right by the given amount. */
    void shiftOffsets(int delta) {
      startOffset += delta;
      endOffset += delta;
    }

    /** For debugging. */
    @Override
    public String toString() {
      String rawText = getRawText();
      int id = slicedRawTextNode.rawTextNode.getId();
      // "<rawText>"@<textNodeId> with \ and " escaped.
      return "\"" + rawText.replaceAll("\"|\\\\", "\\\\$0") + "\"#" + id;
    }
  }

  /** The backing raw text node. */
  private RawTextNode rawTextNode;
  /** The context in which the text node starts. */
  private final Context startContext;
  /** The context in which the text node ends. */
  private Context endContext;
  /** A collection of all the slices of a particular raw text node in order. */
  private final List<RawTextSlice> slices = Lists.newArrayList();

  public SlicedRawTextNode(RawTextNode rawTextNode, Context startContext) {
    this.rawTextNode = rawTextNode;
    this.startContext = startContext;
  }

  public RawTextNode getRawTextNode() {
    return rawTextNode;
  }

  public List<RawTextSlice> getSlices() {
    return Collections.unmodifiableList(slices);
  }

  /** The context in which the text node ends. */
  public Context getEndContext() {
    return endContext;
  }

  void setEndContext(Context endContext) {
    this.endContext = endContext;
  }

  /**
   * Called by the builder to add slices as their context becomes known.
   *
   * @param startOffset an offset (inclusive) into the rawTextNode's string content.
   * @param endOffset an offset (exclusive) into the rawTextNode's string content.
   * @param context the context for the slice.
   */
  void addSlice(int startOffset, int endOffset, Context context) {
    int lastSliceIndex = slices.size() - 1;
    // Merge adjacent tokens that don't change context.
    if (lastSliceIndex >= 0) {
      RawTextSlice last = slices.get(lastSliceIndex);
      if (last.endOffset == startOffset && context.equals(last.context)) {
        slices.remove(lastSliceIndex);
        startOffset = last.startOffset;
      }
    }
    slices.add(new RawTextSlice(context, this, startOffset, endOffset));
  }

  /** Replaces the backing node in the parse tree and internally. */
  void replaceNode(RawTextNode replacement) {
    rawTextNode.getParent().replaceChild(rawTextNode, replacement);
    this.rawTextNode = replacement;
  }

  /**
   * Inserts a slice, updating the offsets of any following slices and returns the newly created
   * slice.
   */
  RawTextSlice insertSlice(int index, Context context, int length) {
    if (length < 0) {
      throw new IllegalArgumentException("length " + length + " < 0");
    }
    int startOffset = index == 0 ? 0 : slices.get(index - 1).endOffset;
    for (RawTextSlice follower : slices.subList(index, slices.size())) {
      follower.shiftOffsets(length);
    }
    RawTextSlice slice = new RawTextSlice(context, this, startOffset, startOffset + length);
    slices.add(index, slice);
    return slice;
  }

  @VisibleForTesting
  void mergeAdjacentSlicesWithSameContext() {
    // Rewrite list from left to right merging adjacent slices with the same context.
    int nMerged = 0;
    for (int i = 0, n = slices.size(), next; i < n; i = next, ++nMerged) {
      next = i + 1;
      RawTextSlice slice = slices.get(i);
      // Walk next forward until we see a different context.
      while (next < n && slice.context.equals(slices.get(next).context)) {
        ++next;
      }
      // Modify slices in place to have exactly one slice corresponding to [i, next).
      RawTextSlice merged;
      if (next - i == 1) {
        // If there haven't been modifications since the last merge, don't orphan slices.
        merged = slice;
      } else {
        merged =
            new RawTextSlice(
                slice.context, this, slice.startOffset, slices.get(next - 1).endOffset);
      }
      slices.set(nMerged, merged);
    }
    // Truncate.
    slices.subList(nMerged, slices.size()).clear();
  }

  /**
   * The slices that occur in the context described by the given predicates.
   *
   *
The order is deterministic but does not necessarily bear any relationship to the order in
   * which slices can appear in the template's output because it is dependent on the ordering of
   * individual templates in the parsed input.
   *
   * @param slicedRawTextNodes The sliced raw text nodes to search.
   * @param prevContextPredicate Applied to the context before the slice being tested.
   * @param sliceContextPredicate Applied to the context of the slice being tested.
   * @param nextContextPredicate Applied to the context after the slice being tested.
   * @return a list of slices such that input predicates are all true when applied to the contexts
   *     at and around that slice.
   */
  public static List<RawTextSlice> find(
      Iterable<? extends SlicedRawTextNode> slicedTextNodes,
      @Nullable Predicate<? super Context> prevContextPredicate,
      @Nullable Predicate<? super Context> sliceContextPredicate,
      @Nullable Predicate<? super Context> nextContextPredicate) {
    if (prevContextPredicate == null) {
      prevContextPredicate = Predicates.<Context>alwaysTrue();
    }
    if (sliceContextPredicate == null) {
      sliceContextPredicate = Predicates.<Context>alwaysTrue();
    }
    if (nextContextPredicate == null) {
      nextContextPredicate = Predicates.<Context>alwaysTrue();
    }

    ImmutableList.Builder<RawTextSlice> matches = ImmutableList.builder();
    for (SlicedRawTextNode slicedTextNode : slicedTextNodes) {
      // insertText can leave adjacent slices with the same context.
      // Merge slices so that each element in find()'s result list stands alone.
      // This could cause problems with concurrent iteration over two find lists, but the mutators
      // check that a slice is part of its parent so we will fail fast.
      slicedTextNode.mergeAdjacentSlicesWithSameContext();

      Context prevContext = slicedTextNode.startContext;
      List<RawTextSlice> slices = slicedTextNode.slices;
      for (int i = 0, n = slices.size(); i < n; ++i) {
        RawTextSlice current = slices.get(i);
        Context nextContext;
        if (i + 1 < n) {
          nextContext = slices.get(i + 1).context;
        } else {
          nextContext = slicedTextNode.endContext;
        }
        // Apply the predicates.
        if (prevContextPredicate.apply(prevContext)
            && sliceContextPredicate.apply(current.context)
            && nextContextPredicate.apply(nextContext)) {
          matches.add(current);
        }
        prevContext = current.context;
      }
    }
    return matches.build();
  }
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Rakko - Installation - Run Artisan Commands</title>

	<link href='http://fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>

	<link rel="stylesheet" type="text/css" href="{{ asset('assets/vendors/bootstrap-3.3.2/css/bootstrap.min.css') }}">
	<link rel="stylesheet" type="text/css" href="{{ asset('assets/vendors/font-awesome-4.3.0/css/font-awesome.css') }}">
	<link rel="stylesheet" type="text/css" href="{{ asset('assets/installer/css/installer.css') }}">

				{{ trans('installer::install.install_artisan') }}

						@if ( $module_migrate === true )

							{{ trans('installer::install.success.migrate') }}
						@else

							{{ trans('installer::install.error.migrations') }}
						@endif

						@if ( $module_seed === true )

							{{ trans('installer::install.success.seed') }}
						@else

							{{ trans('installer::install.error.seeds') }}
						@endif

						@if ( ($module_migrate === false) || ($module_seed === false) )

									{{ trans('installer::install.error.db_seed') }}

						@else

										{{ trans('installer::install.button.next') }}

						@endif

			{{ Config::get('general.footer') }}


text:
package DataReader;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author G.A.P. II
 */

public abstract class AbstractReader implements IDataReader {

    private static final Logger LOGGER = Logger.getLogger(AbstractReader.class.getName());

    protected String inputFilePath;

    public AbstractReader (String filePath) {
        inputFilePath = filePath;
    }

    public static Object loadSerializedObject(String fileName) {
        Object object = null;
        try {
            InputStream file = new FileInputStream(fileName);
            InputStream buffer = new BufferedInputStream(file);
            ObjectInput input = new ObjectInputStream(buffer);
            try {
                object = input.readObject();
            } finally {
                input.close();
            }
        } catch (ClassNotFoundException cnfEx) {
            LOGGER.log(Level.SEVERE, null, cnfEx);
            return null;
        } catch (IOException ioex) {
            LOGGER.log(Level.SEVERE, null, ioex);
            return null;
        }

        return object;
    }

    @Override
    public void storeSerializedObject(Object object, String outputPath) {
        try {
            OutputStream file = new FileOutputStream(outputPath);
            OutputStream buffer = new BufferedOutputStream(file);
            ObjectOutput output = new ObjectOutputStream(buffer);
            try {
                output.writeObject(object);
            } finally {
                output.close();
            }
        } catch (IOException ioex) {
            LOGGER.log(Level.SEVERE, null, ioex);
        }
    }
}


text:
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/smtp"
	"os"
	"strings"
	"time"
)

//
func main() {
	sourceRoot := os.Args[1]
	if sourceRoot == "" {
		fmt.Fprintf(os.Stderr, "expected path to build sources as first argument")
		os.Exit(1)
	}

	var indata struct {
		Source struct {
			SMTP struct {
				Host     string
				Port     string
				Username string
				Password string
			}
			From string
			To   []string
		}
		Params struct {
			Subject       string
			Body          string
			SendEmptyBody bool `json:"send_empty_body"`
		}
	}

	inbytes, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		panic(err)
	}

	err = json.Unmarshal(inbytes, &indata)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error parsing input as JSON: %s", err)
		os.Exit(1)
	}

	if indata.Source.SMTP.Host == "" {
		fmt.Fprintf(os.Stderr, `missing required field "source.smtp.host"`)
		os.Exit(1)
	}

	if indata.Source.SMTP.Port == "" {
		fmt.Fprintf(os.Stderr, `missing required field "source.smtp.port"`)
		os.Exit(1)
	}

	if indata.Source.SMTP.Username == "" {
		fmt.Fprintf(os.Stderr, `missing required field "source.smtp.username"`)
		os.Exit(1)
	}

	if indata.Source.SMTP.Password == "" {
		fmt.Fprintf(os.Stderr, `missing required field "source.smtp.password"`)
		os.Exit(1)
	}

	if indata.Source.From == "" {
		fmt.Fprintf(os.Stderr, `missing required field "source.from"`)
		os.Exit(1)
	}

	if len(indata.Source.To) == 0 {
		fmt.Fprintf(os.Stderr, `missing required field "source.to"`)
		os.Exit(1)
	}

	if indata.Params.Subject == "" {
		fmt.Fprintf(os.Stderr, `missing required field "params.subject"`)
		os.Exit(1)
	}

	subject := indata.Params.Subject

	headers := "MIME-version: 1.0\nContent-Type: text/html; charset='UTF-8'"

	body := ""
	if indata.Params.Body != "" {
		body = indata.Params.Body
	}

	type MetadataItem struct {
		Name  string
		Value string
	}
	var outdata struct {
		Version struct {
			Time time.Time
		} `json:"version"`
		Metadata []MetadataItem
	}
	outdata.Version.Time = time.Now().UTC()
	outdata.Metadata = []MetadataItem{
		{Name: "smtp_host", Value: indata.Source.SMTP.Host},
		{Name: "subject", Value: subject},
	}
	outbytes, err := json.Marshal(outdata)
	if err != nil {
		panic(err)
	}

	var messageData []byte
	messageData = append(messageData, []byte("To: "+strings.Join(indata.Source.To, ", ")+"\n")...)
	messageData = append(messageData, []byte("From: "+indata.Source.From+"\n")...)
	if headers != "" {
		messageData = append(messageData, []byte(headers+"\n")...)
	}
	messageData = append(messageData, []byte("Subject: "+subject+"\n")...)

	messageData = append(messageData, []byte("\n")...)
	messageData = append(messageData, []byte(body)...)

	if indata.Params.SendEmptyBody == false && len(body) == 0 {
		fmt.Fprintf(os.Stderr, "Message not sent because the message body is empty and send_empty_body parameter was set to false. Github readme: https://github.com/jointeffort/email-resource")
		fmt.Printf("%s", []byte(outbytes))
		return
	}

	err = smtp.SendMail(
		fmt.Sprintf("%s:%s", indata.Source.SMTP.Host, indata.Source.SMTP.Port),
		smtp.PlainAuth(
			"",
			indata.Source.SMTP.Username,
			indata.Source.SMTP.Password,
			indata.Source.SMTP.Host,
		),
		indata.Source.From,
		indata.Source.To,
		messageData,
	)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to send an email using SMTP server %s on port %s: %v",
			indata.Source.SMTP.Host, indata.Source.SMTP.Port, err)
		os.Exit(1)
	}

	fmt.Printf("%s", []byte(outbytes))
}


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-comp-4329',
  templateUrl: './comp-4329.component.html',
  styleUrls: ['./comp-4329.component.css']
})
export class Comp4329Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
package fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import com.hustunique.myapplication.DetailActivity;
import com.hustunique.myapplication.MyApplication;
import com.hustunique.myapplication.R;
import java.util.ArrayList;
import java.util.List;
import adapter.MyOnItemClickListener;
import adapter.MyOnItemLongClickListener;
import adapter.BookRecyclerAdapter;
import data.Book;
import data.DBOperate;
import jp.wasabeef.recyclerview.animators.SlideInDownAnimator;
import service.QueryBooksTask;
import ui.DividerItemDecoration;
import util.Constant;
import util.TimeUtil;

/**
 * book operate
 * book type change(db deal with book change)
 * now to before:book type change,all chapters type change,update
 * now to after:book type change,all chapters type change,update
 * 持有数据:id
 * 数据操作:
 * 改变书籍类型,改变数据库书籍类型,typeS=type
 * 改变书籍内容,改变数据库书籍内容,status=modify
 * 删除书籍,标记书籍删除状态
 */
public class NowFragment extends Fragment implements NumFragment {

    private RecyclerView mRecycler;
    private AlertDialog mDialog;
    private AlertDialog mPlanDialog;
    private AlertDialog mDeleteDialog;
    private DatePicker mPicker;
    private EditText mTime;

    private int mPosition;
    private List<Book> mBookList;
    private BookRecyclerAdapter mAdapter;

    private static NowFragment mFragmentInstance;

    Bundle savedState;

    private final static boolean DEBUG = true;
    public final static String TAG = "life cycle-before";

    @Override
    public int getItemNum() {
        if(mBookList != null)
            return mBookList.size();
        return 0;
    }

    public static NowFragment newInstance() {
        if(DEBUG)
                Log.d(TAG, "now new instance");
        if (mFragmentInstance == null) {
            mFragmentInstance = new NowFragment();
            mFragmentInstance.setArguments(new Bundle());
        }
        return mFragmentInstance;
    }

    @Override
    public void onDetach() {
        if(DEBUG)
            Log.d(TAG, "now on detach");
        super.onDetach();
        mHandler.removeCallbacks(null);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if(DEBUG)
            Log.d(TAG, "now create");
        View root = inflater.inflate(R.layout.fragment_bookshelf_now, container, false);
        mRecycler = (RecyclerView) root;
        mRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecycler.setItemAnimator(new SlideInDownAnimator());
        mRecycler.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL_LIST, 5f));
        createDialogs();
        return root;
    }

    //创建三个对话框:选项、计划、删除
    private void createDialogs()
    {
        mDialog = new AlertDialog.Builder(getActivity(), AlertDialog.THEME_HOLO_LIGHT)
                .setItems(
                        new String[]{"修改阅读计划","已完成", "放弃治疗", "删除此书"},
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch(which){
                                    case 0:
                                        mTime.setText(null);
                                        mPlanDialog.show();
                                        break;
                                    case 1:
                                        //标记为已读,finishNum = chapterNum
                                        //所有章节标记为完成
                                        if(DEBUG)
                                            Log.d(TAG, "book to before, local");
                                        Book book = mBookList.get(mPosition);
                                        book.setType(Constant.TYPE_BEFORE);
                                        book.setFinishNum(book.getChapterNum());

                                        DBOperate dbOperate = MyApplication.getDBOperateInstance();
                                        dbOperate.setBookBefore(
                                                book.getId(), TimeUtil.getNeedTime(System.currentTimeMillis()));

                                        mBookList.remove(mPosition);
                                        mAdapter.notifyItemRemoved(mPosition);
                                        mAdapter.notifyDataSetChanged();
                                        ReadingFragment.executeLoad();
                                        BeforeFragment.executeLoad();
                                        MyApplication.setShouldUpdate(Constant.INDEX_READ);
                                        MyApplication.setShouldUpdate(Constant.INDEX_BEFORE);
                                        break;
                                    case 2:

                                        if(DEBUG)
                                            Log.d(TAG, "book to after, local");
                                        Book book2 = mBookList.get(mPosition);
                                        book2.setType(Constant.TYPE_AFTER);
                                        book2.setFinishNum(0);

                                        DBOperate db = MyApplication.getDBOperateInstance();
                                        db.setBookAfter(
                                                book2.getId(), TimeUtil.getNeedTime(System.currentTimeMillis()));

                                        mBookList.remove(mPosition);
                                        mAdapter.notifyItemRemoved(mPosition);
                                        mAdapter.notifyDataSetChanged();
                                        ReadingFragment.executeLoad();
                                        AfterFragment.executeLoad();
                                        MyApplication.setShouldUpdate(Constant.INDEX_READ);
                                        MyApplication.setShouldUpdate(Constant.INDEX_AFTER);
                                        break;
                                    case 3:
                                        int count = MyApplication.getDBOperateInstance().
                                                getBookReadingNum(mBookList.get(mPosition).getId());
                                        mDeleteDialog.setMessage("本书有"+count+"章在今日阅读计划中,是否仍要删除");
                                        mDeleteDialog.show();
                                        break;
                                }
                            }
                        })
                .create();
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), AlertDialog.THEME_HOLO_LIGHT);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.plan_dialog, null);
        mPicker = (DatePicker)view.findViewById(R.id.dialog_datePicker);
        mTime = (EditText)view.findViewById(R.id.dialog_time);
        builder.setView(view);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(DEBUG)
                    Log.d(TAG, "start --"+which);
                long startTime = TimeUtil.getTimeMillis(mPicker.getYear(), mPicker.getMonth(), mPicker.getDayOfMonth());
                long days = (mTime.getText().toString().length() <=0)? 1 : Long.parseLong(mTime.getText().toString());
                if(days == 0)
                    days = 1;
                long endTime = startTime+days*24*60*60*1000;
                Book book = mBookList.get(mPosition);
                if(DEBUG)
                    Log.d(TAG, "end --"+which);
                book.setStartTime(TimeUtil.getNeedTime(startTime));
                book.setEndTime(TimeUtil.getNeedTime(endTime));
                    //标记为在读
                DBOperate dbOperate = MyApplication.getDBOperateInstance();
                dbOperate.updateBook(book);
                int status = Constant.STATUS_MOD;
                if(book.getStatus() == Constant.STATUS_ADD)
                    status = Constant.STATUS_ADD;
                dbOperate.setBookStatus(book.getId(), status);

                mAdapter.notifyItemChanged(mPosition);
            }
        });
        builder.setNegativeButton("取消", null);
        mPlanDialog = builder.create();
        mDeleteDialog = new AlertDialog.Builder(getActivity(), AlertDialog.THEME_HOLO_LIGHT)
                .setTitle("确定删除此书")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //删除此书及所有章节

                        MyApplication.getDBOperateInstance().setBookDelete(mBookList.get(mPosition).getId());
                        mBookList.remove(mPosition);

                        mAdapter.notifyItemRemoved(mPosition);
                        mAdapter.notifyDataSetChanged();
                        ReadingFragment.executeLoad();
                        MyApplication.setShouldUpdate(Constant.INDEX_READ);
                        Toast.makeText(getActivity(), "已删除", Toast.LENGTH_SHORT).show();

                    }
                })
                .setNegativeButton("否", null)
                .create();
    }

    //打印log
    @Override
    public void onStart() {
        if(DEBUG)
            Log.d(TAG, "now start");
        super.onStart();

    }

    @Override
    public void onResume() {
        if(DEBUG)
            Log.d(TAG, "now resume");
        super.onResume();
        if (MyApplication.getUpdateFlag(Constant.INDEX_NOW) || !restoreStateFromArguments()) {
            // First Time, Initialize something here
            load();
        }
        else if(mAdapter != null &&mBookList != null && mPosition >= 0 && mPosition < mBookList.size())
        {
            Book book = mBookList.get(mPosition);
            if(book != null ) {
                book.setFinishNum(
                        MyApplication.getDBOperateInstance().getBookFinishNum(book.getId()));
                mAdapter.notifyItemChanged(mPosition);
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if(DEBUG)
            Log.d(TAG, "now pause");
    }

    @Override
    public void onStop() {
        if(DEBUG)
            Log.d(TAG, "now stop");
        super.onStop();
    }

    //保存恢复数据或刷新数据
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Restore State Here

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // Save State Here
        saveStateToArguments();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(DEBUG)
            Log.d(TAG, "before destroy");

        // Save State Here
        saveStateToArguments();
    }

    ////////////////////
    // Don't Touch !!
    ////////////////////

    private void saveStateToArguments() {
        if (getView() != null)
            savedState = saveState();
        if (savedState != null) {
            Bundle b = getArguments();
            b.putBundle("internalSavedViewState", savedState);
        }
    }

    ////////////////////
    // Don't Touch !!
    ////////////////////

    private boolean restoreStateFromArguments() {
        Bundle b = getArguments();
        savedState = b.getBundle("internalSavedViewState");
        if (savedState != null) {
            restoreState();
            return true;
        }
        return false;
    }

    public Bundle getSavedState() {
        return savedState;
    }

    public void setSavedState(Bundle savedState) {
        this.savedState = savedState;
    }

    /////////////////////////////////
    // Restore Instance State Here
    /////////////////////////////////

    private void restoreState() {
        if (savedState != null) {
            // For Example
            //tv1.setText(savedState.getString("text"));
            onRestoreState(savedState);
        }
    }

    protected void onRestoreState(Bundle savedInstanceState) {
        mBookList =  savedInstanceState.getParcelableArrayList(Constant.KEY_BOOKS);
        if(mBookList == null)
            mBookList = new ArrayList<>();
        if(DEBUG)
            Log.d(TAG, "now restore, book list size:"+mBookList.size());
        if(mBookList.size() > 0)
            setupAdapter();
        else
            load();
    }

    //////////////////////////////
    // Save Instance State Here
    //////////////////////////////

    private Bundle saveState() {
        Bundle state = new Bundle();
        // For Example
        //state.putString("text", tv1.getText().toString());
        onSaveState(state);
        return state;
    }

    protected void onSaveState(Bundle outState) {
        outState.putParcelableArrayList(Constant.KEY_BOOKS, (ArrayList<Book>)mBookList);
    }

    private Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 0)
            {
                setupAdapter();
            }

        }
    };

    //从网络或本地数据库读取数据至list,并创建adapter
    private void load()
    {
        if(DEBUG)
            Log.d(TAG, "now load data");
        if(mBookList == null)
            mBookList = new ArrayList<>();
        else
            mBookList.clear();
        new QueryBooksTask(mBookList, mHandler).execute(Constant.TYPE_NOW);
        if(DEBUG)
            Log.d(TAG, "now finish load data");
    }

    //绑定设置adapter
    private void setupAdapter()
    {
        if(mAdapter == null) {
            mAdapter = new BookRecyclerAdapter(getActivity(), mBookList, true);
            mAdapter.setOnItemClickListener(mOnItemClickListener);
            mAdapter.setOnItemLongClickListener(mOnItemLongClickListener);
            mRecycler.setAdapter(mAdapter);
            if(DEBUG)
                Log.d(TAG, "now create and set adapter:" + mBookList.size());
        }
        else if(mRecycler.getAdapter() == null)
        {
            mRecycler.setAdapter(mAdapter);
            if(DEBUG)
                Log.d(TAG, "now set adapter:"+mBookList.size());
        }
        else
        {
            mAdapter.notifyDataSetChanged();
            if(DEBUG)
                Log.d(TAG, "now adapter notify:"+mBookList.size());
        }
    }

    private MyOnItemClickListener mOnItemClickListener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(View view, Book book, int position) {
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra(Constant.KEY_ACTION, Constant.ADD_CHAPTER);
            intent.putExtra(Constant.KEY_BOOK, book);
            startActivityForResult(intent, Constant.ADD_CHAPTER);
        }
    };

    private MyOnItemLongClickListener mOnItemLongClickListener = new MyOnItemLongClickListener() {
        @Override
        public void onItemLongClick(View view, Book book, int position) {
            mPosition = position;
            mDialog.show();
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == Constant.ADD_CHAPTER
                && resultCode == Activity.RESULT_OK
                && data != null)
        {
            Book book = mBookList.get(mPosition);
            book.setFinishNum(
                    MyApplication.getDBOperateInstance().getBookFinishNum(book.getId()));
            mAdapter.notifyItemChanged(mPosition);
        }
    }

    public static void executeLoad()
    {
        if(DEBUG)
            Log.d(TAG, "now execute load");
        if(mFragmentInstance != null) {
            mFragmentInstance.load();
        }
    }
}


text:
module Azure end
module Azure::EventHub end
module Azure::EventHub::Mgmt end


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'TwitterRecentEntries'
        db.create_table('cmsplugin_twitterrecententries', (
            ('cmsplugin_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['cms.CMSPlugin'], unique=True, primary_key=True)),
            ('title', self.gf('django.db.models.fields.CharField')(max_length=75, blank=True)),
            ('twitter_user', self.gf('django.db.models.fields.CharField')(max_length=75)),
            ('count', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=3)),
            ('link_hint', self.gf('django.db.models.fields.CharField')(max_length=75, blank=True)),
        ))
        db.send_create_signal('djangocms_twitter', ['TwitterRecentEntries'])

        # Adding model 'TwitterSearch'
        db.create_table('cmsplugin_twittersearch', (
            ('cmsplugin_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['cms.CMSPlugin'], unique=True, primary_key=True)),
            ('title', self.gf('django.db.models.fields.CharField')(max_length=75, blank=True)),
            ('query', self.gf('django.db.models.fields.CharField')(default='', max_length=200, blank=True)),
            ('count', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=3)),
        ))
        db.send_create_signal('djangocms_twitter', ['TwitterSearch'])

    def backwards(self, orm):
        # Deleting model 'TwitterRecentEntries'
        db.delete_table('cmsplugin_twitterrecententries')

        # Deleting model 'TwitterSearch'
        db.delete_table('cmsplugin_twittersearch')

    models = {
        'cms.cmsplugin': {
            'Meta': {'object_name': 'CMSPlugin'},
            'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 6, 23, 0, 0)'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}),
            'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}),
            'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
            'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
        },
        'cms.placeholder': {
            'Meta': {'object_name': 'Placeholder'},
            'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'})
        },
        'djangocms_twitter.twitterrecententries': {
            'Meta': {'object_name': 'TwitterRecentEntries', 'db_table': "'cmsplugin_twitterrecententries'", '_ormbases': ['cms.CMSPlugin']},
            'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}),
            'count': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '3'}),
            'link_hint': ('django.db.models.fields.CharField', [], {'max_length': '75', 'blank': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '75', 'blank': 'True'}),
            'twitter_user': ('django.db.models.fields.CharField', [], {'max_length': '75'})
        },
        'djangocms_twitter.twittersearch': {
            'Meta': {'object_name': 'TwitterSearch', 'db_table': "'cmsplugin_twittersearch'", '_ormbases': ['cms.CMSPlugin']},
            'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}),
            'count': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '3'}),
            'query': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '200', 'blank': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '75', 'blank': 'True'})
        }
    }

    complete_apps = ['djangocms_twitter']


text:
<?php

/**
 * Untaint strings
 *
 * @phpstub-variable-parameters
 * @phpstub
 *
 * @param string $string
 * @param string $_
 *
 * @return bool
 */
function untaint(&$string, $_ = NULL)
{
}


text:
@class DVTObservingToken, GPUResourceEditor, GPUSharedTabUIState, GPUTraceDocumentLocation, GPUTraceModelFactory, NSArrayController, NSCollectionView, NSDictionary, NSMutableArray, NSScrollView, NSString;

__attribute__((visibility("hidden")))
@interface GPUTraceResourcesEditor : GPUMainEditor <NSCollectionViewDelegate, IDEGPUAssistantEditorAdditions, DVTFindBarFindable>
{
    GPUTraceModelFactory *_modelFactory;
    GPUTraceDocumentLocation *_currentLocation;
    NSDictionary *_previousEditorState;
    BOOL _loadingEditor;
    DVTObservingToken *_programShaderObserver;
    int _lastShaderType;
    GPUSharedTabUIState *_sharedTabState;
    NSString *_identifier;
    NSMutableArray *_resources;
    NSArrayController *_resourceArrayController;
    NSCollectionView *_resourceCollectionView;
    GPUResourceEditor *_currentSubViewController;
    NSScrollView *_resourceCollectionViewEnclosure;
}

+ (long long)version;
+ (void)configureStateSavingObjectPersistenceByName:(id)arg1;
+ (id)assetBundle;
+ (id)defaultViewNibBundle;
+ (id)defaultViewNibName;
@property(retain, nonatomic) NSScrollView *resourceCollectionViewEnclosure; // @synthesize resourceCollectionViewEnclosure=_resourceCollectionViewEnclosure;
@property(nonatomic) __weak GPUResourceEditor *currentSubViewController; // @synthesize currentSubViewController=_currentSubViewController;
@property(nonatomic) __weak NSCollectionView *resourceCollectionView; // @synthesize resourceCollectionView=_resourceCollectionView;
@property(nonatomic) __weak NSArrayController *resourceArrayController; // @synthesize resourceArrayController=_resourceArrayController;
@property(retain, nonatomic) NSMutableArray *resources; // @synthesize resources=_resources;
- (void).cxx_destruct;
- (struct _NSRange)selectedRangeForFindBar:(id)arg1;
- (id)startingLocationForFindBar:(id)arg1 findingBackwards:(BOOL)arg2;
- (void)dvtFindBar:(id)arg1 didUpdateCurrentResult:(id)arg2;
- (void)dvtFindBar:(id)arg1 didUpdateResults:(id)arg2;
- (BOOL)findBarSupported;
- (void)_takeStateDictionaryFromPreviousGPUAssistantEditor:(id)arg1;
- (BOOL)_shouldInstallGPUEditorWithPreviousStateDictionaryOrNil:(id)arg1;
- (void)commitStateToDictionary:(id)arg1;
- (void)revertStateWithDictionary:(id)arg1;
- (id)_findOutlineItemForHistoryAction;
- (id)_currentAssistantDocumentLocations;
- (id)_getSubEditorItemFromPreviousEditorState;
- (void)doubleClick:(id)arg1;
- (void)_openResourceLocation:(id)arg1;
- (void)handleOpenScrubberTriggeredNewLocation:(id)arg1;
- (void)handleDebugBarNavigationWithDocumentLocation:(id)arg1;
- (void)selectDocumentLocations:(id)arg1;
- (id)currentSelectedDocumentLocations;
- (id)currentSelectedItems;
- (void)_setCurrentLocation:(id)arg1;
- (void)_loadResourceEditorForNavItem:(id)arg1;
- (void)_handleFunctionResourceItem:(id)arg1;
- (id)_findNavigableForShaderItem:(id)arg1;
- (BOOL)_isValidSourceURLPathForShaderItem:(id)arg1;
- (id)_editorForResourceItem:(id)arg1;
- (void)handleResourceItemThumbnailsInvalidation:(id)arg1;
- (void)handleReloadResourceItem:(id)arg1;
- (void)resetResourcesInTree:(id)arg1;
- (void)_resetResource:(id)arg1;
- (void)_loadRelevantDisplayableForProgramOrShaderItem:(id)arg1;
- (void)didSetupEditor;
- (void)viewWillUninstall;
- (void)viewDidInstall;
- (void)primitiveInvalidate;
- (void)loadView;
- (void)takeFocus;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
layout: post
title: Get a life! Now!
date: 2007-07-05T13:20:00.000Z
author: Marcus Hammarberg
tags:
  - Fun
modified_time: 2007-07-05T13:22:38.297Z
blogger_id: tag:blogger.com,1999:blog-36533086.post-2977175341533347912
blogger_orig_url: http://www.marcusoft.net/2007/07/get-life-now.html
---

This guy must be the most dedicated lego-builder in the world. Read the
text in the outset... get a cup of coffee and just be happy that you
have something to do. May it be just the dishes


text:
class StatsManagerTest : public ::testing::Test
                       , public SimpleTwoSwitchGraph
{
protected:
    virtual void SetUp() {
        initGraph();
        xid_generator = std::make_shared<RequestIdGenerator>();
        stats_manager = std::make_shared<StatsManager>(xid_generator);

        node1 = nodes.emplace(nodes.end(),
            Node(1u, rule1, NetworkSpace::wholeSpace(),
                Transfer::identityTransfer(), 1u));
        node2 = nodes.emplace(nodes.end(),
            Node(2u, rule2, NetworkSpace::wholeSpace(),
                Transfer::identityTransfer(), 1u));
        path = domain_paths.emplace(domain_paths.end(),
            DomainPath(1u, node1, node2, TimestampFactory().createTimestamp()));
    }

    virtual void TearDown() {
        stats_manager.reset();
        xid_generator.reset();
        nodes.clear();
        domain_paths.clear();
        destroyGraph();
    }

    std::shared_ptr<RequestIdGenerator> xid_generator;
    std::shared_ptr<StatsManager> stats_manager;

    std::list<Node> nodes;
    std::list<DomainPath> domain_paths;
    NodePtr node1, node2;
    DomainPathPtr path;
};

TEST_F(StatsManagerTest, BucketTest)
{
    StatsBucket bucket(xid_generator);
    auto stats = std::make_shared<RuleStats>(stats_manager->frontTime(), rule1);
    bucket.addStats(stats);
    EXPECT_TRUE(bucket.queriesExist());
    auto requests = bucket.getRequests();
    ASSERT_EQ(1u, requests.data.size());
    bucket.passRequest(requests.data[0]);
    EXPECT_TRUE(bucket.isFull());
    auto complete_stats = bucket.popStatsList();
    ASSERT_EQ(1u, complete_stats.size());
}

TEST_F(StatsManagerTest, BasicTest)
{
    uint64_t packet_count = 100u;

    stats_manager->requestRule(rule1);
    stats_manager->requestPath(path);
    stats_manager->discardPathRequest(path);

    auto requests = stats_manager->getNewRequests();
    ASSERT_EQ(1u, requests.data.size());
    auto rule_request = RuleRequest::pointerCast(requests.data[0]);
    ASSERT_NE(nullptr, rule_request);
    EXPECT_EQ(*rule1->info(), *rule_request->rule);
    EXPECT_LT(rule_request->time.value, stats_manager->frontTime().value);
    rule_request->stats.packet_count = packet_count;
    stats_manager->passRequest(rule_request);
    auto stats_list = stats_manager->popStatsList();
    ASSERT_EQ(1u, stats_list.stats.size());
    auto rule_stats = std::dynamic_pointer_cast<RuleStats>(
        *stats_list.stats.begin()
    );
    ASSERT_NE(nullptr, rule_stats);
    EXPECT_EQ(rule1->id(), rule_stats->rule->id());
    EXPECT_EQ(packet_count, rule_stats->stats_fields.packet_count);
}

class FlowPredictorTest : public ::testing::Test
                        , public SimpleTwoSwitchGraph
{
protected:
    using H = HeaderSpace;
    using N = NetworkSpace;

    virtual void SetUp() {
        initFlowPredictor();
        updateSpecialRuleEdges();
        updateTableMissEdges();
    }

    virtual void TearDown() {
        flow_predictor.reset();
        xid_generator.reset();
        destroyGraph();
    }

    void initFlowPredictor() {
        initGraph();
        xid_generator = std::make_shared<RequestIdGenerator>();
        flow_predictor = std::make_shared<FlowPredictor>(dependency_graph,
                                                         xid_generator);
    }

    void updateSpecialRuleEdges() {
        installSpecialRules();
        flow_predictor->updateEdges(drop_diff);
        flow_predictor->updateEdges(controller_diff);

        flow_predictor->updateEdges(p11_source_diff);
        flow_predictor->updateEdges(p11_sink_diff);
        flow_predictor->updateEdges(p12_source_diff);
        flow_predictor->updateEdges(p12_sink_diff);

        flow_predictor->updateEdges(p21_source_diff);
        flow_predictor->updateEdges(p21_sink_diff);
        flow_predictor->updateEdges(p22_source_diff);
        flow_predictor->updateEdges(p22_sink_diff);
    }

    void updateTableMissEdges() {
        installTableMissRules();
        flow_predictor->updateEdges(table_miss1_diff);
        flow_predictor->updateEdges(table_miss2_diff);
    }

    void updateFirstRuleEdges() {
        installFirstRule();
        flow_predictor->updateEdges(rule1_diff);
    }

    void updateSecondRuleEdges() {
        installSecondRule();
        flow_predictor->updateEdges(rule2_diff);
    }

    void updateAllRules() {
        // Get table miss instruction
        flow_predictor->getInstruction();

        // Get rule1 instruction
        updateFirstRuleEdges();
        flow_predictor->getInstruction();

        // Get rule2 instruction
        updateSecondRuleEdges();
        flow_predictor->getInstruction();
    }

    void updateLinkInstallation() {
        installLink();
        flow_predictor->updateEdges(link_diff);
    }

    void updateLinkDeletion() {
        flow_predictor->getInstruction();
        deleteLink();
        flow_predictor->updateEdges(link_deletion_diff);
    }

    RuleInfoPtr getRule(SwitchId sw_id, NetworkSpace domain,
                        const std::list<RuleInfoPtr>& rules) {
        auto it = std::find_if(rules.begin(), rules.end(),
            [sw_id, domain](RuleInfoPtr rule) {
                if (rule->switch_id) {
                    return rule->switch_id == sw_id &&
                        rule->match == domain.match();
                }
                return false;
            }
        );
        return (it != rules.end()) ? *it : nullptr;
    }

    RuleInfoPtr getRequestedRule(SwitchId sw_id, NetworkSpace domain,
                             const RequestList& request_list) {
        auto it = std::find_if(
            request_list.data.begin(), request_list.data.end(),
            [sw_id, domain](RequestPtr request) {
                auto rule_request = RuleRequest::pointerCast(request);
                if (not rule_request) return false;

                auto rule = rule_request->rule;
                if (rule->switch_id) {
                    return rule->switch_id == sw_id &&
                        rule->match == domain.match();
                }
                return false;
            }
        );
        if (it != request_list.data.end()) {
            auto rule_request = RuleRequest::pointerCast(*it);
            return rule_request->rule;
        }
        else {
            return nullptr;
        }
    }

    std::shared_ptr<RequestIdGenerator> xid_generator;
    std::shared_ptr<FlowPredictor> flow_predictor;
};

TEST_F(FlowPredictorTest, CreationTest)
{
    TearDown();
    initFlowPredictor();
    updateSpecialRuleEdges();

    auto instruction = flow_predictor->getInstruction();
    EXPECT_TRUE(instruction.interceptor_diff.empty());
    EXPECT_TRUE(instruction.requests.data.empty());
}

TEST_F(FlowPredictorTest, TableMissTest)
{
    auto instruction = flow_predictor->getInstruction();
    auto& new_rules = instruction.interceptor_diff.rules_to_add;
    EXPECT_EQ(4u, new_rules.size());
    EXPECT_NE(nullptr, getRule(1u, N(1), new_rules));
    EXPECT_NE(nullptr, getRule(1u, N(2), new_rules));
    EXPECT_NE(nullptr, getRule(2u, N(1), new_rules));
    EXPECT_NE(nullptr, getRule(2u, N(2), new_rules));
    EXPECT_TRUE(instruction.interceptor_diff.rules_to_delete.empty());
    EXPECT_TRUE(instruction.requests.data.empty());
}

TEST_F(FlowPredictorTest, AddRuleTest)
{
    // Get table miss instruction
    auto table_miss_instruction = flow_predictor->getInstruction();
    auto& table_miss_new_rules =
          table_miss_instruction.interceptor_diff.rules_to_add;
    auto table_miss_source1 = getRule(1u, N(1), table_miss_new_rules);
    ASSERT_NE(nullptr, table_miss_source1);

    // Get rule1 instruction
    updateFirstRuleEdges();
    auto rule1_instruction = flow_predictor->getInstruction();

    // Check rule1 requests
    ASSERT_EQ(1u, rule1_instruction.requests.data.size());
    auto request = *rule1_instruction.requests.data.begin();
    auto rule_request = RuleRequest::pointerCast(request);
    ASSERT_NE(nullptr, rule_request);
    EXPECT_EQ(*table_miss_source1, *rule_request->rule);

    // Check rule1 new rules
    auto& rule1_new_rules = rule1_instruction.interceptor_diff.rules_to_add;
    EXPECT_EQ(2u, rule1_new_rules.size());
    auto rule1_new_rule1 = getRule(1u, N(1, H("0000xxxx")), rule1_new_rules);
    auto rule1_new_rule2 = getRule(1u, N(1, H("xxxxxxxx") - H("0000xxxx")),
                                   rule1_new_rules);
    EXPECT_NE(nullptr, rule1_new_rule1);
    EXPECT_NE(nullptr, rule1_new_rule2);

    // Check rule1 deleted rules
    auto& rule1_deleted_rules = rule1_instruction.interceptor_diff.rules_to_delete;
    ASSERT_EQ(1u, rule1_deleted_rules.size());
    auto rule1_old_rule1 = getRule(1u, N(1), rule1_deleted_rules);
    ASSERT_NE(nullptr, rule1_old_rule1);
    EXPECT_EQ(*table_miss_source1, *rule1_old_rule1);

    // Get rule2 instruction
    updateSecondRuleEdges();
    auto rule2_instruction = flow_predictor->getInstruction();
    EXPECT_EQ(1u, rule2_instruction.requests.data.size());
    EXPECT_EQ(2u, rule2_instruction.interceptor_diff.rules_to_add.size());
    EXPECT_EQ(1u, rule2_instruction.interceptor_diff.rules_to_delete.size());
}

TEST_F(FlowPredictorTest, DeleteRuleTest)
{
    updateAllRules();

    // Delete rule
    dependency_graph->deleteRule(rule1);
    auto diff = dependency_graph->popEdgeDiff();
    flow_predictor->updateEdges(diff);
    auto instruction = flow_predictor->getInstruction();

    // Check requests
    EXPECT_EQ(2u, instruction.requests.data.size());
    auto requested_rule1 = getRequestedRule(
        1u, N(1, H("0000xxxx")), instruction.requests
    );
    auto requested_rule2 = getRequestedRule(
        1u, N(1, H("xxxxxxxx") - H("0000xxxx")), instruction.requests
    );
    EXPECT_NE(nullptr, requested_rule1);
    EXPECT_NE(nullptr, requested_rule2);

    // Check new rules
    auto& new_rules = instruction.interceptor_diff.rules_to_add;
    EXPECT_EQ(1u, new_rules.size());
    auto new_rule = getRule(1u, N(1), new_rules);
    EXPECT_NE(nullptr, new_rule);

    // Check deleted rules
    auto& deleted_rules = instruction.interceptor_diff.rules_to_delete;
    EXPECT_EQ(2u, deleted_rules.size());
    auto deleted_rule1 = getRule(1u, N(1, H("0000xxxx")), deleted_rules);
    auto deleted_rule2 = getRule(1u, N(1, H("xxxxxxxx") - H("0000xxxx")),
                                 deleted_rules);
    ASSERT_NE(nullptr, deleted_rule1);
    ASSERT_NE(nullptr, deleted_rule2);
}

TEST_F(FlowPredictorTest, AddLinkTest)
{
    updateAllRules();

    // Add link
    updateLinkInstallation();
    auto instruction = flow_predictor->getInstruction();

    // Check requests
    EXPECT_EQ(4u, instruction.requests.data.size());
    auto requested_rule1 = getRequestedRule(
        1u, N(1, H("0000xxxx")), instruction.requests
    );
    auto requested_rule2 = getRequestedRule(
        2u, N(1, H("000000xx")), instruction.requests
    );
    auto requested_rule3 = getRequestedRule(
        1u, N(2, H("xxxxxxxx")), instruction.requests
    );
    auto requested_rule4 = getRequestedRule(
        2u, N(1, H("xxxxxxxx") - H("000000xx")), instruction.requests
    );
    EXPECT_NE(nullptr, requested_rule1);
    EXPECT_NE(nullptr, requested_rule2);
    EXPECT_NE(nullptr, requested_rule3);
    EXPECT_NE(nullptr, requested_rule4);

    // Check new rules
    auto& new_rules = instruction.interceptor_diff.rules_to_add;
    EXPECT_EQ(2u, new_rules.size());
    auto new_rule1 = getRule(
        1u, N(1, H("0000xxxx") & H("000000xx")), new_rules
    );
    auto new_rule2 = getRule(
        1u, N(1, H("0000xxxx") - H("000000xx")), new_rules
    );
    EXPECT_NE(nullptr, new_rule1);
    EXPECT_NE(nullptr, new_rule2);

    // Check deleted rules
    auto& deleted_rules = instruction.interceptor_diff.rules_to_delete;
    EXPECT_EQ(4u, deleted_rules.size());
    auto deleted_rule1 = getRule(
        1u, N(1, H("0000xxxx")), deleted_rules
    );
    auto deleted_rule2 = getRule(
        2u, N(1, H("000000xx")), deleted_rules
    );
    auto deleted_rule3 = getRule(
        1u, N(2, H("xxxxxxxx")), deleted_rules
    );
    auto deleted_rule4 = getRule(
        2u, N(1, H("xxxxxxxx") - H("000000xx")), deleted_rules
    );
    EXPECT_NE(nullptr, deleted_rule1);
    EXPECT_NE(nullptr, deleted_rule2);
    EXPECT_NE(nullptr, deleted_rule3);
    EXPECT_NE(nullptr, deleted_rule4);
}

TEST_F(FlowPredictorTest, DeleteLinkTest)
{
    updateAllRules();
    updateLinkInstallation();

    // Delete link
    updateLinkDeletion();
    auto instruction = flow_predictor->getInstruction();

    // Check requests
    EXPECT_EQ(2u, instruction.requests.data.size());
    auto requested_rule1 = getRequestedRule(
        1u, N(1, H("0000xxxx") & H("000000xx")), instruction.requests
    );
    auto requested_rule2 = getRequestedRule(
        1u, N(1, H("0000xxxx") - H("000000xx")), instruction.requests
    );
    EXPECT_NE(nullptr, requested_rule1);
    EXPECT_NE(nullptr, requested_rule2);

    // Check new rules
    auto& new_rules = instruction.interceptor_diff.rules_to_add;
    EXPECT_EQ(4u, new_rules.size());
    auto new_rule1 = getRule(
        1u, N(1, H("0000xxxx")), new_rules
    );
    auto new_rule2 = getRule(
        2u, N(1, H("000000xx")), new_rules
    );
    auto new_rule3 = getRule(
        1u, N(2, H("xxxxxxxx")), new_rules
    );
    auto new_rule4 = getRule(
        2u, N(1, H("xxxxxxxx") - H("000000xx")), new_rules
    );
    EXPECT_NE(nullptr, new_rule1);
    EXPECT_NE(nullptr, new_rule2);
    EXPECT_NE(nullptr, new_rule3);
    EXPECT_NE(nullptr, new_rule4);

    // Check deleted rules
    auto& deleted_rules = instruction.interceptor_diff.rules_to_delete;
    EXPECT_EQ(2u, deleted_rules.size());
    auto deleted_rule1 = getRule(
        1u, N(1, H("0000xxxx") & H("000000xx")), deleted_rules
    );
    auto deleted_rule2 = getRule(
        1u, N(1, H("0000xxxx") - H("000000xx")), deleted_rules
    );
    EXPECT_NE(nullptr, deleted_rule1);
    EXPECT_NE(nullptr, deleted_rule2);
}

TEST_F(FlowPredictorTest, PredictionTest)
{
    updateAllRules();
}


text:
title: Extra Yarn
written_by:
available: 'January 17th, 2012'
isbn: '9780061953385'
binding: Hardcover
link_to_buy_page:
image_path: 'https://images.booksense.com/images/385/953/9780061953385.jpg'
link:
---

Extra Yarn, a Caldecott Honor Book, Boston Globe-Horn Book Award winner, and a New York Times bestseller, is the story of how a young girl and her box of magical yarn transform a community.

With spare, gently humorous illustrations and a palette that moves from black-and-white to a range of color, this modern fairy tale has the feel of a new classic.

Extra Yarn is written by Mac Barnett and illustrated by Jon Klassen, who also won a Caldecott Medal for This Is Not My Hat.

Supports the Common Core State Standards.


text:
// Generated by xsd compiler for ios/objective-c
// DO NOT CHANGE!

#import <Foundation/Foundation.h>
#import "PicoClassSchema.h"
#import "PicoPropertySchema.h"
#import "PicoConstants.h"
#import "PicoBindable.h"

/**
 (public class)

 @ingroup StockQuoteSoap
*/
@interface GetQuote : NSObject <PicoBindable> {

@private
    NSString *_symbol;

}

/**
 (public property)

 type : NSString, wrapper for primitive string
*/
@property (nonatomic, retain) NSString *symbol;

@end


text:
from __future__ import division
import time
import math
import smbus

class Hat:

    address = 0x40
    mode1 = 0x00
    mode2 = 0x01
    prescale = 0xFE

    bus = smbus.SMBus(1)

    def __init__(self):

        self.set_all_pwm(0, 0)

        self.bus.write_byte_data(self.address, self.mode2, 0x04)
        self.bus.write_byte_data(self.address, self.mode1, 0x01)

        time.sleep(0.005)  # wait for oscillator

        mode1 = self.bus.read_byte_data(self.address, self.mode1) & 0xFF
        mode1 = mode1 & ~0x10  # wake up (reset sleep)

        self.bus.write_byte_data(self.address, self.mode1, mode1)
        time.sleep(0.005)  # wait for oscillator

    def set_pwm_freq(self, freq_hz):

        prescaleval = 25000000.0    # 25MHz
        prescaleval /= 4096.0       # 12-bit
        prescaleval /= float(freq_hz)
        prescaleval -= 1.0
        prescale = int(math.floor(prescaleval + 0.5))

        oldmode = self.bus.read_byte_data(self.address, self.mode1) & 0xFF
        newmode = (oldmode & 0x7F) | 0x10  # sleep

        self.bus.write_byte_data(self.address, self.mode1, newmode)  # go to sleep
        self.bus.write_byte_data(self.address, self.prescale, prescale)
        self.bus.write_byte_data(self.address, self.mode1, oldmode)
        time.sleep(0.005)
        self.bus.write_byte_data(self.address, self.mode1, oldmode | 0x80)

    def set_pwm(self, channel, on, off):
        self.bus.write_byte_data(self.address, 0x06 + 4 * channel, on & 0xFF)
        self.bus.write_byte_data(self.address, 0x07 + 4 * channel, on >> 8)
        self.bus.write_byte_data(self.address, 0x08 + 4 * channel, off & 0xFF)
        self.bus.write_byte_data(self.address, 0x09 + 4 * channel, off >> 8)

    def set_all_pwm(self, on, off):
        self.bus.write_byte_data(self.address, 0xFA, on & 0xFF)
        self.bus.write_byte_data(self.address, 0xFB, on >> 8)
        self.bus.write_byte_data(self.address, 0xFC, off & 0xFF)
        self.bus.write_byte_data(self.address, 0xFD, off >> 8)


text:
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser

class MyUserManager(BaseUserManager):
    def create_user(self, username=None, email=None, password=None):
        """
        Creates and saves a User with the given username, email, and password.
        """
        if not username:
            raise ValueError('Users must have an username')
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
        username = username,
            email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, email,  password):
        """
        Creates and saves a superuser with the given username, email, and password.
        """
        user = self.create_user(
            username=username,
            email=Email
            password=password,
        )

        user.is_admin = True
        user.save(using=self._db)
        return user

class MyUser(AbstractBaseUser):
    username = models.CharField(
        max_length=255,
        unique=True,
    )
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    first_name = models.CharField(
            max_length=120,
            null=True,
            blank=True,
    )
    last_name = models.CharField(
            max_length=120,
            null=True,
            blank=True,
    )
    is_member = models.BooleanField(default=False, verbose_name='Is a paid member')
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['date_of_birth']

    def get_full_name(self):
        # The user is identified by their email address
        return "%s %s" (self.first_name, self.last_name)

    def get_short_name(self):
        # The user is identified by their email address
        return self.first_name

    def __unicode__(self):              # __unicode__ on Python 2
        return self.username

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin


text:
const ProvinceCard = require('../../provincecard.js');
import { CardTypes, TargetModes } from '../../Constants.js';
const AbilityDsl = require('../../abilitydsl');

class DishonorableAssault extends ProvinceCard {
    setupCardAbilities() {
        this.action({
            title: 'Discard cards to dishonor attackers',
            effect: 'discard {1} and dishonor {2}',
            effectArgs: context => [context.costs.discardCardsUpToVariableX.map(a => a.name).sort().join(', '), context.target],
            cost: AbilityDsl.costs.discardCardsUpToVariableX(context => this.getNumberOfLegalTargets(context)),
            target: {
                mode: TargetModes.ExactlyVariable,
                numCardsFunc: (context) => {
                    if(context && context.costs && context.costs.discardCardsUpToVariableX) {
                        return context.costs.discardCardsUpToVariableX.length;
                    }

                    return this.getNumberOfLegalTargets(context);
                },
                cardType: CardTypes.Character,
                cardCondition: card => card.isAttacking(),
                gameAction: AbilityDsl.actions.dishonor()
            },
            cannotTargetFirst: true
        });
    }

    getNumberOfLegalTargets(context) {
        if(this.game.isDuringConflict()) {
            let cards = this.game.currentConflict.getParticipants(card => card.isAttacking());
            let count = 0;
            cards.forEach(card => {
                if(card.allowGameAction('dishonor', context)) {
                    count++;
                }
            });

            return count;
        }
        return 0;
    }
}

DishonorableAssault.id = 'dishonorable-assault';

module.exports = DishonorableAssault;


text:
package cvpb

//go:generate cproto -use-grpc-plugin


text:
<?php

namespace lavrentiev\widgets\toastr;

use yii\helpers\Json;

/**
 * Class NotificationFlash
 * @package lavrentiev\widgets\toastr
 */
class NotificationFlash extends Notification
{
    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function run()
    {
        $session = \Yii::$app->session;

        $flashes = $session->getAllFlashes();

        foreach ($flashes as $type => $data) {

            $data = (array) $data;

            foreach ($data as $i => $message) {

                Notification::widget(['type' => $type, 'message' => $message, 'options' => ($this->options) ? Json::decode($this->options) : []]);

            }

            $session->removeFlash($type);
        }
    }
}


text:
FROM openjdk:8-windowsservercore
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop';"]

RUN iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex; `
    choco install -y 7zip; `
    Invoke-WebRequest -Uri 'http://dl.ubnt.com/unifi/5.6.29/UniFi-installer.exe' -Outfile 'C:\UniFi-installer.exe';
RUN 7z x C:\UniFi-installer.exe -oC:\app\;

VOLUME [ "C:/app/data" ]

EXPOSE 8080 8081 8443 8843 8880 3478

COPY docker-entrypoint.ps1 /

CMD . .\docker-entrypoint.ps1


text:
require_dependency "renalware/letters/letter"

module Renalware
  module Letters
    class Letter::Approved < Letter
      def self.policy_class
        ApprovedLetterPolicy
      end

      def complete(by:)
        becomes!(Completed).tap do |letter|
          letter.by = by
          letter.completed_by = by
          letter.completed_at = Time.current
        end
      end
    end
  end
end


text:
package com.nesscomputing.httpserver;

import java.lang.annotation.Annotation;

import javax.servlet.Servlet;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.handler.HandlerWrapper;

import com.google.inject.Binder;
import com.google.inject.binder.LinkedBindingBuilder;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Names;
import com.google.inject.servlet.GuiceFilter;

/**
 * Bind additional {@link Handler} elements into the http server.
 */
public final class HttpServerHandlerBinder
{
    public static final String HANDLER_NAME = "_handlers";
    public static final Annotation HANDLER_NAMED = Names.named(HANDLER_NAME);

    public static final String LOGGING_NAME = "_logging";
    public static final Annotation LOGGING_NAMED = Names.named(LOGGING_NAME);

    public static final String SECURITY_NAME = "_security";
    public static final Annotation SECURITY_NAMED = Names.named(SECURITY_NAME);

    public static final String CATCHALL_NAME = "_catchall";
    public static final Annotation CATCHALL_NAMED = Names.named(CATCHALL_NAME);

    private HttpServerHandlerBinder()
    {
    }

    /**
     * Bind a new handler into the jetty service. These handlers are bound before the servlet handler and can handle parts
     * of the URI space before a servlet sees it.
     *
     * Do not use this method to bind logging handlers as they would be called before any functionality has been executed and
     * logging information would be incomplete. Use {@link HttpServerHandlerBinder#bindLoggingHandler(Binder) instead.
     */
    public static LinkedBindingBuilder<Handler> bindHandler(final Binder binder)
    {
        final Multibinder<Handler> handlers = Multibinder.newSetBinder(binder, Handler.class, HANDLER_NAMED);
        return handlers.addBinding();
    }

    /**
     * Bind a new handler into the jetty service. These handlers are bound after the servlet handler and will not see any requests before they
     * have been handled. This is intended to bind logging, statistics etc. which want to operate on the results of a request to the server.
     *
     * Any handler intended to manage content or a part of the URI space should use {@link HttpServerHandlerBinder#bindHandler(Binder)}.
     */
    public static LinkedBindingBuilder<Handler> bindLoggingHandler(final Binder binder)
    {
        final Multibinder<Handler> handlers = Multibinder.newSetBinder(binder, Handler.class, LOGGING_NAMED);
        return handlers.addBinding();
    }

    /**
     * Bind a delegating security handler. Any request will be routed through this handler and can be allowed or denied by this handler. If no handler
     * is bound, requests are forwarded to the internal handler collection.
     */
    public static LinkedBindingBuilder<HandlerWrapper> bindSecurityHandler(final Binder binder)
    {
        return binder.bind(HandlerWrapper.class).annotatedWith(SECURITY_NAMED);
    }

    /**
     * Configure the "get all requests" servlet that backs the {@link GuiceFilter}. This servlet should log all requests as legal request should never
     * hit it.
     */
    public static LinkedBindingBuilder<Servlet> bindCatchallServlet(final Binder binder)
    {
        return binder.bind (Servlet.class).annotatedWith(CATCHALL_NAMED);
    }
}