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

class Node {
    public int Value { get; set; }
    public Node Left { get; set; }
    public Node Right { get; set; }
}

class Program {
    static Node Fill(int low, int high) {
        if (low > high) {
            return null;
        }

        int mid = low + (high - low) / 2;
        return new Node { Value = mid,
                          Left = Fill(low, mid - 1),
                          Right = Fill(mid + 1, high) };
    }

    static IEnumerable<Node> Inorder(Node root) {
        Stack<Node> stack = new Stack<Node>();
        while (stack.Any() || root != null) {
            if (root == null) {
                root = stack.Pop();
                yield return root;
                root = root.Right;
            } else {
                stack.Push(root);
                root = root.Left;
            }
        }
    }

    static bool IsBst(Node root, int low, int high) {
        return root == null || (low <= root.Value && root.Value <= high &&
                                IsBst(root.Left, low, root.Value) &&
                                IsBst(root.Right, root.Value, high));
    }

    static void Main() {
        Node root = Fill(1, 10);
        Console.WriteLine(String.Join(",", Inorder(root).Select(x => x.Value)));
        Console.WriteLine(IsBst(root, int.MinValue, int.MaxValue));
        root.Value = 0;
        Console.WriteLine(IsBst(root, int.MinValue, int.MaxValue));
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
class ControllerExtensionModuleGoogleHangouts extends Controller {
	private $error = array();

	public function index() {
		$this->load->language('extension/module/google_hangouts');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('setting/setting');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			$this->model_setting_setting->editSetting('module_google_hangouts', $this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			$this->response->redirect($this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true));
		}

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->error['code'])) {
			$data['error_code'] = $this->error['code'];
		} else {
			$data['error_code'] = '';
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_extension'),
			'href' => $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('extension/module/google_hangouts', 'user_token=' . $this->session->data['user_token'], true)
		);

		$data['action'] = $this->url->link('extension/module/google_hangouts', 'user_token=' . $this->session->data['user_token'], true);

		$data['cancel'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true);

		if (isset($this->request->post['module_google_hangouts_code'])) {
			$data['module_google_hangouts_code'] = $this->request->post['module_google_hangouts_code'];
		} else {
			$data['module_google_hangouts_code'] = $this->config->get('module_google_hangouts_code');
		}

		if (isset($this->request->post['module_google_hangouts_status'])) {
			$data['module_google_hangouts_status'] = $this->request->post['module_google_hangouts_status'];
		} else {
			$data['module_google_hangouts_status'] = $this->config->get('module_google_hangouts_status');
		}

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('extension/module/google_hangouts', $data));
	}

	protected function validate() {
		if (!$this->user->hasPermission('modify', 'extension/module/google_hangouts')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		if (!$this->request->post['module_google_hangouts_code']) {
			$this->error['code'] = $this->language->get('error_code');
		}

		return !$this->error;
	}
}


text:
published: true
title: Telomere paper posted to BioRxiv
layout: post
tags: news
---
Dan's telomere-length variation paper [posted on bioRxiv](http://biorxiv.org/content/early/2016/05/02/051276)!


text:
<!--
Any issue created without this markup will be immediately closed

Reporting a bug?
================
- Always search for your issue first. It may have already been answered, planned or fixed in some branch.

