text:
package org.hawkular.inventory.api.model;

import java.util.Map;
import java.util.Set;

/**
 * @author Lukas Krejci
 * @since 0.4.0
 */
public final class OperationType extends Entity<OperationType.Blueprint, OperationType.Update> {

    @SuppressWarnings("unused")
    private OperationType() {
    }

    public OperationType(CanonicalPath path) {
        super(path);
    }

    public OperationType(CanonicalPath path, Map<String, Object> properties) {
        super(path, properties);
    }

    @Override
    public <R, P> R accept(ElementVisitor<R, P> visitor, P parameter) {
        return visitor.visitOperationType(this, parameter);
    }

    @Override
    public Updater<Update, OperationType> update() {
        return new Updater<>((u) -> new OperationType(getPath(), u.getProperties()));
    }

    public static final class Blueprint extends Entity.Blueprint {

        public static Builder builder() {
            return new Builder();
        }

        /**
         * Serialization support
         */
        @SuppressWarnings("unused")
        private Blueprint() {
            super(null, null);
        }

        public Blueprint(String id, Map<String, Object> properties) {
            super(id, properties);
        }

        public Blueprint(String id, Map<String, Object> properties,
                         Map<String, Set<CanonicalPath>> outgoing,
                         Map<String, Set<CanonicalPath>> incoming) {
            super(id, properties, outgoing, incoming);
        }

        @Override
        public <R, P> R accept(ElementBlueprintVisitor<R, P> visitor, P parameter) {
            return visitor.visitOperationType(this, parameter);
        }

        public static final class Builder extends Entity.Blueprint.Builder<Blueprint, Builder> {
            @Override
            public Blueprint build() {
                return new Blueprint(id, properties, outgoing, incoming);
            }
        }
    }

    public static final class Update extends Entity.Update {

        public static Builder builder() {
            return new Builder();
        }

        /**
         * Serialization support
         */
        @SuppressWarnings("unused")
        private Update() {
            this(null);
        }

        public Update(Map<String, Object> properties) {
            super(properties);
        }

        @Override
        public <R, P> R accept(ElementUpdateVisitor<R, P> visitor, P parameter) {
            return visitor.visitOperationType(this, parameter);
        }

        public static final class Builder extends Entity.Update.Builder<Update, Builder> {
            @Override
            public Update build() {
                return new Update(properties);
            }
        }
    }
}


text:
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import React from 'react';
import renderer from 'react-test-renderer';

import Chat from './Chat';
import ChatForm from './ChatForm';
import ChatMessage from './ChatMessage';

Enzyme.configure({ adapter: new Adapter() });

const messages = [
    {
        id: '1',
        creator: { id: '2', name: 'Tester 2' },
        message: 'text 1',
        created_at: '2017-04-11T18:18:36.000Z',
    },
    {
        id: '2',
        creator: { id: '1', name: 'Tester 1' },
        message: 'text 2',
        created_at: '2017-05-11T18:18:36.000Z',
    },
    {
        id: '3',
        creator: { id: '2', name: 'Tester 2' },
        message: 'text 3',
        created_at: '2017-06-11T18:18:36.000Z',
    },
];
const user = { id: '1', name: 'Tester 1' };
const noUser = { isEmpty: true };

it('should show chat form for logged in user', () => {
    const chat = shallow(<Chat messages={messages} user={user} id="1" />);
    expect(chat.find(ChatForm).length).toBe(1);
});

it('should show not show chat form for non-logged in user', () => {
    const chat = shallow(<Chat messages={messages} user={noUser} id="1" />);
    expect(chat.find(ChatForm).length).toBe(0);
});

it('should render three messages', () => {
    const chat = shallow(<Chat messages={messages} user={user} id="1" />);
    expect(chat.find(ChatMessage).length).toBe(3);
});

test('should render correctly', () => {
    const chat = renderer.create(
        <Chat messages={messages} user={user} id="1" />
    );
    const tree = chat.toJSON();
    expect(tree).toMatchSnapshot();
});

redpajama_set_name: RedPajamaGithub


text:
import { mount } from 'enzyme';
import React from 'react';
import { act } from 'react-dom/test-utils';
import { Modal } from '../..';
import { sleep } from '../../../tests/utils';
import ConfigProvider from '../../config-provider';
import zhCN from '../zh_CN';

class Demo extends React.Component {
  static defaultProps = {};

  componentDidMount() {
    if (this.props.type === 'dashboard') {
      Modal.confirm({ title: 'Hello World!' });
    }
  }

  render() {
    return
{this.props.type}
;
  }
}

describe('Locale Provider demo', () => {
  it('change type', async () => {
    jest.useFakeTimers();

    const BasicExample = () => {
      const [type, setType] = React.useState('');
      return (

           setType('about')}>
            about

           setType('dashboard')}>
            dashboard

            {type === 'about' && (
              <ConfigProvider locale={zhCN}>
                <Demo type="about" />
              </ConfigProvider>
            )}
            {type === 'dashboard' && (
              <ConfigProvider locale={zhCN}>
                <Demo type="dashboard" />
              </ConfigProvider>
            )}

      );
    };
    const wrapper = mount(<BasicExample />);

    wrapper.find('.about').at(0).simulate('click');
    await act(async () => {
      jest.runAllTimers();
      await sleep();
    });

    wrapper.find('.dashboard').at(0).simulate('click');
    await act(async () => {
      jest.runAllTimers();
      await sleep();
    });

    expect(document.body.querySelectorAll('.ant-btn-primary span')[0].textContent).toBe('确 定');
    Modal.destroyAll();
    jest.useRealTimers();
  });
});


text:
ulele
=====

Projecte Ulele

Acabo d'actualitzar aquest arxiu
Això era un cacau!
Que de puta mare


text:
package org.drools.games.wumpus;

import org.kie.api.definition.type.PropertyReactive;

@PropertyReactive
public class Gold extends Thing {

    public Gold(int row,
                int col) {
        super( row, col );
    }

    @Override
    public String toString() {
        return "Gold [row=" + getRow() + ", col=" + getCol() + "]";
    }

}


text:
<!doctype html>

<link href='http://fonts.googleapis.com/css?family=Donegal+One' rel='stylesheet' type='text/css'>
<link href='style.css' rel='stylesheet' type='text/css'>
<title>Javascript API</title>

< rt2.me

Javascript API

Include rt2.js and then use it as follows:

rt2([url to convert], [callback of converted url]);

Example:

There's a div below that has an ID of "output". Here is some code:

document.getElementById("output").innerHTML = "Fetching...";

rt2("http://www.youtube.com/watch?v=dQw4w9WgXcQ", function(result) {
  document.getElementById("output").innerHTML = result;
});

<button onclick=demo()>Run this code</button>


text:
cask "sourcetree" do
  if MacOS.version <= :sierra
    version "2.7.6a"
    sha256 "d60614e9ab603e0ed158b6473c36e7944b2908d9943e332c505eba03dc1d829e"

    url "https://downloads.atlassian.com/software/sourcetree/Sourcetree_#{version}.zip",
        verified: "atlassian.com/software/sourcetree/"
  elsif MacOS.version <= :high_sierra
    version "3.2.1,225"
    sha256 "4bd82affa3402814c3d07ff613fbc8f45da8b0cda294d498ffbb0667bf729c9f"

    url "https://product-downloads.atlassian.com/software/sourcetree/ga/Sourcetree_#{version.before_comma}_#{version.after_comma}.zip",
        verified: "atlassian.com/software/sourcetree/"
  else
    version "4.0.2,236"
    sha256 "c9ad12f135077363a11102925ff50f1f3f59c95625362d4105c6fc414aab7c83"

    url "https://product-downloads.atlassian.com/software/sourcetree/ga/Sourcetree_#{version.before_comma}_#{version.after_comma}.zip",
        verified: "atlassian.com/software/sourcetree/"
  end

  name "Atlassian SourceTree"
  desc "Graphical client for Git version control"
  homepage "https://www.sourcetreeapp.com/"

  livecheck do
    url "https://product-downloads.atlassian.com/software/sourcetree/Appcast/SparkleAppcastGroup0.xml"
    strategy :sparkle
  end

  auto_updates true
  depends_on macos: ">= :el_capitan"

  app "Sourcetree.app"
  binary "#{appdir}/Sourcetree.app/Contents/Resources/stree"

  uninstall launchctl: "com.atlassian.SourceTreePrivilegedHelper2",
            quit:      "com.torusknot.SourceTreeNotMAS"

  zap trash: [
    "~/Library/Application Support/SourceTree",
    "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.torusknot.sourcetreenotmas.sfl2",
    "~/Library/Caches/com.torusknot.SourceTreeNotMAS",
    "~/Library/Preferences/com.torusknot.SourceTreeNotMAS.plist",
    "~/Library/Preferences/com.torusknot.SourceTreeNotMAS.LSSharedFileList.plist",
    "~/Library/Saved Application State/com.torusknot.SourceTreeNotMAS.savedState",
  ]
end


text:
The goal of this project is to wrap the Bootbox Javascript library with Opal, providing a simple Ruby interface to Bootbox functionality.

Bootbox.js is a small open source (MIT) JavaScript library which implements dialog (alert, prompt, confirm) boxes using Bootstrap modals.

To find out more about Bootbox, go to http://bootboxjs.com.

To find out more about Opal, go to http://opalrb.org

## Installation

Install opal-bootbox from RubyGems:

```
$ gem install opal-bootbox
```

Or include it in your Gemfile for Bundler:

```
ruby
gem 'opal-bootbox'
```

## Cloning this repository

```
$ git clone https://github.com/balmoral/opal-bootbox
```

## Getting Started

### Usage

`opal-bootbox` can be added to your opal application sources using a standard require:

```
ruby
# app/application.rb
require 'opal'
require 'opal-bootbox'
```

You need to bring your own `bootbox.js` or `bootbox.min.js` and bootstrap files

* http://bootboxjs.com/download/
* http://getbootstrap.com/getting-started/#download

and put the files in `app/` or whichever directory you are compiling assets from.

The Opal/Ruby interface is largely consistent with the Javascript interface.

See http://bootboxjs.com/documentation.html for Javascript library documentation.

Where a method expects a single callback substitute a block for the JS function.

The value for a `callback:` keyword argument should be a Ruby proc.

Keyword arguments should preserve the JS camelcase (e.g. className:).

### Examples

```
$bootbox.alert('Hello world!') do
  puts 'hello world acknowledged'
end
```

```
$bootbox.alert(
  size: 'small',
  title: 'Alert',
  message: 'Hello world!',
  callback: -> {puts 'hello world acknowledged'}
)
```

```
$bootbox.confirm('Are you sure?') do |result|
  puts "user is #{result ? 'sure' : 'unsure'}"
end
```

```
$bootbox.confirm(
  size: 'small',
  title: 'Confirmation',
  message: 'Are you sure?'
  callback: ->(result) {
    puts "user is #{result ? 'sure' : 'unsure'}"
  }
end
```

```
$bootbox.prompt('What is your name?') do |result|
  if result
    puts "user's name is '#{result}'"
  else
    puts "prompt dismissed"
  end
end
```

```
$bootbox.prompt(
  size: 'small',
  title: 'Prompt',
  message: 'What is your name?',
  value: 'default name'),
  callback: ->(result) {
    if result
      puts "user's name is '#{result}'"
    else
      puts "prompt dismissed"
  }
)
```

