text:
module Ensconce

  # Used to convert pairs of arrays into a hash.
  #
  #     hash_builder = HashBuilder.new :keys => ['a', 'b'], :values => ['1', '2']
  #     hash_builder.hash   --> {'a' => '1', 'b' => '2'}
  #
  # Also allows modification of keys or values
  #
  #    hash_builder.keys_mod = lambda {|key| key.upcase}
  #    hash_builder.hash   --> {'A' => '1', 'B' => '2'}
  #
  #    hash_builder.values_mod = lambda {|value| (value.to_i * 4).to_s}
  #    hash_builder.hash   --> {'A' => '4', 'B' => '8'}
  #
  # You can use a Proc to define a mod, but I'd recommend not doing so as a
  # return statement in the Proc can cause an unexpected result (see tests).
  #
  class HashBuilder

    attr_accessor :keys, :values, :keys_mod, :values_mod

    def initialize(args = {})
      @keys = args[:keys]
      @values = args[:values]
      @keys_mod = args[:keys_mod]
      @values_mod = args[:values_mod]
    end

    def valid?
      check_required_attributes_present
      check_mods_are_valid
    end

    def hash
      valid?
      map = [processed_keys, processed_values].transpose
      Hash[map]
    end

    def check_mods_are_valid
      mod_attributes.each do |mod|
        mod = send mod
        next unless mod
        raise ":#{mod} must be a Proc or lambda" unless mod.kind_of? Proc
      end
    end

    def check_required_attributes_present
      required_attibutes.each do |attribute|
        raise ":#{attribute} is a required attribute but was not found" unless send(attribute)
      end
    end

    def required_attibutes
      [:keys, :values]
    end

    def mod_attributes
      [:keys_mod, :values_mod]
    end

    def processed_keys
      keys_mod ? keys.collect(&keys_mod) : keys
    end

    def processed_values
      values_mod ? values.collect(&values_mod) : values
    end
  end

end


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

<TITLE>
ShapePainter (POI API Documentation)
</TITLE>

<META NAME="date" CONTENT="2012-11-26">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.poi.hslf.model

Class ShapePainter

java.lang.Object
  org.apache.poi.hslf.model.ShapePainter

public final class ShapePainter
extends java.lang.Object

Paint a shape into java.awt.Graphics2D

Author:

Yegor Kozlov

Field Summary

protected static POILogger
logger

Constructor Summary

ShapePainter()

Method Summary

static void
paint(SimpleShape shape,
      java.awt.Graphics2D graphics)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

logger

protected static POILogger logger

Constructor Detail

ShapePainter

public ShapePainter()

Method Detail

paint

public static void paint(SimpleShape shape,
                         java.awt.Graphics2D graphics)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

                Copyright 2012 The Apache Software Foundation or
        its licensors, as applicable.

redpajama_set_name: RedPajamaGithub


text:
describe CardSheet do
  include_context "db"
  let(:factory) { CardSheetFactory.new(db) }

  %W[basic common uncommon rare mythic].each do |rarity|
    it "rarity #{rarity}" do
      expected = db.search("e:m10 r:#{rarity}").printings
      actual = factory.rarity("m10", rarity).elements.map(&:main_front)
      expected.should match_array(actual)
    end

    it "cards" do
      sheet = factory.rare_mythic("m10")
      sheet.cards.size.should eq(15+53)
      expected = db.search("e:m10 r>=rare").printings
      actual = sheet.cards.map(&:main_front)
      expected.should match_array(actual)
    end
  end

  context "#probabilities" do
    context "typical set" do
      let(:rare_mythic_sheet) { factory.rare_mythic("m10") }
      let(:uncommon_sheet) { factory.rarity("m10", "uncommon") }
      let(:common_sheet) { factory.rarity("m10", "common") }
      let(:basic_sheet) { factory.rarity("m10", "basic") }
      let(:mythic_card) { physical_card("e:m10 baneslayer angel") }
      let(:rare_card) { physical_card("e:m10 birds of paradise") }
      let(:uncommon_card) { physical_card("e:m10 acidic slime") }
      let(:common_card) { physical_card("e:m10 assassinate") }
      let(:basic_card) { physical_card("e:m10 island") }

      it do
        rare_mythic_sheet.probabilities[mythic_card].should eq Rational(1, 121)
        rare_mythic_sheet.probabilities[rare_card].should eq Rational(2, 121)
        uncommon_sheet.probabilities[uncommon_card].should eq Rational(1, 60)
        common_sheet.probabilities[common_card].should eq Rational(1, 101)
        basic_sheet.probabilities[basic_card].should eq Rational(1, 20)
      end
    end

    context "typical set - foil sheet" do
      let(:foil_sheet) { factory.foil("m10") }
      let(:mythic_card) { physical_card("e:m10 baneslayer angel", true) }
      let(:rare_card) { physical_card("e:m10 birds of paradise", true) }
      let(:uncommon_card) { physical_card("e:m10 acidic slime", true) }
      let(:common_card) { physical_card("e:m10 assassinate", true) }
      let(:basic_card) { physical_card("e:m10 island", true) }

      it do
        # These are based on some guessing
        foil_sheet.probabilities[mythic_card].should eq Rational(1, 121) * Rational(3,20)
        foil_sheet.probabilities[rare_card].should eq Rational(2, 121) * Rational(3,20)
        foil_sheet.probabilities[uncommon_card].should eq Rational(1, 60) * Rational(5,20)
        foil_sheet.probabilities[common_card].should eq Rational(1, 20+101) * Rational(12,20)
        foil_sheet.probabilities[basic_card].should eq Rational(1, 20+101) * Rational(12,20)
      end
    end
  end
end


text:
require 'gooddata/rest/rest'

describe 'Behavior during polling and retries' do
  before :each do
    WebMock.enable!

    @server = GoodData::Environment::ConnectionHelper::DEFAULT_SERVER

    @coef = GoodData::Rest::Connection::RETRY_TIME_COEFFICIENT
    @init = GoodData::Rest::Connection::RETRY_TIME_INITIAL_VALUE
    @poll = GoodData::Rest::Client::DEFAULT_SLEEP_INTERVAL

    GoodData::Rest::Connection.send(:remove_const, :RETRY_TIME_COEFFICIENT) if GoodData::Rest::Connection.const_defined?(:RETRY_TIME_COEFFICIENT)
    GoodData::Rest::Connection.send(:remove_const, :RETRY_TIME_INITIAL_VALUE) if GoodData::Rest::Connection.const_defined?(:RETRY_TIME_INITIAL_VALUE)
    GoodData::Rest::Client.send(:remove_const, :DEFAULT_SLEEP_INTERVAL) if GoodData::Rest::Client.const_defined?(:DEFAULT_SLEEP_INTERVAL)

    GoodData::Rest::Connection.const_set(:RETRY_TIME_COEFFICIENT, 1)
    GoodData::Rest::Connection.const_set(:RETRY_TIME_INITIAL_VALUE, 0)
    GoodData::Rest::Client.const_set(:DEFAULT_SLEEP_INTERVAL, 0)

    stub_request(:post, "#{@server}/gdc/account/login")
      .to_return(:body => { :userLogin => { :profile => "/profile/123" }}.to_json, :headers => { 'Content-Type' => "application/json" })
    stub_request(:get, "#{@server}/gdc/account/token")
      .to_return(:body => {}.to_json, :headers => { 'Content-Type' => "application/json" })
    stub_request(:get, "#{@server}/profile/123")
      .to_return(:body => {}.to_json, :headers => { 'Content-Type' => "application/json" })
    stub_request(:get, "#{@server}/poll_test")
      .to_return(:body => {stuff: :aaa}.to_json, :headers => { 'Content-Type' => "application/json"} )
    stub_request(:get, "#{@server}/too_many_reqs")
      .to_return(:body => {}.to_json, :status => 429, :headers => { 'Content-Type' => "application/json"} )
    stub_request(:get, "#{@server}/out_of_service")
      .to_return(:body => {}.to_json, :status => 503, :headers => { 'Content-Type' => "application/json"} )
    stub_request(:get, "#{@server}/internal_error")
      .to_return(:body => {}.to_json, :status => 500, :headers => { 'Content-Type' => "application/json"} )

    @client = GoodData.connect('aaa', 'bbbb')
    GoodData.logging_on
  end

  after :each do
    WebMock.disable!
    GoodData::Rest::Connection.send(:remove_const, :RETRY_TIME_COEFFICIENT) if GoodData::Rest::Connection.const_defined?(:RETRY_TIME_COEFFICIENT)
    GoodData::Rest::Connection.send(:remove_const, :RETRY_TIME_INITIAL_VALUE) if GoodData::Rest::Connection.const_defined?(:RETRY_TIME_INITIAL_VALUE)
    GoodData::Rest::Client.send(:remove_const, :DEFAULT_SLEEP_INTERVAL) if GoodData::Rest::Client.const_defined?(:DEFAULT_SLEEP_INTERVAL)

    GoodData::Rest::Connection.const_set(:RETRY_TIME_COEFFICIENT, @coef)
    GoodData::Rest::Connection.const_set(:RETRY_TIME_INITIAL_VALUE, @init)
    GoodData::Rest::Client.const_set(:DEFAULT_SLEEP_INTERVAL, @poll)
  end

  it 'should fail a poller after timelimit passes' do
    expect do
      @client.poll_on_response('/poll_test', time_limit: 0.1) { |_| true }
    end.to raise_error(GoodData::ExecutionLimitExceeded)
  end

  it 'should make MAX_REQUESTS when hitting 429' do
    expect do
      @client.get('/too_many_reqs')
    end.to raise_error(RestClient::TooManyRequests)
    expect(a_request(:get, "#{@server}/too_many_reqs")).to have_been_made.times(10)
  end

  it 'should make MAX_REQUESTS when hitting 503' do
    expect do
      @client.get('/out_of_service')
    end.to raise_error(RestClient::ServiceUnavailable)
    expect(a_request(:get, "#{@server}/out_of_service")).to have_been_made.times(10)
  end

  it 'should make 1 additional request when hitting 500' do
    expect do
      @client.get('/internal_error')
    end.to raise_error(RestClient::InternalServerError)
    expect(a_request(:get, "#{@server}/internal_error")).to have_been_made.times(3)
  end

  it 'Number of requests can be overriden' do
    expect do
      @client.get('/internal_error', :tries => 4)
    end.to raise_error(RestClient::InternalServerError)
    expect(a_request(:get, "#{@server}/internal_error")).to have_been_made.times(4)
  end
end


text:
package com.wrapper.spotify.requests.data.player;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.wrapper.spotify.exceptions.SpotifyWebApiException;
import com.wrapper.spotify.model_objects.miscellaneous.Device;
import com.wrapper.spotify.requests.data.AbstractDataRequest;
import org.apache.hc.core5.http.ParseException;

import java.io.IOException;

/**
 * Get information about a user's available devices.
 */
@JsonDeserialize(builder = GetUsersAvailableDevicesRequest.Builder.class)
public class GetUsersAvailableDevicesRequest extends AbstractDataRequest<Device[]> {