- Can you reproduce the issue outside of your environment? Please provide a jsfiddle or codepen example that demonstrates the bug. A codepen template can be found [here](https://codepen.io/johnjleider/pen/bgJOrX)

Have a feature request?
=======================
- Remove the template from below and provide thoughtful commentary.

- Answer those questions:
  - What will it allow you to do that you can't do today?
  - How will it make current work-arounds straightforward?
  - What potential bugs and edge cases does it help to avoid?

Do not create new features based on a problem that will only solve edge cases for your project.
-->

<!-- BUG REPORT TEMPLATE -->

### Steps to reproduce

### Versions
<!-- Which versions of Vue, Vuetify, OS, browsers are affected? -->

### What is expected ?
<!-- The behavior you would expect to see -->

### What is actually happening ?
<!-- Is there anything else we should know? -->

### Reproduction Link
<!-- Any issues without a reproduction link will be closed -->


text:
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// 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.devtools.build.lib.runtime;

import static com.google.devtools.build.lib.profiler.AutoProfiler.profiled;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.eventbus.EventBus;
import com.google.devtools.build.lib.actions.PackageRootResolver;
import com.google.devtools.build.lib.actions.cache.ActionCache;
import com.google.devtools.build.lib.actions.cache.CompactPersistentActionCache;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.analysis.BuildView;
import com.google.devtools.build.lib.analysis.SkyframePackageRootResolver;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.config.BuildConfigurationCollection;
import com.google.devtools.build.lib.analysis.config.BuildOptions;
import com.google.devtools.build.lib.analysis.config.DefaultsPackage;
import com.google.devtools.build.lib.analysis.config.InvalidConfigurationException;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.events.Reporter;
import com.google.devtools.build.lib.exec.OutputService;
import com.google.devtools.build.lib.packages.NoSuchThingException;
import com.google.devtools.build.lib.packages.Target;
import com.google.devtools.build.lib.pkgcache.PackageCacheOptions;
import com.google.devtools.build.lib.pkgcache.PackageManager;
import com.google.devtools.build.lib.pkgcache.TargetPatternEvaluator;
import com.google.devtools.build.lib.profiler.AutoProfiler;
import com.google.devtools.build.lib.profiler.ProfilerTask;
import com.google.devtools.build.lib.skyframe.SkyframeBuildView;
import com.google.devtools.build.lib.skyframe.SkyframeExecutor;
import com.google.devtools.build.lib.util.AbruptExitException;
import com.google.devtools.build.lib.util.ExitCode;
import com.google.devtools.build.lib.util.Preconditions;
import com.google.devtools.build.lib.util.io.TimestampGranularityMonitor;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.common.options.OptionPriority;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.common.options.OptionsParsingException;
import com.google.devtools.common.options.OptionsProvider;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Encapsulates the state needed for a single command. The environment is dropped when the current
 * command is done and all corresponding objects are garbage collected.
 */
public final class CommandEnvironment {
  private final BlazeRuntime runtime;
  private final BlazeWorkspace workspace;
  private final BlazeDirectories directories;

  private final UUID commandId;  // Unique identifier for the command being run
  private final Reporter reporter;
  private final EventBus eventBus;
  private final BlazeModule.ModuleEnvironment blazeModuleEnvironment;
  private final Map<String, String> clientEnv = new HashMap<>();
  private final TimestampGranularityMonitor timestampGranularityMonitor;

  private PathFragment relativeWorkingDirectory = PathFragment.EMPTY_FRAGMENT;
  private long commandStartTime;
  private OutputService outputService;
  private Path workingDirectory;

  private AtomicReference<AbruptExitException> pendingException = new AtomicReference<>();

  private class BlazeModuleEnvironment implements BlazeModule.ModuleEnvironment {
    @Override
    public Path getFileFromWorkspace(Label label)
        throws NoSuchThingException, InterruptedException, IOException {
      Target target = getPackageManager().getTarget(reporter, label);
      return (outputService != null)
          ? outputService.stageTool(target)
          : target.getPackage().getPackageDirectory().getRelative(target.getName());
    }

    @Override
    public void exit(AbruptExitException exception) {
      pendingException.compareAndSet(null, exception);
    }
  }

  CommandEnvironment(BlazeRuntime runtime, BlazeWorkspace workspace, EventBus eventBus) {
    this.runtime = runtime;
    this.workspace = workspace;
    this.directories = workspace.getDirectories();
    this.commandId = UUID.randomUUID();
    this.reporter = new Reporter();
    this.eventBus = eventBus;
    this.blazeModuleEnvironment = new BlazeModuleEnvironment();
    this.timestampGranularityMonitor = new TimestampGranularityMonitor(runtime.getClock());
    // Record the command's starting time again, for use by
    // TimestampGranularityMonitor.waitForTimestampGranularity().
    // This should be done as close as possible to the start of
    // the command's execution.
    timestampGranularityMonitor.setCommandStartTime();

    // TODO(ulfjack): We don't call beforeCommand() in tests, but rely on workingDirectory being set
    // in setupPackageCache(). This leads to NPE if we don't set it here.
    this.workingDirectory = directories.getWorkspace();

    workspace.getSkyframeExecutor().setEventBus(eventBus);
  }

  public BlazeRuntime getRuntime() {
    return runtime;
  }

  public BlazeWorkspace getBlazeWorkspace() {
    return workspace;
  }

  public BlazeDirectories getDirectories() {
    return directories;
  }

  /**
   * Returns the reporter for events.
   */
  public Reporter getReporter() {
    return reporter;
  }

  public EventBus getEventBus() {
    return eventBus;
  }

  public BlazeModule.ModuleEnvironment getBlazeModuleEnvironment() {
    return blazeModuleEnvironment;
  }

  /**
   * Return an unmodifiable view of the blaze client's environment when it invoked the current
   * command.
   */
  public Map<String, String> getClientEnv() {
    return Collections.unmodifiableMap(clientEnv);
  }

  @VisibleForTesting
  void updateClientEnv(List<Map.Entry<String, String>> clientEnvList, boolean ignoreClientEnv) {
    Preconditions.checkState(clientEnv.isEmpty());

    Collection<Map.Entry<String, String>> env =
        ignoreClientEnv ? System.getenv().entrySet() : clientEnvList;
    for (Map.Entry<String, String> entry : env) {
      clientEnv.put(entry.getKey(), entry.getValue());
    }
  }

  public TimestampGranularityMonitor getTimestampGranularityMonitor() {
    return timestampGranularityMonitor;
  }

  public PackageManager getPackageManager() {
    return getSkyframeExecutor().getPackageManager();
  }

  public PathFragment getRelativeWorkingDirectory() {
    return relativeWorkingDirectory;
  }

  /**
   * Creates and returns a new target pattern parser.
   */
  public TargetPatternEvaluator newTargetPatternEvaluator() {
    TargetPatternEvaluator result = getPackageManager().newTargetPatternEvaluator();
    result.updateOffset(relativeWorkingDirectory);
    return result;
  }

  public PackageRootResolver getPackageRootResolver() {
    return new SkyframePackageRootResolver(getSkyframeExecutor(), reporter);
  }

  /**
   * Returns the UUID that Blaze uses to identify everything logged from the current build command.
   * It's also used to invalidate Skyframe nodes that are specific to a certain invocation, such as
   * the build info.
   */
  public UUID getCommandId() {
    return commandId;
  }

  public SkyframeExecutor getSkyframeExecutor() {
    return workspace.getSkyframeExecutor();
  }

  public SkyframeBuildView getSkyframeBuildView() {
    return getSkyframeExecutor().getSkyframeBuildView();
  }

  /**
   * Returns the working directory of the server.
   *
   *
This is often the first entry on the {@code --package_path}, but not always.
   * Callers should certainly not make this assumption. The Path returned may be null.
   */
  public Path getWorkspace() {
    return getDirectories().getWorkspace();
  }

  public String getWorkspaceName() {
    Path workspace = getDirectories().getWorkspace();
    if (workspace == null) {
      return "";
    }
    return workspace.getBaseName();
  }

  /**
   * Returns if the client passed a valid workspace to be used for the build.
   */
  public boolean inWorkspace() {
    return getDirectories().inWorkspace();
  }

  /**
   * Returns the output base directory associated with this Blaze server
   * process. This is the base directory for shared Blaze state as well as tool
   * and strategy specific subdirectories.
   */
  public Path getOutputBase() {
    return getDirectories().getOutputBase();
  }

  /**
   * Returns the output path associated with this Blaze server process..
   */
  public Path getOutputPath() {
    return getDirectories().getOutputPath();
  }

  /**
   * Returns the execution root directory associated with this Blaze server
   * process. This is where all input and output files visible to the actual
   * build reside.
   */
  public Path getExecRoot() {
    return getDirectories().getExecRoot();
  }

  /**
   * Returns the working directory of the {@code blaze} client process.
   *
   *
This may be equal to {@code BlazeRuntime#getWorkspace()}, or beneath it.
   *
   * @see #getWorkspace()
   */
  public Path getWorkingDirectory() {
    return workingDirectory;
  }

  /**
   * @return the OutputService in use, or null if none.
   */
  public OutputService getOutputService() {
    return outputService;
  }

  public ActionCache getPersistentActionCache() throws IOException {
    return workspace.getPersistentActionCache(reporter);
  }

  /**
   * An array of String values useful if Blaze crashes.
   * For now, just returns the size of the action cache and the build id.
   */
  public String[] getCrashData() {
    return new String[]{
        getFileSizeString(CompactPersistentActionCache.cacheFile(workspace.getCacheDirectory()),
                          "action cache"),
        getCommandId() + " (build id)",
    };
  }

  private static String getFileSizeString(Path path, String type) {
    try {
      return String.format("%d bytes (%s)", path.getFileSize(), type);
    } catch (IOException e) {
      return String.format("unknown file size (%s)", type);
    }
  }

  /**
   * This method only exists for the benefit of InfoCommand, which needs to construct a {@link
   * BuildConfigurationCollection} without running a full loading phase. Don't add any more clients;
   * instead, we should change info so that it doesn't need the configuration.
   */
  public BuildConfigurationCollection getConfigurations(OptionsProvider optionsProvider)
      throws InvalidConfigurationException, InterruptedException {
    BuildOptions buildOptions = runtime.createBuildOptions(optionsProvider);
    boolean keepGoing = optionsProvider.getOptions(BuildView.Options.class).keepGoing;
    return getSkyframeExecutor().createConfigurations(reporter, runtime.getConfigurationFactory(),
        buildOptions, ImmutableSet.<String>of(), keepGoing);
  }

  /**
   * Hook method called by the BlazeCommandDispatcher right before the dispatch
   * of each command ends (while its outcome can still be modified).
   */
  ExitCode precompleteCommand(ExitCode originalExit) {
    eventBus.post(new CommandPrecompleteEvent(originalExit));
    // If Blaze did not suffer an infrastructure failure, check for errors in modules.
    ExitCode exitCode = originalExit;
    AbruptExitException exception = pendingException.get();
    if (!originalExit.isInfrastructureFailure() && exception != null) {
      exitCode = exception.getExitCode();
    }
    return exitCode;
  }

  /**
   * Throws the exception currently queued by a Blaze module.
   *
   *
This should be called as often as is practical so that errors are reported as soon as
   * possible. Ideally, we'd not need this, but the event bus swallows exceptions so we raise
   * the exception this way.
   */
  public void throwPendingException() throws AbruptExitException {
    AbruptExitException exception = pendingException.get();
    if (exception != null) {
      throw exception;
    }
  }

  /**
   * Initializes the package cache using the given options, and syncs the package cache. Also
   * injects a defaults package using the options for the {@link BuildConfiguration}.
   *
   * @see DefaultsPackage
   */
  public void setupPackageCache(PackageCacheOptions packageCacheOptions,
      String defaultsPackageContents) throws InterruptedException, AbruptExitException {
    SkyframeExecutor skyframeExecutor = getSkyframeExecutor();
    if (!skyframeExecutor.hasIncrementalState()) {
      skyframeExecutor.resetEvaluator();
    }
    skyframeExecutor.sync(reporter, packageCacheOptions, getOutputBase(),
        getWorkingDirectory(), defaultsPackageContents, commandId,
        timestampGranularityMonitor);
  }

  public void recordLastExecutionTime() {
    workspace.recordLastExecutionTime(getCommandStartTime());
  }

  public void recordCommandStartTime(long commandStartTime) {
    this.commandStartTime = commandStartTime;
  }

  public long getCommandStartTime() {
    return commandStartTime;
  }

  void setWorkingDirectory(Path workingDirectory) {
    this.workingDirectory = workingDirectory;
  }

  /**
   * Hook method called by the BlazeCommandDispatcher prior to the dispatch of
   * each command.
   *
   * @param options The CommonCommandOptions used by every command.
   * @throws AbruptExitException if this command is unsuitable to be run as specified
   */
  void beforeCommand(Command command, OptionsParser optionsParser,
      CommonCommandOptions options, long execStartTimeNanos, long waitTimeInMs)
      throws AbruptExitException {
    commandStartTime -= options.startupTime;

    eventBus.post(new GotOptionsEvent(runtime.getStartupOptionsProvider(), optionsParser));
    throwPendingException();

    outputService = null;
    BlazeModule outputModule = null;
    for (BlazeModule module : runtime.getBlazeModules()) {
      OutputService moduleService = module.getOutputService();
      if (moduleService != null) {
        if (outputService != null) {
          throw new IllegalStateException(String.format(
              "More than one module (%s and %s) returns an output service",
              module.getClass(), outputModule.getClass()));
        }
        outputService = moduleService;
        outputModule = module;
      }
    }

    SkyframeExecutor skyframeExecutor = getSkyframeExecutor();
    skyframeExecutor.setOutputService(outputService);

    // Ensure that the working directory will be under the workspace directory.
    Path workspace = getWorkspace();
    Path workingDirectory;
    if (inWorkspace()) {
      workingDirectory = workspace.getRelative(options.clientCwd);
    } else {
      workspace = FileSystemUtils.getWorkingDirectory(getDirectories().getFileSystem());
      workingDirectory = workspace;
    }
    this.relativeWorkingDirectory = workingDirectory.relativeTo(workspace);
    this.workingDirectory = workingDirectory;

    updateClientEnv(options.clientEnv, options.ignoreClientEnv);

    // Fail fast in the case where a Blaze command forgets to install the package path correctly.
    skyframeExecutor.setActive(false);
    // Let skyframe figure out if it needs to store graph edges for this build.
    skyframeExecutor.decideKeepIncrementalState(
        runtime.getStartupOptionsProvider().getOptions(BlazeServerStartupOptions.class).batch,
        optionsParser.getOptions(BuildView.Options.class));

    // Start the performance and memory profilers.
    runtime.beforeCommand(this, options, execStartTimeNanos);

    if (command.builds()) {
      Map<String, String> testEnv = new TreeMap<>();
      for (Map.Entry<String, String> entry :
          optionsParser.getOptions(BuildConfiguration.Options.class).testEnvironment) {
        testEnv.put(entry.getKey(), entry.getValue());
      }

      try {
        for (Map.Entry<String, String> entry : testEnv.entrySet()) {
          if (entry.getValue() == null) {
            String clientValue = clientEnv.get(entry.getKey());
            if (clientValue != null) {
              optionsParser.parse(OptionPriority.SOFTWARE_REQUIREMENT,
                  "test environment variable from client environment",
                  ImmutableList.of(
                      "--test_env=" + entry.getKey() + "=" + clientEnv.get(entry.getKey())));
            }
          }
        }
      } catch (OptionsParsingException e) {
        throw new IllegalStateException(e);
      }
    }
    for (BlazeModule module : runtime.getBlazeModules()) {
      module.handleOptions(optionsParser);
    }

    eventBus.post(new CommandStartEvent(
        command.name(), commandId, getClientEnv(), workingDirectory, getDirectories(),
        waitTimeInMs + options.waitTime));
  }

  /** Returns the name of the file system we are writing output to. */
  public String determineOutputFileSystem() {
    // If we have a fancy OutputService, this may be different between consecutive Blaze commands
    // and so we need to compute it freshly. Otherwise, we can used the immutable value that's
    // precomputed by our BlazeWorkspace.
    if (getOutputService() != null) {
      try (AutoProfiler p = profiled("Finding output file system", ProfilerTask.INFO)) {
        return getOutputService().getFilesSystemName();
      }
    }
    return workspace.getOutputBaseFilesystemTypeName();
  }
}


text:
Reusing params and containers
================================

After defining config params, you can use them later when defining other params. The same is true for containers.

This is important for avoiding config/code duplication.


text:
title: Waterloo using Scheme for 1st Year Computer Science
author: ajordens
layout: post
permalink: /2008/03/waterloo-using-scheme-for-1st-year-computer-science/
categories:
  - citations
---
[CompSci.ca/blog][1]

> First-year computer science courses at the University of Waterloo will undergo a major revision in fall 2008. CS at UW is part of the Faculty of Mathematics, and all Math students (including not only CS and traditional Math students, but accountants, actuaries, statisticians, and many others) take two courses in CS as part of their core requirements, but they have typically had a choice of courses depending on interest and experience. For the first time in fall 2008, all of the first-term courses will use the programming language Scheme.

I realize that [Waterloo][2] isn't the first University to take this tact but it's probably the highest profile school in Canada to do so. It'll be interesting to see if it rubs off on other schools and we start to see a bit less emphasis on Java as a teaching language.

 [1]: http://compsci.ca/blog/computer-science-at-waterloo-the-new-scheme-of-things/
 [2]: http://www.uwaterloo.ca/


text:
#include <limits.h>
#include <math.h>

#include "vpx_mem/vpx_mem.h"

#include "vp9/common/vp9_pred_common.h"
#include "vp9/common/vp9_tile_common.h"

#include "vp9/encoder/vp9_cost.h"
#include "vp9/encoder/vp9_segmentation.h"

void vp9_enable_segmentation(struct segmentation *seg) {
  seg->enabled = 1;
  seg->update_map = 1;
  seg->update_data = 1;
}

void vp9_disable_segmentation(struct segmentation *seg) {
  seg->enabled = 0;
  seg->update_map = 0;
  seg->update_data = 0;
}

void vp9_set_segment_data(struct segmentation *seg, signed char *feature_data,
                          unsigned char abs_delta) {
  seg->abs_delta = abs_delta;

  memcpy(seg->feature_data, feature_data, sizeof(seg->feature_data));
}
void vp9_disable_segfeature(struct segmentation *seg, int segment_id,
                            SEG_LVL_FEATURES feature_id) {
  seg->feature_mask[segment_id] &= ~(1 << feature_id);
}

void vp9_clear_segdata(struct segmentation *seg, int segment_id,
                       SEG_LVL_FEATURES feature_id) {
  seg->feature_data[segment_id][feature_id] = 0;
}

void vp9_psnr_aq_mode_setup(struct segmentation *seg) {
  int i;

  vp9_enable_segmentation(seg);
  vp9_clearall_segfeatures(seg);
  seg->abs_delta = SEGMENT_DELTADATA;

  for (i = 0; i < MAX_SEGMENTS; ++i) {
    vp9_set_segdata(seg, i, SEG_LVL_ALT_Q, 2 * (i - (MAX_SEGMENTS / 2)));
    vp9_enable_segfeature(seg, i, SEG_LVL_ALT_Q);
  }
}

void vp9_perceptual_aq_mode_setup(struct VP9_COMP *cpi,
                                  struct segmentation *seg) {
  const VP9_COMMON *cm = &cpi->common;
  const int seg_counts = cpi->kmeans_ctr_num;
  const int base_qindex = cm->base_qindex;
  const double base_qstep = vp9_convert_qindex_to_q(base_qindex, cm->bit_depth);
  const double mid_ctr = cpi->kmeans_ctr_ls[seg_counts / 2];
  const double var_diff_scale = 4.0;
  int i;

  assert(seg_counts <= MAX_SEGMENTS);

  vp9_enable_segmentation(seg);
  vp9_clearall_segfeatures(seg);
  seg->abs_delta = SEGMENT_DELTADATA;

  for (i = 0; i < seg_counts / 2; ++i) {
    double wiener_var_diff = mid_ctr - cpi->kmeans_ctr_ls[i];
    double target_qstep = base_qstep / (1.0 + wiener_var_diff / var_diff_scale);
    int target_qindex = vp9_convert_q_to_qindex(target_qstep, cm->bit_depth);
    assert(wiener_var_diff >= 0.0);

    vp9_set_segdata(seg, i, SEG_LVL_ALT_Q, target_qindex - base_qindex);
    vp9_enable_segfeature(seg, i, SEG_LVL_ALT_Q);
  }

  vp9_set_segdata(seg, i, SEG_LVL_ALT_Q, 0);
  vp9_enable_segfeature(seg, i, SEG_LVL_ALT_Q);

  for (; i < seg_counts; ++i) {
    double wiener_var_diff = cpi->kmeans_ctr_ls[i] - mid_ctr;
    double target_qstep = base_qstep * (1.0 + wiener_var_diff / var_diff_scale);
    int target_qindex = vp9_convert_q_to_qindex(target_qstep, cm->bit_depth);
    assert(wiener_var_diff >= 0.0);

    vp9_set_segdata(seg, i, SEG_LVL_ALT_Q, target_qindex - base_qindex);
    vp9_enable_segfeature(seg, i, SEG_LVL_ALT_Q);
  }
}

// Based on set of segment counts calculate a probability tree
static void calc_segtree_probs(int *segcounts, vpx_prob *segment_tree_probs) {
  // Work out probabilities of each segment
  const int c01 = segcounts[0] + segcounts[1];
  const int c23 = segcounts[2] + segcounts[3];
  const int c45 = segcounts[4] + segcounts[5];
  const int c67 = segcounts[6] + segcounts[7];

  segment_tree_probs[0] = get_binary_prob(c01 + c23, c45 + c67);
  segment_tree_probs[1] = get_binary_prob(c01, c23);
  segment_tree_probs[2] = get_binary_prob(c45, c67);
  segment_tree_probs[3] = get_binary_prob(segcounts[0], segcounts[1]);
  segment_tree_probs[4] = get_binary_prob(segcounts[2], segcounts[3]);
  segment_tree_probs[5] = get_binary_prob(segcounts[4], segcounts[5]);
  segment_tree_probs[6] = get_binary_prob(segcounts[6], segcounts[7]);
}

// Based on set of segment counts and probabilities calculate a cost estimate
static int cost_segmap(int *segcounts, vpx_prob *probs) {
  const int c01 = segcounts[0] + segcounts[1];
  const int c23 = segcounts[2] + segcounts[3];
  const int c45 = segcounts[4] + segcounts[5];
  const int c67 = segcounts[6] + segcounts[7];
  const int c0123 = c01 + c23;
  const int c4567 = c45 + c67;

  // Cost the top node of the tree
  int cost = c0123 * vp9_cost_zero(probs[0]) + c4567 * vp9_cost_one(probs[0]);

  // Cost subsequent levels
  if (c0123 > 0) {
    cost += c01 * vp9_cost_zero(probs[1]) + c23 * vp9_cost_one(probs[1]);

    if (c01 > 0)
      cost += segcounts[0] * vp9_cost_zero(probs[3]) +
              segcounts[1] * vp9_cost_one(probs[3]);
    if (c23 > 0)
      cost += segcounts[2] * vp9_cost_zero(probs[4]) +
              segcounts[3] * vp9_cost_one(probs[4]);
  }

  if (c4567 > 0) {
    cost += c45 * vp9_cost_zero(probs[2]) + c67 * vp9_cost_one(probs[2]);

    if (c45 > 0)
      cost += segcounts[4] * vp9_cost_zero(probs[5]) +
              segcounts[5] * vp9_cost_one(probs[5]);
    if (c67 > 0)
      cost += segcounts[6] * vp9_cost_zero(probs[6]) +
              segcounts[7] * vp9_cost_one(probs[6]);
  }

  return cost;
}

static void count_segs(const VP9_COMMON *cm, MACROBLOCKD *xd,
                       const TileInfo *tile, MODE_INFO **mi,
                       int *no_pred_segcounts,
                       int (*temporal_predictor_count)[2],
                       int *t_unpred_seg_counts, int bw, int bh, int mi_row,
                       int mi_col) {
  int segment_id;

  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;

  xd->mi = mi;
  segment_id = xd->mi[0]->segment_id;

  set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, cm->mi_rows, cm->mi_cols);

  // Count the number of hits on each segment with no prediction
  no_pred_segcounts[segment_id]++;

  // Temporal prediction not allowed on key frames
  if (cm->frame_type != KEY_FRAME) {
    const BLOCK_SIZE bsize = xd->mi[0]->sb_type;
    // Test to see if the segment id matches the predicted value.
    const int pred_segment_id =
        get_segment_id(cm, cm->last_frame_seg_map, bsize, mi_row, mi_col);
    const int pred_flag = pred_segment_id == segment_id;
    const int pred_context = vp9_get_pred_context_seg_id(xd);

    // Store the prediction status for this mb and update counts
    // as appropriate
    xd->mi[0]->seg_id_predicted = pred_flag;
    temporal_predictor_count[pred_context][pred_flag]++;

    // Update the "unpredicted" segment count
    if (!pred_flag) t_unpred_seg_counts[segment_id]++;
  }
}

