text:
Migrating from Java4 CommonsLang to Java6 Guava to Java8
======

![alt text](screenshots/160523003321875.png)

This tutorial cover code migration from different historical technical stacks. It goes from Java 1.4 with Commons-Lang (2005, Apache), to Java 1.6 with Guava (2009, Google) then to Java 8 (2015). These technical stacks are knowned to be Java language extension (Jakarta and Guava). Most basic usecases will be covered:

* condition
* check
* filter
* map
* error handling
* load file
* load resource

by implementing this Interface:

```java
public interface IJavaUseCases {

    boolean condition(String arg);
    void check(String arg);

    List<String> filter(List<String> input);
    List<String> map(List<String> input);

    void errorHandling(Exception e);

    String loadFile(String path) throws Exception;
    String loadResource(String name) throws Exception;

}
```

## Java 1.4 (vanilla)

This source code is pure old Java, with a lot of boilerplate and very unsafe (missing generics, for each). For historical purpose only.

```java
// UNSTABLE: UNSAFE COLLECTIONS, BOILERPLATES
public class Java4AVanillaImpl implements IJavaUseCases {

    public boolean condition(String arg) {
        return arg != null && arg.trim().length() > 0;
    }

    public void check(String arg) {
        if (!condition(arg)) {
            throw new IllegalArgumentException();
        }
    }

    public List filter(List input) {
        List output = new ArrayList();
        for (int i = 0; i < input.size(); i++) {
            String current = (String) input.get(i);
            if (condition(current)) {
                output.add(current);
            }
        }
        return output;
    }

    public List map(List input) {
        List output = new ArrayList();
        for (int i = 0; i < input.size(); i++) {
            String current = (String) input.get(i);
            String transformed = current.toUpperCase();
            output.add(transformed);
        }
        return output;
    }

    public void errorHandling(Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    public String loadFile(String path) throws Exception {
        FileInputStream stream = new FileInputStream(path);
        try {
            Reader br = new BufferedReader(new InputStreamReader(stream));
            StringBuffer sb = new StringBuffer();
            for (int c = br.read(); c != -1; c = br.read())
                sb.append((char) c);
            return sb.toString();
        } finally {
            stream.close();
        }
    }

    public String loadResource(String name) throws Exception {
        InputStream stream = getClass().getClassLoader().getResourceAsStream(
                name);
        try {
            Reader br = new BufferedReader(new InputStreamReader(stream));
            StringBuffer sb = new StringBuffer();
            for (int c = br.read(); c != -1; c = br.read())
                sb.append((char) c);
            return sb.toString();
        } finally {
            stream.close();
        }
    }

}
```

## Java 1.4 with Commons-Lang (2005)

This is typical old Java 1.4 source code using Apache Commons-Lang. There is less boilerplate, but it's still very unsafe (missing generics, for each).

```java
// STABLE: COMMONS-LANG
public class Java4CommonsLangImpl implements IJavaUseCases {

    public boolean condition(String arg) {
        return StringUtils.isNotBlank(arg);
    }

    public void check(String arg) {
        if (!condition(arg)) {
            throw new IllegalArgumentException();
        }
    }

    public List filter(List input) {
        ...
    }

    public List map(List input) {
        ...
    }

    public void errorHandling(Exception e) {
        ...
    }

    public String loadFile(String path) throws Exception {
        File file = new File(path);
        return FileUtils.readFileToString(file);
    }

    public String loadResource(String name) throws Exception {
        ClassLoader classLoader = this.getClass().getClassLoader();
        return IOUtils.toString(classLoader.getResourceAsStream(name));
    }
}
```

## Java 1.6 with Commons-Lang (2007)

This is lazy old Java 1.6 source code, still using outdated Commons-lang instead of more modern library like Spring or Guava. Not very different, but saffer (generics, foreach).

```java
// STABLE: COMMONS-LANG, JAVA GENERICS
public class Java6CommonsLangImpl implements IJavaUseCases {

    public boolean condition(String arg) {
        ...
    }

    public void check(String arg) {
        ...
    }

    public List<String> filter(List<String> input) {
        List<String> output = new ArrayList<String>();
        for (String current : input) {
            if (condition(current)) {
                output.add(current);
            }
        }
        return output;
    }

    public List<String> map(List<String> input) {
        List<String> output = new ArrayList<String>();
        for (String current : input) {
            String transformed = current.toUpperCase();
            output.add(transformed);
        }
        return output;
    }

    public void errorHandling(Exception e) {
        ...
    }

    public String loadFile(String path) throws Exception {
        ...
    }

    public String loadResource(String name) throws Exception {
        ...
    }
}
```

## Java 1.6 with Guava (2011)

This is actual Java 1.6 source code. Using modern library like Guava. This version is practilly bug-free and comprehensive because of the removing of boilerplate (using guava API and Impl instead).

```java
// STABLE: GUAVA UTILS
// FAST: GUAVA IMPL
public class Java6GuavaImpl implements IJavaUseCases {

    public boolean condition(String arg) {
        return !Strings.nullToEmpty(arg).trim().isEmpty();
    }

    public void check(String arg) {
        Preconditions.checkArgument(condition(arg));
    }

    public List<String> filter(List<String> input) {
        return new ArrayList(Collections2.filter(input,
                new Predicate<String>() {
                    public boolean apply(String input) {
                        return condition(input);
                    }
                }));
    }

    public List<String> map(List<String> input) {
        return Lists.transform(input, new Function<String, String>() {
            public String apply(String input) {
                return input.toUpperCase();
            }
        });
    }

    public void errorHandling(Exception e) {
        throw Throwables.propagate(e);
    }

    public String loadFile(String path) throws IOException {
        File file = new File(path);
        return Files.toString(file, Charsets.UTF_8);
    }

    public String loadResource(String name) throws IOException {
        URL url = Resources.getResource(name);
        return Resources.toString(url, Charsets.UTF_8);
    }
}
```

## Java 8 (2015)

This is actual "state of the art" Java 8. Using new Java API instead of Guava. The source code is a lot smaller, comprehensive, and faster because of the implementation delegation. Good functions like check() and isBlanck() are still missing. Maybe relying on JavaEE with BeanValidation annotation like @NotNull, @NotEmpty.

```java
// STABLE: GUAVA UTILS, JAVA 8 UTILS
// FAST: JAVA 8 IMPL
public class Java8GuavaImpl implements IJavaUseCases {

    public boolean condition(String arg) {
        ...
    }

    public void check(String arg) {
        ...
    }

    public List<String> filter(List<String> input) {
        return input.stream() //
                .filter(i -> condition(i)) //
                .collect(Collectors.toList());
    }

    public List<String> map(List<String> input) {
        return input.stream() //
                .map(i -> i.toUpperCase()) //
                .collect(Collectors.toList());
    }

    public void errorHandling(Exception e) {
        ...
    }

    public String loadFile(String path) throws IOException {
        return new String(Files.readAllBytes(Paths.get(path)));
    }

    public String loadResource(String name) throws Exception {
        URI uri = ClassLoader.getSystemResource(name).toURI();
        return new String(Files.readAllBytes(Paths.get(uri)));
    }
}
```

## Demo

![alt text](screenshots/160523003321968.jpg)

The same test suite will be played for each technical stacks, by using JUnit Parameterized. JavaUseCasesTest.java

```java
@RunWith(value = Parameterized.class)
public class JavaUseCasesTest {

    private IJavaUseCases classToTest;

    public JavaUseCasesTest(IJavaUseCases classToTest) {
        this.classToTest = classToTest;
    }

    @Parameters(name = "test of class {0}")
    public static Iterable<Object[]> data() {
        return asList(new Object[][] { //
        //
                { new Java4AVanillaImpl() }, //
                { new Java4CommonsLangImpl() }, //
                { new Java6CommonsLangImpl() }, //
                { new Java6GuavaImpl() }, //
                { new Java8GuavaImpl() } });
    }

    @Test
    public void test_Condition() {
        assertTrue(classToTest.condition("Valid"));
        assertFalse(classToTest.condition(null));
        assertFalse(classToTest.condition(""));
        assertFalse(classToTest.condition(" "));
    }

    @Test
    public void test_Check() {
        classToTest.check("Valid");
        try {
            classToTest.check(null);
            fail("EXPECTED ERROR!");
        } catch (Exception e) {
            assertTrue(e instanceof IllegalArgumentException);
        }
        try {
            classToTest.check("");
            fail("EXPECTED ERROR!");
        } catch (Exception e) {
            assertTrue(e instanceof IllegalArgumentException);
        }
    }

    @Test
    public void test_Transform() {
        List<String> args = asList(new String[] { "a", "b", "c" });
        List<String> expected = asList(new String[] { "A", "B", "C" });
        List<String> result = classToTest.map(args);
        assertNotNull(result);
        assertEquals(expected.size(), result.size());
        for (int i = 0; i < result.size(); i++) {
            assertEquals(expected.get(i), result.get(i));
        }
    }

    @Test
    public void test_Filter() {
        List<String> args = asList(new String[] { "a", "", "c" });
        List<String> expected = asList(new String[] { "a", "c" });
        List<String> result = classToTest.filter(args);
        assertNotNull(result);
        assertEquals(expected.size(), result.size());
        for (int i = 0; i < result.size(); i++) {
            assertEquals(expected.get(i), result.get(i));
        }
    }

    @Test
    public void test_Error_Handling() {
        IllegalStateException arg = new IllegalStateException("AAhhh!");
        try {
            classToTest.errorHandling(arg);
            fail("EXPECTED ERROR!");
        } catch (Exception e) {
            assertTrue(e instanceof RuntimeException);
            assertEquals(arg.getMessage(), e.getMessage());
        }
    }

    @Test
    public void test_Load_File() throws Exception {
        String result = classToTest.loadFile("src/main/resources/file.txt");
        assertEquals("file content", result);
    }

    @Test
    public void test_Load_Resource() throws Exception {
        String result = classToTest.loadResource("resource.txt");
        assertEquals("resource content", result);
    }
}
```

pom.xml

```xml
<?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>
    <groupId>com.damienfremont.blog</groupId>
    <artifactId>20150806-java-commonslang_guava_java8</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- APACHE LANGUAGE EXTENSION -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <!-- GOOGLE LANGUAGE EXTENSION -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
```

##

## Conclusion

There is no going back, for the purpose of quality and productivity. The only reason not to use this last source code is if Java8 is not allowed on your project. Same for Java6 with Guava, or Java4 with Commons-Lang. On the opposite, vanilla Java 1.4 or Java 1.6 with Commons-Lang are no longer relevant.

## Source