```
$bootbox.dialog(
  # required
  message: "I am a custom dialog",

  # optional - adds a header to the dialog and places this text in an h4
  title: "Custom title",

  # optional - allows the user to dismiss the dialog by hitting ESC
  # which will call this proc
  onEscape: -> { puts 'user press escape' },

  # optional - whether the dialog should be shown immediately
  show: true,

  # optional - whether the dialog should be have a backdrop or not
  backdrop: true,

  # optional - whether to show a close button (default true)
  closeButton: true,

  # optional - whether to animate (default true)
  animate: true,

  # optional - an additional CSS class to apply to the Bootstrap dialog wrapper
  className: "my-modal",

  # optional - a hash of buttons to be shown in the dialog's footer
  buttons: {

    success: {
      # optional - the button label
      label: "Success!",

      # optional - an additional CSS class to apply to the button
      className: "btn-success",

      # optional - call proc when button is clicked
      callback: -> { puts 'success!' }
    },

    "Danger!": {
      # no label is provided so the key is used as the button label

      # optional - an additional CSS class to apply to the button
      className: "btn-danger",

      callback: -> { puts 'danger!' }
    },

    # if the only value supplied is a callback proc,
    # the key is used as the button label and all
    # other options are defaulted

    "Warning!": -> { puts 'warning!}
  }
)
```

`$bootbox` is a global variable. `Opal::Bootbox` may be substituted.

Strings (text) provided as arguments to bootbox methods may be HTML format.

All methods are executed asynchronously, hence the use of callback blocks and procs.

## To do

* Documentation
* Testing
* snake case keywords ?

## Getting involved

To contribute to this project, follow the steps below.

1. Fork the repo ( https://github.com/balmoral/opal-bootbox/fork )
2. Create your feature branch (`git checkout -b new-branch`)
3. Commit your changes (`git commit -am 'description of commit'`)
4. Push to the branch (`git push origin new-branch`)
5. Create a Pull Request

Contributions welcome.

## Licenses

### Bootbox
Open source (MIT) licence.
See https://github.com/makeusabrew/bootbox/blob/master/LICENSE.md for details.

###opal-bootbox
MIT Licence.
See LICENSE.txt


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="co.mscsea.allsharelib"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="com.sec.android.permission.PERSONAL_MEDIA"/>
    <uses-permission android:name="com.android.setting.permission.ALLSHARE_CAST_SERVICE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
    </application>

</manifest>


text:
/*
 * 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 io.prestosql.orc.metadata.statistics;

import com.google.common.collect.ImmutableList;
import org.testng.annotations.Test;

import java.util.List;
import java.util.stream.LongStream;
import java.util.stream.Stream;

import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.prestosql.orc.metadata.statistics.AbstractStatisticsBuilderTest.StatisticsType.DOUBLE;
import static io.prestosql.orc.metadata.statistics.DoubleStatistics.DOUBLE_VALUE_BYTES;
import static java.lang.Double.NEGATIVE_INFINITY;
import static java.lang.Double.NaN;
import static java.lang.Double.POSITIVE_INFINITY;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;

public class TestDoubleStatisticsBuilder
        extends AbstractStatisticsBuilderTest<DoubleStatisticsBuilder, Double>
{
    private static final List<Long> ZERO_TO_42 = LongStream.rangeClosed(0, 42).boxed().collect(toImmutableList());

    public TestDoubleStatisticsBuilder()
    {
        super(DOUBLE, () -> new DoubleStatisticsBuilder(new NoOpBloomFilterBuilder()), DoubleStatisticsBuilder::addValue);
    }

    @Test
    public void testMinMaxValues()
    {
        assertMinMaxValues(0.0, 0.0);
        assertMinMaxValues(42.42, 42.42);
        assertMinMaxValues(NEGATIVE_INFINITY, NEGATIVE_INFINITY);
        assertMinMaxValues(POSITIVE_INFINITY, POSITIVE_INFINITY);

        assertMinMaxValues(0.0, 42.42);
        assertMinMaxValues(42.42, 42.42);
        assertMinMaxValues(NEGATIVE_INFINITY, 42.42);
        assertMinMaxValues(42.42, POSITIVE_INFINITY);
        assertMinMaxValues(NEGATIVE_INFINITY, POSITIVE_INFINITY);

        assertValues(0.0, 88.88, toDoubleList(0.0, 88.88, ZERO_TO_42));
        assertValues(-88.88, 0.0, toDoubleList(-88.88, 0.0, ZERO_TO_42));
        assertValues(-44.44, 44.44, toDoubleList(-44.44, 44.44, ZERO_TO_42));
    }

    private static List<Double> toDoubleList(Double minValue, Double maxValue, List<Long> values)
    {
        return values.stream()
                .flatMap(value -> Stream.of(maxValue - value, minValue + value))
                .collect(toImmutableList());
    }

    @Test
    public void testNanValue()
    {
        DoubleStatisticsBuilder statisticsBuilder = new DoubleStatisticsBuilder(new NoOpBloomFilterBuilder());
        statisticsBuilder.addValue(NaN);
        assertNoColumnStatistics(statisticsBuilder.buildColumnStatistics(), 1);
        statisticsBuilder.addValue(NaN);
        assertNoColumnStatistics(statisticsBuilder.buildColumnStatistics(), 2);
        statisticsBuilder.addValue(42.42);
        assertNoColumnStatistics(statisticsBuilder.buildColumnStatistics(), 3);

        statisticsBuilder = new DoubleStatisticsBuilder(new NoOpBloomFilterBuilder());
        statisticsBuilder.addValue(42.42);
        assertColumnStatistics(statisticsBuilder.buildColumnStatistics(), 1, 42.42, 42.42);
        statisticsBuilder.addValue(NaN);
        assertNoColumnStatistics(statisticsBuilder.buildColumnStatistics(), 2);
        statisticsBuilder.addValue(42.42);
        assertNoColumnStatistics(statisticsBuilder.buildColumnStatistics(), 3);
    }

    @Test
    public void testMinAverageValueBytes()
    {
        assertMinAverageValueBytes(0L, ImmutableList.of());
        assertMinAverageValueBytes(DOUBLE_VALUE_BYTES, ImmutableList.of(42D));
        assertMinAverageValueBytes(DOUBLE_VALUE_BYTES, ImmutableList.of(0D));
        assertMinAverageValueBytes(DOUBLE_VALUE_BYTES, ImmutableList.of(0D, 42D, 42D, 43D));
    }

    @Test
    public void testBloomFilter()
    {
        DoubleStatisticsBuilder statisticsBuilder = new DoubleStatisticsBuilder(new Utf8BloomFilterBuilder(3, 0.01));
        statisticsBuilder.addValue(3.14);
        statisticsBuilder.addValue(10.11);
        statisticsBuilder.addValue(42.42);
        BloomFilter bloomFilter = statisticsBuilder.buildColumnStatistics().getBloomFilter();
        assertNotNull(bloomFilter);
        assertTrue(bloomFilter.testDouble(3.14));
        assertTrue(bloomFilter.testDouble(10.11));
        assertTrue(bloomFilter.testDouble(42.42));
        assertFalse(bloomFilter.testDouble(100));
    }
}


text:
package com.jme3.texture.image;

import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.texture.Image;
import java.nio.ByteBuffer;

public class DefaultImageRaster extends ImageRaster {

    private final int[] components = new int[4];
    private ByteBuffer buffer;
    private final Image image;
    private final ImageCodec codec;
    private final int width;
    private final int height;
    private final byte[] temp;
    private int slice;

    private void rangeCheck(int x, int y) {
        if (x < 0 || y < 0 || x >= width || y >= height) {
            throw new IllegalArgumentException("x and y must be inside the image dimensions");
        }
    }

    public DefaultImageRaster(Image image, int slice) {
        this.image = image;
        this.slice = slice;
        this.buffer = image.getData(slice);
        this.codec = ImageCodec.lookup(image.getFormat());
        this.width = image.getWidth();
        this.height = image.getHeight();
        if (codec instanceof ByteAlignedImageCodec || codec instanceof ByteOffsetImageCodec) {
            this.temp = new byte[codec.bpp];
        } else {
            this.temp = null;
        }
    }

    @Override
    public int getWidth() {
        return width;
    }

    @Override
    public int getHeight() {
        return height;
    }

    @Override
    public void setPixel(int x, int y, ColorRGBA color) {
        rangeCheck(x, y);

        // Check flags for grayscale
        if (codec.isGray) {
            float gray = color.r * 0.27f + color.g * 0.67f + color.b * 0.06f;
            color = new ColorRGBA(gray, gray, gray, color.a);
        }

        switch (codec.type) {
            case ImageCodec.FLAG_F16:
                components[0] = (int) FastMath.convertFloatToHalf(color.a);
                components[1] = (int) FastMath.convertFloatToHalf(color.r);
                components[2] = (int) FastMath.convertFloatToHalf(color.g);
                components[3] = (int) FastMath.convertFloatToHalf(color.b);
                break;
            case ImageCodec.FLAG_F32:
                components[0] = (int) Float.floatToIntBits(color.a);
                components[1] = (int) Float.floatToIntBits(color.r);
                components[2] = (int) Float.floatToIntBits(color.g);
                components[3] = (int) Float.floatToIntBits(color.b);
                break;
            case 0:
                // Convert color to bits by multiplying by size
                components[0] = Math.min( (int) (color.a * codec.maxAlpha + 0.5f), codec.maxAlpha);
                components[1] = Math.min( (int) (color.r * codec.maxRed + 0.5f), codec.maxRed);
                components[2] = Math.min( (int) (color.g * codec.maxGreen + 0.5f), codec.maxGreen);
                components[3] = Math.min( (int) (color.b * codec.maxBlue + 0.5f), codec.maxBlue);
                break;
        }
        codec.writeComponents(getBuffer(), x, y, width, components, temp);
        image.setUpdateNeeded();
    }

    private ByteBuffer getBuffer(){
        if(buffer == null){
            this.buffer = image.getData(slice);
        }
        return buffer;
    }

    @Override
    public ColorRGBA getPixel(int x, int y, ColorRGBA store) {
        rangeCheck(x, y);

        codec.readComponents(getBuffer(), x, y, width, components, temp);
        if (store == null) {
            store = new ColorRGBA();
        }
        switch (codec.type) {
            case ImageCodec.FLAG_F16:
                store.set(FastMath.convertHalfToFloat((short)components[1]),
                          FastMath.convertHalfToFloat((short)components[2]),
                          FastMath.convertHalfToFloat((short)components[3]),
                          FastMath.convertHalfToFloat((short)components[0]));
                break;
            case ImageCodec.FLAG_F32:
                store.set(Float.intBitsToFloat((int)components[1]),
                          Float.intBitsToFloat((int)components[2]),
                          Float.intBitsToFloat((int)components[3]),
                          Float.intBitsToFloat((int)components[0]));
                break;
            case 0:
                // Convert to float and divide by bitsize to get into range 0.0 - 1.0.
                store.set((float)components[1] / codec.maxRed,
                          (float)components[2] / codec.maxGreen,
                          (float)components[3] / codec.maxBlue,
                          (float)components[0] / codec.maxAlpha);
                break;
        }
        if (codec.isGray) {
            store.g = store.b = store.r;
        } else {
            if (codec.maxRed == 0) {
                store.r = 1;
            }
            if (codec.maxGreen == 0) {
                store.g = 1;
            }
            if (codec.maxBlue == 0) {
                store.b = 1;
            }
            if (codec.maxAlpha == 0) {
                store.a = 1;
            }
        }
        return store;
    }
}


text:
class Admin::AdminUsersController < Admin::BaseController
  resource_controller
  before_filter :admin_permission_check_member
  before_filter :load_admin

  index.before do
    if session[:admin_user].master_shop?
      @admin_users = AdminUser.find(:all,
                                    :order => 'position')
    else
      @admin_users = AdminUser.find(:all,
                                    :conditions => ["retailer_id = ?", session[:admin_user].retailer_id],
                                    :order => 'position')
    end
  end

  [create, update].each do |action|
    action.wants.html do
      if params[:id].to_i == session[:admin_user].id
        if AdminUser.find(params[:id]).retailer_id != session[:admin_user].retailer_id
          redirect_to :controller => "admin/accounts", :action => "logout"
        else
          redirect_to :action => "index"
        end
      else
        redirect_to :action => "index"
      end
    end
  end

  destroy.before do
    if session[:admin_user].id == params[:id].to_i
      raise "You can't delete yourself"
    end
  end

  edit.before do
    unless session[:admin_user].master_shop?
      raise ActiveRecord::RecordNotFound if AdminUser.find(params[:id]).retailer_id != session[:admin_user].retailer_id
    end
  end

  def up
    super
    redirect_to :action => "index"
  end
  def down
    super
    redirect_to :action => "index"
  end

  #稼働/非稼働チェック(Ajax)
  def update_activity
    record = AdminUser.find_by_id(params[:id])
    if params[:activity] == "true"
      record.update_attribute(:activity, true)
    elsif params[:activity] == "false"
      record.update_attribute(:activity, false)
    end
    render :text=>true
  end
end


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.query_tiles;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withParent;
import static android.support.test.espresso.matcher.ViewMatchers.withText;

import static org.hamcrest.Matchers.not;

import static org.chromium.chrome.browser.query_tiles.ListMatchers.isScrolledToFront;
import static org.chromium.chrome.browser.query_tiles.ListMatchers.matchList;
import static org.chromium.chrome.browser.query_tiles.ViewActions.scrollTo;

import android.support.test.InstrumentationRegistry;
import android.support.test.espresso.assertion.ViewAssertions;
import android.support.test.filters.SmallTest;
import android.view.KeyEvent;
import android.view.View;

import org.hamcrest.Matcher;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.omnibox.UrlBar;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.chrome.test.ChromeTabbedActivityTestRule;
import org.chromium.chrome.test.util.NewTabPageTestUtils;
import org.chromium.chrome.test.util.OmniboxTestUtils;
import org.chromium.chrome.test.util.browser.Features;
import org.chromium.components.embedder_support.util.UrlConstants;
import org.chromium.components.query_tiles.QueryTile;
import org.chromium.components.query_tiles.TestTileProvider;

/**
 * Provides a set of tests to validate that QueryTiles works properly in the NTP given the following
 * experiment flags:
 * - ChromeFeatureList.QUERY_TILES
 * - ChromeFeatureList.QUERY_TILES_ENABLE_QUERY_EDITING
 */
@RunWith(ChromeJUnit4ClassRunner.class)
@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE})
@Features.
EnableFeatures({ChromeFeatureList.QUERY_TILES, ChromeFeatureList.QUERY_TILES_ENABLE_QUERY_EDITING})
public class QueryTileSectionToOmniboxTest {
    @Rule
    public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule();