static void count_segs_sb(const VP9_COMMON *cm, MACROBLOCKD *xd,
                          const TileInfo *tile, MODE_INFO **mi,
                          int *no_pred_segcounts,
                          int (*temporal_predictor_count)[2],
                          int *t_unpred_seg_counts, int mi_row, int mi_col,
                          BLOCK_SIZE bsize) {
  const int mis = cm->mi_stride;
  int bw, bh;
  const int bs = num_8x8_blocks_wide_lookup[bsize], hbs = bs / 2;

  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;

  bw = num_8x8_blocks_wide_lookup[mi[0]->sb_type];
  bh = num_8x8_blocks_high_lookup[mi[0]->sb_type];

  if (bw == bs && bh == bs) {
    count_segs(cm, xd, tile, mi, no_pred_segcounts, temporal_predictor_count,
               t_unpred_seg_counts, bs, bs, mi_row, mi_col);
  } else if (bw == bs && bh < bs) {
    count_segs(cm, xd, tile, mi, no_pred_segcounts, temporal_predictor_count,
               t_unpred_seg_counts, bs, hbs, mi_row, mi_col);
    count_segs(cm, xd, tile, mi + hbs * mis, no_pred_segcounts,
               temporal_predictor_count, t_unpred_seg_counts, bs, hbs,
               mi_row + hbs, mi_col);
  } else if (bw < bs && bh == bs) {
    count_segs(cm, xd, tile, mi, no_pred_segcounts, temporal_predictor_count,
               t_unpred_seg_counts, hbs, bs, mi_row, mi_col);
    count_segs(cm, xd, tile, mi + hbs, no_pred_segcounts,
               temporal_predictor_count, t_unpred_seg_counts, hbs, bs, mi_row,
               mi_col + hbs);
  } else {
    const BLOCK_SIZE subsize = subsize_lookup[PARTITION_SPLIT][bsize];
    int n;

    assert(bw < bs && bh < bs);

    for (n = 0; n < 4; n++) {
      const int mi_dc = hbs * (n & 1);
      const int mi_dr = hbs * (n >> 1);

      count_segs_sb(cm, xd, tile, &mi[mi_dr * mis + mi_dc], no_pred_segcounts,
                    temporal_predictor_count, t_unpred_seg_counts,
                    mi_row + mi_dr, mi_col + mi_dc, subsize);
    }
  }
}

void vp9_choose_segmap_coding_method(VP9_COMMON *cm, MACROBLOCKD *xd) {
  struct segmentation *seg = &cm->seg;

  int no_pred_cost;
  int t_pred_cost = INT_MAX;

  int i, tile_col, mi_row, mi_col;

  int temporal_predictor_count[PREDICTION_PROBS][2] = { { 0 } };
  int no_pred_segcounts[MAX_SEGMENTS] = { 0 };
  int t_unpred_seg_counts[MAX_SEGMENTS] = { 0 };

  vpx_prob no_pred_tree[SEG_TREE_PROBS];
  vpx_prob t_pred_tree[SEG_TREE_PROBS];
  vpx_prob t_nopred_prob[PREDICTION_PROBS];

  // Set default state for the segment tree probabilities and the
  // temporal coding probabilities
  memset(seg->tree_probs, 255, sizeof(seg->tree_probs));
  memset(seg->pred_probs, 255, sizeof(seg->pred_probs));

  // First of all generate stats regarding how well the last segment map
  // predicts this one
  for (tile_col = 0; tile_col < 1 << cm->log2_tile_cols; tile_col++) {
    TileInfo tile;
    MODE_INFO **mi_ptr;
    vp9_tile_init(&tile, cm, 0, tile_col);

    mi_ptr = cm->mi_grid_visible + tile.mi_col_start;
    for (mi_row = 0; mi_row < cm->mi_rows;
         mi_row += 8, mi_ptr += 8 * cm->mi_stride) {
      MODE_INFO **mi = mi_ptr;
      for (mi_col = tile.mi_col_start; mi_col < tile.mi_col_end;
           mi_col += 8, mi += 8)
        count_segs_sb(cm, xd, &tile, mi, no_pred_segcounts,
                      temporal_predictor_count, t_unpred_seg_counts, mi_row,
                      mi_col, BLOCK_64X64);
    }
  }

  // Work out probability tree for coding segments without prediction
  // and the cost.
  calc_segtree_probs(no_pred_segcounts, no_pred_tree);
  no_pred_cost = cost_segmap(no_pred_segcounts, no_pred_tree);

  // Key frames cannot use temporal prediction
  if (!frame_is_intra_only(cm)) {
    // Work out probability tree for coding those segments not
    // predicted using the temporal method and the cost.
    calc_segtree_probs(t_unpred_seg_counts, t_pred_tree);
    t_pred_cost = cost_segmap(t_unpred_seg_counts, t_pred_tree);

    // Add in the cost of the signaling for each prediction context.
    for (i = 0; i < PREDICTION_PROBS; i++) {
      const int count0 = temporal_predictor_count[i][0];
      const int count1 = temporal_predictor_count[i][1];

      t_nopred_prob[i] = get_binary_prob(count0, count1);

      // Add in the predictor signaling cost
      t_pred_cost += count0 * vp9_cost_zero(t_nopred_prob[i]) +
                     count1 * vp9_cost_one(t_nopred_prob[i]);
    }
  }

  // Now choose which coding method to use.
  if (t_pred_cost < no_pred_cost) {
    seg->temporal_update = 1;
    memcpy(seg->tree_probs, t_pred_tree, sizeof(t_pred_tree));
    memcpy(seg->pred_probs, t_nopred_prob, sizeof(t_nopred_prob));
  } else {
    seg->temporal_update = 0;
    memcpy(seg->tree_probs, no_pred_tree, sizeof(no_pred_tree));
  }
}

void vp9_reset_segment_features(struct segmentation *seg) {
  // Set up default state for MB feature flags
  seg->enabled = 0;
  seg->update_map = 0;
  seg->update_data = 0;
  memset(seg->tree_probs, 255, sizeof(seg->tree_probs));
  vp9_clearall_segfeatures(seg);
}