  /**
   * The private {@link GetUsersAvailableDevicesRequest} constructor.
   *
   * @param builder A {@link GetUsersAvailableDevicesRequest.Builder}.
   */
  private GetUsersAvailableDevicesRequest(final Builder builder) {
    super(builder);
  }

  /**
   * Get an user's available devices.
   *
   * @return An user's available devices.
   * @throws IOException            In case of networking issues.
   * @throws SpotifyWebApiException The Web API returned an error further specified in this exception's root cause.
   */
  public Device[] execute() throws
    IOException,
    SpotifyWebApiException,
    ParseException {
    return new Device.JsonUtil().createModelObjectArray(getJson(), "devices");
  }

  /**
   * Builder class for building a {@link GetUsersAvailableDevicesRequest}.
   */
  public static final class Builder extends AbstractDataRequest.Builder<Device[], Builder> {

    /**
     * Create a new {@link GetUsersAvailableDevicesRequest.Builder}.
     *

     * Your access token must have the {@code user-read-playback-state} scope authorized in order to read information.
     *
     * @param accessToken Required. A valid access token from the Spotify Accounts service.
     * @see Spotify: Using Scopes
     */
    public Builder(final String accessToken) {
      super(accessToken);
    }

    /**
     * The request build method.
     *
     * @return A custom {@link GetUsersAvailableDevicesRequest}.
     */
    @Override
    public GetUsersAvailableDevicesRequest build() {
      setPath("/v1/me/player/devices");
      return new GetUsersAvailableDevicesRequest(this);
    }

    @Override
    protected Builder self() {
      return this;
    }
  }
}


text:
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('devicegroups', '0001_initial'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='devicegroup',
            options={'verbose_name': 'Devicegroup', 'verbose_name_plural': 'Devicegroups'},
        ),
    ]


text:
/* $Id$ */

package org.apache.fop.util;

import javax.xml.transform.ErrorListener;
import javax.xml.transform.TransformerException;

import org.apache.commons.logging.Log;

/**
 * Standard ErrorListener implementation for in-FOP use. Some Xalan-J versions don't properly
 * re-throw exceptions.
 */
public class DefaultErrorListener implements ErrorListener {

    private Log log;

    /**
     * Main constructor
     * @param log the log instance to send log events to
     */
    public DefaultErrorListener(Log log) {
        this.log = log;
    }

    /**
     * {@inheritDoc}
     */
    public void warning(TransformerException exc) {
        log.warn(exc.toString());
    }

    /**
     * {@inheritDoc}
     */
    public void error(TransformerException exc) throws TransformerException {
        throw exc;
    }

    /**
     * {@inheritDoc}
     */
    public void fatalError(TransformerException exc)
            throws TransformerException {
        throw exc;
    }

}


text:
<?php

namespace Oro\Bundle\FormBundle\Tests\Unit\Form\Type;

use Oro\Bundle\FormBundle\Form\Type\OroEntitySelectOrCreateInlineType;
use Symfony\Component\Form\Test\FormIntegrationTestCase;

class OroEntitySelectOrCreateInlineTypeTest extends FormIntegrationTestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $securityFacade;

    /**
     * @var OroEntitySelectOrCreateInlineType
     */
    protected $formType;

    protected function setUp()
    {
        parent::setUp();

        $this->securityFacade = $this->getMockBuilder('Oro\Bundle\SecurityBundle\SecurityFacade')
            ->disableOriginalConstructor()
            ->getMock();
        $this->formType = new OroEntitySelectOrCreateInlineType($this->securityFacade);
    }

    /**
     * @return array
     */
    protected function getExtensions()
    {
        $entityManager = $this->getMockBuilder('Doctrine\ORM\EntityManager')
            ->disableOriginalConstructor()
            ->getMock();
        $metadata = $this->getMockBuilder('\Doctrine\ORM\Mapping\ClassMetadata')
            ->disableOriginalConstructor()
            ->getMock();
        $metadata->expects($this->any())
            ->method('getSingleIdentifierFieldName')
            ->will($this->returnValue('id'));
        $entityManager->expects($this->any())
            ->method('getClassMetadata')
            ->will($this->returnValue($metadata));
        $searchRegistry = $this->getMockBuilder('Oro\Bundle\FormBundle\Autocomplete\SearchRegistry')
            ->disableOriginalConstructor()
            ->getMock();

        return array(
            new EntitySelectOrCreateInlineFormExtension($entityManager, $searchRegistry)
        );
    }

    /**
     * @dataProvider requiredOptionsDataProvider
     * @param array $inputOptions
     * @param string $exceptionMessage
     */
    public function testRequiredOptions(array $inputOptions, $exceptionMessage)
    {
        $this->setExpectedException(
            'Symfony\Component\OptionsResolver\Exception\MissingOptionsException',
            $exceptionMessage
        );
        $form = $this->factory->create($this->formType, null, $inputOptions);
        $form->submit(null);
    }

    /**
     * @return array
     */
    public function requiredOptionsDataProvider()
    {
        return array(
            array(
                array(),
                'The required option "grid_name" is  missing.'
            )
        );
    }

    /**
     * @dataProvider formTypeDataProvider
     * @param array $inputOptions
     * @param array $expectedOptions
     * @param bool $aclAllowed
     * @param bool $aclExpectedToCall
     * @param array $expectedViewVars
     */
    public function testExecute(
        array $inputOptions,
        array $expectedOptions,
        $aclAllowed,
        $aclExpectedToCall,
        array $expectedViewVars = array()
    ) {
        if ($aclExpectedToCall) {
            if (!empty($expectedOptions['create_acl'])) {
                $this->securityFacade->expects($this->once())
                    ->method('isGranted')
                    ->with($expectedOptions['create_acl'])
                    ->will($this->returnValue($aclAllowed));
            } else {
                $this->securityFacade->expects($this->once())
                    ->method('isGranted')
                    ->with('CREATE', 'Entity:Oro\Bundle\FormBundle\Tests\Unit\Form\Stub\TestEntity')
                    ->will($this->returnValue($aclAllowed));
            }
        } else {
            $this->securityFacade->expects($this->never())
                ->method('isGranted');
        }

        $form = $this->factory->create($this->formType, null, $inputOptions);
        foreach ($expectedOptions as $name => $expectedValue) {
            $this->assertTrue($form->getConfig()->hasOption($name), sprintf('Expected option %s not found', $name));
            $this->assertEquals(
                $expectedValue,
                $form->getConfig()->getOption($name),
                sprintf('Option %s value is incorrect', $name)
            );
        }

        $form->submit(null);

        $formView = $form->createView();
        foreach ($expectedViewVars as $name => $expectedValue) {
            $this->assertArrayHasKey($name, $formView->vars, sprintf('View vars %s not found', $name));
            $this->assertEquals($expectedValue, $formView->vars[$name], sprintf('View var %s is incorrect', $name));
        }
    }

    /**
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     * @return array
     */
    public function formTypeDataProvider()
    {
        return array(
            'create disabled' => array(
                array(
                    'grid_name' => 'test',
                    'converter' => $this->getMock('Oro\Bundle\FormBundle\Autocomplete\ConverterInterface'),
                    'entity_class' => 'Oro\Bundle\FormBundle\Tests\Unit\Form\Stub\TestEntity',
                    'configs' => array(
                        'route_name' => 'test'
                    ),
                    'create_enabled' => false
                ),
                array(
                    'grid_name' => 'test',
                    'existing_entity_grid_id' => 'id',
                    'create_enabled' => false
                ),
                false,
                false,
                array(
                    'grid_name' => 'test',
                    'existing_entity_grid_id' => 'id',
                    'create_enabled' => false
                )
            ),
            'create no route' => array(
                array(
                    'grid_name' => 'test',
                    'converter' => $this->getMock('Oro\Bundle\FormBundle\Autocomplete\ConverterInterface'),
                    'entity_class' => 'Oro\Bundle\FormBundle\Tests\Unit\Form\Stub\TestEntity',
                    'configs' => array(
                        'route_name' => 'test'
                    ),
                    'create_enabled' => true
                ),
                array(
                    'grid_name' => 'test',
                    'existing_entity_grid_id' => 'id',
                    'create_enabled' => false
                ),
                false,
                false,
                array(
                    'grid_name' => 'test',
                    'existing_entity_grid_id' => 'id',
                    'create_enabled' => false
                )
            ),
            'create has route disabled' => array(
                array(
                    'grid_name' => 'test',
                    'converter' => $this->getMock('Oro\Bundle\FormBundle\Autocomplete\ConverterInterface'),
                    'entity_class' => 'Oro\Bundle\FormBundle\Tests\Unit\Form\Stub\TestEntity',
                    'configs' => array(
                        'route_name' => 'test'
                    ),
                    'create_enabled' => false,
                    'create_form_route' => 'test',
                ),
                array(
                    'grid_name' => 'test',
                    'existing_entity_grid_id' => 'id',
                    'create_form_route' => 'test',
                    'create_enabled' => false
                ),
                false,
                false,
                array(
                    'grid_name' => 'test',
                    'existing_entity_grid_id' => 'id',
                    'create_form_route' => 'test',
                    'create_enabled' => false
                )
            ),
            'create enabled acl disallowed' => array(
                array(
                    'grid_name' => 'test',
                    'converter' => $this->getMock('Oro\Bundle\FormBundle\Autocomplete\ConverterInterface'),
                    'entity_class' => 'Oro\Bundle\FormBundle\Tests\Unit\Form\Stub\TestEntity',
                    'configs' => array(
                        'route_name' => 'test'
                    ),
                    'create_enabled' => true,
                    'create_form_route' => 'test',
                ),
                array(
                    'grid_name' => 'test',
                    'existing_entity_grid_id' => 'id',
                    'create_form_route' => 'test',
                    'create_enabled' => false
                ),
                false,
                true,
                array(
                    'grid_name' => 'test',
                    'existing_entity_grid_id' => 'id',
                    'create_form_route' => 'test',
                    'create_enabled' => false
                )
            ),
            'create enabled acl allowed' => array(
                array(
                    'grid_name' => 'test',
                    'converter' => $this->getMock('Oro\Bundle\FormBundle\Autocomplete\ConverterInterface'),
                    'entity_class' => 'Oro\Bundle\FormBundle\Tests\Unit\Form\Stub\TestEntity',
                    'configs' => array(
                        'route_name' => 'test'
                    ),
                    'create_enabled' => true,
                    'create_form_route' => 'test',
                ),
                array(
                    'grid_name' => 'test',
                    'existing_entity_grid_id' => 'id',
                    'create_form_route' => 'test',
                    'create_enabled' => true
                ),
                true,
                true,
                array(
                    'grid_name' => 'test',
                    'existing_entity_grid_id' => 'id',
                    'create_form_route' => 'test',
                    'create_enabled' => true
                )
            ),
            'create enabled acl allowed custom' => array(
                array(
                    'grid_name' => 'test',
                    'converter' => $this->getMock('Oro\Bundle\FormBundle\Autocomplete\ConverterInterface'),
                    'entity_class' => 'Oro\Bundle\FormBundle\Tests\Unit\Form\Stub\TestEntity',
                    'configs' => array(
                        'route_name' => 'test'
                    ),
                    'create_enabled' => true,
                    'create_form_route' => 'test',
                    'create_form_route_parameters' => array('name' => 'US'),
                    'create_acl' => 'acl',
                ),
                array(
                    'grid_name' => 'test',
                    'existing_entity_grid_id' => 'id',
                    'create_form_route' => 'test',
                    'create_enabled' => true,
                    'create_acl' => 'acl',
                    'create_form_route_parameters' => array('name' => 'US'),
                ),
                true,
                true,
                array(
                    'grid_name' => 'test',
                    'existing_entity_grid_id' => 'id',
                    'create_form_route' => 'test',
                    'create_enabled' => true,
                    'create_form_route_parameters' => array('name' => 'US'),
                )
            ),
        );
    }
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Blog.DbContext;
using Blog.Entities;