    private Tab mTab;
    private TestTileProvider mTileProvider;

    private void setUp(int levels) {
        mTileProvider = new TestTileProvider(levels, 8 /* count */);
        TileProviderFactory.setTileProviderForTesting(mTileProvider);
        mActivityTestRule.startMainActivityOnBlankPage();
        mActivityTestRule.loadUrl(UrlConstants.NTP_URL);
        mTab = mActivityTestRule.getActivity().getActivityTab();
        NewTabPageTestUtils.waitForNtpLoaded(mTab);
    }

    /** Tests that tiles show up as expected whe the NTP is opened. */
    @Test
    @SmallTest
    public void testShowQueryTileSection() throws Exception {
        setUp(1 /* levels */);
        matchList(withParent(withId(R.id.query_tiles)), mTileProvider.getChildrenOf());
    }

    /** Tests that clicking a tile on a single depth list opens the omnibox. */
    @Test
    @SmallTest
    public void testClickTileOpensOmnibox() throws Exception {
        setUp(1 /* levels */);
        Matcher<View> recyclerViewMatcher = withParent(withId(R.id.query_tiles));
        matchList(recyclerViewMatcher, mTileProvider.getChildrenOf());

        // Simulate a click on the tile.
        QueryTile tile = mTileProvider.getTileAt(0);
        onView(recyclerViewMatcher).perform(scrollTo(0));
        onView(withText(tile.displayTitle)).perform(click());

        // Make sure the omnibox opens.
        OmniboxTestUtils.waitForFocusAndKeyboardActive(
                (UrlBar) mActivityTestRule.getActivity().findViewById(R.id.url_bar), true);
        onView(withId(R.id.url_bar))
                .check(ViewAssertions.matches(
                        withText(org.hamcrest.Matchers.containsString(tile.queryText))));
    }

    /** Tests that clicking a tile on a multi-depth list opens the omnibox. */
    @Test
    @SmallTest
    public void testClickTileOpensOmniboxTwoTiers() throws Exception {
        setUp(2 /* levels */);
        Matcher<View> recyclerViewMatcher = withParent(withId(R.id.query_tiles));
        matchList(recyclerViewMatcher, mTileProvider.getChildrenOf());

        // Simulate a click on the first tile.
        QueryTile tile1 = mTileProvider.getTileAt(3);
        QueryTile tile2 = mTileProvider.getTileAt(3, 2);
        onView(recyclerViewMatcher).perform(scrollTo(3));
        onView(withText(tile1.displayTitle)).perform(click());
        matchList(recyclerViewMatcher, mTileProvider.getChildrenOf(3));

        // Simulate a click on the second tile.
        onView(recyclerViewMatcher).perform(scrollTo(2));
        onView(withText(tile2.displayTitle)).perform(click());

        // Make sure the omnibox opens.
        OmniboxTestUtils.waitForFocusAndKeyboardActive(
                (UrlBar) mActivityTestRule.getActivity().findViewById(R.id.url_bar), true);
        onView(withId(R.id.url_bar))
                .check(ViewAssertions.matches(
                        withText(org.hamcrest.Matchers.containsString(tile2.queryText))));
    }

    /** Test that clicking on a tile to open the omnibox and pressing back shows the right tiles. */
    @Test
    @SmallTest
    public void testBackOutOfOmniboxRestoresTilePosition() throws Exception {
        setUp(1 /* levels */);
        Matcher<View> recyclerViewMatcher = withParent(withId(R.id.query_tiles));
        matchList(recyclerViewMatcher, mTileProvider.getChildrenOf());

        // Simulate a click on the tile.
        QueryTile tile = mTileProvider.getTileAt(0);
        onView(recyclerViewMatcher).perform(scrollTo(0));
        onView(withText(tile.displayTitle)).perform(click());

        // Make sure the omnibox opens.
        UrlBar urlBar = mActivityTestRule.getActivity().findViewById(R.id.url_bar);
        OmniboxTestUtils.waitForFocusAndKeyboardActive(urlBar, true);
        onView(withId(R.id.url_bar))
                .check(ViewAssertions.matches(
                        withText(org.hamcrest.Matchers.containsString(tile.queryText))));

        // Press back to hide the omnibox.
        // Press back twice - once to minimize keyboard, once to minimize omnibox (sigh).
        InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
        InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
        OmniboxTestUtils.waitForFocusAndKeyboardActive(urlBar, false);
        onView(recyclerViewMatcher).check(ViewAssertions.matches(isScrolledToFront()));
        matchList(recyclerViewMatcher, mTileProvider.getChildrenOf());
    }

    @Test
    @SmallTest
    public void testFocusOmniboxWithZeroSuggest() {
        setUp(1 /* levels */);
        Matcher<View> recyclerViewMatcher = withParent(withId(R.id.query_tiles));
        matchList(recyclerViewMatcher, mTileProvider.getChildrenOf());
        onView(withId(R.id.query_tiles_chip)).check(matches(not(isDisplayed())));

        // Click on the search box. Omnibox should show up.
        onView(withId(R.id.search_box_text)).perform(click());
        UrlBar urlBar = (UrlBar) mActivityTestRule.getActivity().findViewById(R.id.url_bar);
        OmniboxTestUtils.waitForFocusAndKeyboardActive(urlBar, true);
        Assert.assertTrue(urlBar.getText().toString().isEmpty());
    }
}


text:
function [] = testAllMotorsAndSensors()

% Connect the Brick via USB
clear all;
b=EV3;
connected = 0;
i=0;
while connected == 0
    disp(sprintf('Please connect the brick via USB and press any key to continue.\n\n'));
    pause();
    try b.connect('usb')
    catch disp('Connection failed, try again...')
        %discard errors
    end;
    connected = b.isConnected();
    i=i+1;
    if i==3
        error('USB connection failed. You can not continue the test. Restart Matlab and the brick, then try again. If the error occurs again, please contact us.');
    end;
end;

% Connect motors and sensors to ports
connectWires();

% Test motors (USB)
USBresultMotor = motorTest(b, 'USB');

if USBresultMotor == 0
    warning('The USB motor test failed. Please contact us.');
end;

% Test sensors (USB)
USBresultSensor = sensorTest(b, 'USB');

if USBresultSensor == 0
    warning('The USB sensor test failed. Please contact us.');
end;

if (USBresultMotor == 1) && (USBresultSensor == 1)
    disp(sprintf('\n--------------All USB tests passed successfully---------------\n'));
else
    disp(sprintf('\n-----End of USB tests. Some tests failed, notice the warnings.-----\n'));
end;

b.disconnect;
pause(1);

%Connect the Brick via BT
b=EV3;
connected = 0;
i=0;
while connected==0
    disp(sprintf('Please remove the USB wire and use btconnect in the terminal, so that the brick can be\nautomatically connected via BT and press any key to continue.\n\n'));
    pause();
    try b.connect('bt', 'serPort', '/dev/rfcomm0')
    catch all
    end;
    try b.connect('bt', 'serPort', '/dev/rfcomm1')
    catch all
    end;
    pause(1);
    connected = b.isConnected();
    i=i+1;
    if i==3
        error('BT connection failed. You can not continue the test. Did you connect the brick with btconnect? If no, start btconnect in the terminal. If yes, restart Matlab and try again. If the error occurs again, please contact us.');
    end;
end;

%Test motors (BT)
BTresultMotor = motorTest(b, 'BT');

if BTresultMotor == 0
    warning('The BT motor test failed. Please contact us.');
end;

%Test sensors (BT)
BTresultSensor = sensorTest(b, 'BT');

if BTresultSensor == 0
    warning('The BT sensor test failed. Please contact us.');
end;

if (BTresultMotor == 1) && (BTresultSensor == 1)
    disp(sprintf('\n---------------All BT tests passed successfully---------------\n'));
else
    disp(sprintf('\n-----End of BT tests. Some tests failed, notice the warnings.-----\n'));
end;

disp(sprintf('\n------------------------End of the test------------------------\n'));
clear all;

end