text:
(function (ns) {

    angular
        .module('springular', ['ngRoute'])
//        .directive("myDirective", ns.MyDirective)
//        .filter("myFilter", ns.MyFilter)
        .service('util', ns.Util)
        .service('connector', ns.Connector)
        .config([
            '$routeProvider', '$locationProvider', '$httpProvider',
            function ($routeProvider, $locationProvider, $httpProvider) {
                // Front pages
                $routeProvider.
                    when('/login', {
                        templateUrl: 'pages/login.htm',
                        controller: ns.LoginController
                    }).when('/admin', {
                        templateUrl: 'pages/admin.htm',
                        controller: ns.AdminController
                    }).otherwise({
                        redirectTo: '/login'
                    });

//                $locationProvider.html5Mode(true);

            }
        ])
        .run(function ($rootScope, $location, $route, connector) {
            $rootScope.$on("$routeChangeStart", function (event, next, current) {
                $rootScope.authenticated = false;

                connector.isAuthenticated(
                    function () {
                        if ($location.url() === '/login') {
                            $location.url("/admin");
                        }
                        $rootScope.authenticated = true;
                    },
                    function () {
                        if ($location.url() !== '/login') {
                            $location.url("/login");
                        }
                        $rootScope.authenticated = false;
                    })
            });
        });
})(com.mc);


text:
classdef lowrank
% Generates matrices of low rank

methods(Static)

function A = from_randn(m, n, r)
    % Returns a low rank matrix constructed by randn(m, r) * randn(r, m)
    X = randn(m, r);
    Y  = randn(r, n);
    A = X * Y;
end % function

end % methods

end % classdef


text:
'use strict';

describe('Controller: PetdetailCtrl', function () {

  // load the controller's module
  beforeEach(module('yoAngularIonicApp'));

  var PetdetailCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    PetdetailCtrl = $controller('PetdetailCtrl', {
      $scope: scope
    });
  }));

  it('should attach a list of awesomeThings to the scope', function () {
    expect(scope.awesomeThings.length).toBe(3);
  });
});


text:
package boltq

type queryOp int

const (
	EQ = iota
	RANGE
	IN
	ANY
	NOT
)

/*
Term holds parameters of a query term
*/
type Term struct {
	op   queryOp
	keys [][]byte
}

/*
Eq creates a new equals query term
*/
func Eq(key []byte) *Term {
	return &Term{EQ, [][]byte{key}}
}

/*
Range creates a new range query term
*/
func Range(lower, upper []byte) *Term {
	return &Term{RANGE, [][]byte{lower, upper}}
}

/*
In creates a new In query term
*/
func In(keys ...[]byte) *Term {
	return &Term{IN, keys}
}

/*
Any creates a wildcard query term
*/
func Any() *Term {
	return &Term{ANY, nil}
}

/*
Not creates a NOT IN query term
*/
func Not(keys ...[]byte) *Term {
	return &Term{NOT, keys}
}

/*
EqAll creates Eq terms for all provided keys
*/
func EqAll(keys [][]byte) []*Term {
	var rval []*Term
	for _, key := range keys {
		rval = append(rval, Eq(key))
	}
	return rval
}

/*
Query holds all information specific to a db query
*/
type Query struct {
	Collection []byte
	Terms      []*Term
}

/*
NewQuery creates a new query from the provided parameters
*/
func NewQuery(collection []byte, terms ...*Term) *Query {
	return &Query{collection, terms}
}


text:
package com.morcinek.android.codegenerator.plugin.utils;

import com.google.common.collect.Lists;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.morcinek.android.codegenerator.extractor.PackageExtractor;
import com.morcinek.android.codegenerator.extractor.XMLPackageExtractor;

import java.util.ArrayList;
import java.util.List;

public class PackageHelper {

    private final PackageExtractor packageExtractor = new XMLPackageExtractor();

    private final ProjectHelper projectHelper = new ProjectHelper();

    public String getPackageName(Project project, AnActionEvent event) {
        try {
            for (String path : possibleManifestPaths()) {
                VirtualFile file = getManifestFileFromPath(project, path);
                if (file != null && file.exists()) {
                    return packageExtractor.extractPackageFromManifestStream(file.getInputStream());
                }
            }
            for (String path : sourceRootPaths(project, event)) {
                VirtualFile file = getManifestFileFromPath(project, path);
                if (file != null && file.exists()) {
                    return packageExtractor.extractPackageFromManifestStream(file.getInputStream());
                }
            }
        } catch (Exception ignored) {
        }
        return "";
    }

    private ArrayList<String> possibleManifestPaths() {
        return Lists.newArrayList("", "app/", "app/src/main/", "src/main/", "res/");
    }

    private List<String> sourceRootPaths(Project project, AnActionEvent event) {
        return projectHelper.getSourceRootPathList(project, event);
    }

    private VirtualFile getManifestFileFromPath(Project project, String path) {
        VirtualFile folder = project.getBaseDir().findFileByRelativePath(path);
        if (folder != null) {
            return folder.findChild("AndroidManifest.xml");
        }
        return null;
    }
}


text:
#ifndef PP_SYSTEM_UI_EVENTS_PAINTEVENTARGS_HPP
#define PP_SYSTEM_UI_EVENTS_PAINTEVENTARGS_HPP

#include "PP/System/UI/Rectangle.hpp"
#include "PP/System/UI/Graphics/Graphics.hpp"

namespace PP
{
    namespace System
    {
        namespace UI
        {
            class Rectangle;
            class Graphics;

            class PaintEventArgs
            {
            public:
                PaintEventArgs(const Rectangle& clipRectangle, const Graphics& graphics);
                ~PaintEventArgs();

                Rectangle getClipRectangle() const;
                Graphics getGraphics() const;

            private:
                Rectangle m_clipRectangle;
                Graphics m_graphics;
            };
        }
    }
}

#endif


text:
'use strict';

const RelayDefaultNetworkLayer = require('RelayDefaultNetworkLayer');
const RelayPublic = require('RelayPublic');
const RelayStore = require('RelayStore');

// By default, assume that GraphQL is served at `/graphql` on the same domain.
RelayStore.injectNetworkLayer(new RelayDefaultNetworkLayer('/graphql'));

module.exports = {
  ...RelayPublic,
  // Expose the default network layer to allow convenient re-configuration.
  DefaultNetworkLayer: RelayDefaultNetworkLayer,
};


text:
#include <set>
using std::set; using std::multiset;

#include <string>
using std::string;

#include <vector>
using std::vector;

#include <iostream>
using std::cout; using std::endl;

int main()
{
	// define a vector with 20 elements,
	// holding two copies of each number from 0 to 9
	vector<int> ivec;
	for (vector<int>::size_type i = 0; i != 10; ++i) {
	    ivec.push_back(i);
	    ivec.push_back(i);  // duplicate copies of each number
	}

	// iset holds unique elements from ivec; miset holds all 20 elements
	set<int> iset(ivec.begin(), ivec.end());
	multiset<int> miset(ivec.begin(), ivec.end());

	cout << ivec.size() << endl;    // prints 20
	cout << iset.size() << endl;    // prints 10
	cout << miset.size() << endl;   // prints 20

	// returns an iterator that refers to the element with key == 1
	iset.find(1);
	iset.find(11);  // returns the iterator == iset.end()
	iset.count(1);  // returns 1
	iset.count(11); // returns 0

	// returns an iterator to the first element with key == 1
	iset.find(1);
	iset.find(11);   // returns the iterator == iset.end()
	miset.count(1);  // returns 2
	miset.count(11); // returns 0

	set<string> set1;    // empty set
	set1.insert("the");  // set1 now has one element
	set1.insert("and");  // set1 now has two elements

	set<int> set2;            // empty set
	int temp[] = {2,4,6,8,2,4,6,8}; // temp has eight elements
	 // set2 has four elements
	set2.insert(temp, temp + sizeof(temp)/sizeof(*temp));

	int temp2[] = {1,3,5,7,1,3,5,7};
	// set2 now has eight elements
	set2.insert(temp2, temp2 + sizeof(temp2)/sizeof(*temp2));

	return 0;
}


text:
package com.firebase.ui.auth.ui.email.fieldvalidators;

import android.support.design.widget.TextInputLayout;
import android.util.Patterns;

import com.firebase.ui.auth.R;

public class EmailFieldValidator extends BaseValidator {

    public EmailFieldValidator(TextInputLayout errorContainer) {
        super(errorContainer);
        mErrorMessage = mErrorContainer.getResources().getString(R.string.fui_invalid_email_address);
        mEmptyMessage = mErrorContainer.getResources().getString(R.string.fui_missing_email_address);
    }

    @Override
    protected boolean isValid(CharSequence charSequence) {
        return Patterns.EMAIL_ADDRESS.matcher(charSequence).matches();
    }
}


text:
class Pyqt5 < Formula
  desc "Python bindings for v5 of Qt"
  homepage "https://www.riverbankcomputing.com/software/pyqt/download5"
  url "https://downloads.sourceforge.net/project/pyqt/PyQt5/PyQt-5.7/PyQt5_gpl-5.7.tar.gz"
  sha256 "892693ba5f79989abb2061dad2d5c4e6f127e9dd3240f73f8220c7152cd35b05"

  bottle do
    sha256 "712463bc94f0658bc160e308b096047de132c860034cb93ed55cfb655a149baf" => :sierra
    sha256 "661671d00238a33251feba784b76ad735c44a95b59f5a2db0ccb2a4e0e901726" => :el_capitan
    sha256 "b0db1a3299549820aca3a54f7e3499c1278d0531c0697ebf68c334396cd80b2d" => :yosemite
  end

  option "with-debug", "Build with debug symbols"
  option "with-docs", "Install HTML documentation and python examples"

  deprecated_option "enable-debug" => "with-debug"

  depends_on :python3 => :recommended
  depends_on :python => :optional
  depends_on "qt5"

  if build.with? "python3"
    depends_on "sip" => "with-python3"
  else
    depends_on "sip"
  end

  def install
    if build.without?("python3") && build.without?("python")
      odie "pyqt5: --with-python3 must be specified when using --without-python"
    end

    Language::Python.each_python(build) do |python, version|
      args = ["--confirm-license",
              "--bindir=#{bin}",
              "--destdir=#{lib}/python#{version}/site-packages",
              "--stubsdir=#{lib}/python#{version}/site-packages/PyQt5",
              "--sipdir=#{share}/sip/Qt5",
              # sip.h could not be found automatically
              "--sip-incdir=#{Formula["sip"].opt_include}",
              # Make sure the qt5 version of qmake is found.
              # If qt4 is linked it will pickup that version otherwise.
              "--qmake=#{Formula["qt5"].bin}/qmake",
              # Force deployment target to avoid libc++ issues
              "QMAKE_MACOSX_DEPLOYMENT_TARGET=#{MacOS.version}",
              "--qml-plugindir=#{pkgshare}/plugins",
              "--verbose"]
      args << "--debug" if build.with? "debug"

      system python, "configure.py", *args
      system "make"
      system "make", "install"
      system "make", "clean"
    end
    doc.install "doc/html", "examples" if build.with? "docs"
  end

  test do
    system "pyuic5", "--version"
    system "pylupdate5", "-version"
    Language::Python.each_python(build) do |python, _version|
      system python, "-c", "import PyQt5"
      %w[
        Gui
        Location
        Multimedia
        Network
        Quick
        Svg
        WebEngineWidgets
        Widgets
        Xml
      ].each { |mod| system python, "-c", "import PyQt5.Qt#{mod}" }
    end
  end
end


text:
@*
 * Copyright 2022 HM Revenue & Customs
 *
 * 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.
 *@

@import play.api.mvc.Call
@import controllers.SummaryController

@import config.FrontendAppConfig
@(rowID: String, displayValues: Seq[String], changeLinkCall: Option[Call], removeLinkCall: Option[Call], removeLinkDefined: Boolean, boldText: Boolean, firstRow: Boolean)(implicit messages: Messages, appConfig: FrontendAppConfig)