namespace Blog.Gateway.Controllers
{
    public class UsersController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: Users
        public ActionResult Index()
        {
            return View(db.Users.ToList());
        }

        // GET: Users/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // GET: Users/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Users/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,isAdmin,UCN,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] User user)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(user);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(user);
        }

        // GET: Users/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // POST: Users/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,isAdmin,UCN,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] User user)
        {
            if (ModelState.IsValid)
            {
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(user);
        }

        // GET: Users/Delete/5
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // POST: Users/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            User user = db.Users.Find(id);
            db.Users.Remove(user);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}


text:
Repository of base images for [PHPDocker.io](http://phpdocker.io) generated environments.

Images are [built daily](https://github.com/phpdocker-io/base-images/actions/workflows/docker-build.yaml) in order to
fetch the latest base image changes as well as available php versions.

## NGINX with PageSpeed

More info on its own [readme](nginx-pagespeed/README.md)

## PHP

### Note: changes to PHP image locations at docker hub

As of end of Nov 2021, container images for php version **7.4 onwards** are pushed into the same docker hub repository,
and we'll be conveying the specific versions via tags. Instead of having different container repositories, one per
version variant, with always the `latest` tag.

In order to avoid breaking existing setups, we'll continue pushing the same build to the old locations, in addition to
the new one. We'll do this until they go EOL and we stop building them at all.

Starting with php 8.1, we'll only publish to the new location.

Example:

| Before                         | Now                            |
|--------------------------------|--------------------------------|
| `phpdockerio/php73-cli:latest` | `phpdockerio/php73-cli:latest` |
| `phpdockerio/php74-fpm:latest` | `phpdockerio/php:7.4-cli`      |
| `phpdockerio/php80-cli:latest` | `phpdockerio/php:8.0-cli`      |
| n/a                            | `phpdockerio/php:8.1-fpm`      |

``

### Supported architectures

* `linux/amd64`
* `linux/arm64`
* `linux/arm/v7`

### OS Base images & PHP Package Sources

All images use an Ubuntu LTS release as base image, except for PHP5.6 which uses Debian Jessie. For each of these base
OS images, we use a third party source for the PHP packages - these packages come from
[Ondřej Surý](https://github.com/oerdnj/deb.sury.org) who is the official maintainer for PHP in Debian which is the
origin of all packages in Ubuntu.

In most cases, we override Ubuntu's PHP packages with Ondřej's to ensure we always have the very latest. For instance,
Ubuntu 20.04 comes with php 7.4.3 but we still install Ondřej's packages to ensure you get the absolutest latest version
of php 7.4 every time. Ubuntu backport security fixes, but not necessarily bugfixes from later patch releases.

### Image types

For each minor PHP version (`MAJOR.MINOR`) we have a `cli` and an `fpm` variant. These two are identical, except for the
fact the `fpm` contains `php-fpm` and their default command is of course `php-fpm`.

We're using `CMD` instead of `ENTRYPOINT` because I don't want to dictate how you use these images. If I were to set an
`ENTRYPOINT` you would not be able to easily open a bash shell into either container using `docker run` or `docker exec`
or docker-compose equivalent without you needing to re-build the container.

We also used to offer a `swoole` variant on some images. We are phasing these out, as the images were created before we
could reliably install the extension via `apt` and we had to compile it from source. It is now available as an
`apt` package and all you need to do is install it.

### Built-in php extensions

* apcu & apcu-bc
* curl
* json (from 8.0, part of php core)
* mbstring
* opcache
* readline
* xml
* zip

These are the minimum extensions I consider necessary for any modern PHP app. They're required by the likes
of `composer`, the `symfony/*` libraries etc.

### Composer

All images use the composer v2. If for whatever reason you need to roll back to v1, add the following to your Dockerfile

```Dockerfile
COPY --from=composer:1 /usr/bin/composer /usr/bin/composer
```

### Available images:

**Notes:**

* Unsupported versions are past PHP EOL (End of Life)
* Daily builds are turned off for versions that run on an OS base that's also EOL (for instance, Debian Jessie)
* Daily builds are kept for PHP versions that have reached EOL but the base OS has not - the base OS still receives
  security updates, including the PHP runtime.
* In general, do not use any unsupported images in a production environment, regardless of whether daily builds are
  still enabled
* Old images are kept in docker hub in the interest of enabling legacy apps to run
* Also, old images could potentially be deleted by Docker Hub if they go unused for a certain period of time - if this
  happens, they won't be restored and you need to upgrade.
* Ondřej Surý is PHP's package maintainer in Debian. His Ubuntu PPA allows us to have more up to date packages beyond
  those provided by the base image OS.

| PHP version  | CLI image                    | FPM image                 | Source                         | Supported | Daily builds? |
| ------------ | ---------------------------- | ------------------------- | ------------------------------ | --------- | ------------- |
| 8.1          | `phpdockerio/php:8.1-cli`    | `phpdockerio/php:8.1-fpm` | Ubuntu 22.04 + Ondřej Surý ppa | ✔         | ✔             |
| 8.0          | `phpdockerio/php:8.0-cli`    | `phpdockerio/php:8.0-fpm` | Ubuntu 20.04 + Ondřej Surý ppa | ✔         | ✔             |
| 7.4          | `phpdockerio/php:7.4-cli`    | `phpdockerio/php:7.4-fpm` | Ubuntu 20.04 + Ondřej Surý ppa | ✔         | ✔             |
| 7.3          | `phpdockerio/php73-cli`      | `phpdockerio/php73-cli`   | Ubuntu 18.04 + Ondřej Surý ppa | ❌         | ✔             |
| 7.2          | `phpdockerio/php72-cli`      | `phpdockerio/php72-cli`   | Ubuntu 18.04 + Ondřej Surý ppa | ❌         | ✔             |
| 7.1          | `phpdockerio/php71-cli`      | `phpdockerio/php71-fpm`   | Ubuntu 16.04 + Ondřej Surý ppa | ❌         | ❌            |
| 7.0          | `phpdockerio/php70-cli`      | `phpdockerio/php70-fpm`   | Ubuntu 16.04                   | ❌         | ❌            |
| 5.6          | `phpdockerio/php56-cli`      | `phpdockerio/php56-fpm`   | Debian Jessie                  | ❌         | ❌            |


text:
 /*
 * $Revision: 2564 $
 *
 * last checkin:
 *   $Author: gutwenger $
 *   $Date: 2012-07-07 00:03:48 +0200 (Sa, 07. Jul 2012) $
 ***************************************************************/

/** \file
 * \brief Implementation of class MaximumCPlanarSubgraph
 *
 * \author Karsten Klein
 *
 * \par License:
 * This file is part of the Open Graph Drawing Framework (OGDF).
 *
 * \par
 * Copyright (C)<br>
 * See README.txt in the root directory of the OGDF installation for details.
 *
 * \par
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * Version 2 or 3 as published by the Free Software Foundation;
 * see the file LICENSE.txt included in the packaging of this file
 * for details.
 *
 * \par
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * \par
 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 * \see  http://www.gnu.org/copyleft/gpl.html
 ***************************************************************/

#ifdef USE_ABACUS

#include <ogdf/cluster/MaximumCPlanarSubgraph.h>
#include <ogdf/cluster/CconnectClusterPlanar.h>
#include <ogdf/basic/simple_graph_alg.h>
#include <sstream>

//#define writefeasiblegraphs

namespace ogdf {

struct connStruct {
	bool connected;
	node v1, v2;
	edge e;
};

Module::ReturnType MaximumCPlanarSubgraph::doCall(const ClusterGraph &G,
            List<edge> &delEdges,
            List<nodePair> &addedEdges)
{
#ifdef OGDF_DEBUG
    cout << "Creating new Masterproblem for clustergraph with "<<G.getGraph().numberOfNodes()<<" nodes\n";
#endif
    Master* cplanMaster = new Master(G,m_heuristicLevel,
    								 m_heuristicRuns,
    							     m_heuristicOEdgeBound,
    							     m_heuristicNPermLists,
    							     m_kuratowskiIterations,
    							     m_subdivisions,
    								 m_kSupportGraphs,
    								 m_kuratowskiHigh,
    								 m_kuratowskiLow,
    								 m_perturbation,
    								 m_branchingGap,
    								 m_time,
    								 m_pricing,
    								 m_checkCPlanar,
    								 m_numAddVariables,
    								 m_strongConstraintViolation,
    								 m_strongVariableViolation,
    								 m_ol);

    cplanMaster->setPortaFile(m_portaOutput);
    cplanMaster->useDefaultCutPool() = m_defaultCutPool;
#ifdef OGDF_DEBUG
    cout << "Starting Optimization\n";
#endif
	ABA_MASTER::STATUS status;
	try {
    	status = cplanMaster->optimize();
	}
	catch (...)
	{
		#ifdef OGDF_DEBUG
		cout << "ABACUS Optimization failed...\n";
		#endif
	}
    m_totalTime    = getDoubleTime(*cplanMaster->totalTime());
    m_heurTime     = getDoubleTime(*cplanMaster->improveTime());
    m_sepTime      = getDoubleTime(*cplanMaster->separationTime());
    m_lpTime       = getDoubleTime(*cplanMaster->lpTime());
    m_lpSolverTime = getDoubleTime(*cplanMaster->lpSolverTime());
    m_totalWTime   = getDoubleTime(*cplanMaster->totalCowTime());
    m_numKCons     = cplanMaster->addedKConstraints();
    m_numCCons     = cplanMaster->addedCConstraints();
    m_numLPs       = cplanMaster->nLp();
    m_numBCs       = cplanMaster->nSub();
    m_numSubSelected = cplanMaster->nSubSelected();
    m_numVars      = cplanMaster->nMaxVars()-cplanMaster->getNumInactiveVars();
#ifdef OGDF_DEBUG
	m_solByHeuristic = cplanMaster->m_solByHeuristic;
#endif
#ifdef OGDF_DEBUG
	if(cplanMaster->pricing())
		Logger::slout() << "Pricing was ON\n";
   	Logger::slout()<<"ABACUS returned with status '"<< ABA_MASTER::STATUS_[status] <<"'\n"<<flush;
#endif

    List<nodePair> allEdges;
    cplanMaster->getDeletedEdges(delEdges);
    cplanMaster->getConnectionOptimalSolutionEdges(addedEdges);
    cplanMaster->getAllOptimalSolutionEdges(allEdges);
    int delE = delEdges.size();
    int addE = addedEdges.size();

#ifdef OGDF_DEBUG
    cout<<delE<< " Number of deleted edges, "<<addE<<" Number of added edges "<<
    allEdges.size()<<" gesamt"<<"\n";
#endif

	if (m_portaOutput)
	{
		writeFeasible(getPortaFileName(), *cplanMaster, status);
	}

	delete cplanMaster;
    switch (status) {
    case ABA_MASTER::Optimal: return Module::retOptimal; break;
    case ABA_MASTER::Error: return Module::retError; break;
    default: break;
    }//switch

    return Module::retError;
}//docall for clustergraph

//returns list of all clusters in subtree at c in bottom up order
void MaximumCPlanarSubgraph::getBottomUpClusterList(const cluster c, List< cluster > & theList)
{
	ListConstIterator<cluster> it = c->cBegin();
	while (it.valid())
	{
		getBottomUpClusterList((*it), theList);
		it++;
	}
	theList.pushBack(c);
}

//outputs the set of feasible solutions
void MaximumCPlanarSubgraph::writeFeasible(const String &filename,
	Master &master,
	ABA_MASTER::STATUS &status)
{
	const ClusterGraph& CG = *(master.getClusterGraph());
	const Graph& G = CG.getGraph();
	node v;
	//first compute the nodepairs that are potential candidates to connect
	//chunks in a cluster
	//potential connection edges
	NodeArray< NodeArray<bool> > potConn(G);
	forall_nodes(v, G)
	{
		potConn[v].init(G, false);
	}
	//we perform a bottom up cluster tree traversal
	List< cluster > clist;
	getBottomUpClusterList(CG.rootCluster(), clist);
	//could use postordertraversal instead

	List< nodePair > connPairs; //holds all connection node pairs
	//counts the number of potential connectivity edges
	//int potCount = 0; //equal to number of true values in potConn

	//we run through the clusters and check connected components
	//we consider all possible edges connecting CCs in a cluster,
	//even if they may be connected by edges in a child cluster
	//(to get the set of all feasible solutions)

	ListConstIterator< cluster > it = clist.begin();
	while (it.valid())
	{
		cluster c = (*it);
		//we compute the subgraph induced by vertices in c
		GraphCopy gcopy;
		gcopy.createEmpty(G);
		List<node> clusterNodes;
		//would be more efficient if we would just merge the childrens' vertices
		//and add c's
		c->getClusterNodes(clusterNodes);
		NodeArray<bool> activeNodes(G, false); //true for all cluster nodes
		EdgeArray<edge> copyEdge(G); //holds the edge copy
		ListConstIterator<node> itn = clusterNodes.begin();
		while (itn.valid())
		{
			activeNodes[(*itn)] = true;
			itn++;
		}
		gcopy.initByActiveNodes(clusterNodes, activeNodes, copyEdge);
		//gcopy now represents the cluster induced subgraph

		//we compute the connected components and store all nodepairs
		//that connect two of them
		NodeArray<int> component(gcopy);
		connectedComponents(gcopy, component);
		//now we run over all vertices and compare the component
		//number of adjacent vertices. If they differ, we found a
		//potential connection edge. We do not care if we find them twice.
		forall_nodes(v, gcopy)
		{
			node w;
			forall_nodes(w, gcopy)
			{
				if (component[v] != component[w])
				{
					cout <<"Indizes: "<<v->index()<<":"<<w->index()<<"\n";
					node vg = gcopy.original(v);
					node wg = gcopy.original(w);
					bool newConn = !((vg->index() < wg->index()) ? potConn[vg][wg] : potConn[wg][vg]);
					if (newConn)
					{
						nodePair np; np.v1 = vg; np.v2 = wg;
						connPairs.pushBack(np);
						if (vg->index() < wg->index())
							potConn[vg][wg] = true;
						else
							potConn[wg][vg] = true;
					}
				}
			}//nodes
		}//nodes

		it++;
	}//while

	cout << "Potentielle Verbindungskanten: "<< connPairs.size()<<"\n";

	//we run through our candidates and save them in an array
	//that can be used for dynamic graph updates
	int i = 0;
	connStruct *cons = new connStruct[connPairs.size()];
	ListConstIterator< nodePair > itnp = connPairs.begin();
	while (itnp.valid())
	{
		connStruct cs;
		cs.connected = false;
		cs.v1 = (*itnp).v1;
		cs.v2 = (*itnp).v2;
		cs.e  = 0;

		cons[i] = cs;
		i++;
		itnp++;
	}//while

	//-------------------------------------------------------------------------
	// WARNING: this is extremely slow for graphs with a large number of cluster
	// chunks now we test all possible connection edge combinations for c-planarity
	Graph G2;

	NodeArray<node> origNodes(CG.getGraph());
	ClusterArray<cluster> origCluster(CG);
	EdgeArray<edge> origEdges(CG.getGraph());
	ClusterGraph testCopy(CG, G2, origCluster, origNodes, origEdges);

	ofstream os(filename.cstr());

	// Output dimension of the LP (number of variables)
	os << "DIM = " << connPairs.size() << "\n";
    os << "COMMENT\n";
	char* stat = new char[10];
	std::sprintf(stat, "%s \n","unknown");
	switch (status) {
     	case ABA_MASTER::Optimal: std::sprintf(stat, "%s \n", "Optimal"); break;
    	case ABA_MASTER::Error: std::sprintf(stat, "%s \n", "Error"); break;
    	default: break;
    }//switch
	os << stat << "\n";
	delete[] stat;
	for (i = 0; i < connPairs.size(); i++)
	{
		os << "Var " << i << ": " << origNodes[cons[i].v1]->index() << "->" << origNodes[cons[i].v2] << "\n";
	}

	os << "CONV_SECTION\n";

	int j = 0; //debug
	if (connPairs.size() > 0)
	while (true)
	{
		//we create the next test configuration by incrementing the edge selection array
		//we create the corresponding graph dynamically on the fly
		i = 0;
		while ( (i < connPairs.size()) && (cons[i].connected == true) )
		{
			cons[i].connected = false;
			OGDF_ASSERT(cons[i].e != 0);
			G2.delEdge(cons[i].e);
			i++;
		}//while
		if (i >= connPairs.size()) break;
		//cout<<"v1graph: "<<&(*(cons[i].v1->graphOf()))<<"\n";
		//cout<<"origNodesgraph: "<<&(*(origNodes.graphOf()))<<"\n";
		cons[i].connected = true; //i.e., (false) will never be a feasible solution
		cons[i].e = G2.newEdge(origNodes[cons[i].v1], origNodes[cons[i].v2]);

		//and test it for c-planarity
		CconnectClusterPlanar CCCP;
		bool cplanar = CCCP.call(testCopy);

		//c-planar graphs define a feasible solution
		if (cplanar)
		{
			cout << "Feasible solution found\n";
			for (int j = 0; j < connPairs.size(); j++)
			{
				char ch = (cons[j].connected ? '1' : '0');
				cout << ch;
				os << ch << " ";
			}
			cout << "\n";
			os << "\n";
#ifdef writefeasiblegraphs
			char* fn = new char[20];
			std::sprintf(fn, "cGraph%d.gml",j++);
			testCopy.writeGML(fn);
			delete[] fn;
#endif
		}
	}//while counting

	delete[] cons;

	os << "\nEND" <<"\n";
	os.close();

	//return;

	os.open(getIeqFileName());
	os << "DIM = " << m_numVars << "\n";
	// Output the status as a comment
	os << "COMMENT\n";
	char* lstat = new char[10];
	std::sprintf(stat, "%s \n","unknown");
	switch (status) {
     	case ABA_MASTER::Optimal: std::sprintf(lstat, "%s \n", "Optimal"); break;
    	case ABA_MASTER::Error: std::sprintf(lstat, "%s \n", "Error"); break;
    	default: break;
    }//switch
	os << lstat << "\n";
	delete[] lstat;
	// In case 0 is not a valid solution, some PORTA functions need
	//a valid solution in the ieq file
	os << "VALID\n";

	os << "\nLOWER_BOUNDS\n";

	for (i = 0; i < m_numVars; i++) os << "0 ";
	os << "\n";

	os << "\nHIGHER_BOUNDS\n";
	for (i = 0; i < m_numVars; i++) os << "1 ";
	os << "\n";

	os << "\nINEQUALITIES_SECTION\n";
	//we first read the standard constraint that are written
	//into a text file by the optimization master
	ifstream isf(master.getStdConstraintsFileName());
	if (!isf)
	{
		cerr << "Could not open optimization master's standard constraint file\n";
		os << "#No standard constraints read\n";
	}
	else
	{
		char* fileLine = new char[maxConLength()];
		while (isf.getline(fileLine, maxConLength()))
		{
			//skip commment lines
			if (fileLine[0] == '#') continue;
			int count = 1;
			std::istringstream iss(fileLine);
			char d;
			bool rhs = false;
			while (iss >> d)
			{
				if ( rhs || ( (d == '<') || (d == '>') || (d == '=') ) )
				{
					os << d;
					rhs = true;
				}
				else
				{
					if (d != '0')
					{
						os <<"+"<< d <<"x"<<count;
					}
					count++;
				}
			}//while chars
			os <<"\n";
		}
		delete[] fileLine;
	}//ifstream
	//now we read the cut pools from the master
	if (master.useDefaultCutPool())
	{
		os << "#No cut constraints read from master\n";
		//ABA_STANDARDPOOL<ABA_CONSTRAINT, ABA_VARIABLE> *connCon = master.cutPool();
	}
	else
	{
		ABA_STANDARDPOOL<ABA_CONSTRAINT, ABA_VARIABLE> *connCon = master.getCutConnPool();
		ABA_STANDARDPOOL<ABA_CONSTRAINT, ABA_VARIABLE> *kuraCon = master.getCutKuraPool();
		ABA_STANDARDPOOL<ABA_VARIABLE, ABA_CONSTRAINT> *stdVar = master.varPool();
		OGDF_ASSERT(connCon != 0);
		OGDF_ASSERT(kuraCon != 0);
		cout << connCon->number() << " Constraints im MasterConnpool \n";
		cout << kuraCon->number() << " Constraints im MasterKurapool \n";
		cout << connCon->size() << " Größe ConnPool"<<"\n";
		outputCons(os, connCon, stdVar);
		outputCons(os, kuraCon, stdVar);
	}//else
	os << "\nEND" <<"\n";
	os.close();
	cout << "Cutting is set: "<<master.cutting()<<"\n";
	//cout <<"Bounds for the variables:\n";
	//ABA_SUB &theSub = *(master.firstSub());
	//for ( i = 0; i < theSub.nVar(); i++)
	//{
	//	cout << i << ": " << theSub.lBound(i) << " - " << theSub.uBound(i) << "\n";
	//}
	/*// OLD CRAP
	cout << "Constraints: \n";
	ABA_STANDARDPOOL< ABA_CONSTRAINT, ABA_VARIABLE > *spool = master.conPool();
	ABA_STANDARDPOOL< ABA_CONSTRAINT, ABA_VARIABLE > *cpool = master.cutPool();

	cout << spool->size() << " Constraints im Masterpool \n";
	cout << cpool->size() << " Constraints im Mastercutpool \n";

	cout << "ConPool Constraints \n";
	for ( i = 0; i < spool->size(); i++)
	{
		ABA_POOLSLOT< ABA_CONSTRAINT, ABA_VARIABLE > * sloty = spool->slot(i);
		ABA_CONSTRAINT *mycon = sloty->conVar();
		switch (mycon->sense()->sense())
		{
			case ABA_CSENSE::Less: cout << "<" << "\n"; break;
			case ABA_CSENSE::Greater: cout << ">" << "\n"; break;
			case ABA_CSENSE::Equal: cout << "=" << "\n"; break;
			default: cout << "Inequality sense doesn't make any sense \n"; break;
		}//switch
	}
	cout << "CutPool Constraints \n";
	for ( i = 0; i < cpool->size(); i++)
	{
		ABA_POOLSLOT< ABA_CONSTRAINT, ABA_VARIABLE > * sloty = cpool->slot(i);
		ABA_CONSTRAINT *mycon = sloty->conVar();
		switch (mycon->sense()->sense())
		{
			case ABA_CSENSE::Less: cout << "<" << "\n"; break;
			case ABA_CSENSE::Greater: cout << ">" << "\n"; break;
			case ABA_CSENSE::Equal: cout << "=" << "\n"; break;
			default: cout << "Inequality sense doesn't make any sense \n"; break;
		}//switch
	}
	*/
	/*
	for ( i = 0; i < theSub.nCon(); i++)
	{
		ABA_CONSTRAINT &theCon = *(theSub.constraint(i));

		for ( i = 0; i < theSub.nVar(); i++)
		{
			double c = theCon.coeff(theSub.variable(i));
			if (c != 0)
				cout << c;
			else cout << "  ";
		}
		switch (theCon.sense()->sense())
		{
			case ABA_CSENSE::Less: cout << "<" << "\n"; break;
			case ABA_CSENSE::Greater: cout << ">" << "\n"; break;
			case ABA_CSENSE::Equal: cout << "=" << "\n"; break;
			default: cout << "doesn't make any sense \n"; break;
		}//switch
		#include<limits> //for numeric_limits
  float fl;
  while(!(std::cin >> fl))
  {
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
  }
	}*/
}//writeportaieq

void MaximumCPlanarSubgraph::outputCons(ofstream &os,
	ABA_STANDARDPOOL<ABA_CONSTRAINT, ABA_VARIABLE> *connCon,
	ABA_STANDARDPOOL<ABA_VARIABLE, ABA_CONSTRAINT> *stdVar)
{
	int i;
	for ( i = 0; i < connCon->number(); i++)
		{
			ABA_POOLSLOT< ABA_CONSTRAINT, ABA_VARIABLE > * sloty = connCon->slot(i);
			ABA_CONSTRAINT *mycon = sloty->conVar();
			OGDF_ASSERT(mycon != 0);
			int count;
			for (count = 0; count < stdVar->size(); count++)
			{
				ABA_POOLSLOT< ABA_VARIABLE, ABA_CONSTRAINT > * slotv = stdVar->slot(count);
				ABA_VARIABLE *myvar = slotv->conVar();
				double d = mycon->coeff(myvar);
				if (d != 0.0) //precision!
				{
					os <<"+"<< d <<"x"<<count+1;
				}
			}//for
			switch (mycon->sense()->sense())
			{
				case ABA_CSENSE::Less: os << " <= "; break;
				case ABA_CSENSE::Greater: os << " >= "; break;
				case ABA_CSENSE::Equal: os << " = "; break;
				default: os << "Inequality sense doesn't make any sense \n";
						 cerr << "Inequality sense unknown \n";
						break;
			}//switch
			os << mycon->rhs();
			os << "\n";
		}
}

} //end namespace ogdf

#endif //USE_ABACUS


text:
package com.harrys.hyppo

import javax.inject.{Inject, Singleton}

import akka.actor._
import akka.pattern.gracefulStop
import com.google.inject.{Injector, Provider}
import com.harrys.hyppo.config.CoordinatorConfig
import com.harrys.hyppo.coordinator.WorkDispatcher
import com.harrys.hyppo.util.ConfigUtils
import com.harrys.hyppo.worker.actor.amqp._
import com.harrys.hyppo.worker.api.proto.WorkerInput
import com.sandinh.akuice.ActorInject
import com.typesafe.config.Config

import scala.concurrent.Await

/**
 * Created by jpetty on 8/28/15.
 */
@Singleton
final class HyppoCoordinator @Inject()
(
  injectorProvider: Provider[Injector],
  system:           ActorSystem,
  config:           CoordinatorConfig,
  httpClient:       RabbitHttpClient
) extends WorkDispatcher with ActorInject {

  override def injector: Injector = injectorProvider.get

  private val responseActor   = injectTopActor[ResponseQueueConsumer]("responses")
  private val enqueueProxy    = injectTopActor[EnqueueWorkQueueProxy]("enqueue-proxy")

  //  Attempt a graceful stop
  system.registerOnTermination({
    this.stop()
  })

  def start(): Unit = {
    responseActor ! Lifecycle.ApplicationStarted
  }

  def stop(): Unit = {
    enqueueProxy  ! PoisonPill
    Await.result(gracefulStop(responseActor, config.rabbitMQTimeout, Lifecycle.ImpendingShutdown), config.rabbitMQTimeout)
  }

  override def enqueue(work: WorkerInput) : Unit = {
    enqueueProxy ! work
  }

  override def fetchLogicalHyppoQueueDetails() : Seq[QueueDetails]   = httpClient.fetchLogicalHyppoQueueDetails()

  override def fetchRawHyppoQueueDetails() : Seq[SingleQueueDetails] = httpClient.fetchRawHyppoQueueDetails()
}

object HyppoCoordinator {

  def createConfig(appConfig: Config): CoordinatorConfig = {
    val config = appConfig.withFallback(referenceConfig())

    val merged = requiredConfig().
      withFallback(config)
      .resolve()

    new CoordinatorConfig(merged)
  }

  def requiredConfig(): Config = ConfigUtils.resourceFileConfig("/com/harrys/hyppo/config/required.conf")

  def referenceConfig(): Config = ConfigUtils.resourceFileConfig("/com/harrys/hyppo/config/reference.conf")

}


text:
<<<<<<< HEAD
'use strict';

app.service('nimGameSvc', ['$http', function ($http) {

  var getNimGame = function (success, error) {

    $http.get('http://www.dudajevagatve.lv/math/math/nim-game/todos.json')
      .success(function(data, status, headers, config) {
        success(data, status, headers, config);
      })
      .error(function(data, status, headers, config) {
        error(data, status, headers, config);
      });
  };

  this.getNimGame = getNimGame;
}]);
=======
'use strict';

app.service('nimGameSvc', ['$http', function ($http) {

  var getNimGame = function (success, error) {

    $http.get('http://www.dudajevagatve.lv/math/math/nim-game/todos.json')
      .success(function(data, status, headers, config) {
        success(data, status, headers, config);
      })
      .error(function(data, status, headers, config) {
        error(data, status, headers, config);
      });
  };

  this.getNimGame = getNimGame;
}]);
>>>>>>> 776dcba87548e5adb70f44f53f0bd1e662e35ffa


text:
package collection

// Names is a collection of names
type Names []Name

// Clone names
func (n Names) Clone() Names {
	r := make([]Name, len(n))
	copy(r, n)
	return r
}


text:
from __future__ import unicode_literals

from django.db import models, migrations
import datetime

class Migration(migrations.Migration):

    dependencies = [
        ('pieces', '0003_piece_studies'),
    ]

    operations = [
        migrations.CreateModel(
            name='PieceTag',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=100, unique=True)),
                ('create_date', models.DateTimeField(default=datetime.datetime.now)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='piece',
            name='tags',
            field=models.ManyToManyField(to='pieces.PieceTag'),
            preserve_default=True,
        ),
    ]


text:
package contract

import "time"

//Date represent RFC3399 date
type Date time.Time

//MarshalJSON override marshalJSON
func (t *Date) MarshalJSON() ([]byte, error) {
	return []byte(time.Time(*t).Format(`"` + time.RFC3339 + `"`)), nil
}

//MarshalText override marshalText
func (t *Date) MarshalText() ([]byte, error) {
	return []byte(time.Time(*t).Format(`"` + time.RFC3339 + `"`)), nil
}

//UnmarshalJSON override unmarshalJSON
func (t *Date) UnmarshalJSON(b []byte) error {
	ts, err := time.Parse(`"`+time.RFC3339+`"`, string(b))
	if err != nil {
		return err
	}

	*t = Date(ts)
	return nil
}

//UnmarshalText override unmarshalText
func (t *Date) UnmarshalText(b []byte) error {
	ts, err := time.Parse(`"`+time.RFC3339+`"`, string(b))
	if err != nil {
		return err
	}

	*t = Date(ts)
	return nil
}

func (t *Date) String() string {
	return time.Time(*t).String()
}


text:
title: Concur Request
layout: reference
reference-type: swagger
---

{% swagger /api-explorer/v4-0/ConcurRequest.swagger2.json %}


text:
"""
Modular batch system handling.

All batch system specific functions are contained within files in the
batch_systems folder.  The files must have the same name as the batch system,
and possible batch systems are set in the DEFINED_SYSTEMS set. Most batch
system functions are set in the modules in this package, but system detection
methods are hardcoded into get_cluster_environment() also.

To add new systems, create a new batch system with identical function and
classes names and return/yield values to those in an existing definition. You
will also need to update the options.py script to include keywords for your
system and the get_cluster_environment() function to include autodetection.
"""
from importlib import import_module as _import

from .. import run as _run
from .. import logme as _logme
from .. import ClusterError as _ClusterError

DEFINED_SYSTEMS = {'torque', 'slurm', 'local'}

MODE = None

# Define job states all batch systems must return one of these states
GOOD_STATES      = ['complete', 'completed', 'special_exit']
ACTIVE_STATES    = ['configuring', 'completing', 'pending',
                    'held', 'running']
BAD_STATES       = ['boot_fail', 'cancelled', 'failed', 'killed',
                    'node_fail', 'timeout', 'disappeared']
UNCERTAIN_STATES = ['preempted', 'stopped',
                    'suspended']
ALL_STATES = GOOD_STATES + ACTIVE_STATES + BAD_STATES + UNCERTAIN_STATES
DONE_STATES = GOOD_STATES + BAD_STATES

_default_batches = None

def get_batch_system(qtype=None):
    """Return a batch_system module."""
    qtype = qtype if qtype else get_cluster_environment()
    if qtype not in DEFINED_SYSTEMS:
        raise _ClusterError(
            'qtype value {0} is not recognized, '.format(qtype) +
            'should be one of {0}'.format(DEFINED_SYSTEMS)
        )
    global _default_batches
    if not _default_batches:
        _default_batches = {}
    if not qtype in _default_batches:
        _default_batches[qtype] = _import(
            'fyrd.batch_systems.{}'.format(qtype)
        )
    return _default_batches[qtype]

#################################
#  Set the global cluster type  #
#################################

def get_cluster_environment(overwrite=False):
    """Detect the local cluster environment and set MODE globally.

    Detect the current batch system by looking for command line utilities.
    Order is important here, so we hard code the batch system lookups.

    Paths to files can also be set in the config file.

    Parameters
    ----------
    overwrite : bool, optional
        If True, run checks anyway, otherwise just accept MODE if it is
        already set.

    Returns
    -------
    MODE : str
    """
    global MODE
    if not overwrite and MODE and MODE in list(DEFINED_SYSTEMS):
        return MODE
    from .. import conf as _conf
    conf_queue = _conf.get_option('queue', 'queue_type', 'auto')
    if conf_queue not in list(DEFINED_SYSTEMS) + ['auto']:
        _logme.log('queue_type in the config file is {}, '.format(conf_queue) +
                   'but it should be one of {}'.format(DEFINED_SYSTEMS) +
                   ' or auto. Resetting it to auto', 'warn')
        _conf.set_option('queue', 'queue_type', 'auto')
        conf_queue = 'auto'
    if conf_queue == 'auto':
        # Hardcode queue lookups here
        sbatch_cmnd = _conf.get_option('queue', 'sbatch')
        qsub_cmnd   = _conf.get_option('queue', 'qsub')
        sbatch_cmnd = sbatch_cmnd if sbatch_cmnd else 'sbatch'
        qsub_cmnd   = qsub_cmnd if qsub_cmnd else 'qsub'
        if _run.which(sbatch_cmnd):
            MODE = 'slurm'
        elif _run.which(qsub_cmnd):
            MODE = 'torque'
        else:
            MODE = 'local'
    else:
        MODE = conf_queue
    if MODE is None:
        _logme.log('No functional batch system detected, will not be able to'
                   'run', 'error')
    elif MODE == 'local':
        _logme.log('No cluster environment detected, using multiprocessing',
                   'debug')
    else:
        _logme.log('{0} detected, using for cluster submissions'.format(MODE),
                   'debug')
    return MODE

##############################
#  Check if queue is usable  #
##############################

def check_queue(qtype=None):
    """Check if *both* MODE and qtype are valid.

    First checks the MODE global and autodetects its value, if that fails, no
    other tests are done, the qtype argument is ignored.

    After MODE is found to be a reasonable value, the queried queue is tested
    for functionality. If qtype is defined, this queue is tested, else the
    queue in MODE is tested.

    Tests are defined per batch system.

    Parameters
    ----------
    qtype : str

    Returns
    ------
    batch_system_functional : bool

    Raises
    ------
    ClusterError
        If MODE or qtype is not in DEFINED_SYSTEMS

    See Also
    --------
    get_cluster_environment : Auto detect the batch environment
    get_batch_system : Return the batch system module
    """
    if 'MODE' not in globals():
        global MODE
        MODE = get_cluster_environment()
    if not MODE:
        MODE = get_cluster_environment()
    if not MODE:
        _logme.log('Queue system not detected', 'error')
        return False
    if MODE not in DEFINED_SYSTEMS:
        raise _ClusterError(
            'MODE value {0} is not recognized, '.format(MODE) +
            'should be one of {0}'.format(DEFINED_SYSTEMS)
        )
    if qtype and qtype not in DEFINED_SYSTEMS:
        raise _ClusterError(
            'qtype value {0} is not recognized, '.format(qtype) +
            'should be one of {0}'.format(DEFINED_SYSTEMS)
        )
    qtype = qtype if qtype else MODE
    batch_system = get_batch_system(qtype)
    return batch_system.queue_test(warn=True)

# Make options easily available everywhere
from . import options


text:
class Api::V1::FavoritesController < ApplicationController
  protect_from_forgery except: [:create, :show]

  def create
    favorite = Favorite.new result_id: params['result_id']

    if favorite.save
      render json: favorite
    else
      render json: favorite
    end
  end

  def show
    favorite = Favorite.where(result_id: params['id'])
    render json: favorite.size
  end
end


text:
'use strict';

const router = require('express').Router();

const ensureAuth = require('app/modules/auth').ensureAuth;

router.get('/', ensureAuth(), (req, res) => {
  res.render('account/home');
});

router.get('/profile', ensureAuth(), (req, res) => {
  res.render('account/profile');
});

module.exports = router;


text:
using IoTHelpers.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Devices.I2c;

namespace IoTHelpers.I2c.Devices
{
    public struct Acceleration
    {
        public double X { get; internal set; }

        public double Y { get; internal set; }

        public double Z { get; internal set; }
    };

    public class Adxl345Accelerometer : I2cTimedDevice
    {
        // Address Constants
        public const byte DefaultI2cAddress = 0x53;         /* 7-bit I2C address of the ADXL345 with SDO pulled low */

        private const byte ACCEL_REG_POWER_CONTROL = 0x2D;  /* Address of the Power Control register */
        private const byte ACCEL_REG_DATA_FORMAT = 0x31;    /* Address of the Data Format register   */
        private const byte ACCEL_REG_X = 0x32;              /* Address of the X Axis data register   */
        private const byte ACCEL_REG_Y = 0x34;              /* Address of the Y Axis data register   */
        private const byte ACCEL_REG_Z = 0x36;              /* Address of the Z Axis data register   */

        private const int ACCEL_RES = 1024;                             /* The ADXL345 has 10 bit resolution giving 1024 unique values */
        private const int ACCEL_DYN_RANGE_G = 8;                        /* The ADXL345 had a total dynamic range of 8G, since we're configuring it to +-4G */
        private const int UNITS_PER_G = ACCEL_RES / ACCEL_DYN_RANGE_G;  /* Ratio of raw int values to G units */

        private static TimeSpan DEFAULT_READ_INTERVAL = TimeSpan.FromMilliseconds(100);

        private Acceleration currentAcceleration = new Acceleration();
        public Acceleration CurrentAcceleration
        {
            get
            {
                if (ReadingMode == ReadingMode.Manual)
                    throw new NotSupportedException($"{nameof(CurrentAcceleration)} is available only when {nameof(ReadingMode)} is set to {ReadingMode.Continuous}.");

                return currentAcceleration;
            }
        }

        public bool RaiseEventsOnUIThread { get; set; } = false;

        public event EventHandler AccelerationChanged;

        public Adxl345Accelerometer(int slaveAddress = DefaultI2cAddress, ReadingMode mode = ReadingMode.Continuous, I2cBusSpeed busSpeed = I2cBusSpeed.FastMode, I2cSharingMode sharingMode = I2cSharingMode.Shared, string i2cControllerName = RaspberryPiI2cControllerName)
            : base(slaveAddress, mode, DEFAULT_READ_INTERVAL, busSpeed, sharingMode, i2cControllerName)
        { }

        protected override Task InitializeSensorAsync()
        {
            /*
            * Initialize the accelerometer:
            *
            * For this device, we create 2-byte write buffers:
            * The first byte is the register address we want to write to.
            * The second byte is the contents that we want to write to the register.
            */
            var writeBuf_DataFormat = new byte[] { ACCEL_REG_DATA_FORMAT, 0x01 };        /* 0x01 sets range to +- 4Gs                         */
            var writeBuf_PowerControl = new byte[] { ACCEL_REG_POWER_CONTROL, 0x08 };    /* 0x08 puts the accelerometer into measurement mode */

            /* Write the register settings */
            Device.Write(writeBuf_DataFormat);
            Device.Write(writeBuf_PowerControl);

            /* Now that everything is initialized, create a timer so we read data every 100mS */
            base.InitializeTimer();

            return Task.FromResult<object>(null);
        }

        protected override void OnTimer()
        {
            var acceleration = this.ReadAcceleration();

            if (currentAcceleration.X != acceleration.X || currentAcceleration.Y != acceleration.Y || currentAcceleration.Z != acceleration.Z)
            {
                currentAcceleration = acceleration;
                RaiseEventHelper.CheckRaiseEventOnUIThread(this, AccelerationChanged, RaiseEventsOnUIThread);
            }
        }

        public Acceleration ReadAcceleration()
        {
            var regAddrBuf = new byte[] { ACCEL_REG_X };  /* Register address we want to read from                                         */
            var readBuf = new byte[6];                    /* We read 6 bytes sequentially to get all 3 two-byte axes registers in one read */

            /*
             * Read from the accelerometer
             * We call WriteRead() so we first write the address of the X-Axis I2C register, then read all 3 axes
             */
            Device.WriteRead(regAddrBuf, readBuf);

            /*
             * In order to get the raw 16-bit data values, we need to concatenate two 8-bit bytes from the I2C read for each axis.
             * We accomplish this by using the BitConverter class.
             */
            var accelerationRawX = BitConverter.ToInt16(readBuf, 0);
            var accelerationRawY = BitConverter.ToInt16(readBuf, 2);
            var accelerationRawZ = BitConverter.ToInt16(readBuf, 4);

            /* Convert raw values to G's */
            var accel = new Acceleration
            {
                X = (double)accelerationRawX / UNITS_PER_G,
                Y = (double)accelerationRawY / UNITS_PER_G,
                Z = (double)accelerationRawZ / UNITS_PER_G
            };

            return accel;
        }

        public override void Dispose()
        {
            base.Dispose();
        }
    }
}


text:
package com.sailing.util;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * 调用HTTP工具类
 * @author  Sailing_LRH on 2018/12/9.
 */
public class ToolHttp {
    private static final Logger LOG = LoggerFactory.getLogger(ToolHttp.class);

    public static <T> T getForObject (String url, Map<String, String> param, Integer timeout, Class<T> responseType) {
        LOG.info("GET invoke [" +url + "] params:" + JSON.toJSONString(param));
        long statTime = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder(url);
        if (param != null && !param.isEmpty()) {
            if (!url.endsWith("?")) {
                sb.append("?");
            }
            for (String key : param.keySet()) {
                sb.append(key).append("=").append(param.get(key)).append("&");
            }
        }
        T t = getRestTemplate(timeout == null? -1: timeout).getForObject(sb.toString(), responseType);
        LOG.info("GET invoke [" +url + "] return:" + JSON.toJSONString(t) + ", cost " + (System.currentTimeMillis() - statTime) + "ms");
        return t;
    }

    public static <T> T postForObject (String url, Object param, Integer timeout, Class<T> responseType) {
        LOG.info("POST invoke [" +url + "] params:" + JSON.toJSONString(param));
        long statTime = System.currentTimeMillis();
        T t = getRestTemplate(timeout == null? -1: timeout).postForObject(url, param, responseType);
        LOG.info("POST invoke [" +url + "] return:" + JSON.toJSONString(t) + ", cost " + (System.currentTimeMillis() - statTime) + "ms");
        return t;
    }

    private static RestTemplate getRestTemplate(int timeout) {
        //复杂构造函数的使用
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(10000);
        requestFactory.setReadTimeout(timeout);
        //利用复杂构造器可以实现超时设置,内部实际实现为 HttpClient
        return new RestTemplate(requestFactory);
    }

    public static <T> T exchange (String url, Map<String, String> headerParam, Object param, Integer timeout, HttpMethod method, Class<T> responseType) {
        LOG.info("exchange [" +url + "] params:" + JSON.toJSONString(param));
        long statTime = System.currentTimeMillis();

        HttpHeaders headers = new HttpHeaders();
        if (headerParam != null && !headerParam.isEmpty()) {
            for (String key : headerParam.keySet()) {
                headers.add(key, headerParam.get(key));
            }
        }
        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(param), headers);

        ResponseEntity<T> responseEntity = getRestTemplate(timeout == null? -1: timeout).exchange(url, method, entity, responseType);
        T t = responseEntity.getBody();
        LOG.info("exchange [" +url + "] return:" + JSON.toJSONString(t) + ", cost " + (System.currentTimeMillis() - statTime) + "ms");
        return t;
    }

}


text:
package org.spongepowered.api.event;

import org.spongepowered.api.util.annotation.ImplementedBy;
import org.spongepowered.api.util.event.callback.CallbackList;

/**
 * An event that occurs in Sponge.
 */
@ImplementedBy(AbstractEvent.class)
public interface Event {

    /**
     * Get a list of callbacks.
     *
     * @return A list of callbacks
     */
    CallbackList getCallbacks();

}


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Ajax extends Controller
{
	/** @var  Model_Admin */
	private $adminModel;

	/** @var  Model_News */
	private $newsModel;

	public function __construct(Request $request, Response $response)
	{
		parent::__construct($request, $response);

		$this->adminModel = Model::factory('Admin');
		$this->newsModel = Model::factory('News');
	}

	public function action_get_typeahead()
	{
		$this->response->body(View::factory('typeahead')->set('words', Model::factory("Word")->getWords($_POST))->set('post', $_POST));
	}

	public function action_get_typeahead_admin()
	{
		$this->response->body(View::factory('typeahead_admin')->set('words', Model::factory("Word")->getWords($_POST))->set('post', $_POST));
	}

	public function action_remove_img()
	{
		$this->response->body($this->adminModel->removeImg($_POST));
	}

	public function action_hide_img()
	{
		$this->response->body($this->adminModel->hideImg($_POST));
	}

	public function action_show_img()
	{
		$this->response->body($this->adminModel->showImg($_POST));
	}

	public function action_remove_project_img()
	{
		$this->response->body($this->adminModel->removeProjectImg($_POST));
	}

	public function action_hide_project_img()
	{
		$this->response->body($this->adminModel->hideProjectImg($_POST));
	}

	public function action_show_project_img()
	{
		$this->response->body($this->adminModel->showProjectImg($_POST));
	}

	public function action_hide_project_gallery_img()
	{
		$this->response->body($this->adminModel->hideProjectGalleryImg($_POST));
	}

	public function action_show_project_gallery_img()
	{
		$this->response->body($this->adminModel->showProjectGalleryImg($_POST));
	}

	public function action_download_news()
	{
		$this->response->body($this->newsModel->downloadNews($this->request->post('id')));
	}

	public function action_remove_news()
	{
		$this->response->body($this->adminModel->removeNews($_POST));
	}

	public function action_hide_news()
	{
		$this->response->body($this->adminModel->hideNews($_POST));
	}

	public function action_show_news()
	{
		$this->response->body($this->adminModel->showNews($_POST));
	}

	public function action_hide_list_news()
	{
		$this->response->body($this->adminModel->hideListNews($_POST));
	}

	public function action_show_list_news()
	{
		$this->response->body($this->adminModel->showListNews($_POST));
	}

	public function action_change_project_link()
	{
		$this->response->body($this->adminModel->changeProjectLink($_POST));
	}

}


text:
/**
 * Autogenerated by Thrift Compiler (0.9.2)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package com.xiaomi.infra.galaxy.sds.thrift;

import libthrift091.scheme.IScheme;
import libthrift091.scheme.SchemeFactory;
import libthrift091.scheme.StandardScheme;

import libthrift091.scheme.TupleScheme;
import libthrift091.protocol.TTupleProtocol;
import libthrift091.protocol.TProtocolException;
import libthrift091.EncodingUtils;
import libthrift091.TException;
import libthrift091.async.AsyncMethodCallback;
import libthrift091.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
/**
 * 小米存储系统认证信息
 */
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2019-4-24")
public class Credential implements libthrift091.TBase<Credential, Credential._Fields>, java.io.Serializable, Cloneable, Comparable<Credential> {
  private static final libthrift091.protocol.TStruct STRUCT_DESC = new libthrift091.protocol.TStruct("Credential");

  private static final libthrift091.protocol.TField TYPE_FIELD_DESC = new libthrift091.protocol.TField("type", libthrift091.protocol.TType.I32, (short)1);
  private static final libthrift091.protocol.TField SECRET_KEY_ID_FIELD_DESC = new libthrift091.protocol.TField("secretKeyId", libthrift091.protocol.TType.STRING, (short)2);
  private static final libthrift091.protocol.TField SECRET_KEY_FIELD_DESC = new libthrift091.protocol.TField("secretKey", libthrift091.protocol.TType.STRING, (short)3);

  private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  static {
    schemes.put(StandardScheme.class, new CredentialStandardSchemeFactory());
    schemes.put(TupleScheme.class, new CredentialTupleSchemeFactory());
  }

  /**
   * 用户登录类型
   *
   * @see UserType
   */
  public UserType type; // optional
  /**
   * 用于服务端查询SecretKey的键值:
   * 1) userId: 对应User Secret
   * 2) appId: 对应App Secret,匿名登录也需设置
   * 3) storageAccessTokenId: 对应Storage Access Token
   */
  public String secretKeyId; // optional
  /**
   * Secret Key
   */
  public String secretKey; // optional

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements libthrift091.TFieldIdEnum {
    /**
     * 用户登录类型
     *
     * @see UserType
     */
    TYPE((short)1, "type"),
    /**
     * 用于服务端查询SecretKey的键值:
     * 1) userId: 对应User Secret
     * 2) appId: 对应App Secret,匿名登录也需设置
     * 3) storageAccessTokenId: 对应Storage Access Token
     */
    SECRET_KEY_ID((short)2, "secretKeyId"),
    /**
     * Secret Key
     */
    SECRET_KEY((short)3, "secretKey");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // TYPE
          return TYPE;
        case 2: // SECRET_KEY_ID
          return SECRET_KEY_ID;
        case 3: // SECRET_KEY
          return SECRET_KEY;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  private static final _Fields optionals[] = {_Fields.TYPE,_Fields.SECRET_KEY_ID,_Fields.SECRET_KEY};
  public static final Map<_Fields, libthrift091.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, libthrift091.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, libthrift091.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.TYPE, new libthrift091.meta_data.FieldMetaData("type", libthrift091.TFieldRequirementType.OPTIONAL,
        new libthrift091.meta_data.EnumMetaData(libthrift091.protocol.TType.ENUM, UserType.class)));
    tmpMap.put(_Fields.SECRET_KEY_ID, new libthrift091.meta_data.FieldMetaData("secretKeyId", libthrift091.TFieldRequirementType.OPTIONAL,
        new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.STRING)));
    tmpMap.put(_Fields.SECRET_KEY, new libthrift091.meta_data.FieldMetaData("secretKey", libthrift091.TFieldRequirementType.OPTIONAL,
        new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.STRING)));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    libthrift091.meta_data.FieldMetaData.addStructMetaDataMap(Credential.class, metaDataMap);
  }

  public Credential() {
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public Credential(Credential other) {
    if (other.isSetType()) {
      this.type = other.type;
    }
    if (other.isSetSecretKeyId()) {
      this.secretKeyId = other.secretKeyId;
    }
    if (other.isSetSecretKey()) {
      this.secretKey = other.secretKey;
    }
  }

  public Credential deepCopy() {
    return new Credential(this);
  }

  @Override
  public void clear() {
    this.type = null;
    this.secretKeyId = null;
    this.secretKey = null;
  }

  /**
   * 用户登录类型
   *
   * @see UserType
   */
  public UserType getType() {
    return this.type;
  }

  /**
   * 用户登录类型
   *
   * @see UserType
   */
  public Credential setType(UserType type) {
    this.type = type;
    return this;
  }

  public void unsetType() {
    this.type = null;
  }

  /** Returns true if field type is set (has been assigned a value) and false otherwise */
  public boolean isSetType() {
    return this.type != null;
  }

  public void setTypeIsSet(boolean value) {
    if (!value) {
      this.type = null;
    }
  }

  /**
   * 用于服务端查询SecretKey的键值:
   * 1) userId: 对应User Secret
   * 2) appId: 对应App Secret,匿名登录也需设置
   * 3) storageAccessTokenId: 对应Storage Access Token
   */
  public String getSecretKeyId() {
    return this.secretKeyId;
  }

  /**
   * 用于服务端查询SecretKey的键值:
   * 1) userId: 对应User Secret
   * 2) appId: 对应App Secret,匿名登录也需设置
   * 3) storageAccessTokenId: 对应Storage Access Token
   */
  public Credential setSecretKeyId(String secretKeyId) {
    this.secretKeyId = secretKeyId;
    return this;
  }

  public void unsetSecretKeyId() {
    this.secretKeyId = null;
  }

  /** Returns true if field secretKeyId is set (has been assigned a value) and false otherwise */
  public boolean isSetSecretKeyId() {
    return this.secretKeyId != null;
  }

  public void setSecretKeyIdIsSet(boolean value) {
    if (!value) {
      this.secretKeyId = null;
    }
  }

  /**
   * Secret Key
   */
  public String getSecretKey() {
    return this.secretKey;
  }

  /**
   * Secret Key
   */
  public Credential setSecretKey(String secretKey) {
    this.secretKey = secretKey;
    return this;
  }

  public void unsetSecretKey() {
    this.secretKey = null;
  }

  /** Returns true if field secretKey is set (has been assigned a value) and false otherwise */
  public boolean isSetSecretKey() {
    return this.secretKey != null;
  }

  public void setSecretKeyIsSet(boolean value) {
    if (!value) {
      this.secretKey = null;
    }
  }

  public void setFieldValue(_Fields field, Object value) {
    switch (field) {
    case TYPE:
      if (value == null) {
        unsetType();
      } else {
        setType((UserType)value);
      }
      break;

    case SECRET_KEY_ID:
      if (value == null) {
        unsetSecretKeyId();
      } else {
        setSecretKeyId((String)value);
      }
      break;

    case SECRET_KEY:
      if (value == null) {
        unsetSecretKey();
      } else {
        setSecretKey((String)value);
      }
      break;

    }
  }

  public Object getFieldValue(_Fields field) {
    switch (field) {
    case TYPE:
      return getType();

    case SECRET_KEY_ID:
      return getSecretKeyId();

    case SECRET_KEY:
      return getSecretKey();

    }
    throw new IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new IllegalArgumentException();
    }

    switch (field) {
    case TYPE:
      return isSetType();
    case SECRET_KEY_ID:
      return isSetSecretKeyId();
    case SECRET_KEY:
      return isSetSecretKey();
    }
    throw new IllegalStateException();
  }

  @Override
  public boolean equals(Object that) {
    if (that == null)
      return false;
    if (that instanceof Credential)
      return this.equals((Credential)that);
    return false;
  }

  public boolean equals(Credential that) {
    if (that == null)
      return false;

    boolean this_present_type = true && this.isSetType();
    boolean that_present_type = true && that.isSetType();
    if (this_present_type || that_present_type) {
      if (!(this_present_type && that_present_type))
        return false;
      if (!this.type.equals(that.type))
        return false;
    }

    boolean this_present_secretKeyId = true && this.isSetSecretKeyId();
    boolean that_present_secretKeyId = true && that.isSetSecretKeyId();
    if (this_present_secretKeyId || that_present_secretKeyId) {
      if (!(this_present_secretKeyId && that_present_secretKeyId))
        return false;
      if (!this.secretKeyId.equals(that.secretKeyId))
        return false;
    }

    boolean this_present_secretKey = true && this.isSetSecretKey();
    boolean that_present_secretKey = true && that.isSetSecretKey();
    if (this_present_secretKey || that_present_secretKey) {
      if (!(this_present_secretKey && that_present_secretKey))
        return false;
      if (!this.secretKey.equals(that.secretKey))
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    List<Object> list = new ArrayList<Object>();

    boolean present_type = true && (isSetType());
    list.add(present_type);
    if (present_type)
      list.add(type.getValue());

    boolean present_secretKeyId = true && (isSetSecretKeyId());
    list.add(present_secretKeyId);
    if (present_secretKeyId)
      list.add(secretKeyId);

    boolean present_secretKey = true && (isSetSecretKey());
    list.add(present_secretKey);
    if (present_secretKey)
      list.add(secretKey);

    return list.hashCode();
  }

  @Override
  public int compareTo(Credential other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;

    lastComparison = Boolean.valueOf(isSetType()).compareTo(other.isSetType());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetType()) {
      lastComparison = libthrift091.TBaseHelper.compareTo(this.type, other.type);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetSecretKeyId()).compareTo(other.isSetSecretKeyId());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetSecretKeyId()) {
      lastComparison = libthrift091.TBaseHelper.compareTo(this.secretKeyId, other.secretKeyId);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetSecretKey()).compareTo(other.isSetSecretKey());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetSecretKey()) {
      lastComparison = libthrift091.TBaseHelper.compareTo(this.secretKey, other.secretKey);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(libthrift091.protocol.TProtocol iprot) throws libthrift091.TException {
    schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  }

  public void write(libthrift091.protocol.TProtocol oprot) throws libthrift091.TException {
    schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder("Credential(");
    boolean first = true;

    if (isSetType()) {
      sb.append("type:");
      if (this.type == null) {
        sb.append("null");
      } else {
        sb.append(this.type);
      }
      first = false;
    }
    if (isSetSecretKeyId()) {
      if (!first) sb.append(", ");
      sb.append("secretKeyId:");
      if (this.secretKeyId == null) {
        sb.append("null");
      } else {
        sb.append(this.secretKeyId);
      }
      first = false;
    }
    if (isSetSecretKey()) {
      if (!first) sb.append(", ");
      sb.append("secretKey:");
      if (this.secretKey == null) {
        sb.append("null");
      } else {
        sb.append(this.secretKey);
      }
      first = false;
    }
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws libthrift091.TException {
    // check for required fields
    // check for sub-struct validity
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new libthrift091.protocol.TCompactProtocol(new libthrift091.transport.TIOStreamTransport(out)));
    } catch (libthrift091.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      read(new libthrift091.protocol.TCompactProtocol(new libthrift091.transport.TIOStreamTransport(in)));
    } catch (libthrift091.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class CredentialStandardSchemeFactory implements SchemeFactory {
    public CredentialStandardScheme getScheme() {
      return new CredentialStandardScheme();
    }
  }

  private static class CredentialStandardScheme extends StandardScheme<Credential> {

    public void read(libthrift091.protocol.TProtocol iprot, Credential struct) throws libthrift091.TException {
      libthrift091.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == libthrift091.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // TYPE
            if (schemeField.type == libthrift091.protocol.TType.I32) {
              struct.type = com.xiaomi.infra.galaxy.sds.thrift.UserType.findByValue(iprot.readI32());
              struct.setTypeIsSet(true);
            } else {
              libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 2: // SECRET_KEY_ID
            if (schemeField.type == libthrift091.protocol.TType.STRING) {
              struct.secretKeyId = iprot.readString();
              struct.setSecretKeyIdIsSet(true);
            } else {
              libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 3: // SECRET_KEY
            if (schemeField.type == libthrift091.protocol.TType.STRING) {
              struct.secretKey = iprot.readString();
              struct.setSecretKeyIsSet(true);
            } else {
              libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();

      // check for required fields of primitive type, which can't be checked in the validate method
      struct.validate();
    }

    public void write(libthrift091.protocol.TProtocol oprot, Credential struct) throws libthrift091.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      if (struct.type != null) {
        if (struct.isSetType()) {
          oprot.writeFieldBegin(TYPE_FIELD_DESC);
          oprot.writeI32(struct.type.getValue());
          oprot.writeFieldEnd();
        }
      }
      if (struct.secretKeyId != null) {
        if (struct.isSetSecretKeyId()) {
          oprot.writeFieldBegin(SECRET_KEY_ID_FIELD_DESC);
          oprot.writeString(struct.secretKeyId);
          oprot.writeFieldEnd();
        }
      }
      if (struct.secretKey != null) {
        if (struct.isSetSecretKey()) {
          oprot.writeFieldBegin(SECRET_KEY_FIELD_DESC);
          oprot.writeString(struct.secretKey);
          oprot.writeFieldEnd();
        }
      }
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class CredentialTupleSchemeFactory implements SchemeFactory {
    public CredentialTupleScheme getScheme() {
      return new CredentialTupleScheme();
    }
  }

  private static class CredentialTupleScheme extends TupleScheme<Credential> {

    @Override
    public void write(libthrift091.protocol.TProtocol prot, Credential struct) throws libthrift091.TException {
      TTupleProtocol oprot = (TTupleProtocol) prot;
      BitSet optionals = new BitSet();
      if (struct.isSetType()) {
        optionals.set(0);
      }
      if (struct.isSetSecretKeyId()) {
        optionals.set(1);
      }
      if (struct.isSetSecretKey()) {
        optionals.set(2);
      }
      oprot.writeBitSet(optionals, 3);
      if (struct.isSetType()) {
        oprot.writeI32(struct.type.getValue());
      }
      if (struct.isSetSecretKeyId()) {
        oprot.writeString(struct.secretKeyId);
      }
      if (struct.isSetSecretKey()) {
        oprot.writeString(struct.secretKey);
      }
    }

    @Override
    public void read(libthrift091.protocol.TProtocol prot, Credential struct) throws libthrift091.TException {
      TTupleProtocol iprot = (TTupleProtocol) prot;
      BitSet incoming = iprot.readBitSet(3);
      if (incoming.get(0)) {
        struct.type = com.xiaomi.infra.galaxy.sds.thrift.UserType.findByValue(iprot.readI32());
        struct.setTypeIsSet(true);
      }
      if (incoming.get(1)) {
        struct.secretKeyId = iprot.readString();
        struct.setSecretKeyIdIsSet(true);
      }
      if (incoming.get(2)) {
        struct.secretKey = iprot.readString();
        struct.setSecretKeyIsSet(true);
      }
    }
  }

}


text:
require File.join(Rails.root, "lib", "gitlabhq", "git_host")

class Repository
  attr_accessor :project

  def self.default_ref
    "master"
  end

  def self.access_options
    {}
  end

  def initialize(project)
    @project = project
  end

  def path
    @path ||= project.path
  end

  def project_id
    project.id
  end

  def write_hooks
    %w(post-receive).each do |hook|
      write_hook(hook, File.read(File.join(Rails.root, 'lib', "#{hook}-hook")))
    end
  end

  def write_hook(name, content)
    hook_file = File.join(project.path_to_repo, 'hooks', name)

    File.open(hook_file, 'w') do |f|
      f.write(content)
    end

    File.chmod(0775, hook_file)
  end

  def repo
    @repo ||= Grit::Repo.new(project.path_to_repo)
  end

  def url_to_repo
    Gitlabhq::GitHost.url_to_repo(path)
  end

  def path_to_repo
    File.join(GIT_HOST["base_path"], "#{path}.git")
  end

  def update_repository
    Gitlabhq::GitHost.system.new.configure do |c|
      c.update_project(path, project)
    end

    write_hooks if File.exists?(project.path_to_repo)
  end

  def destroy_repository
    Gitlabhq::GitHost.system.new.configure do |c|
      c.destroy_project(@project)
    end
  end

  def repo_exists?
    @repo_exists ||= (repo && !repo.branches.empty?)
  rescue
    @repo_exists = false
  end

  def tags
    repo.tags.map(&:name).sort.reverse
  end

  def heads
    @heads ||= repo.heads
  end

  def tree(fcommit, path = nil)
    fcommit = commit if fcommit == :head
    tree = fcommit.tree
    path ? (tree / path) : tree
  end

  def commit(commit_id = nil)
    commit = if commit_id
               repo.commits(commit_id).first
             else
               repo.commits.first
             end
    Commit.new(commit) if commit
  end

  def fresh_commits(n = 10)
    commits = heads.map do |h|
      repo.commits(h.name, n).map { |c| Commit.new(c, h) }
    end.flatten.uniq { |c| c.id }

    commits.sort! do |x, y|
      y.committed_date <=> x.committed_date
    end

    commits[0...n]
  end

  def commits_with_refs(n = 20)
    commits = repo.branches.map { |ref| Commit.new(ref.commit, ref) }

    commits.sort! do |x, y|
      y.committed_date <=> x.committed_date
    end

    commits[0..n]
  end

  def commits_since(date)
    commits = heads.map do |h|
      repo.log(h.name, nil, :since => date).each { |c| Commit.new(c, h) }
    end.flatten.uniq { |c| c.id }

    commits.sort! do |x, y|
      y.committed_date <=> x.committed_date
    end

    commits
  end

  def commits(ref, path = nil, limit = nil, offset = nil)
    if path
      repo.log(ref, path, :max_count => limit, :skip => offset)
    elsif limit && offset
      repo.commits(ref, limit, offset)
    else
      repo.commits(ref)
    end.map{ |c| Commit.new(c) }
  end

  def commits_between(from, to)
    repo.commits_between(from, to).map { |c| Commit.new(c) }
  end
end


text:
A simple api for ETL jobs

Say you have data in csv file that you want to load in mongodb:

```js
var fluxFoundry = require('flux-foundry'),
    foundry = fluxFoundry.foundry();

foundry.use('csv');
foundry.use('fs','mongo');

// parse csv file, transform rows into objects and insert in mongodb
foundry
  .flux('fluxId')
  .source('fs:path/to/file.csv')
  .convert('csv:object',{columns:['_id','name','email']})
  .write('mongodb://localhost:27017/target-db/target-collection',{
    mode:'upsert',
    batch:10
  })
  .convert('object:json')
  .log('{{data}}');

foundry
  .onError(function() {})
  .onFinish(function() {});

foundry.start()

```