text:
body {
    font-size: 24px;
    background-color: #fdfd96;
    color: #fff;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;
    background-size: cover;
    text-shadow: 5px 5px #000;
}
.title {
    font-size: 200px;
    padding: 70px 0;
    text-align: center;
}
.subtitle {
    font-size: 100px;
    padding: 70px 0;
    text-align: center;
}
.footer {
   position: fixed;
   left: 0;
   bottom: 0;
   width: 100%;
   text-align: center;
   font-size: 50px;
}
a {
  color: inherit;
  text-decoration: none;
}


text:
require 'spec_helper'

describe 'file_ensure' do
  let (:msg) { 'ensure set to present on file resource' }

  context 'with fix disabled' do
    context 'correct file resource declarations' do
      let (:code) {
        <<-EOS
        file { '/etc/sudoers':
          ensure => file,
        }

        file { '/etc/fstab':
          ensure => 'target',
          target => '/etc/mtab',
        }

        file { '/tmp/foo':
          ensure => $present,
        }
        EOS
      }

      it 'should not detect any problems' do
        expect(problems).to have(0).problems
      end
    end

    context 'wrong file resource declarations' do
      let (:code) {
        <<-EOS
        file { '/etc/sudoers':
          ensure => present,
        }

        file { '/etc/fstab':
          ensure => 'present',
          target => '/etc/mtab',
        }

        file { '/tmp/foo':
          ensure => $present,
        }
        EOS
      }

      it 'should detect problems' do
        expect(problems).to have(2).problems
      end

      it 'should create a warning' do
        expect(problems).to contain_warning(msg).on_line(2).in_column(21)
        expect(problems).to contain_warning(msg).on_line(6).in_column(21)
      end
    end
  end

  context 'with fix enabled' do
    before do
      PuppetLint.configuration.fix = true
    end

    after do
      PuppetLint.configuration.fix = false
    end

    context 'correct file resource declarations' do
      let (:code) {
        <<-EOS
        file { '/etc/sudoers':
          ensure => file,
        }

        file { '/etc/fstab':
          ensure => 'target',
          target => '/etc/mtab',
        }

        file { '/tmp/foo':
          ensure => $present,
        }
        EOS
      }

      it 'should not detect any problems' do
        expect(problems).to have(0).problems
      end

      it 'should not modify the manifest' do
        expect(manifest).to eq(code)
      end
    end

    context 'wrong file resource declarations' do
      let (:code) {
        <<-EOS
        file { '/etc/sudoers':
          ensure => present,
        }

        file { '/etc/fstab':
          ensure => 'present',
          target => '/etc/mtab',
        }

        file { '/tmp/foo':
          ensure => $present,
        }
        EOS
      }

      it 'should detect two problems' do
        expect(problems).to have(2).problems
      end

      it 'should create a warning' do
        expect(problems).to contain_fixed(msg).on_line(2).in_column(21)
        expect(problems).to contain_fixed(msg).on_line(6).in_column(21)
      end

      it 'should fix the ensure parameter' do
        expect(manifest).to eq(
          <<-EOS
        file { '/etc/sudoers':
          ensure => file,
        }

        file { '/etc/fstab':
          ensure => 'link',
          target => '/etc/mtab',
        }

        file { '/tmp/foo':
          ensure => $present,
        }
          EOS
        )
      end
    end
  end
end


text:
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information.

namespace Aqua.Tests.Dynamic.DynamicObjectMapper
{
    using Aqua.Dynamic;
    using Shouldly;
    using System.Collections.Generic;
    using System.Linq;
    using Xunit;

    public class When_mapping_list_of_string_as_object
    {
        private readonly DynamicObject dynamicObject;

        public When_mapping_list_of_string_as_object()
        {
            dynamicObject = new DynamicObjectMapper().MapObject(new List<string> { "One", null });
        }

        [Fact]
        public void Dynamic_object_should_have_one_property_with_empty_name()
        {
            dynamicObject.Properties.Single().Name.ShouldBe(string.Empty);
        }

        [Fact]
        public void Dynamic_object_type_should_be_array_of_string()
        {
            dynamicObject.Type.ToType().ShouldBe(typeof(List<string>));
        }

        [Fact]
        public void Dynamic_object_should_have_items_property_with_object_array()
        {
            var items = dynamicObject.Values.Single().ShouldBeOfType<object[]>();
            items[0].ShouldBe("One");
            items[1].ShouldBeNull();
        }

        [Fact]
        public void Dynamic_object_should_result_in_list_of_string_when_mapped_back()
        {
            var list = dynamicObject.CreateObject().ShouldBeOfType<List<string>>();
            list[0].ShouldBe("One");
            list[1].ShouldBeNull();
        }
    }
}


text:
import { baseUpdate } from './base'
import { castFunction, castPath } from './util'
import getKey from './getKey'
import setKey from './setKey'

export default function update(data, maybePath, updater) {
  return data == null ? data : baseUpdate(data, castPath(maybePath, data), castFunction(updater), setKey, getKey)
}


text:
package com.evolveum.midpoint.testing.selenide.tests.basictests;

import static com.codeborne.selenide.Condition.*;

import com.codeborne.selenide.SelenideElement;
import com.evolveum.midpoint.testing.selenide.tests.AbstractSelenideTest;
import org.openqa.selenium.By;
import org.testng.annotations.Test;

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

import static com.codeborne.selenide.Selectors.byAttribute;
import static com.codeborne.selenide.Selectors.byText;
import static com.codeborne.selenide.Selectors.byValue;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.close;

/**
 * Created by Kate on 22.08.2015.
 */
public class RoleTests extends AbstractSelenideTest {
    //role fields
    public static final String ROLE_NAME_FIELD = "name:textWrapper:text";
    public static final String ROLE_DISPLAY_NAME_FIELD = "displayName:textWrapper:text";
    public static final String ROLE_DESCRIPTION_FIELD = "description:textWrapper:text";
    public static final String ROLE_TYPE_FIELD = "roleType:textWrapper:text";
    public static final String ROLE_IDENTIFIER_FIELD = "identifier:textWrapper:text";
    public static final String ROLE_RISK_LEVEL_FIELD = "riskLevel:textWrapper:text";
    //role values
    public static final String ROLE_NAME_VALUE = "TestRole";
    public static final String ROLE_DISPLAY_NAME_VALUE = "RoleDisplayName";
    public static final String ROLE_DESCRIPTION_VALUE = "RoleDescription";
    public static final String ROLE_TYPE_VALUE = "RoleType";
    public static final String ROLE_IDENTIFIER_VALUE = "RoleIdentifier";
    public static final String ROLE_RISK_LEVEL_VALUE = "RoleRiskLevel";

    private Map<String, String> roleAttributes = new HashMap<>();

    @Test(priority = 0)
    public void test001createRoleTest(){
        close();
        login();
        //click Roles menu
        $(By.partialLinkText("Roles")).shouldBe(visible).click();
        //click New role menu item
        $(By.linkText("New role")).shouldBe(visible).click();
        //set new role attributes
        roleAttributes.put(ROLE_NAME_FIELD, ROLE_NAME_VALUE);
        roleAttributes.put(ROLE_DISPLAY_NAME_FIELD, ROLE_DISPLAY_NAME_VALUE);
        roleAttributes.put(ROLE_DESCRIPTION_FIELD, ROLE_DESCRIPTION_VALUE);
        roleAttributes.put(ROLE_TYPE_FIELD, ROLE_TYPE_VALUE);
        roleAttributes.put(ROLE_IDENTIFIER_FIELD, ROLE_IDENTIFIER_VALUE);
        roleAttributes.put(ROLE_RISK_LEVEL_FIELD, ROLE_RISK_LEVEL_VALUE);
        setFieldValues(roleAttributes);
        //click Save button
        $(By.linkText("Save")).shouldBe(visible).click();
        //check if Success message appears
        $(byText("Success")).shouldBe(visible);
        //search for newly created role
        searchForElement(ROLE_NAME_VALUE);
        //click on the found role
        $(By.linkText(ROLE_NAME_VALUE)).shouldBe(visible).click();
        //check role attributes are filled in with correct values
        checkObjectAttributesValues(roleAttributes);

    }

    @Test(priority = 1, dependsOnMethods = {"test001createRoleTest"})
    public void test002updateRoleTest(){
        //click Roles menu
        $(By.partialLinkText("Roles")).shouldBe(visible).click();
        //click List roles menu item
        $(By.linkText("List roles")).shouldBe(visible).click();
        //search for newly created role
        searchForElement(ROLE_NAME_VALUE);
        //click on the found role
        $(By.linkText(ROLE_NAME_VALUE)).shouldBe(visible).click();
        //update role attributes values
        Set<String> attributeFielldNames = roleAttributes.keySet();
        Map<String, String> roleAttributesUpdated = new HashMap<>();
        for (String attributeFieldName : attributeFielldNames){
            roleAttributesUpdated.put(attributeFieldName, roleAttributes.get(attributeFieldName) + UPDATED_VALUE);
        }
        setFieldValues(roleAttributesUpdated);
        //click Save button
        $(By.linkText("Save")).shouldBe(visible).click();
        //check if Success message appears
        $(byText("Success")).shouldBe(visible);
        //search for newly created role
        searchForElement(ROLE_NAME_VALUE + UPDATED_VALUE);
        //click on the found role
        $(By.linkText(ROLE_NAME_VALUE  + UPDATED_VALUE)).shouldBe(visible).click();
        //check role attributes are filled in with correct values
        checkObjectAttributesValues(roleAttributesUpdated);
    }

    @Test (priority = 2, dependsOnMethods = {"test001createRoleTest"})
    public void test003deleteRoleTest(){
        //click Roles menu
        $(By.partialLinkText("Roles")).shouldBe(visible).click();
        //click List roles menu item
        $(By.linkText("List roles")).shouldBe(visible).click();
        //search for created role
        searchForElement(ROLE_NAME_VALUE + UPDATED_VALUE);
        //select found role checkbox
        $(byAttribute("type", "checkbox")).shouldBe(visible).click();
        //click on the menu icon in the upper right corner of the roles list
        $(By.className("cog")).find(By.className("caret")).shouldBe(visible).click();
        //click Delete menu item
        $(By.linkText("Delete")).shouldBe(visible).click();
        //click Yes button in the Confirm delete window
        $(By.linkText("Yes")).shouldBe(visible).click();
        //check if success message appears after role deletion
        $(byText("The role(s) have been successfully deleted.")).shouldBe(visible);
    }

}


text:
<?php
class Tache extends CI_Controller {

	public function __construct() {

		parent::__construct();
		$this->load->model('Tache_model');
	}

	public function view($id) {

		$this->load->library('form_validation');
		$this->load->model('Projet_model');

		$tache = $this->Tache_model->get_tache($id);
		$data['tache'] = $tache;
		$data['equipiers'] = $tache->sharedPersonneList;

        $projet = $this->Projet_model->get_projet($tache->projet_id);

        $data['equipiersDispo'] = $projet->ownPersonneList;

        $this->form_validation->set_rules('equipier', 'equipier', 'required');

        if ($this->form_validation->run() === FALSE)
        {
        	$this->title = $tache->nom;
            $this->load->view('tache/view', $data);
        }
        else
        {
            $this->Tache_model->affecter_equipier($tache);
            $tache = $tache->fresh();
			$data['tache'] = $tache;
			$data['equipiers'] = $tache->sharedPersonneList;
            $this->load->view('tache/view', $data);
        }
	}

