text:
package com.facebook.react.flat;

import android.graphics.Rect;
import android.os.Build;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.uimanager.PointerEvents;
import com.facebook.react.uimanager.ReactClippingViewGroupHelper;
import com.facebook.react.uimanager.ViewProps;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.views.view.ReactDrawableHelper;

import javax.annotation.Nullable;
import java.util.Map;

/**
 * ViewManager that creates instances of RCTView.
 */
public final class RCTViewManager extends FlatViewManager {

  /* package */ static final String REACT_CLASS = ViewProps.VIEW_CLASS_NAME;

  private static final int[] TMP_INT_ARRAY = new int[2];

  private static final int CMD_HOTSPOT_UPDATE = 1;
  private static final int CMD_SET_PRESSED = 2;

  @Override
  public String getName() {
    return REACT_CLASS;
  }

  public Map<String, Integer> getCommandsMap() {
    return MapBuilder.of("hotspotUpdate", CMD_HOTSPOT_UPDATE, "setPressed", CMD_SET_PRESSED);
  }

  @Override
  public RCTView createShadowNodeInstance() {
    return new RCTView();
  }

  @Override
  public Class<RCTView> getShadowNodeClass() {
    return RCTView.class;
  }

  @ReactProp(name = "nativeBackgroundAndroid")
  public void setHotspot(FlatViewGroup view, @Nullable ReadableMap bg) {
    view.setHotspot(bg == null ?
      null : ReactDrawableHelper.createDrawableFromJSDescription(view.getContext(), bg));
  }

  @Override
  public void receiveCommand(
    FlatViewGroup view,
    int commandId,
    @Nullable ReadableArray args) {
    switch (commandId) {
      case CMD_HOTSPOT_UPDATE: {
        if (args == null || args.size() != 2) {
          throw new JSApplicationIllegalArgumentException(
            "Illegal number of arguments for 'updateHotspot' command");
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
          view.getLocationOnScreen(TMP_INT_ARRAY);
          float x = PixelUtil.toPixelFromDIP(args.getDouble(0)) - TMP_INT_ARRAY[0];
          float y = PixelUtil.toPixelFromDIP(args.getDouble(1)) - TMP_INT_ARRAY[1];
          view.drawableHotspotChanged(x, y);
        }
        break;
      }
      case CMD_SET_PRESSED: {
        if (args == null || args.size() != 1) {
          throw new JSApplicationIllegalArgumentException(
            "Illegal number of arguments for 'setPressed' command");
        }
        view.setPressed(args.getBoolean(0));
        break;
      }
    }
  }

  @ReactProp(name = ViewProps.NEEDS_OFFSCREEN_ALPHA_COMPOSITING)
  public void setNeedsOffscreenAlphaCompositing(
    FlatViewGroup view,
    boolean needsOffscreenAlphaCompositing) {
    view.setNeedsOffscreenAlphaCompositing(needsOffscreenAlphaCompositing);
  }

  @ReactProp(name = "pointerEvents")
  public void setPointerEvents(FlatViewGroup view, @Nullable String pointerEventsStr) {
    view.setPointerEvents(parsePointerEvents(pointerEventsStr));
  }

  @ReactProp(name = ReactClippingViewGroupHelper.PROP_REMOVE_CLIPPED_SUBVIEWS)
  public void setRemoveClippedSubviews(FlatViewGroup view, boolean removeClippedSubviews) {
    view.setRemoveClippedSubviews(removeClippedSubviews);
  }

  private static PointerEvents parsePointerEvents(@Nullable String pointerEventsStr) {
    if (pointerEventsStr != null) {
      switch (pointerEventsStr) {
        case "none":
          return PointerEvents.NONE;
        case "auto":
          return PointerEvents.AUTO;
        case "box-none":
          return PointerEvents.BOX_NONE;
        case "box-only":
          return PointerEvents.BOX_ONLY;
      }
    }
    // default or invalid
    return PointerEvents.AUTO;
  }

  @ReactProp(name = "hitSlop")
  public void setHitSlop(FlatViewGroup view, @Nullable ReadableMap hitSlop) {
    if (hitSlop == null) {
      view.setHitSlopRect(null);
    } else {
      view.setHitSlopRect(new Rect(
        (int) PixelUtil.toPixelFromDIP(hitSlop.getDouble("left")),
        (int) PixelUtil.toPixelFromDIP(hitSlop.getDouble("top")),
        (int) PixelUtil.toPixelFromDIP(hitSlop.getDouble("right")),
        (int) PixelUtil.toPixelFromDIP(hitSlop.getDouble("bottom"))
      ));
    }
  }
}


text:
<?php

use PHRETS\Capabilities;

class CapabilitiesTest extends PHPUnit_Framework_TestCase {

    /** @test **/
    public function it_tracks()
    {
        $cpb = new Capabilities;
        $cpb->add('login', 'http://www.reso.org/login');

        $this->assertNotNull($cpb->get('login'));
        $this->assertNull($cpb->get('test'));
    }

    /** @test **/
    public function it_barfs_when_not_given_enough_information_to_build_absolute_urls()
    {
        $this->setExpectedException('InvalidArgumentException');
        $cpb = new Capabilities;
        $cpb->add('Login', '/rets/Login');
    }

    /** @test **/
    public function it_can_build_absolute_urls_from_relative_ones()
    {
        $cpb = new Capabilities;
        $cpb->add('Login', 'http://www.google.com/login');

        $cpb->add('Search', '/search');
        $this->assertSame('http://www.google.com:80/search', $cpb->get('Search'));
    }