[https://github.com/DamienFremont/blog/tree/master/20150806-java-commonslang_guava_java8](https://github.com/DamienFremont/blog/tree/master/20150806-java-commonslang_guava_java8)
https://github.com/DamienFremont/blog/tree/master/20150806-java-commonslang_guava_java8

## References

[https://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html](https://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html)
https://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html

[https://code.google.com/p/guava-libraries/wiki/GuavaExplained](https://code.google.com/p/guava-libraries/wiki/GuavaExplained)
https://code.google.com/p/guava-libraries/wiki/GuavaExplained

[http://tutorials.jenkov.com/java-collections/streams.html](http://tutorials.jenkov.com/java-collections/streams.html)
http://tutorials.jenkov.com/java-collections/streams.html

[http://www.mkyong.com/unittest/junit-4-tutorial-6-parameterized-test/](http://www.mkyong.com/unittest/junit-4-tutorial-6-parameterized-test/)
http://www.mkyong.com/unittest/junit-4-tutorial-6-parameterized-test/

## Origin
[https://damienfremont.com/2015/08/06/migrating-from-java4-commonslang-to-java6-guava-to-java8/](https://damienfremont.com/2015/08/06/migrating-from-java4-commonslang-to-java6-guava-to-java8/)


text:
// Copyright 2022 Google LLC
//
// Licensed 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.google.api.ads.admanager.jaxws.v202208;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Lists all errors associated with forecast adjustments.
 *
 *
 *
Java class for ForecastAdjustmentError complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ForecastAdjustmentError">
 *   <complexContent>
 *     <extension base="{https://www.google.com/apis/ads/publisher/v202208}ApiError">
 *       <sequence>
 *         <element name="reason" type="{https://www.google.com/apis/ads/publisher/v202208}ForecastAdjustmentError.Reason" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ForecastAdjustmentError", propOrder = {
    "reason"
})
public class ForecastAdjustmentError
    extends ApiError
{

    @XmlSchemaType(name = "string")
    protected ForecastAdjustmentErrorReason reason;

    /**
     * Gets the value of the reason property.
     *
     * @return
     *     possible object is
     *     {@link ForecastAdjustmentErrorReason }
     *
     */
    public ForecastAdjustmentErrorReason getReason() {
        return reason;
    }

    /**
     * Sets the value of the reason property.
     *
     * @param value
     *     allowed object is
     *     {@link ForecastAdjustmentErrorReason }
     *
     */
    public void setReason(ForecastAdjustmentErrorReason value) {
        this.reason = value;
    }

}

redpajama_set_name: RedPajamaGithub


text:
package ${package}.complete.game;

import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import ${package}.common.ExampleUtils;
import ${package}.complete.game.utils.WriteWindowedToBigQuery;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.PipelineResult;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.io.PubsubIO;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.Aggregator;
import org.apache.beam.sdk.transforms.Combine;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.MapElements;
import org.apache.beam.sdk.transforms.Mean;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.Sum;
import org.apache.beam.sdk.transforms.Values;
import org.apache.beam.sdk.transforms.View;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.FixedWindows;
import org.apache.beam.sdk.transforms.windowing.IntervalWindow;
import org.apache.beam.sdk.transforms.windowing.OutputTimeFns;
import org.apache.beam.sdk.transforms.windowing.Sessions;
import org.apache.beam.sdk.transforms.windowing.Window;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.sdk.values.TypeDescriptors;
import org.joda.time.DateTimeZone;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class is the fourth in a series of four pipelines that tell a story in a 'gaming'
 * domain, following {@link UserScore}, {@link HourlyTeamScore}, and {@link LeaderBoard}.
 * New concepts: session windows and finding session duration; use of both
 * singleton and non-singleton side inputs.
 *
 *
This pipeline builds on the {@link LeaderBoard} functionality, and adds some "business
 * intelligence" analysis: abuse detection and usage patterns. The pipeline derives the Mean user
 * score sum for a window, and uses that information to identify likely spammers/robots. (The robots
 * have a higher click rate than the human users). The 'robot' users are then filtered out when
 * calculating the team scores.
 *
 *
Additionally, user sessions are tracked: that is, we find bursts of user activity using
 * session windows. Then, the mean session duration information is recorded in the context of
 * subsequent fixed windowing. (This could be used to tell us what games are giving us greater
 * user retention).
 *
 *
Run {@code org.apache.beam.examples.complete.game.injector.Injector} to generate
 * pubsub data for this pipeline. The {@code Injector} documentation provides more detail.
 *
 *
To execute this pipeline using the Dataflow service, specify the pipeline configuration
 * like this:
 *
{@code
 *   --project=YOUR_PROJECT_ID
 *   --tempLocation=gs://YOUR_TEMP_DIRECTORY
 *   --runner=BlockingDataflowRunner
 *   --dataset=YOUR-DATASET
 *   --topic=projects/YOUR-PROJECT/topics/YOUR-TOPIC
 * }
 *

 * where the BigQuery dataset you specify must already exist. The PubSub topic you specify should
 * be the same topic to which the Injector is publishing.
 */
public class GameStats extends LeaderBoard {

  private static final String TIMESTAMP_ATTRIBUTE = "timestamp_ms";

  private static DateTimeFormatter fmt =
      DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS")
          .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST")));

  /**
   * Filter out all but those users with a high clickrate, which we will consider as 'spammy' uesrs.
   * We do this by finding the mean total score per user, then using that information as a side
   * input to filter out all but those user scores that are larger than
   * {@code (mean * SCORE_WEIGHT)}.
   */
  // [START DocInclude_AbuseDetect]
  public static class CalculateSpammyUsers
      extends PTransform<PCollection<KV<String, Integer>>, PCollection<KV<String, Integer>>> {
    private static final Logger LOG = LoggerFactory.getLogger(CalculateSpammyUsers.class);
    private static final double SCORE_WEIGHT = 2.5;

    @Override
    public PCollection<KV<String, Integer>> expand(PCollection<KV<String, Integer>> userScores) {

      // Get the sum of scores for each user.
      PCollection<KV<String, Integer>> sumScores = userScores
          .apply("UserSum", Sum.<String>integersPerKey());

      // Extract the score from each element, and use it to find the global mean.
      final PCollectionView<Double> globalMeanScore = sumScores.apply(Values.<Integer>create())
          .apply(Mean.<Integer>globally().asSingletonView());

      // Filter the user sums using the global mean.
      PCollection<KV<String, Integer>> filtered = sumScores
          .apply("ProcessAndFilter", ParDo
              // use the derived mean total score as a side input
              .withSideInputs(globalMeanScore)
              .of(new DoFn<KV<String, Integer>, KV<String, Integer>>() {
                private final Aggregator<Long, Long> numSpammerUsers =
                  createAggregator("SpammerUsers", Sum.ofLongs());
                @ProcessElement
                public void processElement(ProcessContext c) {
                  Integer score = c.element().getValue();
                  Double gmc = c.sideInput(globalMeanScore);
                  if (score > (gmc * SCORE_WEIGHT)) {
                    LOG.info("user " + c.element().getKey() + " spammer score " + score
                        + " with mean " + gmc);
                    numSpammerUsers.addValue(1L);
                    c.output(c.element());
                  }
                }
              }));
      return filtered;
    }
  }
  // [END DocInclude_AbuseDetect]

  /**
   * Calculate and output an element's session duration.
   */
  private static class UserSessionInfoFn extends DoFn<KV<String, Integer>, Integer> {
    @ProcessElement
    public void processElement(ProcessContext c, BoundedWindow window) {
      IntervalWindow w = (IntervalWindow) window;
      int duration = new Duration(
          w.start(), w.end()).toPeriod().toStandardMinutes().getMinutes();
      c.output(duration);
    }
  }

  /**
   * Options supported by {@link GameStats}.
   */
  interface Options extends LeaderBoard.Options {
    @Description("Numeric value of fixed window duration for user analysis, in minutes")
    @Default.Integer(60)
    Integer getFixedWindowDuration();
    void setFixedWindowDuration(Integer value);

    @Description("Numeric value of gap between user sessions, in minutes")
    @Default.Integer(5)
    Integer getSessionGap();
    void setSessionGap(Integer value);

    @Description("Numeric value of fixed window for finding mean of user session duration, "
        + "in minutes")
    @Default.Integer(30)
    Integer getUserActivityWindowDuration();
    void setUserActivityWindowDuration(Integer value);

    @Description("Prefix used for the BigQuery table names")
    @Default.String("game_stats")
    String getGameStatsTablePrefix();
    void setGameStatsTablePrefix(String value);
  }

  /**
   * Create a map of information that describes how to write pipeline output to BigQuery. This map
   * is used to write information about team score sums.
   */
  protected static Map<String, WriteWindowedToBigQuery.FieldInfo<KV<String, Integer>>>
      configureWindowedWrite() {
    Map<String, WriteWindowedToBigQuery.FieldInfo<KV<String, Integer>>> tableConfigure =
        new HashMap<String, WriteWindowedToBigQuery.FieldInfo<KV<String, Integer>>>();
    tableConfigure.put(
        "team",
        new WriteWindowedToBigQuery.FieldInfo<KV<String, Integer>>(
            "STRING", (c, w) -> c.element().getKey()));
    tableConfigure.put(
        "total_score",
        new WriteWindowedToBigQuery.FieldInfo<KV<String, Integer>>(
            "INTEGER", (c, w) -> c.element().getValue()));
    tableConfigure.put(
        "window_start",
        new WriteWindowedToBigQuery.FieldInfo<KV<String, Integer>>(
            "STRING",
            (c, w) -> {
              IntervalWindow window = (IntervalWindow) w;
              return fmt.print(window.start());
            }));
    tableConfigure.put(
        "processing_time",
        new WriteWindowedToBigQuery.FieldInfo<KV<String, Integer>>(
            "STRING", (c, w) -> fmt.print(Instant.now())));
    return tableConfigure;
  }

  /**
   * Create a map of information that describes how to write pipeline output to BigQuery. This map
   * is used to write information about mean user session time.
   */
  protected static Map<String, WriteWindowedToBigQuery.FieldInfo<Double>>
      configureSessionWindowWrite() {

    Map<String, WriteWindowedToBigQuery.FieldInfo<Double>> tableConfigure =
        new HashMap<String, WriteWindowedToBigQuery.FieldInfo<Double>>();
    tableConfigure.put(
        "window_start",
        new WriteWindowedToBigQuery.FieldInfo<Double>(
            "STRING",
            (c, w) -> {
              IntervalWindow window = (IntervalWindow) w;
              return fmt.print(window.start());
            }));
    tableConfigure.put(
        "mean_duration",
        new WriteWindowedToBigQuery.FieldInfo<Double>("FLOAT", (c, w) -> c.element()));
    return tableConfigure;
  }

  public static void main(String[] args) throws Exception {

    Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
    // Enforce that this pipeline is always run in streaming mode.
    options.setStreaming(true);
    ExampleUtils exampleUtils = new ExampleUtils(options);
    Pipeline pipeline = Pipeline.create(options);

    // Read Events from Pub/Sub using custom timestamps
    PCollection<GameActionInfo> rawEvents = pipeline
        .apply(PubsubIO.<String>read()
            .timestampLabel(TIMESTAMP_ATTRIBUTE).topic(options.getTopic())
            .withCoder(StringUtf8Coder.of()))
        .apply("ParseGameEvent", ParDo.of(new ParseEventFn()));

    // Extract username/score pairs from the event stream
    PCollection<KV<String, Integer>> userEvents =
        rawEvents.apply("ExtractUserScore",
          MapElements.via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore()))
            .withOutputType(
                TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers())));

    // Calculate the total score per user over fixed windows, and
    // cumulative updates for late data.
    final PCollectionView<Map<String, Integer>> spammersView = userEvents
      .apply("FixedWindowsUser", Window.<KV<String, Integer>>into(
          FixedWindows.of(Duration.standardMinutes(options.getFixedWindowDuration()))))

      // Filter out everyone but those with (SCORE_WEIGHT * avg) clickrate.
      // These might be robots/spammers.
      .apply("CalculateSpammyUsers", new CalculateSpammyUsers())
      // Derive a view from the collection of spammer users. It will be used as a side input
      // in calculating the team score sums, below.
      .apply("CreateSpammersView", View.<String, Integer>asMap());

    // [START DocInclude_FilterAndCalc]
    // Calculate the total score per team over fixed windows,
    // and emit cumulative updates for late data. Uses the side input derived above-- the set of
    // suspected robots-- to filter out scores from those users from the sum.
    // Write the results to BigQuery.
    rawEvents
      .apply("WindowIntoFixedWindows", Window.<GameActionInfo>into(
          FixedWindows.of(Duration.standardMinutes(options.getFixedWindowDuration()))))
      // Filter out the detected spammer users, using the side input derived above.
      .apply("FilterOutSpammers", ParDo
              .withSideInputs(spammersView)
              .of(new DoFn<GameActionInfo, GameActionInfo>() {
                @ProcessElement
                public void processElement(ProcessContext c) {
                  // If the user is not in the spammers Map, output the data element.
                  if (c.sideInput(spammersView).get(c.element().getUser().trim()) == null) {
                    c.output(c.element());
                  }
                }
              }))
      // Extract and sum teamname/score pairs from the event data.
      .apply("ExtractTeamScore", new ExtractAndSumScore("team"))
      // [END DocInclude_FilterAndCalc]
      // Write the result to BigQuery
      .apply("WriteTeamSums",
          new WriteWindowedToBigQuery<KV<String, Integer>>(
              options.getGameStatsTablePrefix() + "_team", configureWindowedWrite()));

    // [START DocInclude_SessionCalc]
    // Detect user sessions-- that is, a burst of activity separated by a gap from further
    // activity. Find and record the mean session lengths.
    // This information could help the game designers track the changing user engagement
    // as their set of games changes.
    userEvents
      .apply("WindowIntoSessions", Window.<KV<String, Integer>>into(
          Sessions.withGapDuration(Duration.standardMinutes(options.getSessionGap())))
          .withOutputTimeFn(OutputTimeFns.outputAtEndOfWindow()))
      // For this use, we care only about the existence of the session, not any particular
      // information aggregated over it, so the following is an efficient way to do that.
      .apply(Combine.perKey(x -> 0))
      // Get the duration per session.
      .apply("UserSessionActivity", ParDo.of(new UserSessionInfoFn()))
      // [END DocInclude_SessionCalc]
      // [START DocInclude_Rewindow]
      // Re-window to process groups of session sums according to when the sessions complete.
      .apply("WindowToExtractSessionMean", Window.<Integer>into(
          FixedWindows.of(Duration.standardMinutes(options.getUserActivityWindowDuration()))))
      // Find the mean session duration in each window.
      .apply(Mean.<Integer>globally().withoutDefaults())
      // Write this info to a BigQuery table.
      .apply("WriteAvgSessionLength",
             new WriteWindowedToBigQuery<Double>(
                options.getGameStatsTablePrefix() + "_sessions", configureSessionWindowWrite()));
    // [END DocInclude_Rewindow]

    // Run the pipeline and wait for the pipeline to finish; capture cancellation requests from the
    // command line.
    PipelineResult result = pipeline.run();
    exampleUtils.waitToFinish(result);
  }
}


text:
package org.elasticsearch.index.mapper.dynamictemplate.pathmatch;

import org.apache.lucene.index.IndexableField;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.FieldMappers;
import org.elasticsearch.index.mapper.ParseContext.Document;
import org.elasticsearch.test.ElasticsearchSingleNodeTest;
import org.junit.Test;

import static org.elasticsearch.common.io.Streams.copyToBytesFromClasspath;
import static org.elasticsearch.common.io.Streams.copyToStringFromClasspath;
import static org.hamcrest.Matchers.equalTo;

/**
 *
 */
public class PathMatchDynamicTemplateTests extends ElasticsearchSingleNodeTest {

    @Test
    public void testSimple() throws Exception {
        String mapping = copyToStringFromClasspath("/org/elasticsearch/index/mapper/dynamictemplate/pathmatch/test-mapping.json");
        DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser().parse(mapping);
        byte[] json = copyToBytesFromClasspath("/org/elasticsearch/index/mapper/dynamictemplate/pathmatch/test-data.json");
        Document doc = docMapper.parse(new BytesArray(json)).rootDoc();

        IndexableField f = doc.getField("name");
        assertThat(f.name(), equalTo("name"));
        assertThat(f.stringValue(), equalTo("top_level"));
        assertThat(f.fieldType().stored(), equalTo(false));

        FieldMappers fieldMappers = docMapper.mappers().fullName("name");
        assertThat(fieldMappers.mappers().size(), equalTo(1));
        assertThat(fieldMappers.mapper().fieldType().stored(), equalTo(false));

        f = doc.getField("obj1.name");
        assertThat(f.name(), equalTo("obj1.name"));
        assertThat(f.fieldType().stored(), equalTo(true));

        fieldMappers = docMapper.mappers().fullName("obj1.name");
        assertThat(fieldMappers.mappers().size(), equalTo(1));
        assertThat(fieldMappers.mapper().fieldType().stored(), equalTo(true));

        f = doc.getField("obj1.obj2.name");
        assertThat(f.name(), equalTo("obj1.obj2.name"));
        assertThat(f.fieldType().stored(), equalTo(false));

        fieldMappers = docMapper.mappers().fullName("obj1.obj2.name");
        assertThat(fieldMappers.mappers().size(), equalTo(1));
        assertThat(fieldMappers.mapper().fieldType().stored(), equalTo(false));

        // verify more complex path_match expressions

        fieldMappers = docMapper.mappers().fullName("obj3.obj4.prop1");
        assertThat(fieldMappers.mappers().size(), equalTo(1));
    }
}


text:
GRUPO=B
PAREJA=08
#Por lo general no se requiere modificar el fichero
#a parir de esta línea
export PGDATABASE:=$(GRUPO)_$(PAREJA)
export PGUSER :=alumnodb
export PGPASSWORD :=alumnodb
#export PGCLIENTENCODING:=LATIN9
export PGHOST:=localhost
DBNAME =$(PGDATABASE)
PSQL = psql
CREATEDB = createdb
DROPDB = dropdb
PG_DUMP = pg_dump
all: borrar db tablas datos respaldo triggerA triggerB procaA funcB funcC procaD
db:
	@echo Creando BBDD
	@$(CREATEDB)
tablas:
	@echo Creando tablas
	@cat tablas.sql | $(PSQL)
ejerD:
	@echo Creando tablas y poblandolas para el ejercicio D
	@cat EjerD.sql | $(PSQL)
cascade:
	@echo Creando tablas sin on delete cascaden
	@cat tablasSinCascade.sql | $(PSQL)
datos:
	@echo Poblando tablas
	@cat datos.sql | $(PSQL)
borrar:
	@echo Eliminando BBDD
	@$(DROPDB) $(DBNAME)
respaldo:
	@echo creando dumpfile
	@$(PG_DUMP) > $(DBNAME).sql
consultaA:
	@echo consultaA
	@cat consultaA.sql | $(PSQL) | tee consultaA.log
consultaB:
	@echo consultaB
	@cat consultaB.sql | $(PSQL) | tee consultaB.log
consultaC:
	@echo consultaC
	@cat consultaC.sql | $(PSQL) | tee consultaC.log
triggerA:
	@echo triggerA:
	@cat triggerA.sql | $(PSQL)
triggerAtest:
	@echo triggerAtest:
	@cat triggerAtest.sql | $(PSQL)
triggerB:
	@echo triggerB:
	@cat triggerB.sql | $(PSQL)
triggerBtest:
	@echo triggerBtest:
	@cat triggerBtest.sql | $(PSQL)
procaA:
	@echo procaA:
	@cat procaA.sql | $(PSQL)
procaAtest:
	@echo procaAtest:
	@cat procaAtest.sql | $(PSQL)
funcB:
	@echo funcB:
	@cat funcB.sql | $(PSQL)
funcBtest:
	@echo funcBtest:
	@cat funcBtest.sql | $(PSQL)
funcC:
	@echo funcC:
	@cat funcC.sql | $(PSQL)
funcCtest:
	@echo funcCtest:
	@cat funcCtest.sql | $(PSQL)
procaD:
	@echo procaD:
	@cat procaD.sql | $(PSQL)
procaDtest:
	@echo procaDtest:
	@cat procaDtest.sql | $(PSQL)


text:
Eliminar Pregunta

En este modulo se elimina una pregunta.

                <form action="admin/pregunta/eliminar" method="post">

                        Factor
                        <input type="text" class="form-control" id="vcfactnombre" name="vcfactnombre" value="<?= $aReg['vcfactnombre']; ?>" readonly />

                        Subfactor
                        <input type="text" class="form-control" id="vcsubfactnombre" name="vcsubfactnombre" value="<?= $aReg['vcsubfactnombre']; ?>" readonly />

                        Nombre
                        <input type="text" class="form-control" id="vcpregnombre" name="vcpregnombre" value="<?= $aReg['vcpregnombre']; ?>" readonly />

                    <input type="hidden" name="idpregunta" id="idpregunta" value="<?= $aReg['idpregunta']; ?>" />
                    <input type="hidden" name="idencuesta" id="idencuesta" value="<?= $idencuesta; ?>" />

                                        <a class="btn btn-default" href="admin/pregunta/index/<?= $idencuesta; ?>">Cancelar
                                        <input class="btn btn-default" type="submit" value="Eliminar">

                </form>


text:
Indicador: {{configureIndicator.indicator.title}}

        {{configureIndicator.error}}
        <md-label>
            Unidad: {{configureIndicator.indicator.data.title}}
        </md-label>
        <md-label>
            Operacion: {{configureIndicator.indicator.datasource.columnOperation | columnOperation}}
        </md-label>
        <md-input-container data-ng-show="configureIndicator.indicator.datasource.columnOperation === 5 && configureIndicator.showQuery">
            Consulta personalizada
            <input type="text" data-ng-model="configureIndicator.indicator.datasource.rowOperation" required>
            Inmediatamente luego de "select" debe ir "${prefijofiltrofecha}"
            El campo con el valor resultado debe ser nombrado como "as result"
            En where debe dejar como ultima condicion and "${filtrofecha}"
        </md-input-container>
        <md-label data-ng-show="configureIndicator.indicator.datasource.dateColumn">
            Columna Utilizada para fecha: {{configureIndicator.indicator.datasource.dateColumn}}
        </md-label>
        <md-label data-ng-show="configureIndicator.indicator.datasource.valueColumn">
            Columna Utilizada como valor para calcular el consolidado: {{configureIndicator.indicator.datasource.valueColumn}}
        </md-label>

Configuracion de Importacion:

Para empezar, elija una fuente de datos (con solo hacer click) y tabla a la izquierda:

Vista previa de datos:

Base: {{configureIndicator.datasource.title}}

 Tabla: {{configureIndicator.table}}

        <md-toolbar class="md-table-toolbar md-default"  aria-hidden="false">

            <ng-md-icon icon="search"></ng-md-icon>
            <form flex=""  class="flex">
            <input type="text" data-ng-model="configureIndicator.query.filter" placeholder="Buscar">
            </form>

        </md-toolbar>
        <md-table-container>

                {{column.title}}

                {{row[column.title] || row[$index]}}

        </md-table-container>
        <md-table-pagination md-limit="configureIndicator.query.limit" md-limit-options="[5, 10, 20]" md-page="configureIndicator.query.page" md-total="{{ (configureIndicator.data | filter: configureIndicator.query.filter).length }}"  md-page-select md-label="{page: 'Página:', rowsPerPage: 'Filas por página:', of: 'de'}"></md-table-pagination>

Elija la columna que utilizaremos para discriminar los meses

        <md-table-container>

                Nombre
                Tipo

                {{column.title}}
                {{column.type}}

        </md-table-container>

Elija la columna que utilizaremos para calcular los valores del indicador

        <md-table-container>

                Nombre
                Tipo

                {{column.title}}
                {{column.type}}

        </md-table-container>

Vista Previa

Periodo calculado: {{configureIndicator.importPreview.period}}

Consolidado: {{configureIndicator.importPreview.value}}

    {{configureIndicator.error}}

 0">
        <md-button class="md-warn" data-ng-click="configureIndicator.cancel()">Cancelar</md-button>
        <md-button class="md-primary" data-ng-show="configureIndicator.step < 4" data-ng-click="configureIndicator.goToNext()">Siguiente</md-button>
        <md-button class="md-primary" data-ng-show="configureIndicator.step === 4" data-ng-click="configureIndicator.save()">Guardar Configuración</md-button>


text:
using System;

namespace CSVDataUtility
{
    public interface ISingleDataType
    {
        Type SystemType { get; }
    }
}


text:
<?php
App::uses('Address', 'Model');

/**
 * Address Test Case
 *
 */
class AddressTest extends CakeTestCase {

/**
 * Fixtures
 *
 * @var array
 */
	public $fixtures = array(
		'app.address',
		'app.user_is'
	);

/**
 * setUp method
 *
 * @return void
 */
	public function setUp() {
		parent::setUp();
		$this->Address = ClassRegistry::init('Address');
	}

/**
 * tearDown method
 *
 * @return void
 */
	public function tearDown() {
		unset($this->Address);

		parent::tearDown();
	}

}


text:
package edu.ucsf.lava.crms.webflow.builder;

import org.springframework.binding.mapping.AttributeMapper;
import org.springframework.binding.mapping.DefaultAttributeMapper;
import org.springframework.binding.mapping.Mapping;
import org.springframework.webflow.action.SetAction;
import org.springframework.webflow.engine.Transition;
import org.springframework.webflow.engine.builder.FlowBuilderException;
import org.springframework.webflow.execution.Action;
import org.springframework.webflow.execution.ScopeType;

import edu.ucsf.lava.core.webflow.LavaFlowRegistrar;
import edu.ucsf.lava.core.webflow.builder.BaseFlowBuilder;

/**
 * Java-based flow builder that builds the delete instrument flow.
 * <p>
 * This encapsulates the page flow of deleting an entity, and is typically
 * typically involved in a larger flow conversation which includes a parent
 * list flow.
 */
public class InstrumentDeleteFlowBuilder extends BaseFlowBuilder {

	public InstrumentDeleteFlowBuilder(LavaFlowRegistrar registry, String actionId) {
    	super(registry, actionId);
    	setFlowEvent("delete");
    }

    public void buildInputMapper() throws FlowBuilderException {
	   	super.buildInputMapper();
	   	AttributeMapper inputMapper = getFlow().getInputMapper();

	   	Mapping idMapping = mapping().source("id").target("flowScope.id").value();
	   	getFlow().setInputMapper(((DefaultAttributeMapper)inputMapper).addMapping(idMapping));
    }

    public void buildEventStates() throws FlowBuilderException {
    	addViewState(getFlowEvent(),
    			null, formAction.getCustomViewSelector(),
    			// setupForm called in flowSetupState so no need to call here
    			new Action[]{invoke("prepareToRender",formAction)},
    			new Transition[] {
                    transition(on("instrument__confirmDelete"), to("finish"),
                    	ifReturnedSuccess(invoke("handleFlowEvent", formAction))),
                    transition(on("instrument__cancelDelete"), to("finishCancel"),
                    	ifReturnedSuccess(invoke("handleFlowEvent", formAction))),
       				transition(on("instrument__switch"), to("finishSwitch"),
       					ifReturnedSuccess(new Action[]{
           			    	new SetAction(settableExpression("id"), ScopeType.FLOW,	expression("requestParameters.id")),
       	    				new SetAction(settableExpression("switchEvent"), ScopeType.FLOW, expression("${requestParameters.switchEvent}")),
   					})),
                    // support a list secondary component for nav events only, since just a reference list
                    buildListNavigationTransitions(getFlowEvent())},
    			null, null, null);

    	addEndState("finishSwitch");
    }

	public void buildOutputMapper() throws FlowBuilderException {
		// for switching from this instrument enter subflow to another instrument subflow. this flow must pass
	    // the mapping attributes back to the parent flow to tell it which instrument ("id") and subflow ("switchEvent")
		// to transition to. these are put into flow scope when the "instrument__switch" event is handled.
		Mapping idMapping = mapping().source("flowScope.id").target("id").value();
		Mapping switchEventMapping = mapping().source("flowScope.switchEvent").target("switchEvent").value();
		getFlow().setOutputMapper(new DefaultAttributeMapper().addMapping(idMapping).addMapping(switchEventMapping));
	}
}


text:
<!DOCTYPE html>
<body>
<script src="../../resources/js-test.js"></script>
<script>
jsTestIsAsync = true;
var form1;
var submit1;

function start() {
    form1 = document.createElement('form');
    submit1 = document.createElement('input');
    submit2 = document.createElement('input');
    submit1.type = 'submit';
    submit2.type = 'image';
    form1.addEventListener('submit', handleSubmit, false);
    form1.action = 'javascript:removeImage()';
    form1.appendChild(submit1);
    form1.appendChild(submit2);
    document.body.appendChild(form1);
    submit1.click();
    testPassed('if not crashed.');
    finishJSTest();
}

function handleSubmit() {
    form1.removeChild(submit1);
}

function removeImage() {
    form1.removeChild(submit2);
    submit2 = null;
    gc();
}

window.onload = start;
</script>
</body>


text:
package com.codexfons.compositesplit;

import java.util.HashMap;
import java.util.Map;

public class Utils {

	public static int getCharIndex(char character) {
		int value = character - 97;
		if (value < 0 || value > 25) {
			value = 25 + Settings.SPECIAL_CHARS.indexOf(character);
		}
		return value;
	}

	private static Map<String, Long> stopwatchTimes = new HashMap<String, Long>();

	public static void startStopwatch(String purpose) {
		if (!Settings.PROFILE) return;
		stopwatchTimes.put(purpose, System.currentTimeMillis());
	}

	public static void stopStopwatch(String purpose) {
		if (!Settings.PROFILE) return;
		System.err.printf("### %s took %dms\n", purpose, System.currentTimeMillis() - stopwatchTimes.get(purpose));
	}

	public static String normalizeInput(String input) {
		input = input.toLowerCase();
		// The given wordlist doesn't contain umlauts. Purge them from input.
		if (Settings.PURGE_UMLAUT) {
			input = input.replace('ä', 'a');
			input = input.replace('ö', 'o');
			input = input.replace('ü', 'u');
			input = input.replace('é', 'e');
			input = input.replace('è', 'e');
		}
		return input;
	}

}


text:
import org.junit.*;
import static org.junit.Assert.*;
import java.util.ArrayList;
import ca.ualberta.cs.oneclick_cookbook.User;
import ca.ualberta.cs.oneclick_cookbook.Pantry;
import ca.ualberta.cs.oneclick_cookbook.Recipe;

/* *********************************
 * Class that tests the User class.
 *
 * Author: Kenneth Armstrong
 *
 */

public class UserTest {
	private User u;

	@Before
	public void setup() {
		u = new User("John Doe", "password", "jd42", "jd42@gmail.com");
	}

	@After
	public void destroy() {
		u = null;
	}

	// Test the basics of the User class
	@Test
	public void testBasics() {
		// Test the constructor and getters/setters
		assertEquals("User:testBasics:Test 1", u.getEmailAddress(), "jd42@gmail.com");
		assertEquals("User:testBasics:Test 2", u.getUserName(), "John Doe");
		assertEquals("User:testBasics:Test 3", u.getScreenName(), "jd42");
	}

	@Test
	public void testAddRemoveRecipe() {
		// Make a recipe
		Recipe r = new Recipe("Sweetroll", new Pantry(), "Cook it.");

		// Add the recipe to the user and make sure it's there
		u.addRecipe(r.getID());
		assertEquals("User:testAddRemove:Test 1", r.getID(), u.getUserRecipes().get(0));

		// Delete the recipe and make sure it's gone.
		u.deleteRecipe(0);
		assertTrue("User:testAddRemove:Test 1", u.getUserRecipes().isEmpty());
	}

	@Test
	public void testRecipesToString() {
		// Create an array list of strings
		ArrayList<String> ids = new ArrayList<String>();
		Recipe recipe;

		// Go through and add the strings to each list
		for (int i = 0; i<20; i++) {
			recipe = new Recipe();
			ids.add(recipe.getID());
			u.addRecipe(recipe.getID());
		}

		// Make sure the lists are the same
		assertEquals("User:testRecipesString:Test 1",
					ids, u.getUserRecipes());

	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Wyam.Common;

namespace Wyam.Core.Modules
{
    public abstract class ContentModule : IModule
    {
        private readonly Func<IDocument, object> _content;
        private readonly IModule[] _modules;

        protected ContentModule(object content)
        {
            _content = x => content;
        }

        protected ContentModule(Func<IDocument, object> content)
        {
            _content = content ?? (x => null);
        }

        // If only one input document is available, it will be used as the initial document for the specified modules
        // If more than one document is available, an empty initial document will be used
        // To force usage of each input document in a set (I.e., A, B, and C input documents specify a unique "template" metadata value and you want to append
        // some result of operating on that template value to each), make the content module a child of the ForEach module
        // Each input will be applied against each result from the specified modules (I.e., if 2 inputs and the module chain results in 2 outputs, there will be 4 total outputs)
        protected ContentModule(params IModule[] modules)
        {
            _modules = modules;
        }

        public IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context)
        {
            if (_modules != null)
            {
                return context.Execute(_modules, inputs.Count == 1 ? inputs : null).SelectMany(x => inputs.SelectMany(y => Execute(x.Content, y, context)));
            }
            return inputs.SelectMany(x => Execute(_content(x), x, context));
        }

        // Note that content can be passed in as null, implementers should guard against that
        protected abstract IEnumerable<IDocument> Execute(object content, IDocument input, IExecutionContext context);
    }
}


text:
SET NAMES 'utf8';

ALTER TABLE `PREFIX_image` MODIFY COLUMN `position` SMALLINT(2) UNSIGNED NOT NULL DEFAULT 0;

INSERT IGNORE INTO `PREFIX_configuration` (`name`, `value`, `date_add`, `date_upd`) VALUES
('PS_OS_CHEQUE', '1', NOW(), NOW()),
('PS_OS_PAYMENT', '2', NOW(), NOW()),
('PS_OS_PREPARATION', '3', NOW(), NOW()),
('PS_OS_SHIPPING', '4', NOW(), NOW()),
('PS_OS_DELIVERED', '5', NOW(), NOW()),
('PS_OS_CANCELED', '6', NOW(), NOW()),
('PS_OS_REFUND', '7', NOW(), NOW()),
('PS_OS_ERROR', '8', NOW(), NOW()),
('PS_OS_OUTOFSTOCK', '9', NOW(), NOW()),
('PS_OS_BANKWIRE', '10', NOW(), NOW()),
('PS_OS_PAYPAL', '11', NOW(), NOW()),
('PS_OS_WS_PAYMENT', '12', NOW(), NOW()),
('PS_IMAGE_QUALITY', 'jpg', NOW(), NOW()),
('PS_PNG_QUALITY', '7', NOW(), NOW()),
('PS_JPEG_QUALITY', '90', NOW(), NOW()),
('PS_COOKIE_LIFETIME_FO', '480', NOW(), NOW()),
('PS_COOKIE_LIFETIME_BO', '480', NOW(), NOW());

ALTER TABLE `PREFIX_lang` ADD `is_rtl` TINYINT(1) NOT NULL DEFAULT '0';

UPDATE `PREFIX_country_lang`
SET `name` = 'United States'
WHERE `name` = 'USA'
AND `id_lang` = (
	SELECT `id_lang`
	FROM `PREFIX_lang`
	WHERE `iso_code` = 'en'
	LIMIT 1
);

UPDATE `PREFIX_hook`
SET `live_edit` = 1
WHERE `name` = 'leftColumn'
OR `name` = 'home'
OR `name` = 'rightColumn'
OR `name` = 'productfooter'
OR `name` = 'payment';

ALTER TABLE `PREFIX_stock_mvt_reason` MODIFY `sign` TINYINT(1) NOT NULL DEFAULT '1' AFTER `id_stock_mvt_reason`;

UPDATE `PREFIX_tab_lang`
SET `name` = 'Geolocation'
WHERE `name` = 'Geolocalization';

UPDATE `PREFIX_tab_lang`
SET `name` = 'Counties'
WHERE `name` = 'County';

ALTER TABLE `PREFIX_tax_rule` MODIFY `id_county` INT NOT NULL AFTER `id_country`;

UPDATE `PREFIX_address_format` set `format`='firstname lastname
company
address1 address2
city, State:name postcode
Country:name
phone'
WHERE `id_country` = (SELECT `id_country` FROM `PREFIX_country` WHERE `iso_code`='US');

ALTER TABLE `PREFIX_attachment` CHANGE `mime` `mime` VARCHAR(128) NOT NULL;

CREATE TABLE IF NOT EXISTS `PREFIX_compare_product` (
  `id_compare_product` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `id_product` int(10) unsigned NOT NULL,
  `id_guest` int(10) unsigned NOT NULL,
  `id_customer` int(10) unsigned NOT NULL,
  `date_add` datetime NOT NULL,
  `date_upd` datetime NOT NULL,
  PRIMARY KEY  (`id_compare_product`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8;

DELETE FROM `PREFIX_configuration` WHERE name = 'PS_LAYERED_NAVIGATION_CHECKBOXES' LIMIT 1;

/* PHP:alter_productcomments_guest_index(); */;


text:
<section admin-header class="content-header"
         title="Parsers"
         sub-title="Overview of your parsers">
</section>
<section ui-view class="content"></section>


text:
<?php

namespace Steppie\Bundle\AppBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * DefaultContentRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class DefaultContentRepository extends EntityRepository
{
}


text:
package org.pmiops.workbench.utils;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletResponse;
import org.pmiops.workbench.exceptions.ExceptionUtils;
import org.springframework.retry.RetryContext;
import org.springframework.retry.policy.SimpleRetryPolicy;

public abstract class ResponseCodeRetryPolicy extends SimpleRetryPolicy {

  private static final Logger logger = Logger.getLogger(ResponseCodeRetryPolicy.class.getName());

  private final String serviceName;

  public ResponseCodeRetryPolicy(String serviceName) {
    this.serviceName = serviceName;
  }

  @Override
  public boolean canRetry(RetryContext context) {
    // canRetry is (counter-intuitively) invoked before the first attempt;
    // in that scenario, getLastThrowable() returns null and we should proceed.
    if (context.getLastThrowable() == null) {
      return true;
    }
    Throwable lastException = context.getLastThrowable();
    int responseCode = getResponseCode(lastException);
    if (canRetry(responseCode)) {
      if (context.getRetryCount() < getMaxAttempts()) {
        logRetry(context.getRetryCount(), lastException);
        return true;
      } else {
        logGivingUp(context.getRetryCount(), lastException);
        return false;
      }
    } else {
      logNoRetry(lastException, responseCode);
      return false;
    }
  }

  protected boolean canRetry(int code) {
    // Retry om 500, 502, 503, 504 error.
    return ExceptionUtils.isServiceUnavailable(code)
        || ExceptionUtils.isInternalServerError(code)
        || ExceptionUtils.isGatewayTimeoutServerError(code);
  }

  protected void logRetry(int retryCount, Throwable t) {
    logger.log(
        Level.WARNING,
        String.format("%s unavailable, retrying after %d attempts", serviceName, retryCount),
        t);
  }

  protected void logGivingUp(int retryCount, Throwable t) {
    logger.log(
        Level.WARNING,
        String.format("%s unavailable, giving up after %d attempts", serviceName, retryCount),
        t);
  }

  protected Level getLogLevel(int responseCode) {
    switch (responseCode) {
      case HttpServletResponse.SC_NOT_FOUND:
        return Level.INFO;
      case HttpServletResponse.SC_UNAUTHORIZED:
      case HttpServletResponse.SC_FORBIDDEN:
      case HttpServletResponse.SC_CONFLICT:
        return Level.WARNING;
      default:
        return Level.SEVERE;
    }
  }

  protected void logNoRetry(Throwable t, int responseCode) {
    logger.log(getLogLevel(responseCode), String.format("Exception calling %s", serviceName), t);
  }

  protected abstract int getResponseCode(Throwable lastException);
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.recoveryservicesbackup.generated;

import com.azure.core.util.Context;
import com.azure.resourcemanager.recoveryservicesbackup.models.EncryptionDetails;
import com.azure.resourcemanager.recoveryservicesbackup.models.IaasVMRestoreRequest;
import com.azure.resourcemanager.recoveryservicesbackup.models.IdentityBasedRestoreDetails;
import com.azure.resourcemanager.recoveryservicesbackup.models.IdentityInfo;
import com.azure.resourcemanager.recoveryservicesbackup.models.RecoveryType;
import com.azure.resourcemanager.recoveryservicesbackup.models.ValidateIaasVMRestoreOperationRequest;

/** Samples for OperationOperation Validate. */
public final class OperationOperationValidateSamples {
    /*
     * x-ms-original-file: specification/recoveryservicesbackup/resource-manager/Microsoft.RecoveryServices/preview/2022-09-01-preview/examples/AzureIaasVm/ValidateOperation_RestoreDisk.json
     */
    /**
     * Sample code: Validate Operation.
     *
     * @param manager Entry point to RecoveryServicesBackupManager.
     */
    public static void validateOperation(
        com.azure.resourcemanager.recoveryservicesbackup.RecoveryServicesBackupManager manager) {
        manager
            .operationOperations()
            .validateWithResponse(
                "testVault",
                "testRG",
                new ValidateIaasVMRestoreOperationRequest()
                    .withRestoreRequest(
                        new IaasVMRestoreRequest()
                            .withRecoveryPointId("348916168024334")
                            .withRecoveryType(RecoveryType.RESTORE_DISKS)
                            .withSourceResourceId(
                                "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/netsdktestrg/providers/Microsoft.Compute/virtualMachines/netvmtestv2vm1")
                            .withStorageAccountId(
                                "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testingRg/providers/Microsoft.Storage/storageAccounts/testAccount")
                            .withRegion("southeastasia")
                            .withCreateNewCloudService(true)
                            .withOriginalStorageAccountOption(false)
                            .withEncryptionDetails(new EncryptionDetails().withEncryptionEnabled(false))
                            .withIdentityInfo(
                                new IdentityInfo()
                                    .withIsSystemAssignedIdentity(false)
                                    .withManagedIdentityResourceId(
                                        "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/asmaskarRG1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/asmaskartestmsi"))),
                Context.NONE);
    }

    /*
     * x-ms-original-file: specification/recoveryservicesbackup/resource-manager/Microsoft.RecoveryServices/preview/2022-09-01-preview/examples/AzureIaasVm/ValidateOperation_RestoreDisk_IdentityBasedRestoreDetails.json
     */
    /**
     * Sample code: Validate Operation with identityBasedRestoreDetails.
     *
     * @param manager Entry point to RecoveryServicesBackupManager.
     */
    public static void validateOperationWithIdentityBasedRestoreDetails(
        com.azure.resourcemanager.recoveryservicesbackup.RecoveryServicesBackupManager manager) {
        manager
            .operationOperations()
            .validateWithResponse(
                "testVault",
                "testRG",
                new ValidateIaasVMRestoreOperationRequest()
                    .withRestoreRequest(
                        new IaasVMRestoreRequest()
                            .withRecoveryPointId("348916168024334")
                            .withRecoveryType(RecoveryType.RESTORE_DISKS)
                            .withSourceResourceId(
                                "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/netsdktestrg/providers/Microsoft.Compute/virtualMachines/netvmtestv2vm1")
                            .withRegion("southeastasia")
                            .withCreateNewCloudService(true)
                            .withOriginalStorageAccountOption(false)
                            .withEncryptionDetails(new EncryptionDetails().withEncryptionEnabled(false))
                            .withIdentityInfo(
                                new IdentityInfo()
                                    .withIsSystemAssignedIdentity(false)
                                    .withManagedIdentityResourceId(
                                        "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/asmaskarRG1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/asmaskartestmsi"))
                            .withIdentityBasedRestoreDetails(
                                new IdentityBasedRestoreDetails()
                                    .withTargetStorageAccountId(
                                        "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testingRg/providers/Microsoft.Storage/storageAccounts/testAccount"))),
                Context.NONE);
    }
}


text:
package io.hops.metadata.yarn.entity;

/**
 * Pojo class for the RMNode.containersToClean set. Hostname, commandport point
 * to the RMNode primary key.
 */
public class ContainerId {

  private final String rmnodeid;
  private final String containerId;

  public ContainerId(String rmnodeid, String containerId) {
    this.rmnodeid = rmnodeid;
    this.containerId = containerId;
  }

  public String getRmnodeid() {
    return rmnodeid;
  }

  public String getContainerId() {
    return containerId;
  }

  @Override
  public String toString() {
    return "HopContainerId{" + "rmnodeid=" + rmnodeid + ", containerId=" +
        containerId + '}';
  }

}


text:
describe("Router Menu service: Menu Items", function () {
    var stateRegistryProvider, routerMenu;

    var $injector;

    beforeEach(module('ui.router.menu', function (_stateRegistryProvider_) {
        stateRegistryProvider = _stateRegistryProvider_;
    }));

    beforeEach(inject(function (_$injector_) {
        $injector = _$injector_;
    }));

    describe("for not nested children states", function () {
        beforeEach(function () {
            var states = {
                name: "main",
                abstract: true,
                menu: {
                    mainState: true
                },
                children: [
                    {
                        name: "menu-child"
                    },
                    {
                        name: "non-menu-child",
                        menu: {
                            isItem: false
                        }
                    },
                    {
                        name: "abstract-child",
                        abstract: true
                    },
                    {
                        name: "abstract-menu-child",
                        abstract: true,
                        menu: {
                            isItem: true
                        }
                    }
                ]
            };
            stateRegistryProvider.state(states);
            routerMenu = $injector.get("routerMenu");
        });

        it("should contain item for child state", function () {
            expect(namesOf(routerMenu.items)).toContain("main.menu-child");
        });

        it("should not contain item for abstract state", function () {
            expect(namesOf(routerMenu.items)).not.toContain("main.abstract-child");
        });

        it("should contain item for abstract state when forcing to be menu item", function () {
            expect(namesOf(routerMenu.items)).toContain("main.abstract-menu-child");
        });

        it("should not contain item for state when forcing to not be menu item", function () {
            expect(namesOf(routerMenu.items)).not.toContain("main.non-menu-child");
        });
    });

    describe("children of menu items", function () {
        beforeEach(function () {
            var states = {
                name: "main",
                abstract: true,
                menu: {
                    mainState: true
                },
                children: [
                    {
                        name: "child",
                        children: [
                            {name: "sub-menu"},
                            {name: "abstract-sub", abstract: true},
                            {name: "abstract-sub-menu", abstract: true, menu: {isItem: true}},
                            {name: "sub-non-menu", menu: {isItem: false}}
                        ]
                    }
                ]
            };
            stateRegistryProvider.state(states);
            routerMenu = $injector.get("routerMenu");
        });

        it("should contain item for sub menu", function () {
            expect(namesOf(routerMenu.items[0].children)).toContain("main.child.sub-menu");
        });

        it("should not contain item for abstract subchild", function () {
            expect(namesOf(routerMenu.items[0].children)).not.toContain("main.child.abstract-sub");
        });

        it("should contain item for abstract sub menu when forcing to be menu item", function () {
            expect(namesOf(routerMenu.items[0].children)).toContain("main.child.abstract-sub-menu");
        });

        it("should not contain item for sub menu when forcing to NOT be menu item", function () {
            expect(namesOf(routerMenu.items[0].children)).not.toContain("main.child.sub-non-menu");
        });
    });

    function namesOf(items) {
        return items.map(function (item) {
            return item.name;
        });
    }
});


text:
build: node_modules
	@./node_modules/.bin/duo index.js

# Test using mocha-phantomjs(1)
test: build-test
	@./node_modules/.bin/mocha-phantomjs ./test/index.html

# Build for tests
build-test:
	@./node_modules/.bin/duo test/specs.js \
		--development \
		--stdout > ./test/build.js

# Check for problems
lint:
	@./node_modules/.bin/jshint ./lib/* \
		--reporter ./node_modules/jshint-stylish/stylish.js

# Install dependencies from npm
node_modules: package.json
	@npm install

# Clean non-checked-in files
clean:
	@rm -rf \
		node_modules \
		components \
		build \
		test/build.js

.PHONY: build build-test test lint clean


text:
module DatersHelper
end


text:
Set-Location "C:\OPEN_PROJECTS\PowerRestCLI\"

$FoundError = $false

$Directories = ("private", "public")
foreach ($Directory in $Directories)
{
    # Import the functions.
    $files = Get-ChildItem .\PowerRestCLI\$Directory
    foreach ($file in $files)
    {
        # Source the file
        $FileName = $file.Name
        Write-Output "Importing file $FileName"
        . .\PowerRestCLI\$Directory\$FileName
    }
    # Execute Pester for the Directory.
    $PesterResults = Invoke-pester .\tests\$Directory\*.ps1 -CodeCoverage .\PowerRestCLI\$Directory\*.ps1 -PassThru

    $MissedCommands = $PesterResults.CodeCoverage.NumberOfCommandsMissed
    $FailedCount = $PesterResults.FailedCount
    Write-Output "Missed commands: $MissedCommands - Failed Tests: $Failedcount"
    if (($MissedCommands -ne "0") -or ($FailedCount -ne "0"))
    {
        $FoundError = $true
        Write-Error "Not at 100% coverage for $Directory Directory, or a test failed. Review results!"
    }
    else
    {
        # No Missed commands.
        Write-Output "No missed commands for $Directory Directory. 100% coverage!"
    }
}
if ($FoundError -eq $true)
{
    # An error was found in the Unit tests.
    Write-Error "An error has been found in the unit Tests. Please review them before commiting the code."
}
else
{
    # No failed Tests found, Code Coverage is 100%
    Write-Output "Tests cover 100% and all pass! Hooray!"
}


text:
package eu.ydp.empiria.player.client.controller.feedback;

import com.google.inject.Inject;
import eu.ydp.empiria.player.client.controller.feedback.processor.SoundActionProcessor;
import eu.ydp.empiria.player.client.controller.feedback.structure.action.FeedbackAction;
import eu.ydp.empiria.player.client.util.events.internal.bus.EventsBus;

public class SoundActionProcessorMock extends SoundActionProcessor {

    @Inject
    public SoundActionProcessorMock(EventsBus eventsBus) {
        super(eventsBus);
    }

    @Override
    public void processSingleAction(FeedbackAction action, FeedbackMark mark) {
        super.processSingleAction(action, mark);
    }

}


text:
@implementation JOECurrencyUtil

#pragma mark - Decimal From Currency String

+ (NSDecimalNumber *)decimalNumberFromCurrencyString:(NSString *)string
{
    return [self decimalNumberFromCurrencyString:string scale:2];
}

+ (NSDecimalNumber *)decimalNumberFromCurrencyString:(NSString *)string scale:(short)scale
{
    NSString *cleanString = [self cleanCurrencyString:string];
    unsigned long long mantissa = strtoull([cleanString UTF8String], NULL, 10);
    NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithMantissa:mantissa exponent:(-1 * scale) isNegative:NO];

    return decimalNumber;
}

#pragma mark - Currency String From Decimal Number

+ (NSString *)stringFromDecimalNumber:(NSDecimalNumber *)number
{
    return [self stringFromDecimalNumber:number scale:2];
}

+ (NSString *)stringFromDecimalNumber:(NSDecimalNumber *)number scale:(short)scale
{
    return [[self currencyFormatter:scale] stringFromNumber:number];
}

#pragma mark - Unformatting Text

+ (NSString *)cleanCurrencyString:(NSString *)string
{
    NSCharacterSet *invertedDecimalSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    NSArray *components = [string componentsSeparatedByCharactersInSet:invertedDecimalSet];
    NSString *_cleanString = [components componentsJoinedByString:@""];

    return _cleanString;
}

+ (NSCharacterSet *)removableCharacterSet
{
    NSMutableCharacterSet *charactersToKeep = [NSMutableCharacterSet decimalDigitCharacterSet];
    [charactersToKeep addCharactersInString:[self currencyFormatter:2].decimalSeparator];

    NSCharacterSet *charactersToRemove = [charactersToKeep invertedSet];

    return charactersToRemove;
}

#pragma mark - Private Methods

+ (NSNumberFormatter *)currencyFormatter:(short)scale
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    [formatter setLocale:[NSLocale currentLocale]];
    [formatter setGeneratesDecimalNumbers: YES];

    if (scale) {
        [formatter setMinimumFractionDigits:scale];
    }

    return formatter;
}

@end


text:
Yet Another Migrations
====

Yet Another Migrations using Doctrine DBAL

= Example Configuration

```
migrations_namespace: ProjMigrations
table_name: yam_migration_versions
migrations_directory: ./build
schema_directory: ./schema

connection:
  dbname:
  user:
  password:
  host:
  driver:
  charset:
  driverOptions:
```


text:
<?php echo Component::get("Framework.Template", array(
	"content" => $content,
	"nowrap" => true
)) ?>


text:
BIN=secrets
OS=$(shell uname -s)
ARCH=$(shell uname -m)
GOVERSION=$(shell go version)
GOBIN=$(shell go env GOBIN)
VERSION=$(shell git describe --tags --candidates=1)
FLAGS=-X main.Version=$(VERSION) -s -w
SRC=$(shell find . -name '*.go')

deps:
	glide install -v

test:
	go test -v $(shell go list ./... | grep -v /vendor/)

build:
	go build -o $(BIN) -ldflags="$(FLAGS)" .

install:
	go install -ldflags="$(FLAGS)" .

$(BIN)-linux-amd64: $(SRC)
	GOOS=linux GOARCH=amd64 go build -o $@ -ldflags="$(FLAGS)" .

$(BIN)-darwin-amd64: $(SRC)
	GOOS=darwin GOARCH=amd64 go build -o $@ -ldflags="$(FLAGS)" .

$(BIN)-windows-386: $(SRC)
	GOOS=windows GOARCH=386 go build -o $@ -ldflags="$(FLAGS)" .

release: $(BIN)-linux-amd64 $(BIN)-darwin-amd64 $(BIN)-windows-386\

clean:
	rm -f $(BIN)-*-*


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace suppress_console_messages
{
    public class PrintTextToConsoleService : IHostedService, IDisposable
    {
        private readonly ILogger _logger;
        private Timer _timer;

        public PrintTextToConsoleService(ILogger<PrintTextToConsoleService> logger)
        {
            _logger = logger;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Starting");

            _timer = new Timer(DoWork, null, TimeSpan.FromSeconds(5),
              TimeSpan.FromSeconds(5));

            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            _logger.LogInformation($"Background work with text: {DateTimeOffset.UtcNow}");
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Stopping.");

            _timer?.Change(Timeout.Infinite, 0);

            return Task.CompletedTask;
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }
    }

}


text:
pub const crypto_stream_salsa208_KEYBYTES: usize = 32;
pub const crypto_stream_salsa208_NONCEBYTES: usize = 8;

extern {
    pub fn crypto_stream_salsa208(
        c: *mut u8,
        clen: c_ulonglong,
        n: *const [u8; crypto_stream_salsa208_NONCEBYTES],
        k: *const [u8; crypto_stream_salsa208_KEYBYTES]) -> c_int;
    pub fn crypto_stream_salsa208_xor(
        c: *mut u8,
        m: *const u8,
        mlen: c_ulonglong,
        n: *const [u8; crypto_stream_salsa208_NONCEBYTES],
        k: *const [u8; crypto_stream_salsa208_KEYBYTES]) -> c_int;
    pub fn crypto_stream_salsa208_keybytes() -> size_t;
    pub fn crypto_stream_salsa208_noncebytes() -> size_t;
}

#[test]
fn test_crypto_stream_salsa208_keybytes() {
    assert!(unsafe { crypto_stream_salsa208_keybytes() as usize } ==
            crypto_stream_salsa208_KEYBYTES)
}
#[test]
fn test_crypto_stream_salsa208_noncebytes() {
    assert!(unsafe { crypto_stream_salsa208_noncebytes() as usize } ==
            crypto_stream_salsa208_NONCEBYTES)
}


text:
<?php

namespace Kassner\LogParser\Tests\Format;

use Kassner\LogParser\LogParser;
use Kassner\LogParser\Tests\Provider\HostName as HostNameProvider;

/**
 * @format %V
 * @description The server name according to the UseCanonicalName setting.
 */
class ServerNameTest extends HostNameProvider
{
    protected $parser = null;

    protected function setUp(): void
    {
        $this->parser = new LogParser();
        $this->parser->setFormat('%v');
    }

    protected function tearDown(): void
    {
        $this->parser = null;
    }

    /**
     * @dataProvider successProvider
     */
    public function testSuccess($line)
    {
        $entry = $this->parser->parse($line);
        $this->assertEquals($line, $entry->serverName);
    }

    /**
     * @dataProvider invalidProvider
     */
    public function testInvalid($line)
    {
        $this->markTestIncomplete('This test has not been implemented yet.');
        $this->expectException(\Kassner\LogParser\FormatException::class);
        $this->parser->parse($line);
    }
}


text:
using System;
using System.Security.AccessControl;

namespace Martini
{
    public enum DuplicateSectionHandling
    {
        Disallow,
        Allow,
        Merge
    }

    public enum DuplicatePropertyHandling
    {
        Disallow,
        Allow,
        KeepFirst,
        KeepLast,
        Rename
    }

    public enum UnqotedValueSpaceHandling
    {
        Trim,
        Keep
    }

    public enum InvalidLineHandling
    {
        Disallow,
        Ignore,
        Keep
    }

    [Flags]
    public enum FormattingOptions
    {
        None,
        BlankLineBeforeSection = 1,
        SpaceAfterCommentIndicator = 2,
        SpaceBeforePropertyValueDelimiter = 4,
        SpaceAfterPropertyValueDelimiter = 8,
        QuoteValuesWithSpaces = 16,
    }

    internal enum SentenceType
    {
        Uninitialized,
        Blank,
        Comment,
        Section,
        Property,
        Invalid
    }

    internal enum TokenType
    {
        Uninitialized,
        StartOfLine,
        EndOfLine,
        LeftSectionDelimiter,
        RightSectionDelimiter,
        ProperetyValueDelimiter,
        Text,
        Section,
        Property,
        Value,
        CommentIndicator,
        Comment,
        QuotationMark,
        EscapeSequence,
    }

    public enum SectionDelimiter
    {
        /// <summary>
        /// Brackets []
        /// </summary>
        [SectionDelimiter(Left = '[', Right = ']')]
        SquareBrackets,

        /// <summary>
        /// Parentheses {}
        /// </summary>
        [SectionDelimiter(Left = '{', Right = '}')]
        RoundBrackets,

        /// <summary>
        /// Braces ()
        /// </summary>
        [SectionDelimiter(Left = '(', Right = ')')]
        CurlyBrackets,

        /// <summary>
        /// Chevrons
        /// </summary>
        [SectionDelimiter(Left = '<', Right = '>')]
        AngleBrackets
    }

    public enum PropertyValueDelimiter
    {
        /// <summary>
        /// =
        /// </summary>
        [PropertyValueDelimiter(Delimiter = '=')]
        EqualSign,

        /// <summary>
        /// :
        /// </summary>
        [PropertyValueDelimiter(Delimiter = ';')]
        Colon
    }

    public enum CommentIndicator
    {
        /// <summary>
        /// ;
        /// </summary>
        [CommentIndicator(Delimiter = ';')]
        Semicolon,

        /// <summary>
        /// #
        /// </summary>
        [CommentIndicator(Delimiter = '#')]
        NumberSign
    }
}


text:
using UnityEngine;
using System.Collections;

public class ProjectileDamage : MonoBehaviour {
    public int DamageAmount;

    void OnCollisionEnter(Collision collision)
    {
        //Debug.Log("Collided on " + collision.gameObject.name);
        GameObject collisionGameObject = collision.gameObject;

        if (collisionGameObject.tag.ToLower() == "obstacle")
        {
            collisionGameObject.SendMessage("TakeDamage", DamageAmount);

        }

        Destroy(gameObject);
    }
}


text:
package platform

// Convert the OS/ARCH-specific utsname.Machine to string
// given as an array of unsigned uint8
func charsToString(ca [65]uint8) string {
	s := make([]byte, len(ca))
	var lens int
	for ; lens < len(ca); lens++ {
		if ca[lens] == 0 {
			break
		}
		s[lens] = ca[lens]
	}
	return string(s[0:lens])
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pluteus aquosus Singer

### Remarks
null


text:
package sampler.io

import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.OpenOption
import java.nio.file.Path
import scala.Array.canBuildFrom
import scala.Array.fallbackCanBuildFrom
import scala.io.Source

/** Facilitates the reading and writing of csv files
 *
 *
Reading files

 *  This object provides methods to read in data from csv files and also query the header line,
 *  including the ability to match the header to expected content
 *  {{{
 *  val file = java.nio.file.Paths.get("test.csv")
 *  CSV.header(file)
 *  }}}
 *  Running the above code in the Scala interpreter would yield:
 *  {{{res: Map[String,Int] = Map(Col1 -> 0, Col2 -> 1, Col3 -> 2)}}}
 *
 *  Files can be read in either in their entirety, or part thereof based on requested column headers.
 *  {{{
 *  val file = java.nio.file.Paths.get("test.csv")
 *  val wholeFile = CSV.read(file)
 *  val selectedColumns = CSV.readByHeader(file, "Col1", "Col3")
 *  }}}
 *  Running the above in the Scala interpreter would yield:
 *  {{{
 *  > wholeFile.toIndexedSeq
 *      res: IndexedSeq[IndexedSeq[String]] = Vector(ArraySeq(Col1, Col2, Col3), ArraySeq(1, 2, 3), ArraySeq(4, 5, 6))
 *
 *  > selectedColumns.toIndexedSeq
 *      res: IndexedSeq[IndexedSeq[String]] = Vector(ArraySeq(Col1, Col3), ArraySeq(1, 3), ArraySeq(4, 6))
 *  }}}
 *
 *
Writing files

 *  Data, in the form of a Traversable of Traversables, can be written to disk given a path to a file. The
 *  file writing methods use the Java.nio StandardOpenOptions to define how a file should be written.
 *  {{{
 *  val outFile = java.nio.file.Paths.get("testOut.csv")
 *  val outData = Seq(Seq("Col1", "Col2", "Col3"),Seq(1,2,3),Seq(4,5,6))
 *  CSV.writeLines(outFile, outData, StandardOpenOption.CREATE)
 *  }}}
 *
 *
Transposing

 *  Often data you might want to write to a csv is handled more naturally in the code as columns, i.e. a data structure with one set of
 *  data that would want to be written to a column. The CSV object writes data row-by-row. There are two options for writing the correct
 *  csv in these situations.
 *
 *  1) Transpose in the code and then write to CSV as in the example below. The method has the benefit of requiring no writing of temporary
 *  files and that it is likely to be faster to execute. However, all the data is required to be present up front.
 *  {{{
 *  val names = Seq("Tom", "Dick", "Harry")
 *  val ages = Seq(25, 32, 18)
 *  val colours = Seq("Red", "Blue", "Green")
 *
 *  val columns = Seq(
 *      "Name" +: names,
 *      "Age" +: ages,
 *      "FavouriteColour" +: colours
 *  )
 *  val transposed = columns.transpose
 *
 *  CSV.writeLines(java.nio.file.Paths.get("transposed.csv"), transposed)
 *  }}}
 *
 *  2) Writing a row based temporary file and then using the CSV methods to transpose the file. The advantage of this methdo being that
 *  you don't need all the data up front and can build up the rows in the temporary file as the data becomes available.
 *  {{{
 *  val col1 = Seq(1,2,3)
 *  val col2 = Seq(4,5,6)
 *
 *  val rowsFile = java.nio.file.Files.createTempFile(null, null)
 *
 *  CSV.writeLine(rowsFile, col1, StandardOpenOption.CREATE)
 *  CSV.writeLine(rowsFile, col2, StandardOpenOption.APPEND)
 *
 *  CSV.transpose(rowsFile, java.nio.file.Paths.get("transposed.csv"), StandardOpenOption.CREATE)
 *  }}}
 */
object CSV {

  /** Reads in the first line of a csv file and returns a map of the header to its column index
   *
   * @param filePath The path to the csv file of interest
   * @return Map from a String (the header) to an Integer (the column index of that header)
   */
	def header(filePath: Path): Map[String, Int] = {
		val strings = Source.fromFile(filePath.toFile).getLines.next.split(',').map(_.trim)
		strings.zipWithIndex.map{case (name, idx) => name -> idx}.toMap
	}

	/** Read in the first line of a csv file and checks it matches the headers of interest
	 *
	 * @param filePath The path to the csv file of interest
	 * @param expected The strings expected in the header
	 */
	def assertHeader(filePath: Path, expected: String*) {
		val strings = Source.fromFile(filePath.toFile).getLines.next.split(',').map(_.trim).toSeq
		assert(strings == expected, {
			val newLine = System.getProperty("line.separator")
s"""Headers in ${filePath.toAbsolutePath()} don't match.
	expected: 	${expected.toString}
	found:		${strings.toString}
"""})
	}

	/** Write a single line to a csv file
	 *
	 * @param filePath The path to the csv file of interest
	 * @param line The data to be written to the file
	 * @param openOptions Options specifying how the file is opened
	 */
	def writeLine(filePath: Path, line: Traversable[Any], openOptions: OpenOption*) {
		val writer = getWriter(filePath, openOptions: _*)
		writer.write(toStrings(line).mkString(","))
		writer.newLine()
		writer.close()
	}

	/** Write multiples lines to a csv file
	 *
	 * @param filePath The path to the csv file of interest
	 * @param lines The data to be written to the file
	 * @param openOptions Options specifying how the file is opened
	 */
	def writeLines(filePath: Path, lines: Traversable[Traversable[Any]], openOptions: OpenOption*) {
		val writer = getWriter(filePath, openOptions: _*)
		lines.foreach{line =>
			writer.write(toStrings(line).mkString(","))
			writer.newLine()
		}
		writer.close()
	}

	private def toStrings(line: Traversable[Any]): Traversable[String] = {
		val strings = line.map(_.toString)
		assert(!strings.exists(_.contains(',')), "CSV lines may not contain commas: "+strings.mkString(" | "," | "," | "))
		strings
	}

	/** Reads in a csv file, transposes the data and writes to another csv
	 *
	 * @param inPath The path to the csv file containing the data to be transposed
	 * @param outFile The path to the csv file to write the transposed data to
	 * @param removeHeader Set to true if the data file contains a header line that needs removing before transposition
	 * @param openOptions Options specifying how the file is opened
	 */
	def transpose(inPath: Path, outFile: Path, outputOpenOptions: OpenOption*) {
		val matrix = Source.fromFile(inPath.toFile)
				.getLines
				.map(line => line.split(',').map(_.trim).toList)
				.toList
		writeLines(outFile, matrix.transpose, outputOpenOptions: _*)
	}

	/** Reads in the data in a csv file
	 *
	 *  @param filePath The path to the csv file to be read in
	 *  @return An iterator which contains each line of data as a IndexedSeq of Strings
	 */
	def read(filePath: Path): Iterator[IndexedSeq[String]] = {
		Source.fromFile(filePath.toFile()).getLines.map{line =>
			line.split(',').map(_.trim)
		}
	}

	/** Reads in selected columns from a csv file
	 *
	 *  @param filePath The path to the csv file to be read in
	 *  @param headers The header titles for the required columns
	 *  @return An iterator which contains each line of data as a IndexedSeq of Strings
	 */
	def readByHeader(filePath: Path, headers: String*): Iterator[IndexedSeq[String]] = {
		val tokenisedLines = read(filePath)
		val headerMap = header(filePath)
		val headerIndexes = headers.map(headerMap).toArray

		tokenisedLines.map{lineToks =>
			headerIndexes.map(lineToks)
		}
	}

	private def getWriter(filePath: Path, openOptions: OpenOption*) = {
		Files.newBufferedWriter(
				filePath,
				Charset.defaultCharset(),
				openOptions:_*
		)
	}
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

  <title>List of All Members for QtSoapQName</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />

  	Home

List of All Members for QtSoapQName

This is the complete list of members for QtSoapQName, including inherited members.

QtSoapQName ( const QString &, const QString & )

~QtSoapQName ()

name () const : QString

uri () const : QString

operator= ( const QString & ) : QtSoapQName &

<address>

Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies)
Trademarks

Qt Solutions

</address>


text:
namespace base {
class Thread;
}

namespace cc {
class OnscreenDisplayClient;
class SurfaceManager;
}

namespace ui {

class InProcessContextFactory : public ContextFactory {
 public:
  // surface_manager is owned by the creator of this and must outlive the
  // context factory.
  InProcessContextFactory(bool context_factory_for_test,
                          cc::SurfaceManager* surface_manager);
  ~InProcessContextFactory() override;

  // If true (the default) an OutputSurface is created that does not display
  // anything. Set to false if you want to see results on the screen.
  void set_use_test_surface(bool use_test_surface) {
    use_test_surface_ = use_test_surface;
  }

  // ContextFactory implementation
  void CreateOutputSurface(base::WeakPtr<Compositor> compositor,
                           bool software_fallback) override;

  scoped_refptr<Reflector> CreateReflector(Compositor* mirrored_compositor,
                                           Layer* mirroring_layer) override;
  void RemoveReflector(scoped_refptr<Reflector> reflector) override;

  scoped_refptr<cc::ContextProvider> SharedMainThreadContextProvider() override;
  void RemoveCompositor(Compositor* compositor) override;
  bool DoesCreateTestContexts() override;
  cc::SharedBitmapManager* GetSharedBitmapManager() override;
  gpu::GpuMemoryBufferManager* GetGpuMemoryBufferManager() override;
  base::MessageLoopProxy* GetCompositorMessageLoop() override;
  scoped_ptr<cc::SurfaceIdAllocator> CreateSurfaceIdAllocator() override;
  void ResizeDisplay(ui::Compositor* compositor,
                     const gfx::Size& size) override;

 private:
  scoped_ptr<base::Thread> compositor_thread_;
  scoped_refptr<cc::ContextProvider> shared_main_thread_contexts_;
  cc::TestSharedBitmapManager shared_bitmap_manager_;
  cc::TestGpuMemoryBufferManager gpu_memory_buffer_manager_;
  uint32_t next_surface_id_namespace_;
  bool use_test_surface_;
  bool context_factory_for_test_;
  cc::SurfaceManager* surface_manager_;

  base::hash_map<Compositor*, cc::OnscreenDisplayClient*> per_compositor_data_;

  DISALLOW_COPY_AND_ASSIGN(InProcessContextFactory);
};

}  // namespace ui

#endif  // UI_COMPOSITOR_TEST_IN_PROCESS_CONTEXT_FACTORY_H_


text:
required_env_vars="AWS_STATE_BUCKET_ACCESS_KEY AWS_STATE_BUCKET_ACCESS_SECRET AWS_STATE_BUCKET_REGION AWS_STATE_BUCKET_NAME AWS_STATE_BUCKET_PROJECT_NAME AWS_STATE_BUCKET_ENVIRONMENT_NAME"
env_missing=false

for VAR in $required_env_vars; do
  VAL=`printenv ${VAR} || echo ''`

  if [ -z "$VAL" ]; then
    echo "Environment param required: ${VAR}"
    env_missing=true
  fi
done

if [ $env_missing == true ]; then
  return 1
fi

# EXPORT TF VARS to be used in TF variables
export TF_VAR_aws_state_bucket_name=${AWS_STATE_BUCKET_NAME}
export TF_VAR_aws_state_bucket_access_key=${AWS_STATE_BUCKET_ACCESS_KEY}
export TF_VAR_aws_state_bucket_access_secret=${AWS_STATE_BUCKET_ACCESS_SECRET}
export TF_VAR_aws_state_bucket_region=${AWS_STATE_BUCKET_REGION}
export TF_VAR_aws_state_bucket_key="${AWS_STATE_BUCKET_PROJECT_NAME}/${AWS_STATE_BUCKET_ENVIRONMENT_NAME}/terraform.tfstate"

export TF_VAR_aws_target_access_key=${AWS_TARGET_ACCESS_KEY-$AWS_STATE_BUCKET_ACCESS_KEY}
export TF_VAR_aws_target_access_secret=${AWS_TARGET_ACCESS_SECRET-$AWS_STATE_BUCKET_ACCESS_SECRET}
export TF_VAR_aws_target_region=${AWS_TARGET_REGION-$AWS_STATE_BUCKET_REGION}

# Init the backend configs
terraform init -backend-config="bucket=${AWS_STATE_BUCKET_NAME}" -backend-config="key=${TF_VAR_aws_state_bucket_key}" -backend-config="region=${AWS_STATE_BUCKET_REGION}" -backend=true -backend-config="access_key=${AWS_STATE_BUCKET_ACCESS_KEY}" -backend-config="secret_key=${AWS_STATE_BUCKET_ACCESS_SECRET}"

echo -e "\nSet S3 State Store in bucket: ${TF_VAR_aws_state_bucket_key}"

# Execute the originally passed in command
echo -e "\nExecuting command: ${@}\n\n"
exit_code=0
$@ || exit_code=$? && true

# Report the exit status
if [[ $exit_code -eq 0 ]]; then
  echo -e "\nSuccess"
else
  echo -e "\nFailed: ${exit_code}"
  exit $exit_code
fi


text:
package de.danoeh.antennapod.core.util;

import android.content.Context;
import android.util.Log;

import org.apache.commons.lang3.StringUtils;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Parses several date formats.
 */
public class DateUtils {
    private DateUtils(){}

	private static final String TAG = "DateUtils";

    private static final TimeZone defaultTimezone = TimeZone.getTimeZone("GMT");

    public static Date parse(final String input) {
        if(input == null) {
            throw new IllegalArgumentException("Date must not be null");
        }
        String date = input.trim().replace('/', '-').replaceAll("( ){2,}+", " ");

        // if datetime is more precise than seconds, make sure the value is in ms
        if(date.contains(".")) {
            int start = date.indexOf('.');
            int current = start+1;
            while(current < date.length() && Character.isDigit(date.charAt(current))) {
                current++;
            }
            // even more precise than microseconds: discard further decimal places
            if(current - start > 4) {
                if(current < date.length()-1) {
                    date = date.substring(0, start + 4) + date.substring(current);
                } else {
                    date = date.substring(0, start + 4);
                }
            // less than 4 decimal places: pad to have a consistent format for the parser
            } else if(current - start < 4) {
                if(current < date.length()-1) {
                    date = date.substring(0, current) + StringUtils.repeat("0", 4-(current-start)) + date.substring(current);
                } else {
                    date = date.substring(0, current) + StringUtils.repeat("0", 4-(current-start));
                }
            }
        }
        String[] patterns = {
                "dd MMM yy HH:mm:ss Z",
                "dd MMM yy HH:mm Z",
                "EEE, dd MMM yyyy HH:mm:ss Z",
                "EEE, dd MMM yyyy HH:mm:ss",
                "EEE, dd MMMM yyyy HH:mm:ss Z",
                "EEE, dd MMMM yyyy HH:mm:ss",
                "EEEE, dd MMM yyyy HH:mm:ss Z",
                "EEEE, dd MMM yy HH:mm:ss Z",
                "EEEE, dd MMM yyyy HH:mm:ss",
                "EEEE, dd MMM yy HH:mm:ss",
                "EEE MMM d HH:mm:ss yyyy",
                "EEE, dd MMM yyyy HH:mm Z",
                "EEE, dd MMM yyyy HH:mm",
                "EEE, dd MMMM yyyy HH:mm Z",
                "EEE, dd MMMM yyyy HH:mm",
                "EEEE, dd MMM yyyy HH:mm Z",
                "EEEE, dd MMM yy HH:mm Z",
                "EEEE, dd MMM yyyy HH:mm",
                "EEEE, dd MMM yy HH:mm",
                "EEE MMM d HH:mm yyyy",
                "yyyy-MM-dd'T'HH:mm:ss",
                "yyyy-MM-dd'T'HH:mm:ss.SSS Z",
                "yyyy-MM-dd'T'HH:mm:ss.SSS",
                "yyyy-MM-dd'T'HH:mm:ssZ",
                "yyyy-MM-dd'T'HH:mm:ss'Z'",
                "yyyy-MM-ddZ",
                "yyyy-MM-dd"
        };

        SimpleDateFormat parser = new SimpleDateFormat("", Locale.US);
        parser.setLenient(false);
        parser.setTimeZone(defaultTimezone);

        ParsePosition pos = new ParsePosition(0);
        for(String pattern : patterns) {
            parser.applyPattern(pattern);
            pos.setIndex(0);
            try {
                Date result = parser.parse(date, pos);
                if (result != null && pos.getIndex() == date.length()) {
                    return result;
                }
            } catch(Exception e) {
                Log.e(TAG, Log.getStackTraceString(e));
            }
        }

        Log.d(TAG, "Could not parse date string \"" + input + "\" [" + date + "]");
        return null;
    }

    /**
     * Takes a string of the form [HH:]MM:SS[.mmm] and converts it to
     * milliseconds.
     *
     * @throws java.lang.NumberFormatException if the number segments contain invalid numbers.
     */
    public static long parseTimeString(final String time) {
        String[] parts = time.split(":");
        long result = 0;
        int idx = 0;
        if (parts.length == 3) {
            // string has hours
            result += Integer.parseInt(parts[idx]) * 3600000L;
            idx++;
        }
        if (parts.length >= 2) {
            result += Integer.parseInt(parts[idx]) * 60000L;
            idx++;
            result += (Float.parseFloat(parts[idx])) * 1000L;
        }
        return result;
    }

    public static String formatRFC822Date(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("dd MMM yy HH:mm:ss Z", Locale.US);
        return format.format(date);
    }

    public static String formatRFC3339Local(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
        return format.format(date);
    }

    public static String formatRFC3339UTC(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
        format.setTimeZone(defaultTimezone);
        return format.format(date);
    }

    public static String formatAbbrev(final Context context, final Date date) {
        if(date == null) {
            return "";
        }
        GregorianCalendar cal = new GregorianCalendar();
        cal.add(GregorianCalendar.YEAR, -1);
        // some padding, because no one really remembers what day of the month it is
        cal.add(GregorianCalendar.DAY_OF_MONTH, 10);
        boolean withinLastYear = date.after(cal.getTime());
        int format = android.text.format.DateUtils.FORMAT_ABBREV_ALL;
        if(withinLastYear) {
            format |= android.text.format.DateUtils.FORMAT_NO_YEAR;
        }
        return android.text.format.DateUtils.formatDateTime(context, date.getTime(), format);
    }
}