	public function nouveau($idProjet) {

		$this->load->helper('form');
		$this->load->library('form_validation');
		$this->load->model('Projet_model');

		$data['title'] = 'Créer une nouvelle tache';

		$projet = $this->Projet_model->get_projet($idProjet);
        $data['projet'] = $projet;

		$this->form_validation->set_rules('nom', 'nom de la tache', 'required');
		$this->form_validation->set_rules('description', 'description', 'required');
		$this->form_validation->set_rules('duree', 'duree', 'required');

		if ($this->form_validation->run() === FALSE)
		{
			$this->title = "Création d'une tache";
			$this->load->view('tache/nouveau', $data);
		}
		else
		{
			$this->Tache_model->set_tache($projet);
			redirect(site_url('projet/listeTache/'.$idProjet));
		}
	}

	public function modifier($id) {

		$this->load->helper('form');
		$this->load->library('form_validation');

		$data['title'] = 'Modifier un tache';
		$tache = $this->Tache_model->get_tache($id);
		$data['tache'] = $tache;

		$this->form_validation->set_rules('nom', 'nom', 'required');
		$this->form_validation->set_rules('description', 'description', 'required');
		$this->form_validation->set_rules('duree', 'duree', 'required');

		if ($this->form_validation->run() === FALSE)
		{
			$this->title = "Modifier d'une tache";
			$this->load->view('tache/modifier', $data);
		}
		else
		{
			$this->Tache_model->update_tache($tache);
			redirect(site_url('projet/listeTache/'.$tache->projet_id));
		}
	}

	public function supprimer($id) {

		$this->load->helper('form');
        $this->load->library('form_validation');

        $data['title'] = 'Supprimer la tache';
        $tache = $this->Tache_model->get_tache($id);
        $data['tache'] = $tache;

        $this->form_validation->set_rules('check', 'check', 'required');

        if ($this->form_validation->run() === FALSE)
        {
            $this->load->view('tache/supprimer', $data);
        }
        else
        {
            $this->Tache_model->delete_tache($id);
            redirect(site_url('projet/listeTache/'.$tache->projet_id));
        }
	}
}


text:
export class EntryView<K, V> {
    key: K;
    value: V;
    cost: Long;
    creationTime: Long;
    expirationTime: Long;
    hits: Long;
    lastAccessTime: Long;
    lastStoreTime: Long;
    lastUpdateTime: Long;
    version: Long;
    evictionCriteriaNumber: Long;
    ttl: Long;
}


text:
package Google::Ads::GoogleAds::V12::Enums::ListingGroupFilterVerticalEnum;

use strict;
use warnings;

use Const::Exporter enums => [
  UNSPECIFIED => "UNSPECIFIED",
  UNKNOWN     => "UNKNOWN",
  SHOPPING    => "SHOPPING"
];

1;


text:
package client

const (
	NodeDaemonEndpointsType                 = "nodeDaemonEndpoints"
	NodeDaemonEndpointsFieldKubeletEndpoint = "kubeletEndpoint"
)

type NodeDaemonEndpoints struct {
	KubeletEndpoint DaemonEndpoint `json:"kubeletEndpoint,omitempty"`
}


text:
/*
 * InterpolationCallback.cpp
 *
 *  Created on: Mar 7, 2013
 *      Author: kristof
 */
#include "peanoclaw/pyclaw/InterpolationCallbackWrapper.h"
#include "peanoclaw/pyclaw/PyClawState.h"
#include "peanoclaw/Patch.h"

peanoclaw::pyclaw::InterpolationCallbackWrapper::InterpolationCallbackWrapper(
  InterPatchCommunicationCallback interpolationCallback
) : _interpolationCallback(interpolationCallback) {

}

peanoclaw::pyclaw::InterpolationCallbackWrapper::~InterpolationCallbackWrapper() {

}

void peanoclaw::pyclaw::InterpolationCallbackWrapper::interpolateSolution (
  const tarch::la::Vector<DIMENSIONS, int>&    destinationSize,
  const tarch::la::Vector<DIMENSIONS, int>&    destinationOffset,
  peanoclaw::Patch& source,
  peanoclaw::Patch& destination,
  bool interpolateToUOld,
  bool interpolateToCurrentTime,
  bool useTimeUNewOrTimeUOld
) {

  PyClawState sourceState(source);
  PyClawState destinationState(destination);

  _interpolationCallback(
    sourceState._q,
    sourceState._qbc,
    sourceState._aux,
    source.getSubdivisionFactor()(0),
    source.getSubdivisionFactor()(1),
    #ifdef Dim3
    source.getSubdivisionFactor()(2),
    #else
    0,
    #endif
    source.getSize()(0),
    source.getSize()(1),
    #ifdef Dim3
    source.getSize()(2),
    #else
    0.0,
    #endif
    source.getPosition()(0),
    source.getPosition()(1),
    #ifdef Dim3
    source.getPosition()(2),
    #else
    0.0,
    #endif
    source.getTimeIntervals().getCurrentTime(),
    source.getTimeIntervals().getTimestepSize(),

    destinationState._q,
    destinationState._qbc,
    destinationState._aux,
    destination.getSubdivisionFactor()(0),
    destination.getSubdivisionFactor()(1),
    #ifdef Dim3
    destination.getSubdivisionFactor()(2),
    #else
    0,
    #endif
    destination.getSize()(0),
    destination.getSize()(1),
    #ifdef Dim3
    destination.getSize()(2),
    #else
    0.0,
    #endif
    destination.getPosition()(0),
    destination.getPosition()(1),
    #ifdef Dim3
    destination.getPosition()(2),
    #else
    0.0,
    #endif
    destination.getTimeIntervals().getCurrentTime(),
    destination.getTimeIntervals().getTimestepSize(),
    source.getUnknownsPerSubcell(),
    source.getNumberOfParametersWithoutGhostlayerPerSubcell()
  );
}


text:
Installation Instructions
=========================