@boldString = {"-bold"}
    @if(rowID == "totalPensionsAmt" || rowID == "ip14TotalPensionsAmt"){

            @Messages("pla.summary.questions.totalPensionsAmt")
            @displayValues.head

            @if(removeLinkDefined) {

            }

    } else {

            @Messages(s"pla.summary.questions.$rowID")

        @for((displayValue, index) <- displayValues.zipWithIndex) {
            @displayValue
        }

        @if(removeLinkDefined && removeLinkCall.isEmpty) {

        }

        @if(removeLinkCall.isDefined) {

                @Messages("pla.base.remove")
                @Messages(s"pla.summary.hiddenLinkText.removePsoHint")

        }
        @if(changeLinkCall.isDefined) {

            @Messages("pla.summary.change")
            @Messages(s"pla.summary.hiddenLinkText.$rowID")

        }

    }


text:
/* $License$ */
/**
 * A market data feed that generates random market data.
 *
 * @author anshul@marketcetera.com
 * @version $Id: package-info.java 16154 2012-07-14 16:34:05Z colin $
 * @since 1.0.0
 */
package org.marketcetera.marketdata.bogus;


text:
using System;

class Program
{
    static int GetMax(int a, int b)
    {
        return a > b ? a : b;
    }

    static void Main()
    {
        int a = int.Parse(Console.ReadLine());
        int b = int.Parse(Console.ReadLine());
        int c = int.Parse(Console.ReadLine());

        Console.WriteLine(GetMax(GetMax(a, b), c));
    }
}


text:
#ifndef GDCMPDATATFPDU_H
#define GDCMPDATATFPDU_H

#include "gdcmTypes.h"
#include "gdcmPresentationDataValue.h"
#include "gdcmBasePDU.h"
#include <limits>

namespace gdcm
{

namespace network
{

/**
 * \brief PDataTFPDU
 * Table 9-22
 * P-DATA-TF PDU FIELDS
 */
class GDCM_EXPORT PDataTFPDU : public BasePDU
{
public:
  PDataTFPDU();
  std::istream &Read(std::istream &is);
  const std::ostream &Write(std::ostream &os) const;

  /// \internal Compute Size
  size_t Size() const;

  void AddPresentationDataValue( PresentationDataValue const &pdv ) {
    V.push_back( pdv );
    assert(Size() < std::numeric_limits<uint32_t>::max());
    ItemLength = (uint32_t)Size() - 6;
    }

  typedef std::vector<PresentationDataValue>::size_type SizeType;
  PresentationDataValue const &GetPresentationDataValue(SizeType i) const {
    assert( !V.empty() && i < V.size() );
    return V[i];
  }
  SizeType GetNumberOfPresentationDataValues() const {
    return V.size();
    }

  void Print(std::ostream &os) const;
  bool IsLastFragment() const;

protected:
  std::istream &ReadInto(std::istream &is, std::ostream &os);
private:
  static const uint8_t ItemType; // PDUType ?
  static const uint8_t Reserved2;
  uint32_t ItemLength; // PDU Length ?
  std::vector<PresentationDataValue> V;
};

} // end namespace network

} // end namespace gdcm

#endif //GDCMPDATATFPDU_H


text:
class Cask::Container::Zip < Cask::Container::Base
  def self.me?(criteria)
    criteria.file.include? 'compressed-encoding=application/zip;'
  end

  def extract
    @command.run!('/usr/bin/ditto', :args => ['-xk', '--', @path, @cask.destination_path])
  end
end


text:
mrsub
=====

MapReduce Based Frequent Subgraph Discovery


text:
package edu.harvard.econcs.turkserver.server;

import java.lang.ref.WeakReference;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

import org.cometd.bayeux.server.ServerSession;

import edu.harvard.econcs.turkserver.api.HITWorker;
import edu.harvard.econcs.turkserver.api.HITWorkerGroup;
import edu.harvard.econcs.turkserver.schema.Session;

public class HITWorkerImpl implements HITWorker, HITWorkerGroup {

	volatile WeakReference<ServerSession> cometdSession;
	volatile Session record;
	volatile ExperimentControllerImpl expCont;

	final AtomicInteger numDisconnects = new AtomicInteger();

	final AtomicReference<Long> lastDisconnectTime = new AtomicReference<Long>();
	final AtomicReference<Long> lastInactiveStart = new AtomicReference<Long>();

	final AtomicLong totalDisconnectedMillis = new AtomicLong();
	final AtomicLong pastInactiveMillis = new AtomicLong();
	final AtomicLong currentInactiveMillis = new AtomicLong();

	public HITWorkerImpl(ServerSession cometdSession, Session dbSession) {
		this.cometdSession = new WeakReference<ServerSession>(cometdSession);
		this.record = dbSession;
	}

	void setServerSession(ServerSession newSession) {
		cometdSession = new WeakReference<ServerSession>(newSession);
	}

	void setExperiment(ExperimentControllerImpl cont) {
		this.expCont = cont;
	}

	@Override
	public String getHitId() {
		return record.getHitId();
	}

	@Override
	public String getAssignmentId() {
		return record.getAssignmentId();
	}

	@Override
	public String getWorkerId() {
		return record.getWorkerId();
	}

	@Override
	public String getUsername() {
		String username = record.getUsername();
		if( username != null ) return username;

		return "User for " + record.getHitId();
	}

	@Override
	public InetAddress getIPAddress() {
		try {
			String ip = record.getIpAddr();
			if (ip == null) return null;
			return InetAddress.getByName(ip);
		} catch (UnknownHostException e) {
			return null;
		}
	}

	@Override
	public boolean isConnected() {
		ServerSession session = cometdSession.get();
		if( session == null ) return false;

		return session.isConnected();
	}

	@Override
	public void deliverExperimentService(Map<String, Object> msg) throws MessageException {
		// Find the experiment this user is on and send a message on that channel
		expCont.sendExperimentService(this, msg);
	}

	public void deliverUserService(Map<String, Object> msg) throws MessageException {
		ServerSession session = cometdSession.get();
		if( session == null || !session.isConnected() ) throw new MessageException();

		session.deliver(session, "/service/user", msg, null);
	}

	/**
	 * call when this worker has disconnected previous and reconnects
	 * records the time since last disconnection, if any
	 */
	void reconnected() {
		Long lastDisc = lastDisconnectTime.getAndSet(null);

		if( lastDisc == null ) {
			// This currently happens on a reload.
			System.out.println("reconnected but don't have record of last disconnect");
			return;
		}

		/*
		 * Add disconnected time to total inactive time
		 *
		 * TODO this doesn't take care of the case where inactive is double-counted
		 * after a non-reloading reconnect
		 */

		long disconnectedMillis = System.currentTimeMillis() - lastDisc;

		pastInactiveMillis.addAndGet(disconnectedMillis);
		totalDisconnectedMillis.addAndGet(disconnectedMillis);
	}

	/**
	 * call when this worker disconnects
	 * records the time
	 */
	void disconnected() {
		lastDisconnectTime.set(System.currentTimeMillis());
		numDisconnects.incrementAndGet();
	}

	/**
	 * Add milliseconds of inactive time
	 * @param millis
	 * @param inactiveTime
	 */
	void addInactiveTime(long inactiveStart, long inactiveTime) {
		Long lastStart = lastInactiveStart.get();

		if( lastStart == null ) {
			currentInactiveMillis.set(inactiveTime);
			lastInactiveStart.set(inactiveStart);
		}
		else if( lastStart == inactiveStart ) {
			currentInactiveMillis.set(inactiveTime);
		}
		else {
			// New inactive segment, add previous segment to total
			long pastMillis = currentInactiveMillis.getAndSet(inactiveTime);
			lastInactiveStart.set(inactiveStart);

			pastInactiveMillis.addAndGet(pastMillis);
		}
	}

	/**
	 * Call at the end of an experiment to finish any uncomputed values
	 */
	public void finalizeActivity() {

		if( !isConnected() ) {
			Long lastDisc = lastDisconnectTime.getAndSet(null);

			if( lastDisc == null ) {
				System.out.println("not connected but don't have record of last disconnect");
				return;
			}
			else if( lastDisc > expCont.expFinishTime ) {
				System.out.println("ignoring last disconnect after experiment end");
				return;
			}

			long disconnectedMillis = expCont.expFinishTime - lastDisc;

			totalDisconnectedMillis.addAndGet(disconnectedMillis);

			// Add inactive time since disconnection as well
			addInactiveTime(lastDisc, disconnectedMillis);
		}

		// Clear out current inactive time
		long pastMillis = currentInactiveMillis.getAndSet(0);
		lastInactiveStart.set(null);

		pastInactiveMillis.addAndGet(pastMillis);
	}

	@Override
	public long getLastDisconnectedTime() {
		Long lastDisc = lastDisconnectTime.get();

		if( lastDisc == null )
			return -1;
		else
			return System.currentTimeMillis() - lastDisc;
	}

	@Override
	public long getTotalDisconnectedTime() {
		Long lastDisc = lastDisconnectTime.get();

		if( lastDisc == null ) {
			return totalDisconnectedMillis.get();
		}
		else {
			return totalDisconnectedMillis.get() + (System.currentTimeMillis() - lastDisc);
		}
	}

	@Override
	public int getNumDisconnects() {
		return numDisconnects.get();
	}

	@Override
	public long getLastInactiveTime() {
		return currentInactiveMillis.get();
	}

	@Override
	public long getTotalInactiveTime() {
		return pastInactiveMillis.get() + currentInactiveMillis.get();
	}

	@Override
	public double getInactivePercent() {
		if( expCont == null ) return 0d;

		long totalTime = System.currentTimeMillis() - expCont.expStartTime;
		return 1.0d * getTotalInactiveTime() / totalTime;
	}

	@Override
	public String getInactiveInfo() {
		return String.format("Inactive a total of %d secs, last inactive %d secs",
				getTotalInactiveTime() / 1000, getLastInactiveTime() / 1000);
	}

	@Override
	public int groupSize() {
		return 1;
	}

	@Override
	public boolean contains(HITWorker hitWorker) {
		return this.equals(hitWorker);
	}

	@Override
	public List<HITWorker> getHITWorkers() {
		return Collections.singletonList((HITWorker) this);
	}

	@Override
	public List<String> getHITIds() {
		return Collections.singletonList( this.getHitId() );
	}

	@Override
	public List<String> getWorkerIds() {
		return Collections.singletonList( this.getWorkerId() );
	}

	@Override
	public HITWorker findByHITId(String hitId) {
		if( hitId == null || !hitId.equals(this.getHitId()))
			return null;

		return this;
	}

	public Session getSessionRecord() {
		return record;
	}

	@Override
	public boolean equals(Object other) {
		// TODO: not sure if we want to implement things this way

		if( ! (other instanceof HITWorker) ) return false;

		HITWorker otherhw = (HITWorker) other;

		String thisHIT = record.getHitId();
		String otherHIT = otherhw.getHitId();
		String thisWorker = record.getWorkerId();
		String otherWorker = otherhw.getWorkerId();

		if( thisHIT == null || otherHIT == null ) return false;
		if( thisWorker == null || otherWorker == null ) return false;

		return thisHIT.equals(otherHIT) && thisWorker.equals(otherWorker);
	}

	public String toString() {
		return String.format("%s @ HIT %s", getWorkerId(), getHitId());
	}

}


text:
import IngredientsList from './IngredientsList'
import Instructions from './Instructions'

const Recipe = ({ name, ingredients, steps }) =>

{ name }

        <IngredientsList list={ ingredients } />
        <Instructions title="Cooking Instructions" steps={ steps } />

export default Recipe