    /** @test **/
    public function it_preserves_explicity_ports()
    {
        $cpb = new Capabilities;
        $cpb->add('Login', 'http://www.google.com:8080/login');

        $cpb->add('Search', '/search');
        $this->assertSame('http://www.google.com:8080/search', $cpb->get('Search'));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.flink.graph.scala

import org.apache.flink.api.java.tuple.Tuple3
import org.apache.flink.graph.{Edge, Vertex}
import org.apache.flink.util.Collector

abstract class NeighborsFunction[K, VV, EV, T]
  extends org.apache.flink.graph.NeighborsFunction[K, VV, EV, T] {

  def iterateNeighbors(neighbors: Iterable[(K, Edge[K, EV], Vertex[K, VV])], out: Collector[T])

  override def iterateNeighbors(
      neighbors: java.lang.Iterable[Tuple3[K, Edge[K, EV], Vertex[K, VV]]],
      out: Collector[T]) = {
    val scalaIterable = scala.collection.JavaConversions
      .iterableAsScalaIterable(neighbors)
      .map(jtuple => (jtuple.f0, jtuple.f1, jtuple.f2))
    iterateNeighbors(scalaIterable, out)
  }
}


text:
import test from 'ava';
import { isImmutable } from '@collectable/core';
import { HashSetStructure, fromArray, has, intersect, size } from '../../src';
import { snapshot } from '../test-utils';

const mainValues = ['A', 'B', 'C', 'D', 'E'];
const otherValues = ['D', 'E', 'F', 'G'];
const expectedValues = ['D', 'E'];

let main: HashSetStructure<string>, mainSnapshot: object, result: HashSetStructure<string>;
let other: HashSetStructure<string>, otherSnapshot: object;

test.before(() => {
  other = fromArray(otherValues);
  otherSnapshot = snapshot(other);
  main = fromArray(mainValues);
  mainSnapshot = snapshot(main);
  result = intersect(other, main);
});

test('a new immutable set is returned', t => {
  t.not(result, main);
  t.true(isImmutable(result));
});

test('the main input set is not modified', t => {
  t.deepEqual(snapshot(main), mainSnapshot);
});

test('the other input set is not modified', t => {
  t.deepEqual(snapshot(other), otherSnapshot);
});

test('the new set excludes items that are unique to the other input', t => {
  t.false(has('A', result));
  t.false(has('B', result));
  t.false(has('C', result));
});

test('the new set excludes items that are unique to the main input', t => {
  t.true(has('D', result));
  t.true(has('E', result));
});

test('the new set includes items that are common to both inputs', t => {
  t.deepEqual(Array.from(result).sort(), expectedValues);
});

test('the size of the new set is equal to the total number of items that are common to both inputs', t => {
  t.is(size(result), expectedValues.length);
});


text:
// Copyright Abel Sinkovics (abel@sinkovics.hu)  2014.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#include <boost/metaparse/repeated.hpp>
#include <boost/metaparse/sequence.hpp>
#include <boost/metaparse/lit_c.hpp>
#include <boost/metaparse/last_of.hpp>
#include <boost/metaparse/first_of.hpp>
#include <boost/metaparse/middle_of.hpp>
#include <boost/metaparse/space.hpp>
#include <boost/metaparse/int_.hpp>
#include <boost/metaparse/foldl_reject_incomplete_start_with_parser.hpp>
#include <boost/metaparse/one_of.hpp>
#include <boost/metaparse/get_result.hpp>
#include <boost/metaparse/token.hpp>
#include <boost/metaparse/entire_input.hpp>
#include <boost/metaparse/string.hpp>
#include <boost/metaparse/build_parser.hpp>

#include <boost/mpl/apply_wrap.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/back.hpp>
#include <boost/mpl/plus.hpp>
#include <boost/mpl/minus.hpp>
#include <boost/mpl/times.hpp>
#include <boost/mpl/divides.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/bool.hpp>

using boost::metaparse::sequence;
using boost::metaparse::lit_c;
using boost::metaparse::last_of;
using boost::metaparse::first_of;
using boost::metaparse::middle_of;
using boost::metaparse::space;
using boost::metaparse::repeated;
using boost::metaparse::build_parser;
using boost::metaparse::int_;
using boost::metaparse::foldl_reject_incomplete_start_with_parser;
using boost::metaparse::get_result;
using boost::metaparse::one_of;
using boost::metaparse::token;
using boost::metaparse::entire_input;

using boost::mpl::apply_wrap1;
using boost::mpl::fold;
using boost::mpl::front;
using boost::mpl::back;
using boost::mpl::plus;
using boost::mpl::minus;
using boost::mpl::times;
using boost::mpl::divides;
using boost::mpl::eval_if;
using boost::mpl::bool_;
using boost::mpl::equal_to;
using boost::mpl::bool_;

/*
 * The grammar
 *
 * expression ::= plus_exp
 * plus_exp ::= prod_exp ((plus_token | minus_token) prod_exp)*
 * prod_exp ::= int_token ((mult_token | div_token) simple_exp)*
 * simple_exp ::= int_token | paren_exp
 * paren_exp ::= open_paren_token expression close_paren_token
 */

typedef token<lit_c<'+'> > plus_token;
typedef token<lit_c<'-'> > minus_token;
typedef token<lit_c<'*'> > mult_token;
typedef token<lit_c<'/'> > div_token;

typedef token<lit_c<'('> > open_paren_token;
typedef token<lit_c<')'> > close_paren_token;

typedef token<int_> int_token;

template <class T, char C>
struct is_c : bool_<T::type::value == C> {};

struct eval_plus
{
  template <class State, class C>
  struct apply :
    eval_if<
      is_c<front<C>, '+'>,
      plus<typename State::type, typename back<C>::type>,
      minus<typename State::type, typename back<C>::type>
    >
  {};
};

struct eval_mult
{
  template <class State, class C>
  struct apply :
    eval_if<
      is_c<front<C>, '*'>,
      times<typename State::type, typename back<C>::type>,
      divides<typename State::type, typename back<C>::type>
    >
  {};
};

struct plus_exp;

typedef middle_of<open_paren_token, plus_exp, close_paren_token> paren_exp;

typedef one_of<int_token, paren_exp> simple_exp;

typedef
  foldl_reject_incomplete_start_with_parser<
    sequence<one_of<mult_token, div_token>, simple_exp>,
    simple_exp,
    eval_mult
  >
  prod_exp;

struct plus_exp :
  foldl_reject_incomplete_start_with_parser<
    sequence<one_of<plus_token, minus_token>, prod_exp>,
    prod_exp,
    eval_plus
  >
{};

typedef last_of<repeated<space>, plus_exp> expression;

typedef build_parser<entire_input<expression> > calculator_parser;

#ifdef _STR
#  error _STR already defined
#endif
#define _STR BOOST_METAPARSE_STRING

#ifdef BOOST_NO_CXX11_CONSTEXPR
int main()
{
  std::cout << "Please use a compiler that support constexpr" << std::endl;
}
#else
int main()
{
  using std::cout;
  using std::endl;

  cout
    << apply_wrap1<calculator_parser, _STR("13")>::type::value << endl
    << apply_wrap1<calculator_parser, _STR(" 1+ 2*4-6/2")>::type::value << endl
    << apply_wrap1<calculator_parser, _STR("1+2*3+4")>::type::value << endl
    << apply_wrap1<calculator_parser, _STR("(1+2)*(3+4)")>::type::value << endl
    << apply_wrap1<calculator_parser, _STR("(2*3)+(4*5)")>::type::value << endl
    << apply_wrap1<calculator_parser, _STR("2 * 3 + 4")>::type::value << endl
    << apply_wrap1<calculator_parser, _STR("2 + (3 * 4)")>::type::value << endl
    ;
}
#endif


text:
[![Build Status](https://travis-ci.org/JuliaRandom/VSL.jl.svg?branch=master)](https://travis-ci.org/sunoru/VSL.jl)
[![codecov](https://codecov.io/gh/JuliaRandom/VSL.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/sunoru/VSL.jl)

This package provides bindings to the Intel Vector Statistics Library.

## Using VSL.jl

You must have the [Intel® Math Kernel Library](http://software.intel.com/en-us/intel-mkl) installed to use VSL.jl, and
the shared library must be in a directory known to the linker.

VML.jl provides several basic random number generators (BRNGs) and distributions, and each distribution has at least
one method to generate random number. After VSL.jl loaded, you can use the distributions such like the followings:

```julia
julia> using VSL

julia> brng = BasicRandomNumberGenerator(VSL_BRNG_MT19937, 12345);
# A BRNG created, in which 12345 is the random seed.

julia> u = Uniform(brng, 0.0, 1.0); # Create a uniform distribution between 0.0 and 1.0.

julia> rand(u) # Generate one random number.
0.41661986871622503

julia> rand(u, 2, 3) # Generate an random 2*3 array.
2×3 Array{Float64,2}:
 0.732685   0.820175  0.802848
 0.0101692  0.825207  0.29864

julia> A = Array{Float64}(3, 4);

julia> rand!(u, A) # Fill an array with random numbers.
3×4 Array{Float64,2}:
 0.855138  0.193661  0.436228  0.124267
 0.368412  0.270245  0.161688  0.874174
 0.931785  0.566008  0.373064  0.432936
```

### Basic random number generators

Use the Enum `BRNGType` to set the type of BRNG.

| BRNGType Enum |
| ------------------------ |
| `VSL_BRNG_MCG31` |
| `VSL_BRNG_R250` |
| `VSL_BRNG_MRG32K3A` |
| `VSL_BRNG_MCG59` |
| `VSL_BRNG_WH` |
| `VSL_BRNG_SOBOL` |
| `VSL_BRNG_NIEDERR` |
| `VSL_BRNG_MT19937` |
| `VSL_BRNG_MT2203` |
| `VSL_BRNG_SFMT19937` |
| `VSL_BRNG_NONDETERM` |
| `VSL_BRNG_ARS5` |
| `VSL_BRNG_PHILOX4X32X10` |

### Supported distributions

Contigurous: `Uniform`, `Gaussian`, `GaussianMV`, `Exponential`, `Laplace`,
    `Weibull`, `Cauchy`, `Rayleigh`, `Lognormal`, `Gumbel`, `Gamma`, `Beta`

Discrete: `UniformDiscrete`, `UniformBits`, `UniformBits32`, `UniformBits64`, `Bernoulli`,
    `Geometric`, `Binomial`, `Hypergeometric`, `Poisson`, `PoissonV`, `NegBinomial`

### Notes

Most of the discrete distributions return values of 32-bit integer. Please be careful when using those distributions.

For more information, please refer to the
[Intel® Math Kernel Library Developer Reference](https://software.intel.com/en-us/articles/mkl-reference-manual)

## License

[MIT license](https://JuliaRandom.mit-license.org)


text:
Data type precedence: conversion NVARCHAR(n)
--SKIPIF--
--FILE--
<?php

require_once("autonomous_setup.php");

// Connect
$connectionInfo = array("UID"=>$username, "PWD"=>$password, "CharacterSet"=>"UTF-8");
$conn = sqlsrv_connect($serverName, $connectionInfo) ?: die();

// Create database
sqlsrv_query($conn,"CREATE DATABASE ". $dbName) ?: die();

// Create table. Column names: passport
$sql = "CREATE TABLE $tableName (c1 NVARCHAR(8))";
$stmt = sqlsrv_query($conn, $sql);

// Insert data. The data type with the lower precedence
// is converted to the data type with the higher precedence
$sql = "INSERT INTO $tableName VALUES (3.1415),(-32),(null)";
$stmt = sqlsrv_query($conn, $sql);

// Insert more data
$sql = "INSERT INTO $tableName VALUES (''),('Galaxy'),('-- GO'),(N'银河系')";
$stmt = sqlsrv_query($conn, $sql);

// Read data from the table
$sql = "SELECT * FROM $tableName";
$stmt = sqlsrv_query($conn, $sql);

while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)) {
	var_dump($row[0]);
}

// DROP database
sqlsrv_query($conn,"DROP DATABASE ". $dbName);

// Free statement and connection resources
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);

print "Done"
?>

--EXPECT--
string(6) "3.1415"
string(8) "-32.0000"
NULL
string(0) ""
string(6) "Galaxy"
string(5) "-- GO"
string(9) "银河系"
Done


text:
using MovieMeter.Model.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MovieMeter.Model;
using MovieMeter.Repository.Contracts;

namespace MovieMeter.Service
{
    public class MovieMeterService : IMovieMeterService
    {
        public MovieMeterService(IMovieMeterRepository repository, IProgramProvider provider)
        {
            if(repository == null)
                throw new ArgumentNullException(nameof(repository));
            if(provider == null)
                throw new ArgumentNullException(nameof(provider));

            Repository = repository;
            ProgramProvider = provider;
        }

        public IMovieMeterRepository Repository { get; private set; }
        public IProgramProvider ProgramProvider { get; private set; }

        public async Task CreateUpdate(string sourceId)
        {
            var source = await Repository.GetSource(sourceId);
            Update newUpdate = new Update()
            {
                UpdatedOn = DateTime.Now
            };
            var programs = await ProgramProvider.GetPrograms(source.ParserId);
            await Repository.AddUpdate(newUpdate, programs, sourceId);

        }

        public async Task<int> GetActiveProgramCount()
        {
            var count = await Repository.GetActiveProgramCount();
            return count;
        }

        public async Task<List<Program>> GetAllPrograms(ProgramQuery query, int count)
        {
            var programs = await Repository.GetAllPrograms(query, count);
            return programs;
        }

        public async Task<List<Source>> GetAllSources()
        {
            return await Repository.GetAllSources();
        }

        public async Task<List<Update>> GetAllUpdates()
        {
            return await Repository.GetAllUpdates();
        }

        public async Task<Update> GetLatestUpdateForSource(string sourceId)
        {
            return await Repository.GetLatestUpdateForSource(sourceId);
        }

        public async Task<Program> GetProgram(string programId)
        {
            return await Repository.GetProgram(programId);
        }

        public async Task<Source> GetSource(string sourceId)
        {
            return await Repository.GetSource(sourceId);
        }

        public async Task<List<Update>> GetUpdatesForSource(string sourceId)
        {
            return await Repository.GetUpdatesForSource(sourceId);
        }

        public async Task HarvestMovieData()
        {
            var programs = await ProgramProvider.GetPrograms(-1);

        }

        public Task UpdateProgram(Program program)
        {
            throw new NotImplementedException();
        }
    }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Forum */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'locked')->dropDownList([ '0', '1', ], ['prompt' => '']) ?>

    <?= $form->field($model, 'category_id')->textInput() ?>

    <?= $form->field($model, 'position')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
"""Tests for TF-GAN internal inception_metrics."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
from absl.testing import parameterized
import tensorflow as tf
import tensorflow_gan as tfgan

mock = tf.compat.v1.test.mock

class FakeInceptionModule(tf.Module):

  @tf.function(input_signature=[tf.TensorSpec(shape=None, dtype=tf.float32)])
  def __call__(self, x):
    bs = tf.shape(x)[0]
    logits = tf.zeros([bs, 1008])
    pool_3 = tf.ones([bs, 2048])
    return {'logits': logits, 'pool_3': pool_3}

class RunInceptionTest(tf.test.TestCase, parameterized.TestCase):

  def setUp(self):
    super(RunInceptionTest, self).setUp()
    self.export_path = os.path.join(self.get_temp_dir(), 'my-module')
    tf.saved_model.save(FakeInceptionModule(), self.export_path)
    classifier_fn = tfgan.eval.classifier_fn_from_tfhub(
        self.export_path, None)
    def run_inception(*args, **kwargs):
      return tfgan.eval.run_inception(
          *args, classifier_fn=classifier_fn, **kwargs)
    self.run_inception = run_inception

  @parameterized.parameters(
      {'num_batches': 1},
      {'num_batches': 4},
  )
  def test_run_inception_graph(self, num_batches):
    """Test `run_inception` graph construction."""
    batch_size = 8
    img = tf.ones([batch_size, 299, 299, 3])

    results = self.run_inception(img, num_batches=num_batches)

    self.assertIsInstance(results, dict)
    self.assertLen(results, 2)

    self.assertIn('logits', results)
    logits = results['logits']
    self.assertIsInstance(logits, tf.Tensor)
    logits.shape.assert_is_compatible_with([batch_size, 1008])

    self.assertIn('pool_3', results)
    pool = results['pool_3']
    self.assertIsInstance(pool, tf.Tensor)
    pool.shape.assert_is_compatible_with([batch_size, 2048])

    # Check that none of the model variables are trainable.
    self.assertListEqual([], tf.compat.v1.trainable_variables())

  def test_run_inception_multicall(self):
    """Test that `run_inception` can be called multiple times."""
    for batch_size in (7, 3, 2):
      img = tf.ones([batch_size, 299, 299, 3])
      self.run_inception(img)

class SampleAndRunInception(tf.test.TestCase, parameterized.TestCase):

  def setUp(self):
    super(SampleAndRunInception, self).setUp()
    self.export_path = os.path.join(self.get_temp_dir(), 'my-module')
    tf.saved_model.save(FakeInceptionModule(), self.export_path)
    classifier_fn = tfgan.eval.classifier_fn_from_tfhub(self.export_path, None)
    def sample_and_run_inception(*args, **kwargs):
      return tfgan.eval.sample_and_run_inception(
          *args, classifier_fn=classifier_fn, **kwargs)
    self.sample_and_run_inception = sample_and_run_inception

  @parameterized.parameters(
      {'num_batches': 1},
      {'num_batches': 4},
  )
  def test_sample_and_run_inception_graph(self, num_batches):
    """Test `sample_and_run_inception` graph construction."""
    batch_size = 8
    def sample_fn(_):
      return tf.ones([batch_size, 244, 244, 3])
    sample_inputs = [1] * num_batches

    results = self.sample_and_run_inception(sample_fn, sample_inputs)

    self.assertIsInstance(results, dict)
    self.assertLen(results, 2)

    self.assertIn('logits', results)
    logits = results['logits']
    self.assertIsInstance(logits, tf.Tensor)
    logits.shape.assert_is_compatible_with([batch_size * num_batches, 1008])

    self.assertIn('pool_3', results)
    pool = results['pool_3']
    self.assertIsInstance(pool, tf.Tensor)
    pool.shape.assert_is_compatible_with([batch_size * num_batches, 2048])

    # Check that none of the model variables are trainable.
    self.assertListEqual([], tf.compat.v1.trainable_variables())

class InceptionScore(tf.test.TestCase, parameterized.TestCase):

  def setUp(self):
    super(InceptionScore, self).setUp()
    self.export_path = os.path.join(self.get_temp_dir(), 'my-module')
    tf.saved_model.save(FakeInceptionModule(), self.export_path)
    classifier_fn = tfgan.eval.classifier_fn_from_tfhub(
        self.export_path, tfgan.eval.INCEPTION_OUTPUT, True)

    def inception_score(*args, **kwargs):
      return tfgan.eval.inception_score(
          *args, classifier_fn=classifier_fn, **kwargs)
    self.inception_score = inception_score

    def inception_score_streaming(*args, **kwargs):
      return tfgan.eval.inception_score_streaming(
          *args, classifier_fn=classifier_fn, **kwargs)
    self.inception_score_streaming = inception_score_streaming

  @parameterized.parameters(
      {'num_batches': 1, 'streaming': True},
      {'num_batches': 1, 'streaming': False},
      {'num_batches': 3, 'streaming': True},
      {'num_batches': 3, 'streaming': False},
  )
  def test_inception_score_graph(self, num_batches, streaming):
    """Test `inception_score` graph construction."""
    if streaming and tf.executing_eagerly():
      # streaming doesn't work in eager execution.
      return
    img = tf.zeros([6, 299, 299, 3])
    if streaming:
      score, update_op = self.inception_score_streaming(
          img, num_batches=num_batches)
      self.assertIsInstance(update_op, tf.Tensor)
      update_op.shape.assert_has_rank(0)
    else:
      score = self.inception_score(img, num_batches=num_batches)

    self.assertIsInstance(score, tf.Tensor)
    score.shape.assert_has_rank(0)

    # Check that none of the model variables are trainable.
    self.assertEmpty(tf.compat.v1.trainable_variables())

class FrechetInceptionDistance(tf.test.TestCase, parameterized.TestCase):

  def setUp(self):
    super(FrechetInceptionDistance, self).setUp()
    self.export_path = os.path.join(self.get_temp_dir(), 'my-module')
    tf.saved_model.save(FakeInceptionModule(), self.export_path)
    classifier_fn = tfgan.eval.classifier_fn_from_tfhub(
        self.export_path, tfgan.eval.INCEPTION_FINAL_POOL, True)

    def frechet_inception_distance(*args, **kwargs):
      return tfgan.eval.frechet_inception_distance(
          *args, classifier_fn=classifier_fn, **kwargs)
    self.frechet_inception_distance = frechet_inception_distance

    def fid_streaming(*args, **kwargs):
      return tfgan.eval.frechet_inception_distance_streaming(
          *args, classifier_fn=classifier_fn, **kwargs)
    self.frechet_inception_distance_streaming = fid_streaming

  @parameterized.parameters(
      {'num_batches': 1, 'streaming': True},
      {'num_batches': 1, 'streaming': False},
      {'num_batches': 3, 'streaming': True},
      {'num_batches': 3, 'streaming': False},
  )
  def test_frechet_inception_distance_graph(self, num_batches, streaming):
    """Test `frechet_inception_distance` graph construction."""
    if streaming and tf.executing_eagerly():
      # streaming doesn't work in eager execution.
      return
    img = tf.ones([6, 299, 299, 3])

    if streaming:
      distance, update_op = self.frechet_inception_distance_streaming(
          img, img, num_batches=num_batches)
      self.assertIsInstance(update_op, tf.Tensor)
      update_op.shape.assert_has_rank(0)
    else:
      distance = self.frechet_inception_distance(
          img, img, num_batches=num_batches)

    self.assertIsInstance(distance, tf.Tensor)
    distance.shape.assert_has_rank(0)

    # Check that none of the model variables are trainable.
    self.assertEmpty(tf.compat.v1.trainable_variables())

if __name__ == '__main__':
  tf.test.main()


text:
Message

      <form class="col s12">

          <textarea ng-model="content" id="content" type="text" class="materialize-textarea"></textarea>
            Message

      </form>

    Send
    Cancel


text:
package com.github.monkey.analyzer.statistics;

import com.github.monkey.analyzer.model.Abnormality;

/**
 * This is an adapter Object of CRASH abnormality which split the abnormality
 * message.

 *

 * The code lines of a CRASH abnormality is chosen as the main key of an
 * abnormality.
 *
 * @author Alex Chen (apack1001@gmail.com)
 *
 */
public class CrashAbnormalityAdapter {
	/**
	 * a brief of Crash Abnormality
	 */
	private String shortMessage = null;
	/**
	 * code lines of a Crash Abnormality
	 */
	private String codeLines = null;

	/**
	 * instantiate from an abnormality
	 *
	 * @param abnormality
	 *            instance of an abnormality
	 */
	public CrashAbnormalityAdapter(final Abnormality abnormality) {
		final String rawMessage = abnormality.getMessage();
		String[] messages = rawMessage.split("\\n");
		if (messages == null || messages.length == 0)
			throw new RuntimeException();

		StringBuilder lines = new StringBuilder();
		for (String message : messages) {
			if (message.contains("Short Msg:"))
				setShortMessage(message.substring(14));
			else if (message.contains("at")) {
				lines.append(message);
				lines.append("\n");
			}

			setCodeLines(lines.toString());
		}
	}

	public void setShortMessage(final String shortMessage) {
		this.shortMessage = shortMessage;
	}

	public void setCodeLines(final String codeLines) {
		this.codeLines = codeLines;
	}

	public String getShortMessage() {
		return shortMessage;
	}

	public String getCodeLines() {
		return codeLines;
	}
}


text:
class SchoolsController < ApplicationController
  def index
    @msg = 'School data'
    @data = School.all
  end

  def show
    @school = School.find(params[:id])
    @characters = Character.where school_id: params[:id]
  end
end


text:
package email_test

import (
	. "github.com/hyperboloide/users/email"
	"github.com/hyperboloide/users/user/mock"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

type testTemplateBuilder struct{}

func (t testTemplateBuilder) Text(template, lang string, data interface{}) ([]byte, error) {
	return []byte("text"), nil
}

func (t testTemplateBuilder) HTML(template, lang string, data interface{}) ([]byte, error) {
	return []byte("html"), nil
}

type testMailer struct {
	dest    string
	subject string
	text    []byte
	html    []byte
}

func (t *testMailer) Send(dest string, subject string, text []byte, html []byte) error {
	t.dest = dest
	t.subject = subject
	t.text = text
	t.html = html
	return nil
}

var _ = Describe("Mailer", func() {

	It("should test mailer", func() {
		mailer := &testMailer{}
		DefaultMailer = mailer
		DefaultTemplateBuilder = testTemplateBuilder{}

		user := mock.Generate()

		msg := &Message{
			user,
			"the subject",
			"test_template",
			nil,
		}
		Ω(msg.Send()).To(BeNil())

		Ω(mailer.dest).To(Equal(user.GetEmail()))
		Ω(mailer.subject).To(Equal("the subject"))
		Ω(mailer.text).To(Equal([]byte("text")))
		Ω(mailer.html).To(Equal([]byte("html")))
	})

})


text:
"""Sanity tests for training a model."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import json
import tempfile

from absl import flags
from absl.testing import absltest  # pylint: disable=g-bad-import-order
from absl.testing import parameterized
import numpy as np
import tensorflow as tf
import xarray

from pde_superresolution import duckarray  # pylint: disable=g-bad-import-order
from pde_superresolution import equations  # pylint: disable=g-bad-import-order
from pde_superresolution import integrate  # pylint: disable=g-bad-import-order
from pde_superresolution import training  # pylint: disable=g-bad-import-order
from pde_superresolution import weno  # pylint: disable=g-bad-import-order

FLAGS = flags.FLAGS

NUM_X_POINTS = 256
RANDOM_SEED = 0

class IntegrateTest(parameterized.TestCase):

  def setUp(self):
    self.checkpoint_dir = tempfile.mkdtemp(dir=FLAGS.test_tmpdir)
    self.model_kwargs = dict(num_layers=1, filter_size=32)

  def train(self, hparams):
    # train a model on random noise
    with tf.Graph().as_default():
      snapshots = 0.01 * np.random.RandomState(0).randn(100, NUM_X_POINTS)
      training.training_loop(snapshots, self.checkpoint_dir, hparams)

  @parameterized.parameters(
      dict(equation='burgers'),
      dict(equation='kdv'),
      dict(equation='ks'),
      dict(equation='burgers', conservative=True),
      dict(equation='kdv', conservative=True),
      dict(equation='ks', conservative=True),
      dict(equation='burgers', conservative=True, numerical_flux=True),
      dict(equation='kdv', conservative=True, numerical_flux=True),
      dict(equation='ks', conservative=True, numerical_flux=True),
      dict(equation='burgers', warmup=1),
      dict(equation='burgers', warmup=1, conservative=True),
      dict(equation='kdv', warmup=1, conservative=True),
      dict(equation='kdv', warmup=1, conservative=True,
           exact_filter_interval=1),
  )
  def test_integrate_exact_baseline_and_model(
      self, warmup=0, conservative=False, resample_factor=4,
      exact_filter_interval=None, **hparam_values):
    hparams = training.create_hparams(
        learning_rates=[1e-3],
        learning_stops=[20],
        eval_interval=10,
        equation_kwargs=json.dumps({'num_points': NUM_X_POINTS}),
        conservative=conservative,
        resample_factor=resample_factor,
        **hparam_values)
    self.train(hparams)

    results = integrate.integrate_exact_baseline_and_model(
        self.checkpoint_dir,
        random_seed=RANDOM_SEED,
        times=np.linspace(0, 1, num=11),
        warmup=warmup,
        exact_filter_interval=exact_filter_interval)

    self.assertIsInstance(results, xarray.Dataset)
    self.assertEqual(dict(results.dims),
                     {'time': 11,
                      'x_high': NUM_X_POINTS,
                      'x_low': NUM_X_POINTS // resample_factor})
    self.assertEqual(results['y_exact'].dims, ('time', 'x_high'))
    self.assertEqual(results['y_baseline'].dims, ('time', 'x_low'))
    self.assertEqual(results['y_model'].dims, ('time', 'x_low'))

    with self.subTest('average should be zero'):
      y_exact_mean = results.y_exact.mean('x_high')
      xarray.testing.assert_allclose(
          y_exact_mean, xarray.zeros_like(y_exact_mean), atol=1e-3)

    with self.subTest('matching initial conditions'):
      if conservative:
        resample = duckarray.resample_mean
      else:
        resample = duckarray.subsample
      y_exact = resample(results.y_exact.isel(time=0).values,
                         resample_factor)
      np.testing.assert_allclose(
          y_exact, results.y_baseline.isel(time=0).values)
      np.testing.assert_allclose(
          y_exact, results.y_model.isel(time=0).values)

    with self.subTest('matches integrate_baseline'):
      equation_type = equations.equation_type_from_hparams(hparams)
      assert equation_type.CONSERVATIVE == conservative
      equation = equation_type(NUM_X_POINTS//resample_factor,
                               resample_factor=resample_factor,
                               random_seed=RANDOM_SEED)
      results2 = integrate.integrate_baseline(
          equation, times=np.linspace(0, 1, num=11), warmup=warmup)
      np.testing.assert_allclose(
          results['y_baseline'].data, results2['y'].data, atol=1e-5)

  @parameterized.parameters(
      dict(equation=equations.BurgersEquation(200)),
      dict(equation=equations.KdVEquation(200)),
      dict(equation=equations.KSEquation(200), warmup=50.0),
  )
  def test_integrate_exact(self, equation, **kwargs):
    results = integrate.integrate_exact(
        equation, times=np.linspace(0, 1, num=11), **kwargs)
    self.assertIsInstance(results, xarray.Dataset)
    self.assertEqual(dict(results.dims), {'time': 11, 'x': 200})
    self.assertEqual(results['y'].dims, ('time', 'x'))

    with self.subTest('average should be zero'):
      y_mean = results.y.mean('x')
      xarray.testing.assert_allclose(
          y_mean, xarray.zeros_like(y_mean), atol=1e-3)

  def test_burgers_exact_weno(self):
    equation = equations.BurgersEquation(200)
    results_exact = integrate.integrate_exact(
        equation, times=np.linspace(0, 1, num=11))

    equation = equations.GodunovBurgersEquation(200)
    results_weno = integrate.integrate_weno(
        equation, times=np.linspace(0, 1, num=11))
    np.testing.assert_allclose(
        results_exact['y'].data, results_weno['y'].data, atol=1e-10)

  @parameterized.parameters(
      dict(equation=equations.KdVEquation(200)),
      dict(equation=equations.KSEquation(200)),
  )
  def test_spectral_exact(self, equation):
    results_exact = integrate.integrate_exact(
        equation, times=np.linspace(0, 1, num=11))
    results_spectra = integrate.integrate_spectral(
        equation, times=np.linspace(0, 1, num=11))
    np.testing.assert_allclose(
        results_exact['y'].data, results_spectra['y'].data, atol=1e-10)

  @parameterized.parameters(
      dict(equation=equations.BurgersEquation(200)),
      dict(equation=equations.ConservativeBurgersEquation(200)),
      dict(equation=equations.KdVEquation(200)),
      dict(equation=equations.KSEquation(200), warmup=50.0),
  )
  def test_integrate_baseline(self, equation, **kwargs):
    results = integrate.integrate_baseline(
        equation, times=np.linspace(0, 1, num=11), **kwargs)
    self.assertIsInstance(results, xarray.Dataset)
    self.assertEqual(dict(results.dims), {'time': 11, 'x': 200})
    self.assertEqual(results['y'].dims, ('time', 'x'))

    # average value should remain near 0
    y_mean = results.y.mean('x')
    xarray.testing.assert_allclose(
        y_mean, xarray.zeros_like(y_mean), atol=1e-3)

  @parameterized.parameters(
      dict(equation=equations.GodunovBurgersEquation(200)),
      dict(equation=equations.GodunovKdVEquation(200), tol=5e-3),
      dict(equation=equations.GodunovKSEquation(200)),
  )
  def test_integrate_baseline_and_weno_consistency(self, equation, tol=1e-3):
    times = np.linspace(0, 1, num=11)
    results_baseline = integrate.integrate_baseline(equation, times=times)
    results_weno = integrate.integrate_weno(equation, times=times)
    xarray.testing.assert_allclose(
        results_baseline.drop('num_evals'), results_weno.drop('num_evals'),
        rtol=tol, atol=tol)

if __name__ == '__main__':
  absltest.main()


text:
<!doctype html>

    <title>a brand new styleguide: Headers and Footers</title>

DysonSphere Styleguide

Github

            Fancy Form Fields

            Headers and Footers

            Layout and Formatting

            Page Sections

            Buttons

            Colors

            Typography

            Misc

            Slick Carousel

            Mixins

Normal Header with Dropdowns

Fixed Headers

Header w/ Search Bar

Footer

Normal Header with Dropdowns

        normal header w/ dropdowns

.contain-to-grid.full-top-bar
  %nav.top-bar( data-topbar role="navigation")
    %ul.title-area
      %li.name
        %img.logo(src="dyson_sphere/launch-logo.png")
        %h1
          %a
            Launch
            %strong Academy
      %li.toggle-topbar.menu-icon
        %a(href="#")
          %span

    %section.top-bar-section
      %ul.left
        %li.has-dropdown
          %a.menu-item Admin
          %ul.dropdown
            %li
              %a Users
            %li
              %a Users

      %ul.right
        %li
          %a Github
        %li.has-dropdown
          %a.menu-item Account Details
          %ul.dropdown
            %li
              %a Profile
            %li
              %a Sign Out

            Launch
            Academy

          Admin

              Users

              Users

          Github

          Account Details

              Profile

              Sign Out

Fixed Headers

        header

.sticky
  %nav.top-bar(data-topbar role="navigation" data-options="sticky_on: [small, medium, large]")
    %ul.plm.title-area
      %li.name
        %img.logo(src="dyson_sphere/launch-logo.png")
        %h1
          %a
            Launch
            %strong Academy
      %li.toggle-topbar.menu-icon
        %a(href="#")
          %span

    %section.top-bar-section
      %ul.left
        %li
          %a.menu-item Admin
        %li.menu-item
          %a.menu-item Sign Out

      %ul.right
        %li
          %a Learn on Campus
        %li
          %a Learn Online
        %li
          %a.btn-pink.cta Apply

            Launch
            Academy

          Admin

          Sign Out

          Learn on Campus

          Learn Online

          Apply

By default, fixed headers will be `$la-blue` no matter where you are on the page.

To make your header transparent when at the top of the page, on a particular page,
add the class `.has-transparent-header` to some later element on the page. (I recommend
the first element of the page, such as the hero image or video.)

Header w/ Search Bar

        header w/ search bar

.contain-to-grid.full-top-bar
  %nav.top-bar( data-topbar role="navigation")
    %ul.title-area
      %li.name
        %img.logo(src="dyson_sphere/launch-logo.png")
        %h1
          %a
            Launch
            %strong Academy
      %li.toggle-topbar.menu-icon
        %a(href="#")
          %span

    %section.top-bar-section
      %ul.left
        %li.has-form
          .row.collapse.search
            %form
              %input.left(id="query" name="query" placeholder="Search" type="text")
              %button.search-button(name="button" type="submit")
                %i.fa.fa-search

            Launch
            Academy

            <form>
              <input class='left' id='query' name='query' placeholder='Search' type='text'>
              <button class='search-button' name='button' type='submit'>

              </button>
            </form>

Footer

Here's the code for making the classic Launch footer.

Note: The icky-looking visual bugs you see here (the photos
not existing and looking weird, the content being pressed up right
against the edges, etc.) won't actually be present when you use this
as an actual footer in your site.

To keep your footer at the bottom of the page no matter what,
add a div with the class of `container` right inside your `body` tag,
and wrap all the rest of your content EXCEPT the footer inside this div.

        basic footer

%footer
  .row
    .address.large-3.columns
      %h5 About Launch Academy
      %p 33 Harrison Ave #501
      %p Boston, MA 02111
      %br
      %p
        T:
        %a.blue-text 857.600.2250
      %p
        E:
        %a.blue-text hello@launchacademy.com
    .team.large-9.columns
      %h5.pbm About The Team

      .large-4.profile.columns
        .photo
          %img(src="" alt="dan-photo")
        .text
          %h6.name Dan Pickett
          %p.role Co-Founder
          %p.bio Founder & Principle at LaunchWare Co-Organizer of Boston Ruby Group Formally Dir. of Engineering @ Gazelle Coding professionally since 2002.
      .large-4.profile.columns
        .photo
          %img(src="" alt="dan-photo")
        .text
          %h6.name Dan Pickett
          %p.role Co-Founder
          %p.bio Founder & Principle at LaunchWare Co-Organizer of Boston Ruby Group Formally Dir. of Engineering @ Gazelle Coding professionally since 2002.
      .large-4.profile.columns
        .photo
          %img(src="" alt="dan-photo")
        .text
          %h6.name Dan Pickett
          %p.role Co-Founder
          %p.bio Founder & Principle at LaunchWare Co-Organizer of Boston Ruby Group Formally Dir. of Engineering @ Gazelle Coding professionally since 2002.
      .columns.view-more
        %a.cta View More

  .row.sub-footer
    .columns
      %ul
        %li
          %a Blog
        %li
          %a Careers
        %li
          %a Codedabulary
        %li
          %a Contact Us
        %li
          %a Privacy
        %li.social-media
          %a
            %i.fa.fa-facebook-square
        %li.social-media
          %a
            %i.fa.fa-twitter-square

      .copyright
        © Copyright 2015 Launch Academy.
        %a Terms and Conditions

About Launch Academy

33 Harrison Ave #501

Boston, MA 02111

        T:
        857.600.2250

        E:
        hello@launchacademy.com

About The Team

Dan Pickett

Co-Founder

Founder & Principle at LaunchWare Co-Organizer of Boston Ruby Group Formally Dir. of Engineering @ Gazelle Coding professionally since 2002.

Dan Pickett

Co-Founder

Founder & Principle at LaunchWare Co-Organizer of Boston Ruby Group Formally Dir. of Engineering @ Gazelle Coding professionally since 2002.

Dan Pickett

Co-Founder

Founder & Principle at LaunchWare Co-Organizer of Boston Ruby Group Formally Dir. of Engineering @ Gazelle Coding professionally since 2002.

        View More

          Blog

          Careers

          Codedabulary

          Contact Us

          Privacy

        © Copyright 2015 Launch Academy.
        Terms and Conditions

This documentation generated using Hologram


text:
angular.module('cms.shared').directive('cmsModalDialogHeader', ['shared.internalModulePath', function (modulePath) {
    return {
        restrict: 'E',
        templateUrl: modulePath + 'UIComponents/Modals/ModalDialogHeader.html',
        transclude: true,
    };
}]);


text:
import fcntl
import glob
import grp
import os
import pwd
import shlex
import socket
import struct
import threading

import eventlet
from eventlet.green import subprocess
from eventlet import greenthread
from oslo_config import cfg
from oslo_log import log as logging
from oslo_rootwrap import client
from oslo_utils import excutils
import six
from six.moves import http_client as httplib

from neutron._i18n import _, _LE
from neutron.agent.common import config
from neutron.common import constants
from neutron.common import utils
from neutron import wsgi

LOG = logging.getLogger(__name__)

class RootwrapDaemonHelper(object):
    __client = None
    __lock = threading.Lock()

    def __new__(cls):
        """There is no reason to instantiate this class"""
        raise NotImplementedError()

    @classmethod
    def get_client(cls):
        with cls.__lock:
            if cls.__client is None:
                cls.__client = client.Client(
                    shlex.split(cfg.CONF.AGENT.root_helper_daemon))
            return cls.__client

def addl_env_args(addl_env):
    """Build arugments for adding additional environment vars with env"""

    # NOTE (twilson) If using rootwrap, an EnvFilter should be set up for the
    # command instead of a CommandFilter.
    if addl_env is None:
        return []
    return ['env'] + ['%s=%s' % pair for pair in addl_env.items()]

def create_process(cmd, run_as_root=False, addl_env=None):
    """Create a process object for the given command.

    The return value will be a tuple of the process object and the
    list of command arguments used to create it.
    """
    cmd = list(map(str, addl_env_args(addl_env) + cmd))
    if run_as_root:
        cmd = shlex.split(config.get_root_helper(cfg.CONF)) + cmd
    LOG.debug("Running command: %s", cmd)
    obj = utils.subprocess_popen(cmd, shell=False,
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)

    return obj, cmd

def execute_rootwrap_daemon(cmd, process_input, addl_env):
    cmd = list(map(str, addl_env_args(addl_env) + cmd))
    # NOTE(twilson) oslo_rootwrap.daemon will raise on filter match
    # errors, whereas oslo_rootwrap.cmd converts them to return codes.
    # In practice, no neutron code should be trying to execute something that
    # would throw those errors, and if it does it should be fixed as opposed to
    # just logging the execution error.
    LOG.debug("Running command (rootwrap daemon): %s", cmd)
    client = RootwrapDaemonHelper.get_client()
    return client.execute(cmd, process_input)

def execute(cmd, process_input=None, addl_env=None,
            check_exit_code=True, return_stderr=False, log_fail_as_error=True,
            extra_ok_codes=None, run_as_root=False):
    try:
        if (process_input is None or
            isinstance(process_input, six.binary_type)):
            _process_input = process_input
        else:
            _process_input = process_input.encode('utf-8')
        if run_as_root and cfg.CONF.AGENT.root_helper_daemon:
            returncode, _stdout, _stderr = (
                execute_rootwrap_daemon(cmd, process_input, addl_env))
        else:
            obj, cmd = create_process(cmd, run_as_root=run_as_root,
                                      addl_env=addl_env)
            _stdout, _stderr = obj.communicate(_process_input)
            returncode = obj.returncode
            obj.stdin.close()
        _stdout = utils.safe_decode_utf8(_stdout)
        _stderr = utils.safe_decode_utf8(_stderr)

        extra_ok_codes = extra_ok_codes or []
        if returncode and returncode not in extra_ok_codes:
            msg = _("Exit code: %(returncode)d; "
                    "Stdin: %(stdin)s; "
                    "Stdout: %(stdout)s; "
                    "Stderr: %(stderr)s") % {
                        'returncode': returncode,
                        'stdin': process_input or '',
                        'stdout': _stdout,
                        'stderr': _stderr}

            if log_fail_as_error:
                LOG.error(msg)
            if check_exit_code:
                raise RuntimeError(msg)
        else:
            LOG.debug("Exit code: %d", returncode)

    finally:
        # NOTE(termie): this appears to be necessary to let the subprocess
        #               call clean something up in between calls, without
        #               it two execute calls in a row hangs the second one
        greenthread.sleep(0)

    return (_stdout, _stderr) if return_stderr else _stdout

def get_interface_mac(interface):
    MAC_START = 18
    MAC_END = 24
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    dev = interface[:constants.DEVICE_NAME_MAX_LEN]
    if isinstance(dev, six.text_type):
        dev = dev.encode('utf-8')
    info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', dev))
    return ''.join(['%02x:' % ord(char)
                    for char in info[MAC_START:MAC_END]])[:-1]

def find_child_pids(pid):
    """Retrieve a list of the pids of child processes of the given pid."""

    try:
        raw_pids = execute(['ps', '--ppid', pid, '-o', 'pid='],
                           log_fail_as_error=False)
    except RuntimeError as e:
        # Unexpected errors are the responsibility of the caller
        with excutils.save_and_reraise_exception() as ctxt:
            # Exception has already been logged by execute
            no_children_found = 'Exit code: 1' in str(e)
            if no_children_found:
                ctxt.reraise = False
                return []
    return [x.strip() for x in raw_pids.split('\n') if x.strip()]

def _get_conf_base(cfg_root, uuid, ensure_conf_dir):
    #TODO(mangelajo): separate responsibilities here, ensure_conf_dir
    #                 should be a separate function
    conf_dir = os.path.abspath(os.path.normpath(cfg_root))
    conf_base = os.path.join(conf_dir, uuid)
    if ensure_conf_dir:
        utils.ensure_dir(conf_dir)
    return conf_base

def get_conf_file_name(cfg_root, uuid, cfg_file, ensure_conf_dir=False):
    """Returns the file name for a given kind of config file."""
    conf_base = _get_conf_base(cfg_root, uuid, ensure_conf_dir)
    return "%s.%s" % (conf_base, cfg_file)

def get_value_from_file(filename, converter=None):

    try:
        with open(filename, 'r') as f:
            try:
                return converter(f.read()) if converter else f.read()
            except ValueError:
                LOG.error(_LE('Unable to convert value in %s'), filename)
    except IOError:
        LOG.debug('Unable to access %s', filename)

def get_value_from_conf_file(cfg_root, uuid, cfg_file, converter=None):
    """A helper function to read a value from one of a config file."""
    file_name = get_conf_file_name(cfg_root, uuid, cfg_file)
    return get_value_from_file(file_name, converter)

def remove_conf_files(cfg_root, uuid):
    conf_base = _get_conf_base(cfg_root, uuid, False)
    for file_path in glob.iglob("%s.*" % conf_base):
        os.unlink(file_path)

def get_root_helper_child_pid(pid, expected_cmd, run_as_root=False):
    """
    Get the first non root_helper child pid in the process hierarchy.

    If root helper was used, two or more processes would be created:

     - a root helper process (e.g. sudo myscript)
     - possibly a rootwrap script (e.g. neutron-rootwrap)
     - a child process (e.g. myscript)
     - possibly its child processes

    Killing the root helper process will leave the child process
    running, re-parented to init, so the only way to ensure that both
    die is to target the child process directly.
    """
    pid = str(pid)
    if run_as_root:
        while True:
            try:
                # We shouldn't have more than one child per process
                # so keep getting the children of the first one
                pid = find_child_pids(pid)[0]
            except IndexError:
                return  # We never found the child pid with expected_cmd

            # If we've found a pid with no root helper, return it.
            # If we continue, we can find transient children.
            if pid_invoked_with_cmdline(pid, expected_cmd):
                break
    return pid

def remove_abs_path(cmd):
    """Remove absolute path of executable in cmd

    Note: New instance of list is returned

    :param cmd: parsed shlex command (e.g. ['/bin/foo', 'param1', 'param two'])

    """
    if cmd and os.path.isabs(cmd[0]):
        cmd = list(cmd)
        cmd[0] = os.path.basename(cmd[0])

    return cmd

def get_cmdline_from_pid(pid):
    if pid is None or not os.path.exists('/proc/%s' % pid):
        return []
    with open('/proc/%s/cmdline' % pid, 'r') as f:
        return f.readline().split('\0')[:-1]

def cmd_matches_expected(cmd, expected_cmd):
    abs_cmd = remove_abs_path(cmd)
    abs_expected_cmd = remove_abs_path(expected_cmd)
    if abs_cmd != abs_expected_cmd:
        # Commands executed with #! are prefixed with the script
        # executable. Check for the expected cmd being a subset of the
        # actual cmd to cover this possibility.
        abs_cmd = remove_abs_path(abs_cmd[1:])
    return abs_cmd == abs_expected_cmd

def pid_invoked_with_cmdline(pid, expected_cmd):
    """Validate process with given pid is running with provided parameters

    """
    cmd = get_cmdline_from_pid(pid)
    return cmd_matches_expected(cmd, expected_cmd)

def wait_until_true(predicate, timeout=60, sleep=1, exception=None):
    """
    Wait until callable predicate is evaluated as True

    :param predicate: Callable deciding whether waiting should continue.
    Best practice is to instantiate predicate with functools.partial()
    :param timeout: Timeout in seconds how long should function wait.
    :param sleep: Polling interval for results in seconds.
    :param exception: Exception class for eventlet.Timeout.
    (see doc for eventlet.Timeout for more information)
    """
    with eventlet.timeout.Timeout(timeout, exception):
        while not predicate():
            eventlet.sleep(sleep)

def ensure_directory_exists_without_file(path):
    dirname = os.path.dirname(path)
    if os.path.isdir(dirname):
        try:
            os.unlink(path)
        except OSError:
            with excutils.save_and_reraise_exception() as ctxt:
                if not os.path.exists(path):
                    ctxt.reraise = False
    else:
        utils.ensure_dir(dirname)

def is_effective_user(user_id_or_name):
    """Returns True if user_id_or_name is effective user (id/name)."""
    euid = os.geteuid()
    if str(user_id_or_name) == str(euid):
        return True
    effective_user_name = pwd.getpwuid(euid).pw_name
    return user_id_or_name == effective_user_name

def is_effective_group(group_id_or_name):
    """Returns True if group_id_or_name is effective group (id/name)."""
    egid = os.getegid()
    if str(group_id_or_name) == str(egid):
        return True
    effective_group_name = grp.getgrgid(egid).gr_name
    return group_id_or_name == effective_group_name

class UnixDomainHTTPConnection(httplib.HTTPConnection):
    """Connection class for HTTP over UNIX domain socket."""
    def __init__(self, host, port=None, strict=None, timeout=None,
                 proxy_info=None):
        httplib.HTTPConnection.__init__(self, host, port, strict)
        self.timeout = timeout
        self.socket_path = cfg.CONF.metadata_proxy_socket

    def connect(self):
        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        if self.timeout:
            self.sock.settimeout(self.timeout)
        self.sock.connect(self.socket_path)

class UnixDomainHttpProtocol(eventlet.wsgi.HttpProtocol):
    # TODO(jlibosva): This is just a workaround not to set TCP_NODELAY on
    # socket due to 40714b1ffadd47b315ca07f9b85009448f0fe63d evenlet change
    # This should be removed once
    # https://github.com/eventlet/eventlet/issues/301 is fixed
    disable_nagle_algorithm = False

    def __init__(self, request, client_address, server):
        if client_address == '':
            client_address = ('<local>', 0)
        # base class is old-style, so super does not work properly
        eventlet.wsgi.HttpProtocol.__init__(self, request, client_address,
                                            server)

class UnixDomainWSGIServer(wsgi.Server):
    def __init__(self, name):
        self._socket = None
        self._launcher = None
        self._server = None
        super(UnixDomainWSGIServer, self).__init__(name, disable_ssl=True)

    def start(self, application, file_socket, workers, backlog, mode=None):
        self._socket = eventlet.listen(file_socket,
                                       family=socket.AF_UNIX,
                                       backlog=backlog)
        if mode is not None:
            os.chmod(file_socket, mode)

        self._launch(application, workers=workers)

    def _run(self, application, socket):
        """Start a WSGI service in a new green thread."""
        logger = logging.getLogger('eventlet.wsgi.server')
        eventlet.wsgi.server(socket,
                             application,
                             max_size=self.num_threads,
                             protocol=UnixDomainHttpProtocol,
                             log=logger)


text:
require 'spec_helper'

describe String do

  it 'underscores' do
    expect('MySweetApp'.underscore).to eq('my_sweet_app')
    expect('MySweet::App'.underscore).to eq('my_sweet/app')
  end

  it 'camelizes' do
    expect('my_sweet_app'.camelize).to eq('MySweetApp')
    expect('my_sweet/app'.camelize).to eq('MySweet::App')
  end

end


text:
import React from 'react';

export const ProfilePanel = () => {
    return (

Profile

    );
};

export default ProfilePanel;


text:
module CloudCapacitor
  module Err
    class NoStrategyConfiguredError < StandardError
    end
  end
end


text:
class SC_ProgramModel : public CM_PersistentObjectModel
{
    Q_OBJECT
public:

    explicit SC_ProgramModel(QObject *parent = 0);

    virtual CM_PersistentObject* createItemObject(QObject *parent = 0)
    {
        //qDebug() << "SC_ProgramModel - CreateItemObject";
        SC_Programs *p = new SC_Programs(parent);
        return p;
    }

};

#endif // SC_PROGRAMMODEL_H


text:
require 'spec_helper'

module Cmsify
  describe Text do
    subject{ FactoryGirl.create(:text) }
    it { validate_presence_of(:content) }
    it { validate_presence_of(:slug) }
    it { validate_uniqueness_of(:slug) }
    it { belong_to(:owner) }
  end
end


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.

require_once(__DIR__ . '/../../../../lib/behat/behat_base.php');

use Behat\Behat\Context\Step\Given as Given,
    Behat\Gherkin\Node\TableNode as TableNode;

/**
 * Glossary-related steps definitions.
 *
 * @package    mod_glossary
 * @category   test
 * @copyright  2013 David Monllaó
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class behat_mod_glossary extends behat_base {

    /**
     * Adds an entry to the current glossary with the provided data. You should be in the glossary page.
     *
     * @Given /^I add a glossary entry with the following data:$/
     * @param TableNode $data
     */
    public function i_add_a_glossary_entry_with_the_following_data(TableNode $data) {
        return array(
            new Given('I press "' . get_string('addentry', 'mod_glossary') . '"'),
            new Given('I fill the moodle form with:', $data),
            new Given('I press "' . get_string('savechanges') . '"')
        );
    }

    /**
     * Adds a category with the specified name to the current glossary. You need to be in the glossary page.
     *
     * @Given /^I add a glossary entries category named "(?P<category_name_string>(?:[^"]|\\")*)"$/
     * @param string $categoryname Category name
     */
    public function i_add_a_glossary_entries_category_named($categoryname) {

        return array(
            new Given('I follow "' . get_string('categoryview', 'mod_glossary') . '"'),
            new Given('I press "' . get_string('editcategories', 'mod_glossary') . '"'),
            new Given('I press "' . get_string('add').' '.get_string('category', 'glossary') . '"'),
            new Given('I fill in "name" with "' . $this->escape($categoryname) . '"'),
            new Given('I press "' . get_string('savechanges') . '"'),
            new Given('I press "' . get_string('back', 'mod_glossary') . '"')
        );
    }
}


text:
import {Adapter} from 'js-data-adapter'

interface IDict {
  [key: string]: any;
}
interface IBaseAdapter extends IDict {
  debug?: boolean,
  raw?: boolean
}
interface IBaseCloudDatastoreAdapter extends IBaseAdapter {
  gcloudOpts?: IDict
  gcloud?: any
}
export class CloudDatastoreAdapter extends Adapter {
  static extend(instanceProps?: IDict, classProps?: IDict): typeof CloudDatastoreAdapter
  constructor(opts?: IBaseCloudDatastoreAdapter)
}
export interface OPERATORS {
  '==': Function
  '===': Function
  '!=': Function
  '!==': Function
  '>': Function
  '>=': Function
  '<': Function
  '<=': Function
}
export interface version {
  full: string
  minor: string
  major: string
  patch: string
  alpha: string | boolean
  beta: string | boolean
}


text:
"use strict";

define(['marionette'],
    function(Marionette) {
        return Marionette.ItemView.extend({
            className: function() {
                return 'domotic-item ' + this.model.getType();
            },

            modelEvents: {
                'change': 'onChange'
            },

            onChange: function() {
                console.log('Saving State for '+ this.model.id);
                this.model.saveChangesOnly();
                this.render();
            },

            templateHelpers: function() {
                return this.model;
            }
        });
    }
);