Getting MvcAccount
------------------
The first step is to install the [MvcAccount](http://www.nuget.org/packages/MvcAccount) package using NuGet:

```powershell
Install-Package MvcAccount
```

Registration
------------
By installing the MvcAccount package it will also install [MvcCodeRouting](http://mvccoderouting.codeplex.com/), which you can use to register MvcAccount like this:

```csharp
using System;
using System.Web.Routing;
using System.Web.Mvc;
using MvcCodeRouting;

void Application_Start() {
   RegisterRoutes(RouteTable.Routes);
   RegisterViewEngines(ViewEngines.Engines);
}

void RegisterRoutes(RouteCollection routes) {

   routes.MapCodeRoutes(
      baseRoute: "Account",
      rootController: typeof(MvcAccount.AccountController),
      settings: new CodeRoutingSettings {
         EnableEmbeddedViews = true,
         Configuration = new MvcAccount.AccountConfiguration {
            // set configuration properties
         }
      }
   );
}

void RegisterViewEngines(ViewEngineCollection engines) {
   engines.EnableCodeRouting();
}
```

The `baseRoute` parameter can be anything you want, adjust the `loginUrl` accordingly:

```xml
<system.web>
   <authentication mode="Forms">
      <forms loginUrl="~/Account/SignIn" />
   </authentication>
</system.web>
```

Dependencies
------------
Before you can start using MvcAccount you must provide its dependencies. There are three ways to do this, you can use constructor injection for MvcAccount's controllers, you can set various resolver settings on [AccountConfiguration](api/MvcAccount/AccountConfiguration/README.md#properties) for each dependency, or you can just set [AccountConfiguration.DependencyResolver](api/MvcAccount/AccountConfiguration/DependencyResolver.md).

### Option 1: Constructor injection for MvcAccount's controllers
If you are not familiar with dependency injection see Option 2.

### Option 2: Set the various resolver settings for each dependency
This option is the easiest one to setup.

```csharp
routes.MapCodeRoutes(
   // ... code omitted for clarity
   settings: new CodeRoutingSettings {
      Configuration = new MvcAccount.AccountConfiguration {
         AccountRepositoryResolver = () => new MyAccountRepository(),
         PasswordServiceResolver => () => new MvcAccount.Web.Helpers.CryptoPasswordService()
      }
   }
);
```

### Option 3: Set AccountConfiguration.DependencyResolver
Use this one if you are already using a dependency injection container.

```csharp
routes.MapCodeRoutes(
   // ... code omitted for clarity
   settings: new CodeRoutingSettings {
      Configuration = new MvcAccount.AccountConfiguration {
         DependencyResolver = (type) => MyContainer.Resolve(type)
      }
   }
);
```

### MvcAccount.AccountRepository
Responsible for querying account information and persisting changes. The Find methods must return an instance of a public class with the following public properties:

```csharp
// The class name has no semantics
public class UserAccount {

   // Any type is allowed (e.g. Int32, Guid, etc.)
   public object Id { get; set; }

   public string Username { get; set; }

   public string Password { get; set; }

   public string Email { get; set; }

   public DateTime? LastSignIn { get; set; }

   public int FailedSignInAttempts { get; set; }

   public DateTime? FailedSignInAttemptWindowStart { get; set; }

   public bool EmailVerified { get; set; }

   public DateTime? EmailVerificationTicketExpiration { get; set; }

   public DateTime? EmailChangeTicketExpiration { get; set; }

   public DateTime? PasswordResetTicketExpiration { get; set; }

   public bool Disabled { get; set; }
}
```

If you use the e-mail address as the username you can simply make the `Username` getter/setter call the `Email` getter/setter.

### MvcAccount.PasswordService
Responsible for encrypting and comparing passwords. MvcAccount includes three implementations you can choose from:

- [ClearTextPasswordService](api/MvcAccount/ClearTextPasswordService/README.md): Use if passwords are stored in clear text.
- [CryptoPasswordService](api/MvcAccount.Web.Helpers/CryptoPasswordService/README.md): PBKDF2 hashing ([Recommended](http://brockallen.com/2012/10/19/password-management-made-easy-in-asp-net-with-the-crypto-api/))
- [SqlMembershipProviderPasswordService](api/MvcAccount.Web.Security/SqlMembershipProviderPasswordService/README.md): Provides SHA1 and MachineKey-based encryption, as implemented by [SqlMembershipProvider](http://msdn.microsoft.com/library/system.web.security.sqlmembershipprovider).

Layout
------
MvcAccount does not include a layout, you have to provide it. The view title is passed via `Page.Title`.

SMTP
----
You need to [configure an SMTP server](http://msdn.microsoft.com/library/w355a94k) so MvcAccount can send notification and verification emails:

```xml
<system.net>
   <mailSettings>
      <smtp from="noreply@example.com">
         <network
            host="mail.example.com"
            userName="noreply@example.com"
            password="ThisIsNotARealPassword"/>
      </smtp>
   </mailSettings>
</system.net>
```

Languages
---------
MvcAccount is fully localized in several languages. Localized resources are available as separate satellite packages:

- [Spanish (es)](http://www.nuget.org/packages/MvcAccount.es)
- [Finnish (fi)](http://www.nuget.org/packages/MvcAccount.fi)
- [Portuguese (pt)](http://www.nuget.org/packages/MvcAccount.pt)

The easiest way to view the pages using the preferred language setting of the user's browser is to set `uiCulture="auto"` in Web.config:

```xml
<system.web>
   <globalization uiCulture="auto" />
</system.web>
```

English (en) is the fallback language.

### Next: [Customization →](Customization.md)


text:
require 'test_helper'

class WorkGroupsControllerTest < ActionController::TestCase

  def est_title
    login_as :normal_user
    get :new
    assert_select "title",:text=>/MethodBox.*/, :count=>1
  end

  def test_create_work_group
    login_as :normal_user
    assert_difference 'WorkGroup.count' do
      create_work_group()
      assert_nil flash[:error]
    end
  end

  def test_create_no_group_refused
    login_as :normal_user
    assert_no_difference 'WorkGroup.count' do
      post :create
      assert_equal flash[:error], "Please use new form"
    end
  end

  def test_create_no_name_refused
    login_as :normal_user
    assert_no_difference 'WorkGroup.count' do
      create_work_group(:name => nil)
      assert_equal flash[:error], "Please use new form"
    end
  end

  def test_create_duplicate_name_refused
    login_as :normal_user
    assert_no_difference 'WorkGroup.count' do
      create_work_group(:name => "Sample Group")
      assert_equal flash[:error], "Title must be unique"
    end
  end

  protected
  def create_work_group(options = {})
    post :create, :group => {:name => 'A Test workgroup', :info => 'A bit of description', :user => users(:work_group_owner) }.merge(options)
  end

end


text:
<?php

namespace Pages\PagesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class PagesController extends Controller
{
    public function menuAction()
    {
        $em = $this->getDoctrine()->getManager();
        $pages = $em->getRepository('PagesBundle:Pages')->findAll();

        return $this->render('PagesBundle:Default:pages/modulesUsed/menu.html.twig',array('pages'=>$pages));
    }

    public function pageAction($slug)
    {
        $em = $this->getDoctrine()->getManager();
        $page = $em->getRepository('PagesBundle:Pages')->findOneBy(array('slug'=>$slug)); // ou findonebyslug

        if (!$page) throw $this->createNotFoundException('la page n\'�xiste pas');

        return $this->render('PagesBundle:Default:pages/layout/pages.html.twig',array('page'=>$page) );
    }
}


text:
using System;
using System.Collections.Generic;
using System.Security.Claims;
using Thinktecture.IdentityModel.Extensions;

namespace Thinktecture.IdentityServer.Protocols.OpenIdConnect
{
    public class IdentityToken : OidcToken
    {
        public string Subject { get; set; }

        protected override List<Claim> CreateClaims()
        {
            if (string.IsNullOrWhiteSpace(Subject))
            {
                throw new InvalidOperationException("Subject is empty");
            }

            var claims = base.CreateClaims();
            claims.Add(new Claim(OidcConstants.ClaimTypes.Subject, Subject));
            claims.Add(new Claim("iat", DateTime.UtcNow.ToEpochTime().ToString()));

            return claims;
        }
    }
}


text:
"""@package src.common.restlib
"""

from argparse import ArgumentError, ArgumentTypeError
import json
import logging
import re
import requests
from django.conf.urls import url, patterns
from django.http import HttpResponse
import inspect

class ServerProxy(object):
    """
    Wrapper class around REST like calls to cc1 functions.

    usage:

    :::python
    #s = ServerProxy("http://samplehost:port")
    ## maps to http://samplehost:port/module1/f1
    #r = s.module1.f1(arg1, arg2, kwarg1=val, ...)
    ## maps to http://samplehost:port/f1
    #r = s.f1(arg1)
    ## maps to http://samplehost:port/module1/submodule2/f1
    #r = s.module1.submodule2.f1(arg1, arg2, kwarg1=val, kwarg2=val)

    returned value is unwrapped from json so it can be readily used.
    Depending on status codes approperiate Exceptions are raised

    """
    class RemoteCaller(object):
        """
        Hepler class used as a simple mapper of dot notation to URL notation, as well as encoding passed arguments to JSON
        and decoding response from JSON
        """

        def __init__(self, server_proxy, function_name, logger=None):
            self.server_proxy = server_proxy
            # :type: string
            self.function_name = function_name
            if logger:
                self.logger = logger
            else:
                logger = logging.getLogger()
                # effectivly disable logging
                logger.setLevel(100)

        def __call__(self, *args, **kwargs):
            self.logger.info("called %s/%s   body: %s" %
                              (self.server_proxy.server_address,
                               self.function_name,
                               json.dumps({"args": args, "kwargs": kwargs})))

            r = requests.get("%s/%s" % (self.server_proxy.server_address, self.function_name),
                             data=json.dumps({"args": args, "kwargs": kwargs}))

            self.logger.info("response from %s/%s    is:%s" % (self.server_proxy.server_address,
                                                                self.function_name, r))

            if not r.ok:
                self.logger.error("HTTP response is not 200, error occured: %s with data: %s" % (r.status_code,
                                                                                r.text))
                raise Exception("Status %s failed to call function" % r.status_code)
            r = json.loads(r.text)
            if not isinstance(r, dict):
                self.logger.error("Returned object is %s expected dict. Data: %s" % (type(r), r))
                raise Exception("Returned object is %s expected dict" % type(r))
            if 'status' not in r or 'data' not in r:
                self.logger.error("Returned object is malformatted: %s" % r)
                raise Exception("Returned object is malformatted: %s" % r)
            return r

        def __getattr__(self, item):
            self.function_name = "%s/%s" % (self.function_name, item)
            self.logger.debug("called . on RemoteCaller. Current address string is: %s/%s" %
                              (self.server_proxy.server_address, self.function_name))
            return self

    def __init__(self, server_address, log_level=100, logger=None):
        """
        :param log_level: this argument is used only if no external logger is supplied. It sets reporting level for an
                          on screen logging Handler. if logger is supplied this argument has no effect. (logging level
                          is defined in handlers connected to that logger)
                          level should be specified as one of the constants defined in logging module:
                          - 100 (effectively disables logging) //default
                          - logging.CRITICAL
                          - logging.ERROR
                          - logging.WARNING / logging.WARN
                          - logging.INFO
                          - logging.DEBUG

        :type log_level: int
        :param logger: Logger object to which logging will be performed, defaults to None (in this case all logging is
                       send to screen
        :type logger: logging.Logger
        :param server_address: server address in format protocol://host:port
                               protocol must be http or https (without certificate checking)
                               server_address can not end with slash '/'
        :type server_address: str
        """

        if logger:
            self.logger = logger
        else:
            h = logging.StreamHandler()
            h.setLevel(log_level)
            self.logger = logging.getLogger()
            self.logger.setLevel(log_level)
            self.logger.addHandler(h)

        self.server_address = server_address
        if not re.match(r'^(http)s?://[a-zA-Z0-9\.]+(:\d+)?/([a-zA-Z0-9]+/)*$', self.server_address):
            self.logger.error("%s is not well formatted address" % self.server_address)
            raise ValueError("%s is not well formatted address" % self.server_address)

    def __getattr__(self, item):
        return ServerProxy.RemoteCaller(self, item, logger=self.logger)

def register_object(object_to_register, prefix='', decorator=None):
    """
    Generates list of django urls pointing to all public (not starting with '_') methods of the supplied object

    generated urls is in form:

    #prefix/name_of_first_public_method
    #prefix/name_of_second_public_method
    #prefix/name_of_third_public_method
    #...

    :param object_to_register:
    :type object_to_register: object
    :param prefix: prefix can not start with the '/' character (same as django urls)
    :type prefix: str
    :param decorator: decorator applied to function before calling it by JSONWrapper (default=None)
    :type decorator: function
    :return: :raise ArgumentError: returns list of django urls
    :rtype: list
    """
    if len(prefix) > 0 and prefix[0] == '/':
        raise ArgumentError("prefix can not start with '/'")
    members = inspect.getmembers(object_to_register, predicate=inspect.ismethod)
    urls = []
    for method_name, function in members:
        if not method_name[0] == "_":
            urls += register_function(function, prefix, decorator)
    return urls

def register_function(function_to_register, prefix='', decorator=None, log_name=None, logger=None):
    """
    Generates list containing single django url pointing to suppled function

    generated url is in form:

    #prefix/name_of_registered_function

    :param function_to_register: function to which sensible django url should be generated. This argument can be either
                                 callable object, or tuple having form (callable, "rest_call_name") where second element
                                 of tuple will be name under which function will be registered. Else defaults to
                                 function_to_register.__name__, this functionality should not be used, except for
                                 situations when decorators apart from the one supplied as argument of this function
                                 are present
    :type function_to_register: __builtin__.callable or tuple
    :param prefix: prefix can not start with the '/' character (same as django urls)
    :type prefix:
    :param decorator: decorator applied to function before calling it by JSONWrapper (default=None)
    :type decorator: function
    :param log_name: this name will be used with logging and error functions, defaults to function_to_register.__name__
                     or if decorator parameter is supplied to "@decorator.__name__(function_to_register.__name__)"
    :type log_name: str
    :return: :raise ArgumentError: returns list of django urls
    :rtype: list
    """

    if len(prefix) > 0 and prefix[0] == '/':
        raise ArgumentError("prefix can not start with '/'")

    if isinstance(function_to_register, tuple):
        rest_call_name = function_to_register[1]
        function_to_register = function_to_register[0]
    else:
        rest_call_name = function_to_register.__name__

    function_to_call = JsonWrapper(function_to_register, function_to_call_name=log_name or function_to_register.__name__, logger=logger)
    if decorator is not None:
        function_to_call = JsonWrapper(decorator(function_to_register),
                                       function_to_call_name=log_name or "@%s(%s)" % (decorator.__name__,
                                                                                function_to_register.__name__), logger=logger)

    urls = patterns('', url("^%s%s" % (prefix, rest_call_name), function_to_call))
    return urls

def register_functions(*args, **kwargs):
    """
    called in form:
    :::python
    #with default prefix '/'
    urls = register_functions(funct1, funct2, funct3, ...)
    #or with prefix
    urls = register_functions(funct1, funct2, funct3, ..., prefix="some/path/")
    #or with decorator
    urls = register_functions(funct1, funct2, funct3, ..., prefix="some/path/", decorator=my_decorator)

    Generates list of django urls pointing to all callables supplied as arguments

    generated url is in form:

    #prefix/name_of_first_registered_function
    #prefix/name_of_second_registered_function
    #prefix/name_of_third_registered_function
    #...

    :param functions_to_register:
    :type functions_to_register: __builtin__.callable
    :param prefix: prefix can not start with the '/' character (same as django urls)
    :type prefix: str
    :param decorator: decorator applied to function before calling it by JSONWrapper (default=None)
    :type decorator: function
    :return: :raise ArgumentError: returns list of django urls
    :rtype: list
    """
    prefix = kwargs.get('prefix', '')
    decorator = kwargs.get('decorator', None)
    urls = []
    for function in args:
        # check if argument is an function
        if not hasattr(function, '__call__'):
            raise ArgumentTypeError("supplied object is not callable")
        urls += register_function(function, prefix=prefix, decorator=decorator, logger=kwargs.get('logger'))
    return urls

class JsonWrapper(object):
    """
    wrapper object for callable object which provides abstraction layer for packing and unpacking json
    (to function arguments) as well as wrapping function return object into http request, as well as encoding exceptions
    raised by function into approperiate http status_codes.
    """

    def __init__(self, function_to_call, function_to_call_name=None, logger=None):
        """
        :param function_to_call_name: this name will be used with any error handling, defaults to function_to_call.__name__
                                      should be used in case of using decorators on base function
        :type function_to_call_name: str
        :param function_to_call: callable object which will be wrapped by JsonWrapper
        :type function_to_call: __builtin__.callable
        """
        self.function_to_call = function_to_call
        self.function_to_call_name = function_to_call_name or function_to_call.__name__
        self.logger = logger

    def __call__(self, request):
        """
        Wrapper around function call, it converts data passed in HTTPRequest into arguments for the wrapped callable

        :param request:
        :type request: django.http.HttpRequest
        :return: returns data returned by wrapped callable, encoded as JSON in body of the HTTPResonse object
                 (status_code depends on the success of call)
        :rtype: HttpResponse
        """

        fulljson = json.loads(request.body)
        args = fulljson.get('args')
        kwargs = fulljson.get('kwargs')
        kwargs['request'] = request
        try:
            r = self.function_to_call(*args, **kwargs)
            if not isinstance(r, dict):
                raise TypeError("object returned by %s is not dict" % self.function_to_call_name)
            if 'status' not in r:
                raise KeyError("object returned by %s does not contain key 'status'" % self.function_to_call_name)
            if 'data' not in r:
                raise KeyError("object returned by %s does not contain key 'data'" % self.function_to_call_name)
            return HttpResponse(json.dumps({"status": r['status'], "data": r['data']}))
        except KeyError as e:
            response = {"status": "KeyError", "data": e.message}
            return HttpResponse(json.dumps(response))
        except TypeError as e:
            response = {"status": "TypeError", "data": e.message}
        except BaseException as e:
            response = {"status": "call", "data": e.message}
        return HttpResponse(json.dumps(response))


text:
package envoy

import (
	"errors"
	"fmt"
	"io/ioutil"
	"math"
	"math/rand"
	"os"
	"strconv"
	"strings"
	"time"

	envoyBootstrap "github.com/envoyproxy/go-control-plane/envoy/config/bootstrap/v2"
	"github.com/ghodss/yaml"
	"github.com/hashicorp/go-multierror"

	"istio.io/pkg/log"
)

const (
	// InvalidBaseID used to indicate that the Envoy BaseID has not been set. Attempting
	// to Close this BaseID will have no effect.
	InvalidBaseID = BaseID(math.MaxUint32)
)

// FlagName is the raw flag name passed to envoy.
type FlagName string

func (n FlagName) String() string {
	return string(n)
}

// Option for an Envoy Instance.
type Option interface {
	// FlagName returns the flag name used on the command line.
	FlagName() FlagName

	// FlagValue returns the flag value used on the command line. Can be empty for boolean flags.
	FlagValue() string

	apply(ctx *configContext)
	validate(ctx *configContext) error
}

type Options []Option

// ToArgs creates the command line arguments for the list of options.
func (options Options) ToArgs() []string {
	// Get the arguments for the command.
	args := make([]string, 0, len(options)*2)
	for _, o := range options {
		name := o.FlagName()
		if name != "" {
			args = append(args, name.String())
			value := o.FlagValue()
			if value != "" {
				args = append(args, value)
			}
		}
	}
	return args
}

// Validate the Options.
func (options Options) Validate() error {
	return options.validate(newConfigContext())
}

// validate is an internal method for validation.
func (options Options) validate(ctx *configContext) error {
	// Check for any duplicate user-specified options
	if err := options.checkDuplicates(); err != nil {
		return err
	}

	// Add a placeholder ConfigPath option. Can and should be overridden by user-provided value.
	// Used for force config validation to ensure that either configPath or configYaml has been set.
	opts := append(Options{ConfigPath("")}, options...)

	// Apply the options to the context.
	for _, o := range opts {
		o.apply(ctx)
	}

	// Validate all of the options.
	for _, o := range opts {
		if err := o.validate(ctx); err != nil {
			return err
		}
	}

	return nil
}

// checkDuplicates ensures to make sure that there are no duplicate options.
func (options Options) checkDuplicates() error {
	optionSet := make(map[FlagName]struct{})
	for _, o := range options {
		if _, ok := optionSet[o.FlagName()]; ok {
			return fmt.Errorf("multiple options specified for %s", o.FlagName())
		}
		optionSet[o.FlagName()] = struct{}{}
	}
	return nil
}

// NewOptions creates new Options from the given raw Envoy arguments. Returns an error if a problem
// was encountered while parsing the arguments.
func NewOptions(args ...string) (Options, error) {
	out := make(Options, 0, len(args))
	var next *genericOption
	for _, arg := range args {
		arg = strings.TrimSpace(arg)
		if strings.HasPrefix(arg, "-") {
			// The argument is a new flag name.
			if next != nil {
				out = append(out, next)
			}

			flagName := FlagName(arg)

			if v, ok := flagValidators[flagName]; ok {
				// Known flag - use an existing validator.
				next = &genericOption{
					v: v,
				}
			} else {
				// Unknown flag - No validator.
				next = &genericOption{
					v: &flagValidator{
						flagName: flagName,
						apply:    func(*configContext, string) {},
						validate: func(*configContext, string) error {
							return nil
						},
					},
				}
			}
		} else {
			// The argument is a flag value.
			if next == nil {
				return nil, fmt.Errorf("raw argument missing flag name: %s", arg)
			}

			// Completed the current flag.
			next.value = arg
			out = append(out, next)
			next = nil
		}
	}

	if next != nil {
		out = append(out, next)
	}

	return out, nil
}

// LogLevel is an Option that sets the Envoy log level.
type LogLevel string

var _ Option = LogLevel("")

const (
	LogLevelTrace    LogLevel = "trace"
	LogLevelDebug    LogLevel = "debug"
	LogLevelInfo     LogLevel = "info"
	LogLevelWarning  LogLevel = "warning"
	LogLevelCritical LogLevel = "critical"
	LogLevelOff      LogLevel = "off"
)

func (l LogLevel) FlagName() FlagName {
	return logLevelValidator.flagName
}

func (l LogLevel) FlagValue() string {
	return string(l)
}

func (l LogLevel) apply(ctx *configContext) {
	logLevelValidator.apply(ctx, l.FlagValue())
}

func (l LogLevel) validate(ctx *configContext) error {
	return logLevelValidator.validate(ctx, l.FlagValue())
}

var logLevelValidator = registerFlagValidator(&flagValidator{
	flagName: "--log-level",
	apply: func(ctx *configContext, flagValue string) {
		// Do nothing.
	},
	validate: func(ctx *configContext, flagValue string) error {
		logLevel := LogLevel(flagValue)
		switch logLevel {
		case LogLevelTrace, LogLevelDebug, LogLevelInfo, LogLevelWarning, LogLevelCritical, LogLevelOff:
			return nil
		default:
			return fmt.Errorf("unsupported log level: %v", logLevel)
		}
	},
})

// ComponentLogLevel defines the log level for a single component.
type ComponentLogLevel struct {
	Name  string
	Level LogLevel
}

func (l ComponentLogLevel) String() string {
	return l.Name + ":" + string(l.Level)
}

// ParseComponentLogLevels parses the given envoy --component-log-level value string.
func ParseComponentLogLevels(value string) ComponentLogLevels {
	parts := strings.Split(value, ",")

	out := make(ComponentLogLevels, 0, len(parts))

	for _, part := range parts {
		keyAndValue := strings.Split(part, ":")
		if len(keyAndValue) == 2 {
			out = append(out, ComponentLogLevel{
				Name:  keyAndValue[0],
				Level: LogLevel(keyAndValue[1]),
			})
		}
	}

	return out
}

// ComponentLogLevels is an Option for multiple component log levels.
type ComponentLogLevels []ComponentLogLevel

var _ Option = ComponentLogLevels{}

func (l ComponentLogLevels) apply(ctx *configContext) {
	componentLogLevelValidator.apply(ctx, l.FlagValue())
}

func (l ComponentLogLevels) validate(ctx *configContext) error {
	return componentLogLevelValidator.validate(ctx, l.FlagValue())
}

func (l ComponentLogLevels) FlagName() FlagName {
	return componentLogLevelValidator.flagName
}

func (l ComponentLogLevels) FlagValue() string {
	strLevels := make([]string, 0, len(l))
	for _, cl := range l {
		strLevels = append(strLevels, cl.String())
	}
	return strings.Join(strLevels, ",")
}

var componentLogLevelValidator = registerFlagValidator(&flagValidator{
	flagName: "--component-log-level",
	apply: func(ctx *configContext, flagValue string) {
		// Do nothing.
	},
	validate: func(ctx *configContext, flagValue string) error {
		l := ParseComponentLogLevels(flagValue)
		for i, cl := range l {
			if cl.Name == "" {
				return fmt.Errorf("name is empty for component log level %d", i)
			}
			if err := cl.Level.validate(ctx); err != nil {
				return fmt.Errorf("level invalid for component log level %d: %v", i, err)
			}
		}
		return nil
	},
})

// IPVersion is an enumeration for IP versions for the --local-address-ip-version flag.
type IPVersion string

const (
	IPV4 IPVersion = "v4"
	IPV6 IPVersion = "v6"
)

// LocalAddressIPVersion sets the --local-address-ip-version flag, which sets the IP address
// version used for the local IP address. The default is V4.
func LocalAddressIPVersion(v IPVersion) Option {
	return &genericOption{
		value: string(v),
		v:     localAddressIPVersionValidator,
	}
}

var localAddressIPVersionValidator = registerFlagValidator(&flagValidator{
	flagName: "--local-address-ip-version",
	validate: func(ctx *configContext, flagValue string) error {
		ipVersion := IPVersion(flagValue)
		switch ipVersion {
		case IPV4, IPV6:
			return nil
		default:
			return fmt.Errorf("invalid LocalAddressIPVersion %v", ipVersion)
		}
	},
})

// ConfigPath sets the --config-path flag, which provides Envoy with the
// to the v2 bootstrap configuration file. If not set, ConfigYaml is required.
func ConfigPath(path string) Option {
	return &genericOption{
		value: path,
		v:     configPathValidator,
	}
}

var configPathValidator = registerFlagValidator(&flagValidator{
	flagName: "--config-path",
	apply: func(ctx *configContext, flagValue string) {
		ctx.configPath = flagValue
	},
	validate: func(ctx *configContext, flagValue string) error {
		// Ensure that either config path or configYaml is specified.
		if ctx.configPath == "" && ctx.configYaml == "" {
			return errors.New("must specify ConfigPath and/or ConfigYaml ")
		}
		if ctx.configPath != "" {
			// Check that the path set in the config exists.
			if _, err := os.Stat(ctx.configPath); os.IsNotExist(err) {
				return fmt.Errorf("configPath file does not exist: %s", ctx.configPath)
			}
		}
		return nil
	},
})

// ConfigYaml sets the --config-yaml flag, which provides Envoy with the
// a YAML string for a v2 bootstrap configuration. If ConfigPath is also set, the values in this
// YAML string will override and merge with the bootstrap loaded from ConfigPath.
func ConfigYaml(yaml string) Option {
	return &genericOption{
		value: yaml,
		v:     configYamlValidator,
	}
}

var configYamlValidator = registerFlagValidator(&flagValidator{
	flagName: "--config-yaml",
	apply: func(ctx *configContext, flagValue string) {
		ctx.configYaml = flagValue
	},
})

// BaseID is an Option that sets the --base-id flag. This is typically only needed when running multiple
// Envoys on the same machine (common in testing environments).
//
// Envoy will allocate shared memory if provided with a BaseID. This shared memory is used during hot restarts.
// It is up to the caller to free this memory by calling Close() on the BaseID when appropriate.
type BaseID uint32

var _ Option = BaseID(0)

func (bid BaseID) FlagName() FlagName {
	return baseIDValidator.flagName
}

func (bid BaseID) FlagValue() string {
	return strconv.FormatUint(uint64(bid), 10)
}

func (bid BaseID) apply(ctx *configContext) {
	baseIDValidator.apply(ctx, bid.FlagValue())
}

func (bid BaseID) validate(ctx *configContext) error {
	return baseIDValidator.validate(ctx, bid.FlagValue())
}

// GetInternalEnvoyValue returns the value used internally by Envoy. Envoy internally multiplies the base ID
// from the command line by 10 so that they have spread of domain sockets.
func (bid BaseID) GetInternalEnvoyValue() uint64 {
	return uint64(bid) * 10
}

// Close removes the shared memory allocated by Envoy for this BaseID.
func (bid BaseID) Close() error {
	if bid != InvalidBaseID {
		// Envoy internally multiplies the base ID from the command line by 10 so that they have spread
		// for domain sockets.
		path := fmt.Sprintf("/dev/shm/envoy_shared_memory_%d", bid.GetInternalEnvoyValue())
		if err := os.Remove(path); err != nil {
			return fmt.Errorf("error deleting Envoy base ID %d shared memory %s: %v", bid, path, err)
		}
		log.Debugf("successfully freed Envoy base ID %d shared memory %s", bid, path)
	}
	return nil
}

var baseIDValidator = registerFlagValidator(&flagValidator{
	flagName: "--base-id",
	apply: func(ctx *configContext, flagValue string) {
		if bid, err := strconv.ParseUint(flagValue, 10, 64); err == nil {
			ctx.baseID = BaseID(bid)
		}
	},
	validate: func(ctx *configContext, flagValue string) error {
		if _, err := strconv.ParseUint(flagValue, 10, 64); err != nil {
			return err
		}
		return nil
	},
})

// GenerateBaseID is a method copied from Envoy server tests.
//
// Computes a numeric ID to incorporate into the names of shared-memory segments and
// domain sockets, to help keep them distinct from other tests that might be running concurrently.
func GenerateBaseID() BaseID {
	// The PID is needed to isolate namespaces between concurrent processes in CI.
	pid := uint32(os.Getpid())

	// A random number is needed to avoid BaseID collisions for multiple Envoys started from the same
	// process.
	randNum := rand.Uint32()

	// Pick a prime number to give more of the 32-bits of entropy to the PID, and the
	// remainder to the random number.
	fourDigitPrime := uint32(7919)
	value := pid*fourDigitPrime + randNum%fourDigitPrime

	// TODO(nmittler): Limit to uint16 - Large values seem to cause unexpected shared memory paths in envoy.
	out := BaseID(value % math.MaxUint16)
	return out
}

// Concurrency sets the --concurrency flag, which sets the number of worker threads to run.
func Concurrency(concurrency uint16) Option {
	return &genericOption{
		value: strconv.FormatUint(uint64(concurrency), 10),
		v:     concurrencyValidator,
	}
}

var concurrencyValidator = registerFlagValidator(&flagValidator{
	flagName: "--concurrency",
	validate: func(ctx *configContext, flagValue string) error {
		if _, err := strconv.ParseUint(flagValue, 10, 64); err != nil {
			return err
		}
		return nil
	},
})

// DisableHotRestart sets the --disable-hot-restart flag.
func DisableHotRestart(disable bool) Option {
	var v *flagValidator
	if disable {
		v = disableHotRestartValidator
	}

	return &genericOption{
		v:     v,
		value: "",
	}
}

var disableHotRestartValidator = registerBoolFlagValidator("--disable-hot-restart")

// LogPath sets the --log-path flag, which specifies the output file for logs. If not set
// logs will be written to stderr.
func LogPath(path string) Option {
	return &genericOption{
		value: path,
		v:     logPathValidator,
	}
}

var logPathValidator = registerFlagValidator(&flagValidator{
	flagName: "--log-path",
})

// LogFormat sets the --log-format flag, which specifies the format string to use for log
// messages.
func LogFormat(format string) Option {
	return &genericOption{
		value: format,
		v:     logFormatValidator,
	}
}

var logFormatValidator = registerFlagValidator(&flagValidator{
	flagName: "--log-format",
})

// Epoch sets the --restart-epoch flag, which specifies the epoch used for hot restart.
type Epoch uint32

func (e Epoch) FlagName() FlagName {
	return epochValidator.flagName
}

func (e Epoch) FlagValue() string {
	return strconv.FormatUint(uint64(e), 10)
}

func (e Epoch) apply(ctx *configContext) {
	epochValidator.apply(ctx, e.FlagValue())
}

func (e Epoch) validate(ctx *configContext) error {
	return epochValidator.validate(ctx, e.FlagValue())
}

var epochValidator = registerFlagValidator(&flagValidator{
	flagName: "--restart-epoch",
	apply: func(ctx *configContext, flagValue string) {
		if e, err := strconv.ParseUint(flagValue, 10, 32); err == nil {
			ctx.epoch = Epoch(e)
		}
	},
	validate: func(ctx *configContext, flagValue string) error {
		if _, err := strconv.ParseUint(flagValue, 10, 32); err != nil {
			return err
		}
		return nil
	},
})

// ServiceCluster sets the --service-cluster flag, which defines the local service cluster
// name where Envoy is running
func ServiceCluster(c string) Option {
	return &genericOption{
		value: c,
		v:     serviceClusterValidator,
	}
}

var serviceClusterValidator = registerFlagValidator(&flagValidator{
	flagName: "--service-cluster",
})

// ServiceNode sets the --service-node flag, which defines the local service node name
// where Envoy is running
func ServiceNode(n string) Option {
	return &genericOption{
		value: n,
		v:     serviceNodeValidator,
	}
}

var serviceNodeValidator = registerFlagValidator(&flagValidator{
	flagName: "--service-node",
})

// DrainDuration sets the --drain-time-s flag, which defines the amount of time that Envoy will
// drain connections during a hot restart.
func DrainDuration(duration time.Duration) Option {
	return &genericOption{
		value: strconv.Itoa(int(duration / time.Second)),
		v:     drainDurationValidator,
	}
}

var drainDurationValidator = registerFlagValidator(&flagValidator{
	flagName: "--drain-time-s",
	validate: func(ctx *configContext, flagValue string) error {
		if _, err := strconv.ParseUint(flagValue, 10, 32); err != nil {
			return err
		}
		return nil
	},
})

// ParentShutdownDuration sets the --parent-shutdown-time-s flag, which defines the amount of
// time that Envoy will wait before shutting down the parent process during a hot restart
func ParentShutdownDuration(duration time.Duration) Option {
	return &genericOption{
		value: strconv.Itoa(int(duration / time.Second)),
		v:     parentShutdownDurationValidator,
	}
}

var parentShutdownDurationValidator = registerFlagValidator(&flagValidator{
	flagName: "--parent-shutdown-time-s",
	validate: func(ctx *configContext, flagValue string) error {
		if _, err := strconv.ParseUint(flagValue, 10, 32); err != nil {
			return err
		}
		return nil
	},
})

func registerBoolFlagValidator(flagName string) *flagValidator {
	return registerFlagValidator(&flagValidator{
		flagName: FlagName(flagName),
		validate: func(ctx *configContext, flagValue string) error {
			switch flagValue {
			case "", "true":
				return nil
			default:
				return fmt.Errorf("unexpected boolean value for flag %s: %s", flagName, flagValue)
			}
		},
	})
}

func getAdminPortFromYaml(yamlData string) (uint32, error) {
	jsonData, err := yaml.YAMLToJSON([]byte(yamlData))
	if err != nil {
		return 0, fmt.Errorf("error converting envoy bootstrap YAML to JSON: %v", err)
	}

	bootstrap := &envoyBootstrap.Bootstrap{}
	if err := unmarshal(string(jsonData), bootstrap); err != nil {
		return 0, fmt.Errorf("error parsing Envoy bootstrap JSON: %v", err)
	}
	if bootstrap.GetAdmin() == nil {
		return 0, errors.New("unable to locate admin in envoy bootstrap")
	}
	if bootstrap.GetAdmin().GetAddress() == nil {
		return 0, errors.New("unable to locate admin/address in envoy bootstrap")
	}
	if bootstrap.GetAdmin().GetAddress().GetSocketAddress() == nil {
		return 0, errors.New("unable to locate admin/address/socket_address in envoy bootstrap")
	}
	if bootstrap.GetAdmin().GetAddress().GetSocketAddress().GetPortValue() == 0 {
		return 0, errors.New("unable to locate admin/address/socket_address/port_value in envoy bootstrap")
	}
	return bootstrap.GetAdmin().GetAddress().GetSocketAddress().GetPortValue(), nil
}

// configContext stores the output of applied Options.
type configContext struct {
	configPath string
	configYaml string
	baseID     BaseID
	epoch      Epoch
}

func newConfigContext() *configContext {
	return &configContext{
		baseID: InvalidBaseID,
	}
}

func (c *configContext) getAdminPort() (uint32, error) {
	var err error

	// First, check the config yaml, which overrides config-path.
	if c.configYaml != "" {
		if port, e := getAdminPortFromYaml(c.configYaml); e != nil {
			err = fmt.Errorf("failed to locate admin port in envoy config-yaml: %v", e)
		} else {
			// Found the port!
			return port, nil
		}
	}

	// Haven't found it yet - check configPath.
	if c.configPath == "" {
		return 0, multierror.Append(err, errors.New("unable to process envoy bootstrap"))
	}

	content, e := ioutil.ReadFile(c.configPath)
	if e != nil {
		return 0, multierror.Append(err, fmt.Errorf("failed reading config-path file %s: %v", c.configPath, e))
	}

	port, e := getAdminPortFromYaml(string(content))
	if e != nil {
		return 0, multierror.Append(err, fmt.Errorf("failed to locate admin port in envoy config-yaml: %v", e))
	}
	// Found the port!
	return port, nil
}

var flagValidators = make(map[FlagName]*flagValidator)

type flagValidator struct {
	flagName FlagName
	apply    func(ctx *configContext, flagValue string)
	validate func(ctx *configContext, flagValue string) error
}

func registerFlagValidator(v *flagValidator) *flagValidator {
	flagValidators[v.flagName] = v

	// Fill in missing methods with defaults.
	if v.apply == nil {
		v.apply = func(*configContext, string) {}
	}
	if v.validate == nil {
		v.validate = func(*configContext, string) error {
			return nil
		}
	}
	return v
}

var _ Option = &genericOption{}

type genericOption struct {
	v     *flagValidator
	value string
}

func (o *genericOption) FlagName() FlagName {
	if o.v != nil {
		return o.v.flagName
	}
	return ""
}

func (o *genericOption) FlagValue() string {
	if o.v != nil {
		return o.value
	}
	return ""
}

func (o *genericOption) apply(ctx *configContext) {
	if o.v != nil && o.v.apply != nil {
		o.v.apply(ctx, o.value)
	}
}

func (o *genericOption) validate(ctx *configContext) error {
	if o.v != nil && o.v.validate != nil {
		return o.v.validate(ctx, o.value)
	}
	return nil
}