text:
'''
gsconfig is a python library for manipulating a GeoServer instance via the GeoServer RESTConfig API.

The project is distributed under a MIT License .
'''

__author__ = "David Winslow"
__copyright__ = "Copyright 2012-2015 Boundless, Copyright 2010-2012 OpenPlans"
__license__ = "MIT"

from geoserver.catalog import Catalog

cat = Catalog("http://localhost:8080/geoserver/rest", "admin", "geoserver")

native_bbox = \
    ['589434.856', '4914006.338', '609527.21', '4928063.398', 'EPSG:26713']
latlon_bbox = ['-103.877', '44.371', '-103.622', '44.5', 'EPSG:4326']

sf = cat.get_workspace('sf')
for rs in cat.get_resources(workspace=sf):
    rs.native_bbox = native_bbox
    rs.latlon_bbox = latlon_bbox
    cat.save(rs)


text:
<Record>
<Term>Cutaneous Verruciform Xanthoma</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Xanthoma</ParentTerm>
<ClassificationPath>Findings_and_Disorders_Kind/Disease, Disorder or Finding/Disease or Disorder/Disorder by Site/Connective and Soft Tissue Disorder/Soft Tissue Disorder/Non-Neoplastic Soft Tissue Disorder/Xanthoma/Cutaneous Verruciform Xanthoma,/NCIThesaurus/Findings_and_Disorders_Kind/Disease, Disorder or Finding/Disease or Disorder/Disorder by Site/Skin Disorder/Non-Neoplastic Skin Disorder/Cutaneous Verruciform Xanthoma</ClassificationPath>
<BroaderTerm>NCIThesaurus</BroaderTerm>
<BroaderTerm>Disorder by Site</BroaderTerm>
<BroaderTerm>Non-Neoplastic Skin Disorder</BroaderTerm>
<BroaderTerm>Non-Neoplastic Soft Tissue Disorder</BroaderTerm>
<BroaderTerm>Xanthoma</BroaderTerm>
<BroaderTerm>Findings_and_Disorders_Kind</BroaderTerm>
<BroaderTerm>Disease, Disorder or Finding</BroaderTerm>
<BroaderTerm>Disease or Disorder</BroaderTerm>
<BroaderTerm>Cutaneous Verruciform Xanthoma</BroaderTerm>
<BroaderTerm>Connective and Soft Tissue Disorder</BroaderTerm>
<BroaderTerm>Cutaneous Verruciform Xanthoma,</BroaderTerm>
<BroaderTerm>Soft Tissue Disorder</BroaderTerm>
<BroaderTerm>Skin Disorder</BroaderTerm>
<Synonym>Cutaneous Verruciform Xanthoma</Synonym>
<Synonym>Skin Verruciform Xanthoma</Synonym>
<Synonym>Verruciform Xanthoma</Synonym>
<Synonym>Verruciform Xanthoma of Skin</Synonym>
<Synonym>Verruciform Xanthoma of the Skin</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


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

<title>org.nats.spring.examples</title>
<meta name="date" content="2015-07-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.nats.spring.examples

Classes

Expire

Pub

Request

Sub

SubUnsub


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<meta name="author" content="William Harmer">
		<meta name="description" content="A technical blog about my work and interests">
		<meta name="generator" content="Hugo 0.15" />
		<title>About · William Harmer Blog</title>
		<link rel="shortcut icon" href="http://willjharmer.github.io/images/favicon.ico">
		<link rel="stylesheet" href="http://willjharmer.github.io/css/style.css">
		<link rel="stylesheet" href="http://willjharmer.github.io/css/highlight.css">

		<link rel="stylesheet" href="http://willjharmer.github.io/css/monosocialiconsfont.css">

		<link href="http://willjharmer.github.io/index.xml" rel="alternate" type="application/rss+xml" title="William Harmer Blog" />

		 ←Home

	Subscribe

William Harmer

Data Scientist - Developer - Creative

A Data Scientist with software engineering experience building automated and production grade data products in an agile delivery environment. Studious in Data Science, continually expanding the depth and breadth of my problem solving skills as well as learning to apply open source technologies to deliver insight in short and frequent iterations. Experience instructing a range of audiences in leading edge Data Science practices.

        circlefacebook

        circlegithub

        circletwitterbird

        © Copyright 2016 William Harmer


text:
<idea-plugin>
    <id>com.viartemev.requestmapper</id>
    <name>Request mapper</name>
    <version>1.0</version>
    <vendor email="viartemev@gmail.com" url="https://github.com/viartemev">Vyacheslav Artemyev</vendor>

    <description><![CDATA[
      Plugin for quick navigation to url mapping declaration.

      Supported languages:

Java

Kotlin

      Supported frameworks:

Spring

JAX-RS

Micronaut

Helidon

    ]]></description>

    <change-notes><![CDATA[

使支持版本2021.1 — 2021.2.3

    ]]>
    </change-notes>

    <depends>com.intellij.modules.lang</depends>
    <depends>com.intellij.java</depends>
    <depends optional="true" config-file="pluginKotlin.xml">org.jetbrains.kotlin</depends>

    <idea-version since-build="201.7000"/>

    <actions>
        <action id="GoToRequestMapping" class="com.viartemev.requestmapper.GoToRequestMappingAction"
                text="Request Mapping" description="Request mapping">
            <add-to-group group-id="GoToTargetEx" anchor="first"/>
            <keyboard-shortcut keymap="$default" first-keystroke="shift ctrl BACK_SLASH"/>
        </action>
    </actions>

    <extensionPoints>
        <extensionPoint name="requestMappingContributor" interface="com.intellij.navigation.ChooseByNameContributor"/>
    </extensionPoints>

    <extensions  defaultExtensionNs="com.intellij">
        <searchEverywhereContributor implementation="com.viartemev.requestmapper.RequestMappingGoToContributor$Factory"/>
    </extensions>

    <extensions defaultExtensionNs="com.viartemev.requestmapper">
        <requestMappingContributor implementation="com.viartemev.requestmapper.contributor.JavaRequestMappingContributor"/>
    </extensions>
</idea-plugin>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Markup;

namespace Markup.Programming.Core
{
    [ContentProperty("Arguments")]
    public abstract class ItemAccessor : ArgumentsExpressionWithType
    {
        public object Index
        {
            get { return (object)GetValue(IndexProperty); }
            set { SetValue(IndexProperty, value); }
        }

        public static readonly DependencyProperty IndexProperty =
            DependencyProperty.Register("Index", typeof(object), typeof(ItemAccessor), null);

        public string IndexPath { get; set; }

        private CodeTree indexCodeTree = new CodeTree();
        protected CodeTree IndexCodeTree { get { return indexCodeTree; } }

        protected override void OnAttached()
        {
            base.OnAttached();
            Attach(IndexProperty);
        }

        protected object GetItem(Engine engine)
        {
            return AccessItem(false, engine, null);
        }

        protected object SetItem(Engine engine, object value)
        {
            return AccessItem(true, engine, value);
        }

        private object AccessItem(bool isSet, Engine engine, object value)
        {
            var op = isSet ? Op.SetItem : Op.GetItem;
            var context = engine.GetContext(Path, CodeTree);
            if (Arguments.Count != 0)
            {
                var combinedArgs = new object[] { context }.Concat(Arguments.Get(engine));
                if (isSet) combinedArgs.Concat(new object[] { value });
                return engine.Operator(op, combinedArgs.ToArray());
            }
            var type = engine.GetType(TypeProperty, TypePath, TypeCodeTree);
            var index = engine.Get(IndexProperty, IndexPath, IndexCodeTree, type);
            if (!isSet) return engine.Operator(op, context, index);
            return engine.Operator(op, context, index, value);
        }
    }
}


text:
#include <aws/gamelift/model/DescribeMatchmakingConfigurationsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::GameLift::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

DescribeMatchmakingConfigurationsResult::DescribeMatchmakingConfigurationsResult()
{
}

DescribeMatchmakingConfigurationsResult::DescribeMatchmakingConfigurationsResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

DescribeMatchmakingConfigurationsResult& DescribeMatchmakingConfigurationsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("Configurations"))
  {
    Array<JsonView> configurationsJsonList = jsonValue.GetArray("Configurations");
    for(unsigned configurationsIndex = 0; configurationsIndex < configurationsJsonList.GetLength(); ++configurationsIndex)
    {
      m_configurations.push_back(configurationsJsonList[configurationsIndex].AsObject());
    }
  }

  if(jsonValue.ValueExists("NextToken"))
  {
    m_nextToken = jsonValue.GetString("NextToken");

  }

  return *this;
}


text:
package com.netflix.genie.common.dto.search;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.DurationDeserializer;
import com.netflix.genie.common.dto.JobStatus;
import com.netflix.genie.common.util.TimeUtils;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import org.hibernate.validator.constraints.NotBlank;

import javax.validation.constraints.NotNull;
import java.time.Duration;
import java.util.Date;
import java.util.Optional;

/**
 * This class represents the subset of data returned from a Job when a search for Jobs is conducted.
 *
 * @author tgianos
 * @since 3.0.0
 */
@Getter
@EqualsAndHashCode(callSuper = true, of = {})
public class JobSearchResult extends BaseSearchResult {

    private static final long serialVersionUID = -3886685874572773514L;

    private final JobStatus status;
    private final Date started;
    private final Date finished;
    private final String clusterName;
    private final String commandName;
    @JsonSerialize(using = ToStringSerializer.class)
    @JsonDeserialize(using = DurationDeserializer.class)
    private final Duration runtime;

    /**
     * Constructor.
     *
     * @param id          The id of the job
     * @param name        The name of the job
     * @param user        The user of the job
     * @param status      The current status of the job
     * @param started     The start time of the job
     * @param finished    The finish time of the job
     * @param clusterName The name of the cluster this job is or was run on
     * @param commandName The name fo the command this job is or was run with
     */
    @JsonCreator
    public JobSearchResult(
        @NotBlank @JsonProperty("id") final String id,
        @NotBlank @JsonProperty("name") final String name,
        @NotBlank @JsonProperty("user") final String user,
        @NotNull @JsonProperty("status") final JobStatus status,
        @JsonProperty("started") final Date started,
        @JsonProperty("finished") final Date finished,
        @JsonProperty("clusterName") final String clusterName,
        @JsonProperty("commandName") final String commandName
    ) {
        super(id, name, user);
        this.status = status;
        this.started = started == null ? null : new Date(started.getTime());
        this.finished = finished == null ? null : new Date(finished.getTime());
        this.clusterName = clusterName;
        this.commandName = commandName;

        this.runtime = TimeUtils.getDuration(this.started, this.finished);
    }

    /**
     * Get the time the job started.
     *
     * @return The started time or null if not set
     */
    public Optional<Date> getStarted() {
        return this.started == null ? Optional.empty() : Optional.of(new Date(this.started.getTime()));
    }

    /**
     * Get the time the job finished.
     *
     * @return The finished time or null if not set
     */
    public Optional<Date> getFinished() {
        return this.finished == null ? Optional.empty() : Optional.of(new Date(this.finished.getTime()));
    }

    /**
     * Get the name of the cluster running the job if there currently is one.
     *
     * @return The name of the cluster where the job is running
     */
    public Optional<String> getClusterName() {
        return Optional.ofNullable(this.clusterName);
    }

    /**
     * Get the name of the command running this job if there currently is one.
     *
     * @return The name of the command
     */
    public Optional<String> getCommandName() {
        return Optional.ofNullable(this.commandName);
    }
}


text:
package main

import (
	"net/http"
	"testing"
	"time"

	"code.google.com/p/go.net/websocket"
)

var server = startTestServer()

func startTestServer() *Server {
	var Store = initStore(nil)
	var server = createServer(nil, &Store)

	go server.initSocketListener()

	go http.ListenAndServe(listenAddr, nil)

	return server
}

func TestAuthenticate(t *testing.T) {
	ws, err := websocket.Dial("ws://localhost:4000/socket", "", "http://localhost/")
	if err != nil {
		t.Fatalf("Authenticate Test failed, Could not connect with error %s", err.Error())
	}

	//sock       := Socket{ws, "", make(chan *Message), make(chan bool)}
	body := make(map[string]interface{})
	body["UID"] = "TEST_UID"
	message := Message{"Authenticate", body, 1234}

	if err := websocket.JSON.Send(ws, message); err != nil {
		t.Fatal("Authenticate Test failed, Could not send Auth message")
	}

	time.Sleep(10 * time.Millisecond)

	_, err1 := server.Store.Client("TEST_UID")

	if err1 != nil {
		t.Errorf("Authenticate Test failed, Failed to Authenticate expected TEST_UID, got %s", err1.Error())
	}
}

func TestListenForMessages(t *testing.T) {
	sock, err := server.Store.Client("TEST_UID")
	if err != nil {
		t.Fatalf("ListenForMessages Test failed, Failed to get Socket TEST_UID, with error: %s", err.Error())
	}

	body := make(map[string]interface{})
	body["UID"] = "TEST_UID"
	message := Message{"MessageUser", body, 1234}

	if err = websocket.JSON.Send(sock.ws, message); err != nil {
		t.Errorf("ListenForMessages Test failed, Failed to get Socket TEST_UID, with error: %s", err.Error())
	}
}

func TestListenForWriter(t *testing.T) {
	t.Fatal("somthing is wrong with this stupes test") //CLIENT WS VS. SERVER WS!?
	sock, err := server.Store.Client("TEST_UID")
	if err != nil {
		t.Fatalf("ListenForWriter Test failed, Failed to get Socket TEST_UID, with error: %s", err.Error())
	}

	go func() {
		time.Sleep(10 * time.Millisecond)
		body := make(map[string]interface{})
		body["UID"] = "TEST_UID"
		msg := make(map[string]int)
		msg["t"] = 1
		body["Message"] = msg
		message := Message{"MessageUser", body, 1234}

		sock.buff <- &message
	}()

	var message Message
	if err = websocket.JSON.Receive(sock.ws, &message); err != nil {
		t.Errorf("ListenForMessages Test failed, Failed to get Socket TEST_UID, with error: %s", err.Error())
	}

	if message.Event != "MessageUser" {
		t.Error("ListenForMessages Test failed, Failed to get Socket TEST_UID")
	}
	sock.Close()
}


text:
import os
import numpy as np
from panda3d.core import loadPrcFile
from panda3d.core import TextNode
from direct.task import Task
from direct.gui.OnscreenText import OnscreenText
from citysim3d.envs import SimpleQuadPanda3dEnv
from citysim3d.spaces import BoxSpace
import citysim3d.utils.transformations as tf

assert "CITYSIM3D_DIR" in os.environ
loadPrcFile(os.path.expandvars('${CITYSIM3D_DIR}/config.prc'))

def add_instructions(app, pos, msg):
    return OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), scale=.05,
                        shadow=(0, 0, 0, 1), parent=app.a2dTopLeft,
                        pos=(0.08, -pos - 0.04), align=TextNode.ALeft)

def as_one(boolean):
    """ Maps True to 1 and False to -1 """
    boolean = bool(boolean)  # ensure it's a boolean
    return 2 * int(boolean) - 1

class CustomSimpleQuadPanda3dEnv(SimpleQuadPanda3dEnv):
    """
    Same as SimpleQuadPanda3dEnv except that actions are directly mapped to
    the car's actions and the quad is constrained to move behind the car.
    """
    def __init__(self, *args, **kwargs):
        super(CustomSimpleQuadPanda3dEnv, self).__init__(*args, **kwargs)

        # change the car's speed limit
        self.car_env.speed_offset_space.low[0] = 0.0
        self.car_env.speed_offset_space.high[0] = np.inf

    @property
    def action_space(self):
        return self.car_env.action_space

    def step(self, action):
        # update the angle of the propellers (for rendering purposes)
        if self.prop_rpm:
            self.prop_angle += (self.prop_rpm * 2 * np.pi / 60) * self.dt
            self.prop_angle -= 2 * np.pi * np.floor(self.prop_angle / (2 * np.pi))
            for quad_prop_id, quad_prop_local_node in enumerate(self.quad_prop_local_nodes):
                is_ccw = quad_prop_id in (1, 2)
                angle = self.prop_angle if is_ccw else -self.prop_angle
                quad_prop_local_node.setQuat(tuple(tf.quaternion_about_axis(angle, np.array([0, 0, 1]))))

        self.car_env.step(action)

        # set the position of the quad to be behind the car
        car_T = tf.pose_matrix(self.car_node.getQuat(), self.car_node.getPos())
        quad_pos = car_T[:3, 3] + car_T[:3, :3].dot(np.array([0., -4., 3.]) * 4)
        # set the rotation of the quad to be the rotation of the car projected so that the z-axis is up
        axis = np.cross(car_T[:3, 2], np.array([0, 0, 1]))
        angle = tf.angle_between_vectors(car_T[:3, 2], np.array([0, 0, 1]))
        if np.isclose(angle, 0.0):
            project_T = np.eye(4)
        else:
            project_T = tf.rotation_matrix(angle, axis)
        quad_T = project_T.dot(car_T)
        quad_quat = tf.quaternion_from_matrix(quad_T[:3, :3])
        tightness = 0.1
        self.quad_node.setPosQuat(tuple((1 - tightness) * np.array(self.quad_node.getPos()) + tightness * quad_pos), tuple(quad_quat))

        return self.observe(), None, False, dict()

    def reset(self):
        """
        Same as SimpleQuadPanda3dEnv.reset except that the car's speed is
        always set to 10.0"""
        # reset to given or random state...
        super(CustomSimpleQuadPanda3dEnv, self).reset()
        state = self.car_env.get_state()
        # ... but then set the car's speed to 10.0
        state[0] = 10.0
        self.car_env.set_state(state)
        return self.observe()

def main():
    # actions are forward acceleration and lateral velocity
    action_space = BoxSpace(low=np.array([-1.0, -1.0]),
                            high=np.array([1.0, 1.0]))
    car_model_names = ['camaro2', 'kia_rio_blue', 'kia_rio_red',
                       'kia_rio_silver', 'kia_rio_white', 'kia_rio_yellow',
                       'mazda6', 'mitsubishi_lancer_evo', 'sport']
    env = CustomSimpleQuadPanda3dEnv(action_space,
                                     sensor_names=[],  # empty sensor_names means no observations
                                     car_model_names=car_model_names)

    num_camera_modes = 3
    key_map = dict(left=False, right=False, up=False, down=False, camera_pressed=False, camera_mode=0)

    def step(task):
        forward_acceleration = as_one(key_map['up']) - as_one(key_map['down'])
        lateral_velocity = as_one(key_map['right']) - as_one(key_map['left'])
        action = np.array([forward_acceleration, lateral_velocity])
        env.step(action)

        if key_map['camera_pressed']:
            key_map['camera_mode'] = (key_map['camera_mode'] + 1) % num_camera_modes
        if key_map['camera_mode'] == 0:
            env.app.cam.reparentTo(env.app.render)
            env.app.cam.setQuat(tuple(tf.quaternion_about_axis(-np.pi / 2, np.array([1, 0, 0]))))
            env.app.cam.setPos(tuple(np.array(env.car_node.getPos()) + np.array([0., 0., 100.])))
        elif key_map['camera_mode'] in (1, 2):
            if key_map['camera_pressed']:
                tightness = 1.0
            else:
                tightness = 0.1
            if key_map['camera_mode'] == 1:
                target_node = env.car_node
                offset = np.array([0., -4., 3.]) * 3
            else:
                target_node = env.quad_node
                offset = np.array([0., -4., 3.]) * .5
            target_T = tf.pose_matrix(target_node.getQuat(), target_node.getPos())
            target_camera_pos = target_T[:3, 3] + target_T[:3, :3].dot(offset)
            env.app.cam.setPos(tuple((1 - tightness) * np.array(env.app.cam.getPos()) + tightness * target_camera_pos))
            env.app.cam.lookAt(target_node)
        else:
            env.app.cam.reparentTo(env.car_node)
            env.app.cam.setQuat((1, 0, 0, 0))
            env.app.cam.setPos(tuple(np.array([0, 1, 2])))  # slightly in front of the car
        key_map['camera_pressed'] = False
        return Task.cont

    env.app.taskMgr.add(step, "step")

    add_instructions(env.app, 0.06, "[ESC]: Quit")
    add_instructions(env.app, 0.12, "[R]: Reset environment")
    add_instructions(env.app, 0.18, "[Left Arrow]: Move car left")
    add_instructions(env.app, 0.24, "[Right Arrow]: Move car right")
    add_instructions(env.app, 0.30, "[Up Arrow]: Accelerate the car")
    add_instructions(env.app, 0.36, "[Down Arrow]: Decelerate the car")
    add_instructions(env.app, 0.42, "[C]: Toggle camera mode")
    add_instructions(env.app, 0.48, "[S]: Take screenshot")

    env.app.accept('r', env.reset)
    env.app.accept('arrow_left', key_map.update, [[('left', True)]])
    env.app.accept('arrow_left-up', key_map.update, [[('left', False)]])
    env.app.accept('arrow_right', key_map.update, [[('right', True)]])
    env.app.accept('arrow_right-up', key_map.update, [[('right', False)]])
    env.app.accept('arrow_up', key_map.update, [[('up', True)]])
    env.app.accept('arrow_up-up', key_map.update, [[('up', False)]])
    env.app.accept('arrow_down', key_map.update, [[('down', True)]])
    env.app.accept('arrow_down-up', key_map.update, [[('down', False)]])
    env.app.accept('c-up', key_map.update, [[('camera_pressed', True)]])
    env.app.accept('s-up', env.app.screenshot)

    env.reset()
    env.app.run()

if __name__ == '__main__':
    main()


text:
package aws

import (
	"log"
	"regexp"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/elasticache"
	"github.com/hashicorp/terraform/helper/schema"
)

// setTags is a helper to set the tags for a resource. It expects the
// tags field to be named "tags"
func setTagsEC(conn *elasticache.ElastiCache, d *schema.ResourceData, arn string) error {
	if d.HasChange("tags") {
		oraw, nraw := d.GetChange("tags")
		o := oraw.(map[string]interface{})
		n := nraw.(map[string]interface{})
		create, remove := diffTagsEC(tagsFromMapEC(o), tagsFromMapEC(n))

		// Set tags
		if len(remove) > 0 {
			log.Printf("[DEBUG] Removing tags: %#v", remove)
			k := make([]*string, len(remove), len(remove))
			for i, t := range remove {
				k[i] = t.Key
			}

			_, err := conn.RemoveTagsFromResource(&elasticache.RemoveTagsFromResourceInput{
				ResourceName: aws.String(arn),
				TagKeys:      k,
			})
			if err != nil {
				return err
			}
		}
		if len(create) > 0 {
			log.Printf("[DEBUG] Creating tags: %#v", create)
			_, err := conn.AddTagsToResource(&elasticache.AddTagsToResourceInput{
				ResourceName: aws.String(arn),
				Tags:         create,
			})
			if err != nil {
				return err
			}
		}
	}

	return nil
}

// diffTags takes our tags locally and the ones remotely and returns
// the set of tags that must be created, and the set of tags that must
// be destroyed.
func diffTagsEC(oldTags, newTags []*elasticache.Tag) ([]*elasticache.Tag, []*elasticache.Tag) {
	// First, we're creating everything we have
	create := make(map[string]interface{})
	for _, t := range newTags {
		create[*t.Key] = *t.Value
	}

	// Build the list of what to remove
	var remove []*elasticache.Tag
	for _, t := range oldTags {
		old, ok := create[*t.Key]
		if !ok || old != *t.Value {
			// Delete it!
			remove = append(remove, t)
		}
	}

	return tagsFromMapEC(create), remove
}

// tagsFromMap returns the tags for the given map of data.
func tagsFromMapEC(m map[string]interface{}) []*elasticache.Tag {
	result := make([]*elasticache.Tag, 0, len(m))
	for k, v := range m {
		t := &elasticache.Tag{
			Key:   aws.String(k),
			Value: aws.String(v.(string)),
		}
		if !tagIgnoredEC(t) {
			result = append(result, t)
		}
	}

	return result
}

// tagsToMap turns the list of tags into a map.
func tagsToMapEC(ts []*elasticache.Tag) map[string]string {
	result := make(map[string]string)
	for _, t := range ts {
		if !tagIgnoredEC(t) {
			result[*t.Key] = *t.Value
		}
	}

	return result
}

// compare a tag against a list of strings and checks if it should
// be ignored or not
func tagIgnoredEC(t *elasticache.Tag) bool {
	filter := []string{"^aws:"}
	for _, v := range filter {
		log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key)
		if r, _ := regexp.MatchString(v, *t.Key); r == true {
			log.Printf("[DEBUG] Found AWS specific tag %s (val: %s), ignoring.\n", *t.Key, *t.Value)
			return true
		}
	}
	return false
}


text:
package com.reason.ide;

import com.intellij.json.psi.*;
import com.intellij.psi.*;
import com.reason.comp.esy.*;
import com.reason.ide.files.*;
import com.reason.ide.search.*;
import com.reason.lang.core.psi.PsiType;
import com.reason.lang.core.psi.*;
import com.reason.lang.core.psi.impl.*;
import icons.*;
import org.jetbrains.annotations.*;

import javax.swing.*;

public class IconProvider extends com.intellij.ide.IconProvider {
  @Nullable
  @Override
  public Icon getIcon(@NotNull PsiElement psiElement, int flags) {
    PsiElement element =
        psiElement instanceof PsiFakeModule ? psiElement.getContainingFile() : psiElement;
    if (element instanceof PsiFile) {
      if (element instanceof OclFile) {
        return ORIcons.OCL_FILE;
      }
      if (element instanceof OclInterfaceFile) {
        return ORIcons.OCL_INTERFACE_FILE;
      }
      if (element instanceof RmlFile) {
        return ORIcons.RML_FILE;
      }
      if (element instanceof RmlInterfaceFile) {
        return ORIcons.RML_INTERFACE_FILE;
      }
      if (element instanceof ResFile) {
        return ORIcons.NS_FILE;
      }
      if (element instanceof ResInterfaceFile) {
        return ORIcons.NS_INTERFACE_FILE;
      }
      if (isEsyPackageJson((PsiFile) element)) {
        return ORIcons.ESY_FILE;
      }
    } else if (element instanceof PsiException) {
      return ORIcons.EXCEPTION;
    } else if (element instanceof PsiInnerModule) {
      return ORIcons.INNER_MODULE;
    } else if (element instanceof PsiFunctor) {
      return ORIcons.FUNCTOR;
    } else if (element instanceof PsiType) {
      return ORIcons.TYPE;
    } else if (element instanceof PsiVariantDeclaration) {
      return ORIcons.VARIANT;
    } else if (element instanceof PsiLet) {
      PsiLet let = (PsiLet) element;
      return let.isRecord() ? ORIcons.OBJECT : (let.isFunction() ? ORIcons.FUNCTION : ORIcons.LET);
    } else if (element instanceof PsiExternal) {
      return ORIcons.EXTERNAL;
    } else if (element instanceof PsiVal) {
      return ORIcons.VAL;
    }
    return null;
  }

  public static @NotNull Icon getFileModuleIcon(@NotNull FileBase element) {
    return getFileModuleIcon(
        FileHelper.isOCaml(element.getFileType()), FileHelper.isInterface(element.getFileType()));
  }

  public static @NotNull Icon getFileModuleIcon(boolean isOCaml, boolean isInterface) {
    if (isOCaml) {
      return isInterface ? ORIcons.OCL_FILE_MODULE_INTERFACE : ORIcons.OCL_FILE_MODULE;
    } else {
      return isInterface ? ORIcons.RML_FILE_MODULE_INTERFACE : ORIcons.RML_FILE_MODULE;
    }
  }

  public static @NotNull Icon getFileModuleIcon(@NotNull IndexedFileModule indexedFile) {
    return getFileModuleIcon(indexedFile.isOCaml(), indexedFile.isInterface());
  }

  private boolean isEsyPackageJson(PsiFile element) {
    return element instanceof JsonFile && EsyPackageJson.isEsyPackageJson(element.getVirtualFile());
  }
}


text:
- Added:
  - Support Rails Admin with built-in generator.
  - Required ruby version to be 2.0.0.

- Refactor
  - Convert ActiveAdmin into a generator for easy access to default configuration.


text:
class BaseCrewController < ApplicationController
  before_action :authenticate_user!
  before_action :not_submitter!
  before_action :any_crew!
  after_action :verify_authorized

  private

  def any_crew!
    authorize Conference, :index?
  end
end


text:
package org.apache.maven.plugins.enforcer;

import java.io.File;
import java.io.IOException;

import org.apache.maven.enforcer.rule.api.EnforcerRuleException;

import junit.framework.TestCase;

/**
 * Test the "require files exist" rule.
 *
 * @author Brett Porter
 */
public class TestRequireFilesExist
    extends TestCase
{
    RequireFilesExist rule = new RequireFilesExist();

    public void testFileExists()
        throws EnforcerRuleException, IOException
    {
        File f = File.createTempFile( "enforcer", "tmp" );
        f.deleteOnExit();

        rule.files = new File[] { f };

        rule.execute( EnforcerTestUtils.getHelper() );

        f.delete();
    }

    public void testEmptyFile()
        throws EnforcerRuleException, IOException
    {
        rule.files = new File[] { null };
        try
        {
            rule.execute( EnforcerTestUtils.getHelper() );
            fail( "Should get exception" );
        }
        catch ( EnforcerRuleException e )
        {
            assertTrue( true );
        }
    }

    public void testEmptyFileAllowNull()
        throws EnforcerRuleException, IOException
    {
        rule.files = new File[] { null };
        rule.allowNulls = true;
        try
        {
            rule.execute( EnforcerTestUtils.getHelper() );
        }
        catch ( EnforcerRuleException e )
        {
            fail( "Unexpected Exception:" + e.getLocalizedMessage() );
        }
    }

    public void testEmptyFileList()
        throws EnforcerRuleException, IOException
    {
        rule.files = new File[] {};
        assertEquals(0,rule.files.length);
        try
        {
            rule.execute( EnforcerTestUtils.getHelper() );
            fail( "Should get exception" );
        }
        catch ( EnforcerRuleException e )
        {
            assertTrue( true );
        }
    }

    public void testEmptyFileListAllowNull()
        throws EnforcerRuleException, IOException
    {
        rule.files = new File[] {};
        assertEquals(0,rule.files.length);
        rule.allowNulls = true;
        try
        {
            rule.execute( EnforcerTestUtils.getHelper() );
        }
        catch ( EnforcerRuleException e )
        {
            fail( "Unexpected Exception:" + e.getLocalizedMessage() );
        }
    }

    public void testFileDoesNotExist()
        throws EnforcerRuleException, IOException
    {
        File f = File.createTempFile( "enforcer", "tmp" );
        f.delete();
        assertTrue(!f.exists());
        rule.files = new File[] { f };

        try
        {
            rule.execute( EnforcerTestUtils.getHelper() );
            fail( "Should get exception" );
        }
        catch ( EnforcerRuleException e )
        {
            assertTrue( true );
        }
    }

    /**
     * Test id.
     */
    public void testId()
    {
        rule.getCacheId();
    }

}


text:
exports.defineManualTests = function(rootEl, addButton) {
  addButton('Attach onSuspend', function() {
    chrome.runtime.onSuspend.addListener(function() {
      console.log('onSuspend fired.');
    });
  });

  addButton('chrome.runtime.reload()', function() {
    chrome.runtime.reload();
  });

  addButton('chrome.runtime.getPlatformInfo()', function() {
    chrome.runtime.getPlatformInfo(function(platformInfo) {
      console.log("Platform OS: " + platformInfo.os);
      console.log(JSON.stringify(platformInfo, null, 4));
    });
  });
};

exports.defineAutoTests = function() {
  'use strict';

  require('cordova-plugin-chrome-apps-test-framework.jasmine_helpers').addJasmineHelpers();

  describe("chrome.runtime", function() {
  it('getManifest() should have a name that is a string', function() {
    var manifest = chrome.runtime.getManifest();
    expect(typeof manifest.name).toBe('string'); // .isEqual(jasmine.any(String)) seems to not work
  });
  it('getBackgroundPage() should throw when args are invalid', function() {
    expect(function() {chrome.runtime.getBackgroundPage();}).toThrow();
    expect(function() {chrome.runtime.getBackgroundPage(1);}).toThrow();
  });
  it('getBackgroundPage() should provide a window object asynchronously.', function(done) {
    var bgPage = null;
    chrome.runtime.getBackgroundPage(function(wnd) {
      bgPage = wnd;
      // TODO: implement runningInBackground
      var runningInBackground = false;
      if (runningInBackground) {
        expect(window == bgPage).toBe(true, 'window should == bgPage');
      } else {
        expect(window == bgPage).toBe(false, 'window should != bgPage');
      }
      done();
    });
    expect(bgPage).toBeNull();
  });
  describe('getURL()', function() {
    var prefix;
    beforeEach(function(done) {
      prefix = location.href.replace(/[^\/]*$/, '');
      done();
    });

    it('should throw when args are missing', function() {
      expect(function() {chrome.runtime.getURL();}).toThrow();
    });
    it('should throw when args are invalid', function() {
      expect(function() {chrome.runtime.getURL(3);}).toThrow();
    });
    it('should work for empty path', function() {
      expect(chrome.runtime.getURL('')).toBe(prefix);
    });
    it('should work', function() {
      expect(chrome.runtime.getURL('b')).toBe(prefix + 'b');
    });
    it('should work for root-relative path', function() {
      expect(chrome.runtime.getURL('/b')).toBe(prefix + 'b');
    });
    it('should not change paths that already have the root prefix', function() {
      var fullUrl = location.href;
      expect(chrome.runtime.getURL(fullUrl)).toBe(fullUrl);
    });
  });
  itShouldHaveAnEvent(chrome.runtime, 'onInstalled');
  itShouldHaveAnEvent(chrome.runtime, 'onStartup');
  itShouldHaveAnEvent(chrome.runtime, 'onSuspend');
  itShouldHaveAnEvent(chrome.runtime, 'onSuspendCanceled');
  itShouldHaveAnEvent(chrome.runtime, 'onUpdateAvailable');
  itShouldHaveAPropertyOfType(chrome.runtime, 'id', 'string');
  itShouldHaveAPropertyOfType(chrome.runtime, 'reload', 'function');
  itShouldHaveAPropertyOfType(chrome.runtime, 'requestUpdateCheck', 'function');
  });

  describe('chrome.app.runtime', function() {
    it('should have onLaunched exist', function() {
      expect(chrome.app.runtime.onLaunched).not.toBeUndefined();
    });
  });
};