text:
<?php
namespace Application\Infrastructure\Persistence\Domain\Doctrine;

use Application\Domain\Company\PostingPeriod\Repository\PostingPeriodQueryRepositoryInterface;
use Application\Domain\Contracts\Repository\CompanySqlFilterInterface;
use Application\Infrastructure\AggregateRepository\AbstractDoctrineRepository;

/**
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
class PostingPeriodQueryRepositoryImpl extends AbstractDoctrineRepository implements PostingPeriodQueryRepositoryInterface
{

    const ROOT_ENTITY_NAME = "\Application\Entity\NmtFinPostingPeriod";

    const LOCAL_ENTITY_NAME = "\Application\Entity\NmtInventoryAttribute";

    public function getById($id)
    {}

    public function getList(CompanySqlFilterInterface $filter)
    {}

    public function getRootByMemberId($memberId)
    {}

    public function getByUUID($uuid)
    {}
}


text:
File file = new File("file.txt");

file.setExecutable(true);
file.setReadable(true);
file.setWritable(true);

redpajama_set_name: RedPajamaGithub


text:
module Insight

  #Variant of the Speed Tracer Panel that performs a nearly complete profile of
  #all code called during a request.  Note that this will slow overall response
  #time by several orders of magnitude, and may return more data than
  #SpeedTracer is prepared to display
  class ProfilingSpeedTracer < SpeedTracer
    def before(env)
      super
      tracer = env['st.tracer']
      Kernel::set_trace_func proc {|event, file, line, name, binding,classname|
        case event
        when "c-call", "call"
          methodname = classname ? "" : classname
          methodname += name.to_s
          tracer.start_event(file, line, name, classname || "", "")
        when "c-return", "return"
          tracer.finish_event
        end
      }
    end

    def after(env, status, headers, body)
      Kernel::set_trace_func(nil)
      super
    end
  end
end


text:
<?php

namespace UserID\Validation;

/**
 * Class Validator
 *
 * @package UserID
 * @author  Pablo Tejada <pablo@ptejada.com>
 */

class ValidationRules
{
    protected $rules;
    protected $validated = false;

    public function __construct(array $rules = array())
    {
        $this->rules = $rules;
    }

    /**
     * Validate all rules to make sure they are properly formatted
     *
     * @return bool
     *
     * @throws \Exception
     */
    function validateRules()
    {
        if ( !$this->validated ) {
            foreach ($this->rules as $fieldName => $options) {
                if ( preg_match('/^[a-zA-Z]\w+$/', $fieldName) ) {
                    if ( !isset($options['rule']) ) {
                        throw new \Exception('Missing validation rule for ' . $fieldName);
                    }

                    if ( isset($options['limit']) && !preg_match('/\d-\d/', $options['limit']) ) {
                        throw new \Exception(
                            'Invalid limit for ' . $fieldName . '. Must be in the format of [min-max].'
                        );
                    }
                } else {
                    throw new \Exception('Invalid field name ' . $fieldName);
                }
            }
        }

        return $this->validated = true;
    }

    public function getAll()
    {
        $this->validateRules(); //TODO: not sure if the validation will perform well here
        return $this->rules;
    }

    /**
     * Add a field validation rule
     *
     * @param        $fieldName
     * @param string $rule
     * @param string $limit
     */
    public function add($fieldName, $rule = '', $limit = '0-100')
    {
        $this->rules[$fieldName] = array(
            'rule'  => $rule,
            'limit' => $limit
        );
    }

    /**
     * Get validation rules for an specific field
     *
     * @param $fieldName
     *
     * @return null
     */
    public function get($fieldName)
    {
        if ( isset($this->rules[$fieldName]) ) {
            return $this->rules[$fieldName];
        } else {
            // Field rule does not exists
            return null;
        }
    }

    /**
     * Add/Updates multiple rules
     *
     * @param array $addRules
     */
    public function update(array $addRules)
    {
        return $this->rules = array_merge_recursive($this->rules, $addRules);

        /*
         * TODO: Code might not be needed
         */
        if ( !empty($this->rules) ) {
            /*
             * Update existing rules with the additional rules
             */
            foreach($addRules as $fieldName => $options)
            {
                if ( isset($this->rules[$fieldName]) && is_array($this->rules[$fieldName])) {
                    /*
                     * Only update the options provided in the update
                     */
                    $this->rules[$fieldName] = array_merge($this->rules[$fieldName], $options);
                } else {
                    /*
                     * Add none existing rule
                     */
                    $this->rules[$fieldName] = $options;
                }
            }
        } else {
            /*
             * No previous rules were defined
             */
            $this->rules = $addRules;
        }
    }
}


text:
package io.lethinh.matterexpansion.tile;

import javax.annotation.Nonnull;

import io.lethinh.matterexpansion.gui.GenericContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IContainerListener;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.NonNullList;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

/**
 *
 * @author Le Thinh
 */
public abstract class GenericMachineTile extends GenericPowerTile implements ISidedInventory, ITickable {

	protected NonNullList<ItemStack> stacks;
	protected long ticks;
	protected boolean isActive;
	public int progress;

	public GenericMachineTile(int size) {
		this.stacks = NonNullList.withSize(size, ItemStack.EMPTY);
		this.ticks = 0;
		this.isActive = false;
		this.progress = 0;
	}

	@Override
	public void readFromNBT(NBTTagCompound compound) {
		super.readFromNBT(compound);

		ItemStackHelper.loadAllItems(compound, this.stacks);
		this.ticks = compound.getLong("Ticks");
		this.progress = compound.getInteger("Progress");
		this.isActive = compound.getBoolean("IsActive");
	}

	@Override
	public NBTTagCompound writeToNBT(NBTTagCompound compound) {
		ItemStackHelper.saveAllItems(compound, this.stacks);
		compound.setLong("Ticks", this.ticks);
		compound.setInteger("Progress", this.progress);
		compound.setBoolean("IsActive", this.isActive);
		return super.writeToNBT(compound);
	}

	/* IInventory */
	@Override
	public void clear() {
		this.stacks.clear();
	}

	@Override
	public void closeInventory(EntityPlayer player) {
	}

	@Nonnull
	@Override
	public ItemStack decrStackSize(int index, int count) {
		return ItemStackHelper.getAndSplit(this.stacks, index, count);
	}

	@Override
	public int getField(int data) {
		return 0;
	}

	@Override
	public int getFieldCount() {
		return 0;
	}

	@Override
	public int getInventoryStackLimit() {
		return 64;
	}

	@Override
	public int getSizeInventory() {
		return this.stacks.size();
	}

	@Nonnull
	@Override
	public ItemStack getStackInSlot(int index) {
		return this.stacks.get(index);
	}

	@Override
	public boolean isEmpty() {
		return this.stacks.stream().anyMatch(itemStack -> !itemStack.isEmpty());
	}

	@Override
	public boolean isItemValidForSlot(int index, @Nonnull ItemStack stack) {
		return false;
	}

	@Override
	public boolean isUsableByPlayer(EntityPlayer player) {
		return player.getDistanceSq(this.pos.getX() + 0.5D, this.pos.getY() + 0.5D, this.pos.getZ() + 0.5D) <= 64.0D
				&& !this.isInvalid() && this.world.getTileEntity(this.pos) == this;
	}

	@Override
	public void openInventory(EntityPlayer player) {
	}

	@Nonnull
	@Override
	public ItemStack removeStackFromSlot(int index) {
		return ItemStackHelper.getAndRemove(this.stacks, index);
	}

	@Override
	public void setField(int data, int value) {
	}

	@Override
	public void setInventorySlotContents(int index, @Nonnull ItemStack stack) {
		this.stacks.set(index, stack);
	}

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

	@Override
	public boolean hasCustomName() {
		return false;
	}

	/* ISidedInventory */
	@Override
	public int[] getSlotsForFace(EnumFacing side) {
		return new int[0];
	}

	@Override
	public boolean canInsertItem(int index, @Nonnull ItemStack stack, EnumFacing side) {
		return !stack.isEmpty();
	}

	@Override
	public boolean canExtractItem(int index, @Nonnull ItemStack stack, EnumFacing side) {
		return stack.isEmpty();
	}

	/* ITickable */
	@Override
	public void update() {
		if (this.world.isRemote) {
			this.doServerWork();
		}

		if (this.canWork()) {
			if (!this.isActive)
				return;

			this.isActive = true;
			this.doClientWork();
			this.markDirty();
		} else if (this.isActive) {
			this.isActive = false;
			this.stopWorking();
			this.markDirty();
		}
	}

	/* WORK */
	/**
	 * Called when the tile wants to check if it can work.
	 *
	 * @return true if the tile can work otherwise false.
	 */
	protected abstract boolean canWork();

	/**
	 * Called when the tile works in server-side.
	 */
	protected void doServerWork() {
		this.ticks++;
	}

	/**
	 * Called when the tile works in client-side. And checked with the
	 * {@link GenericMachineTile#canWork} if it can work.
	 */
	protected abstract void doClientWork();

	/**
	 * Called when the tile stops working. And do something when it stopped
	 * (reset the timer, set the block state, ...)
	 */
	protected abstract void stopWorking();

	/* CONTAINER */
	@SideOnly(Side.CLIENT)
	public void getGuiNetworkData(int data, int value) {
		this.progress = value;
	}

	public void sendGuiNetworkData(GenericContainer container, IContainerListener listener) {
		listener.sendProgressBarUpdate(container, 0, this.progress);
	}
}


text:
using sdmap.Macros;
using System;
using Xunit;
using static sdmap.Macros.Implements.MacroUtil;

namespace sdmap.unittest.MacroTest
{
    public class RuntimeCheckTest
    {
        [Fact]
        public void EmptyNullOk()
        {
            var mockedMacro = new Macro
            {
                Name = "Test",
                Arguments = new SdmapTypes[0]
            };
            var ok = RuntimeCheck(null, mockedMacro);

            Assert.True(ok.IsSuccess);
        }

        [Fact]
        public void IsDate()
        {
            var mockedMacro = new Macro
            {
                Name = "Test",
                Arguments = new[] {SdmapTypes.Date}
            };
            var ok = RuntimeCheck(new object[] { DateTime.Now }, mockedMacro);

            Assert.True(ok.IsSuccess);
        }

        [Fact]
        public void NullableTest()
        {
            var mockedMacro = new Macro
            {
                Name = "Test",
                Arguments = new[] { SdmapTypes.Date }
            };
            var ok = RuntimeCheck(new object[] { new DateTime?(DateTime.Now) }, mockedMacro);

            Assert.True(ok.IsSuccess);
        }

        [Fact]
        public void NotDate()
        {
            var mockedMacro = new Macro
            {
                Name = "Test",
                Arguments = new[] { SdmapTypes.Date }
            };
            var ok = RuntimeCheck(new object[] { 3 }, mockedMacro);

            Assert.False(ok.IsSuccess);
            Assert.Equal("Macro 'Test' argument 1 requires Date but provides Int32.", ok.Error);
        }

        [Fact]
        public void IsSyntax()
        {
            var mockedMacro = new Macro
            {
                Name = "Test",
                Arguments = new[]
                {
                    SdmapTypes.Syntax
                }
            };
            var ok = RuntimeCheck(new object[] { "ZipCode" }, mockedMacro);

            Assert.True(ok.IsSuccess);
        }
    }
}


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

<meta http-equiv="Content-Type" content="text/html" charset="iso-8859-1">
<title>Overview (Apache Commons Configuration 1.10 API)</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Apache Commons Configuration 1.10 API

Packages

Package
Description

org.apache.commons.configuration

The Configuration main package.

org.apache.commons.configuration.beanutils

In this package a Configuration implementation can be found that
implements the DynaBean interface.

org.apache.commons.configuration.event

This package contains interfaces and classes for receiving notifications
about changes at configurations.

org.apache.commons.configuration.interpol

A package with helper classes used for interpolation (variable substitution).

org.apache.commons.configuration.plist

Configuration classes supporting NeXT / OpenStep /GNUStep style configuration.

org.apache.commons.configuration.reloading

The reloading package contains the definition of the
ReloadingStrategy interface, which provides automatic reloading
facilities for file based configurations.

org.apache.commons.configuration.resolver

A package containing EntityResolvers.

org.apache.commons.configuration.tree

A package with helper and utility classes used by hierarchical configurations.

org.apache.commons.configuration.tree.xpath

This package contains the implementation of the XPathExpressionEngine class, which
enables XPATH support for querying configuration properties.

org.apache.commons.configuration.web

This package contains some implementations of the Configuration
interface that are useful in web environments.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2001–2013 The Apache Software Foundation. All rights reserved.


text:
class CreateNamespacedWhizzers < ActiveRecord::Migration
  def change
    create_table :namespaced_whizzers do |t|
      t.string :permalink

      t.timestamps
    end
  end
end


text:
<?php
namespace Troupe\Tests\Unit\Source;

require_once realpath(__DIR__ . '/../../../../bootstrap.php');

use \Troupe\Source\Svn;
use \Troupe\Status\Success;
use \Troupe\Status\Failure;

class SvnTest extends \Troupe\Tests\TestCase {

  function setUp() {
    $this->executor  = $this->getMock('Troupe\Executor');
    $this->url = 'http://svn.source.com/example';
    $this->data_dir = 'a/path/to/a/directory';
    $this->vdm = $this->quickMock('Troupe\VendorDirectory\Manager');
    $this->svn_source = new Svn($this->url, $this->vdm, $this->executor, $this->data_dir);
  }

  function testGetCliCheckOutCommand() {
    $folder_name = md5($this->url);
    $this->assertEquals(
      "svn co '{$this->url}' '{$this->data_dir}/$folder_name'",
      $this->svn_source->getCliCheckOutCommand($this->url, "{$this->data_dir}/$folder_name")
    );
  }
  function testGetCliUpdateCommand() {
    $folder_name = md5($this->url);
    $this->assertEquals(
      "svn update '{$this->data_dir}/$folder_name'",
      $this->svn_source->getCliUpdateCommand($this->url, "{$this->data_dir}/$folder_name")
    );
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<products xmlns:xlink="http://www.w3.org/1999/xlink">
   <latestpdf>MidoNet_Quick_Start_Guide_RHEL-7_Liberty-OSP-8_EN_5.2-rev2-latest.pdf</latestpdf>
   <pdfoutname>MidoNet_Quick_Start_Guide_RHEL-7_Liberty-OSP-8_EN_5.2-rev2.pdf</pdfoutname>
   <docname>MidoNet Quick Start Guide for RHEL 7 / Liberty (OSP 8)</docname>
   <productname>MidoNet Quick Start Guide</productname>
   <webappname>quick-start-guide/rhel-7_liberty-osp_en</webappname>
   <pominfo>
      <groupid>org.midonet</groupid>
      <artifactid>midonet-docs-quick-start-guide-rhel-7-liberty-osp-en</artifactid>
      <version>5.2-rev2</version>
      <pomname>midonet-docs-quick-start-guide-rhel-7-liberty-osp-en v5.2-rev2</pomname>
   </pominfo>
</products>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
This file is subject to the terms and conditions defined in the
files 'LICENSE' and 'NOTICE', which are part of this source
code package.
-->
<entity-engine-xml>
    <SecurityGroupPermission groupId="FULLADMIN" permissionId="SETUP_ADMIN"/>
</entity-engine-xml>


text:
package org.github.solegaonkar.photography.framework;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;

import org.github.solegaonkar.photography.framework.Database.Record;

import com.flickr4java.flickr.Flickr;
import com.flickr4java.flickr.FlickrException;
import com.flickr4java.flickr.REST;
import com.flickr4java.flickr.RequestContext;
import com.flickr4java.flickr.activity.ActivityInterface;
import com.flickr4java.flickr.auth.Auth;
import com.flickr4java.flickr.auth.Permission;
import com.flickr4java.flickr.favorites.FavoritesInterface;
import com.flickr4java.flickr.groups.Group;
import com.flickr4java.flickr.groups.GroupList;
import com.flickr4java.flickr.groups.GroupsInterface;
import com.flickr4java.flickr.people.PeopleInterface;
import com.flickr4java.flickr.photos.PhotosInterface;
import com.flickr4java.flickr.photosets.Photoset;
import com.flickr4java.flickr.photosets.PhotosetsInterface;
import com.flickr4java.flickr.uploader.UploadMetaData;
import com.flickr4java.flickr.uploader.Uploader;

/**
 * A utility class that provides a good interface to the required subset of the FlickrAPI
 *
 * @author vs0016025
 *
 */
public class FlickrUtil {
	public static final String				FlickrBaseUrl		= "http://flickr.com";
	static final String						nsid				= "";
	static final String						userName			= "";
	static final Flickr						flickr				= connect();
	static final ActivityInterface			activityInterface	= flickr.getActivityInterface();
	static final FavoritesInterface			favoritesInterface	= flickr.getFavoritesInterface();
	static final GroupsInterface			groupsInterface		= flickr.getGroupsInterface();
	static final PhotosInterface			photosInterface		= flickr.getPhotosInterface();
	static final PhotosetsInterface			photosetInterface	= flickr.getPhotosetsInterface();
	static final PeopleInterface			peopleInterface		= flickr.getPeopleInterface();
	static final Uploader					uploader			= flickr.getUploader();
	static final HashMap<String, Photoset>	albumMap			= loadAlbumMap();
	static final GroupList<Group>			groups				= loadUserGroups();

	public static Set<String> getAlbumNames() {
		return albumMap.keySet();
	}

	/**
	 * Upload the photograph to Flickr; add it to the corresponding albums - creating new albums if required.
	 *
	 * @param record
	 * @throws Exception
	 */
	public static void upload(Record record) throws Exception {
		UploadMetaData metaData = new UploadMetaData();
		metaData.setPublicFlag(true);
		metaData.setDescription(record.getDescription());
		metaData.setContentType(Flickr.CONTENTTYPE_PHOTO);
		metaData.setSafetyLevel(Flickr.SAFETYLEVEL_SAFE);
		metaData.setTitle(makeSafeFilename(record.getTitle()));

		String flickrId = uploader.upload(new File(record.getPath()), metaData);
		if (flickrId != null) {
			record.setFlickrId(flickrId);
			for (String album : record.getAlbums()) {
				if (!albumMap.containsKey(album)) {
					photosetInterface.create(album, album, flickrId);
				} else {
					photosetInterface.addPhoto(albumMap.get(album).getId(), flickrId);
				}
			}
		}
	}

	public static String getImageUrl(Record record) throws Exception {
		if (!record.getFlickrId().isEmpty()) {
			photosInterface.getPhoto(record.getFlickrId()).getUrl();
		}
		return "";
	}

	/**
	 * Get the corresponding image from Flickr
	 *
	 * @param photoId
	 * @return The BufferedImage object
	 * @throws Exception
	 */
	public static BufferedImage getImage(String photoId) throws Exception {
		return photosInterface.getImage(photosInterface.getPhoto(photoId).getLargeUrl());
	}

	/**
	 * Remove unwanted characters from the input string.
	 *
	 * @param input
	 * @return
	 */
	private static String makeSafeFilename(String input) {
		byte[] fname = input.getBytes();
		byte[] bad = new byte[] { '\\', '/', '"', '*' };
		byte replace = '_';
		for (int i = 0; i < fname.length; i++) {
			for (byte element : bad) {
				if (fname[i] == element) {
					fname[i] = replace;
				}
			}
			if (fname[i] == ' ')
				fname[i] = '_';
		}
		return new String(fname);
	}

	/**
	 * Connect to Flickr using the key/token/secrets obtained from Flickr
	 *
	 * @return
	 */
	private static Flickr connect() {
		String apikey = "";
		String secret = "";

		Flickr.debugRequest = false;
		Flickr.debugStream = false;
		Flickr flickr = new Flickr(apikey, secret, new REST());

		RequestContext requestContext = RequestContext.getRequestContext();
		Auth auth = new Auth();
		auth.setPermission(Permission.DELETE);
		auth.setToken("");
		auth.setTokenSecret("");
		requestContext.setAuth(auth);

		return flickr;
	}

	/**
	 * Get the list of albums for the user.
	 *
	 * @return
	 */
	private static Collection<Photoset> loadPhotoSets() {
		try {
			return photosetInterface.getList(nsid).getPhotosets();
		} catch (FlickrException e) {
			CommonUtils.exception(e);
		}
		return null;
	}

	/**
	 * Get the list of groups that the user subscribes.
	 *
	 * @return
	 */
	private static GroupList<Group> loadUserGroups() {
		try {
			return peopleInterface.getGroups(nsid);
		} catch (FlickrException e) {
			CommonUtils.exception(e);
		}
		return null;
	}

	private static HashMap<String, Photoset> loadAlbumMap() {
		HashMap<String, Photoset> map = new HashMap<String, Photoset>();
		for (Photoset ps : loadPhotoSets()) {
			map.put(ps.getTitle(), ps);
		}
		return map;
	}
}


text:
<!DOCTYPE html>

    <meta http-equiv='X-UA-Compatible' content='IE=edge' />
    <title>Hello World</title>


text:
package org.jgentleframework.integration.remoting;

import org.jgentleframework.integration.RuntimeIntegrationException;

/**
 * The Class RemotingException.
 *
 * @author LE QUOC CHUNG - mailto: <a
 *         href="mailto:skydunkpro@yahoo.com">skydunkpro@yahoo.com</a>
 * @date Feb 26, 2008
 */
public class RemotingException extends RuntimeIntegrationException {
	/**
	 *
	 */
	private static final long	serialVersionUID	= -7820208802741116092L;

	/**
	 * Instantiates a new remoting exception.
	 */
	public RemotingException() {

		super();
	}

	/**
	 * Instantiates a new remoting exception.
	 *
	 * @param strEx
	 *            the str ex
	 */
	public RemotingException(String strEx) {

		super(strEx);
	}

	/**
	 * Instantiates a new remoting exception.
	 *
	 * @param message
	 *            the message
	 * @param cause
	 *            the cause
	 */
	public RemotingException(String message, Throwable cause) {

		super(message, cause);
	}

	/**
	 * Instantiates a new remoting exception.
	 *
	 * @param cause
	 *            the cause
	 */
	public RemotingException(Throwable cause) {

		super(cause);
	}
}


text:
@class BHEVoronoiMapViewController;

@interface BHEVoronoiMapViewController : UIViewController <MKMapViewDelegate, UINavigationControllerDelegate>

@property (strong, nonatomic) BHEVoronoiMap *vMap;
@property (strong, nonatomic) BHEVoronoiCellTower *currentlySelectedTower;

@property (weak, nonatomic) IBOutlet MKMapView *mapView;
- (IBAction)done:(UIBarButtonItem *)sender;

@end


text:
require 'test_helper'

class UserMailerTest < ActionMailer::TestCase
  test "account_activation" do
    user = users(:example_user)
    user.activation_token = User.new_token
    mail = UserMailer.account_activation(user)
    assert_equal "[HackTheArch] Account activation", mail.subject
    assert_equal [user.email], mail.to
    assert_equal ["noreply@example.com"], mail.from
    assert_match user.fname,              mail.body.encoded
    assert_match user.activation_token,   mail.body.encoded
    assert_match CGI::escape(user.email), mail.body.encoded
  end

  test "password_reset" do
    user = users(:example_user)
    user.reset_token = User.new_token
    mail = UserMailer.password_reset(user)
    assert_equal "[HackTheArch] Password reset", mail.subject
    assert_equal [user.email], mail.to
    assert_equal ["noreply@example.com"], mail.from
    assert_match user.reset_token,        mail.body.encoded
    assert_match CGI::escape(user.email), mail.body.encoded
  end

end


text:
//
//  FoodRequests.m
//  FoodEx
//
//  Created by Adam Gaynor on 2/28/16.
//  Copyright © 2016 FoodEx. All rights reserved.
//

#import "FoodRequests.h"

static NSString* const kBaseURL = @"http://ec2-54-92-150-113.compute-1.amazonaws.com:8000/";
static NSString* const kRequests = @"requests";
static NSString* const kMyOrders = @"myOrders";
static NSString* const kMyDeliveries = @"myDeliveries";
static NSString* const kDeliveryAccept = @"deliveryAccept";

@implementation FoodRequests

- (id)init
{
    self = [super init];
    if (self) {
        _requests = [NSMutableArray array];
    }
    return self;
}

- (void)parseAndAddLocations:(NSArray*)requests toArray:(NSMutableArray*)destinationArray
{
    for(NSDictionary *item in requests){
        FoodRequest *request = [[FoodRequest alloc] initWithDictionary:item];
        if(item[@"image_id"])
        {
            NSLog(@"%@", item[@"image_id"]);

        }
        else{
            NSLog(@"No Image Set");
        }

        [destinationArray addObject:request];
    }

}

- (void)parseAndRemoveLocations:(FoodRequest *)removeRequest fromArray:(NSMutableArray*)destinationArray
{
    FoodRequest *requestToRemove = nil;
    for(FoodRequest *request in destinationArray)
    {
        if([request._id isEqualToString:removeRequest._id])
        {
            requestToRemove = request;
        }
    }

    if(requestToRemove)
    {
        [destinationArray removeObject:requestToRemove];
    }
}

-(void) addRequest:(FoodRequest *)request{
    [self.requests addObject:request];
}

-(void) import: (void (^)(BOOL completion))completionBlock {

    NSURL *url = [NSURL URLWithString:[kBaseURL stringByAppendingPathComponent:kRequests]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

    NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { //5
        if (error == nil) {
            NSArray* responseArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; //6
            [self parseAndAddLocations:responseArray toArray:self.requests]; //7
            if(completionBlock)
            {
                completionBlock(YES);
            }
        }
    }];

    [dataTask resume];

}

-(void) importMyOrders:(BOOL)future andCompletion: (void (^)(BOOL completion))completionBlock{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];

    NSString *queryParam;
    NSString *fullQuery;
    if(future){
        queryParam = [NSString stringWithFormat:@"{\"$gt\":\"%@\"}", [dateFormat stringFromDate:[NSDate date]]];

    }
    else{
        queryParam = [NSString stringWithFormat:@"{\"$lt\":\"%@\"}", [dateFormat stringFromDate:[NSDate date]]];

    }

    fullQuery = [NSString stringWithFormat:@"{\"pickup_at\":%@}", queryParam];

    NSLog(@"%@", fullQuery);
    NSString* escQuery = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                (CFStringRef) fullQuery,
                                                                                NULL,
                                                                                (CFStringRef) @"!*();':@&=+$,/?%#[]{}",
                                                                                kCFStringEncodingUTF8));
    NSString *query = [NSString stringWithFormat:@"?query=%@", escQuery];

    NSURL *url = [NSURL URLWithString:[[[kBaseURL stringByAppendingPathComponent:kRequests] stringByAppendingPathComponent:kMyOrders] stringByAppendingString:query]];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

    NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { //5
        if (error == nil) {
            NSArray* responseArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; //6
            NSLog(@"%ul", [responseArray count]);
            [self.requests removeAllObjects];
            [self parseAndAddLocations:responseArray toArray:self.requests];

            if(completionBlock)
            {
                completionBlock(YES);
            }
        }
    }];

    [dataTask resume];

}

-(void) importMyDeliveries:(BOOL)future andCompletion: (void (^)(BOOL completion))completionBlock{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];

    NSString *queryParam;
    NSString *fullQuery;
    if(future){
        queryParam = [NSString stringWithFormat:@"{\"$gt\":\"%@\"}", [dateFormat stringFromDate:[NSDate date]]];

    }
    else{
        queryParam = [NSString stringWithFormat:@"{\"$lt\":\"%@\"}", [dateFormat stringFromDate:[NSDate date]]];

    }

    fullQuery = [NSString stringWithFormat:@"{\"pickup_at\":%@}", queryParam];

    NSLog(@"%@", fullQuery);
    NSString* escQuery = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                (CFStringRef) fullQuery,
                                                                                NULL,
                                                                                (CFStringRef) @"!*();':@&=+$,/?%#[]{}",
                                                                                kCFStringEncodingUTF8));
    NSString *query = [NSString stringWithFormat:@"?query=%@", escQuery];

    NSURL *url = [NSURL URLWithString:[[[kBaseURL stringByAppendingPathComponent:kRequests] stringByAppendingPathComponent:kMyDeliveries] stringByAppendingString:query]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

    NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { //5
        if (error == nil) {
            NSArray* responseArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; //6
            [self.requests removeAllObjects];
            [self parseAndAddLocations:responseArray toArray:self.requests]; //7

            if(completionBlock)
            {
                completionBlock(YES);
            }
        }
    }];

    [dataTask resume];

}

-(void)deleteRequest:(FoodRequest *)foodRequest andCompletion: (void (^)(BOOL completion))completionBlock
{
    NSURL *url = [NSURL URLWithString:[[[kBaseURL stringByAppendingPathComponent:kRequests] stringByAppendingPathComponent:foodRequest._id] stringByAppendingPathComponent:foodRequest.buyer_id]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"DELETE";
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

    NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { //5
        if (error == nil) {
            NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            FoodRequest *requestToRemove = [[FoodRequest alloc] initWithDictionary:responseDict];

            [self parseAndRemoveLocations:requestToRemove fromArray:self.requests]; //7

            if(completionBlock)
            {
                completionBlock(YES);
            }
        }

    }];

    [dataTask resume];

}

-(void) persist:(FoodRequest *)foodRequest andCompletion: (void (^)(BOOL completion))completionBlock {
    if(!foodRequest || foodRequest == nil){
        return;
    }

    NSString *requestString = [kBaseURL stringByAppendingPathComponent:kRequests];

    BOOL isExistingLocation = foodRequest._id != nil;

    requestString = isExistingLocation ? [requestString stringByAppendingPathComponent:foodRequest._id] : requestString;

    NSURL *url = [NSURL URLWithString:requestString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = isExistingLocation ? @"PUT" : @"POST";

    NSData* data = [NSJSONSerialization dataWithJSONObject:[foodRequest toDictionary] options:0 error:NULL];

    request.HTTPBody = data;

    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSArray* responseArray = @[[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]];
            [self parseAndAddLocations:responseArray toArray:self.requests];

            if(completionBlock)
            {
                completionBlock(YES);
            }
        }
    }];
    [dataTask resume];
}

-(void) persist:(FoodRequest *)foodRequest withDeliveryAcceptTo:(FoodRequests *)myDeliveries andCompletion: (void (^)(BOOL completion))completionBlock{
    if(!foodRequest || foodRequest == nil){
        return;
    }

    NSString *requestString = [[[kBaseURL stringByAppendingPathComponent:kRequests] stringByAppendingPathComponent:foodRequest._id] stringByAppendingPathComponent:kDeliveryAccept];

    NSURL *url = [NSURL URLWithString:requestString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"PUT";

    NSData* data = [NSJSONSerialization dataWithJSONObject:[foodRequest toDictionary] options:0 error:NULL];

    request.HTTPBody = data;

    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSArray* responseArray = @[[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]];

            FoodRequest *request = [[FoodRequest alloc] initWithDictionary:[responseArray objectAtIndex:0]];
            [self parseAndRemoveLocations:request fromArray:self.requests];
            [myDeliveries addRequest:request];

            if(completionBlock)
            {
                completionBlock(YES);
            }
        }
    }];
    [dataTask resume];
}

-(void) runQuery:(NSString *)queryString andCompletion:(void (^)(BOOL completion))completionBlock{
    NSString *urlStr = [[kBaseURL stringByAppendingPathComponent:kRequests] stringByAppendingString:queryString];
    NSURL *url = [NSURL URLWithString:urlStr];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

    NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {
            [self.requests removeAllObjects];
            NSArray* responseArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            NSLog(@"received %lu items", (unsigned long)responseArray.count);
            [self parseAndAddLocations:responseArray toArray:self.requests];

            if(completionBlock)
            {
                completionBlock(YES);
            }
        }
    }];

    [dataTask resume];
}

-(void) queryUndeliveredRequestsWithTime:(NSDate *)date andCompletion:(void (^)(BOOL completion))completionBlock{
    NSString *queryParam = [NSString stringWithFormat:@"{\"$exists\":false}"];
    NSString *doesntExist = [NSString stringWithFormat:@"{\"deliverer_id\":%@,", queryParam];

    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    [dateComponents setMinute:-30];
    NSDate *halfHourAgo = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];

    [dateComponents setMinute:30];
    NSDate *halfHourFromNow = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];

    NSDate *earliestTime = [halfHourAgo laterDate:[NSDate date]];

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];

    NSString *queryTimeParam;
    NSString *fullTimeQuery;

    queryTimeParam = [NSString stringWithFormat:@"{\"$lt\":\"%@\", \"$gt\":\"%@\"}", [dateFormat stringFromDate:halfHourFromNow], [dateFormat stringFromDate:earliestTime]];

    fullTimeQuery = [NSString stringWithFormat:@"\"pickup_at\":%@}", queryTimeParam];
    NSString *fullQuery = [doesntExist stringByAppendingString:fullTimeQuery];

    NSLog(@"%@", fullQuery);

    NSString* escQuery = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                (CFStringRef) fullQuery,
                                                                                NULL,
                                                                                (CFStringRef) @"!*();':@&=+$,/?%#[]{}",
                                                                                kCFStringEncodingUTF8));
    NSString *query = [NSString stringWithFormat:@"?query=%@", escQuery];
    [self runQuery:query andCompletion:^(BOOL completion){
        if(completionBlock)
            completionBlock(completion);

    }];

}

/*
- (void) queryRegion:(MKCoordinateRegion)region
{
    CLLocationDegrees x0 = region.center.longitude - region.span.longitudeDelta;
    CLLocationDegrees x1 = region.center.longitude + region.span.longitudeDelta;
    CLLocationDegrees y0 = region.center.latitude - region.span.latitudeDelta;
    CLLocationDegrees y1 = region.center.latitude + region.span.latitudeDelta;

    //query format {"$geoWithin":{"$box": [[x1,y1], [x2,y2]]}}
    //specifying bounds for search
    NSString* boxQuery = [NSString stringWithFormat:@"{\"$geoWithin\":{\"$box\":[[%f,%f],[%f,%f]]}}",x0,y0,x1,y1];
    //specify field to search on
    NSString *locationInBox = [NSString stringWithFormat:@"{\"location\":%@}", boxQuery];
    //Escaping string for url encoding
    NSString* escBox = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                (CFStringRef) locationInBox,
                                                                                NULL,
                                                                                (CFStringRef) @"!*();':@&=+$,/?%#[]{}",
                                                                                kCFStringEncodingUTF8));
    NSString *query = [NSString stringWithFormat:@"?query=%@", escBox];
    [self runQuery:query];
}
 */

@end


text:
using System;
using Newtonsoft.Json;
using Xunit;

namespace OpenStack
{
    public class IdentifierTests
    {
        public class Thing
        {
            public Identifier Id { get; set; }
        }

        [Fact]
        public void Serialize()
        {
            var rawId = Guid.NewGuid();
            var id = (Identifier)rawId;

            var result = OpenStackNet.Serialize(id);

            Assert.Equal(string.Format("\"{0}\"", rawId.ToString("D")), result);
        }

        [Fact]
        public void Serialize_WithinAClass()
        {
            var thing = new Thing {Id = Guid.NewGuid()};

            var result = OpenStackNet.Serialize(thing);

            Assert.Equal(string.Format("{{\"Id\":\"{0}\"}}", thing.Id), result);
        }

        [Fact]
        public void Deserialize()
        {
            var id = new Identifier(Guid.NewGuid());

            var json = OpenStackNet.Serialize(id);
            var result = OpenStackNet.Deserialize<Identifier>(json);

            Assert.Equal(id, result);
        }

        [Fact]
        public void CanCompareWithString()
        {
            var rawId = Guid.NewGuid().ToString("D");
            var id = new Identifier(rawId);

            Assert.Equal(rawId, id);
            Assert.Equal(id, rawId);
            Assert.True(id == rawId);
            Assert.True(rawId == id);
            Assert.True(id.Equals(rawId));
            Assert.Equal(rawId, id);
        }

        [Fact]
        public void CanCompareWithGuid()
        {
            var rawId = Guid.NewGuid();
            var id = new Identifier(rawId);

            Assert.Equal(rawId, id);
            Assert.Equal(id, rawId);
            Assert.True(id == rawId);
            Assert.True(rawId == id);
            Assert.True(id.Equals(rawId));
        }
    }
}


text:
import TextFeature from './TextFeature';

export interface Options {
    altitudeMode?: IGCZ | string | undefined;
}
export enum IGCZ {
    BAROMETRIC = 'barometric',
    GPS = 'gps',
    NONE = 'none',
}
export default class IGC extends TextFeature {
    constructor(opt_options?: Options);
}


text:
package com.makoto.pizzastore.factory.pizza;

import com.makoto.pizzastore.pizza.Pizza;
import com.makoto.pizzastore.pizza.california.CaliforniaStyleCheesePizza;
import com.makoto.pizzastore.pizza.california.CaliforniaStyleClamPizza;
import com.makoto.pizzastore.pizza.california.CaliforniaStylePepperoniPizza;
import com.makoto.pizzastore.pizza.california.CaliforniaStyleVeggiePizza;

/**
 * The Chicago pizza store
 *
 * @author makoton
 *
 */
public class CaliforniaPizzaStore extends PizzaStore
{

	@Override
	protected Pizza createPizza(String type)
	{
		if (type.equals("cheese")) return new CaliforniaStyleCheesePizza();
		else if (type.equals("veggie")) return new CaliforniaStyleVeggiePizza();
		else if (type.equals("clam")) return new CaliforniaStyleClamPizza();
		else if (type.equals("pepperoni")) return new CaliforniaStylePepperoniPizza();
		return null;
	}

}


text:
sgaurav
=======

Personal page at sgaurav.in


text:
<?php

namespace DannySuryadi\Providers;

use View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider {

	/**
	 * Register bindings in the container
	 *
	 * @return void
	 */
	public function boot()
	{
        View::composer('admin.templates.sidebar', 'DannySuryadi\Http\ViewComposers\Admin\SidebarComposer');
	}

	/**
	 * Register
	 *
	 * @return void
	 */
	public function register()
	{

	}

}


text:
r"""
==============================================================
Compressed Sparse Graph Routines (:mod:`scipy.sparse.csgraph`)
==============================================================

.. currentmodule:: scipy.sparse.csgraph

Fast graph algorithms based on sparse matrix representations.

Contents
========

.. autosummary::
   :toctree: generated/

   connected_components -- determine connected components of a graph
   laplacian -- compute the laplacian of a graph
   shortest_path -- compute the shortest path between points on a positive graph
   dijkstra -- use Dijkstra's algorithm for shortest path
   floyd_warshall -- use the Floyd-Warshall algorithm for shortest path
   bellman_ford -- use the Bellman-Ford algorithm for shortest path
   johnson -- use Johnson's algorithm for shortest path
   breadth_first_order -- compute a breadth-first order of nodes
   depth_first_order -- compute a depth-first order of nodes
   breadth_first_tree -- construct the breadth-first tree from a given node
   depth_first_tree -- construct a depth-first tree from a given node
   minimum_spanning_tree -- construct the minimum spanning tree of a graph
   reverse_cuthill_mckee -- compute permutation for reverse Cuthill-McKee ordering
   maximum_bipartite_matching -- compute permutation to make diagonal zero free
   structural_rank -- compute the structural rank of a graph
   NegativeCycleError

.. autosummary::
   :toctree: generated/

   construct_dist_matrix
   csgraph_from_dense
   csgraph_from_masked
   csgraph_masked_from_dense
   csgraph_to_dense
   csgraph_to_masked
   reconstruct_path

Graph Representations
=====================
This module uses graphs which are stored in a matrix format.  A
graph with N nodes can be represented by an (N x N) adjacency matrix G.
If there is a connection from node i to node j, then G[i, j] = w, where
w is the weight of the connection.  For nodes i and j which are
not connected, the value depends on the representation:

- for dense array representations, non-edges are represented by
  G[i, j] = 0, infinity, or NaN.

- for dense masked representations (of type np.ma.MaskedArray), non-edges
  are represented by masked values.  This can be useful when graphs with
  zero-weight edges are desired.

- for sparse array representations, non-edges are represented by
  non-entries in the matrix.  This sort of sparse representation also
  allows for edges with zero weights.

As a concrete example, imagine that you would like to represent the following
undirected graph::

              G

             (0)
            /   \
           1     2
          /       \
        (2)       (1)

This graph has three nodes, where node 0 and 1 are connected by an edge of
weight 2, and nodes 0 and 2 are connected by an edge of weight 1.
We can construct the dense, masked, and sparse representations as follows,
keeping in mind that an undirected graph is represented by a symmetric matrix::

    >>> G_dense = np.array([[0, 2, 1],
    ...                     [2, 0, 0],
    ...                     [1, 0, 0]])
    >>> G_masked = np.ma.masked_values(G_dense, 0)
    >>> from scipy.sparse import csr_matrix
    >>> G_sparse = csr_matrix(G_dense)

This becomes more difficult when zero edges are significant.  For example,
consider the situation when we slightly modify the above graph::

             G2

             (0)
            /   \
           0     2
          /       \
        (2)       (1)

This is identical to the previous graph, except nodes 0 and 2 are connected
by an edge of zero weight.  In this case, the dense representation above
leads to ambiguities: how can non-edges be represented if zero is a meaningful
value?  In this case, either a masked or sparse representation must be used
to eliminate the ambiguity::

    >>> G2_data = np.array([[np.inf, 2,      0     ],
    ...                     [2,      np.inf, np.inf],
    ...                     [0,      np.inf, np.inf]])
    >>> G2_masked = np.ma.masked_invalid(G2_data)
    >>> from scipy.sparse.csgraph import csgraph_from_dense
    >>> # G2_sparse = csr_matrix(G2_data) would give the wrong result
    >>> G2_sparse = csgraph_from_dense(G2_data, null_value=np.inf)
    >>> G2_sparse.data
    array([ 2.,  0.,  2.,  0.])

Here we have used a utility routine from the csgraph submodule in order to
convert the dense representation to a sparse representation which can be
understood by the algorithms in submodule.  By viewing the data array, we
can see that the zero values are explicitly encoded in the graph.

Directed vs. Undirected
-----------------------
Matrices may represent either directed or undirected graphs.  This is
specified throughout the csgraph module by a boolean keyword.  Graphs are
assumed to be directed by default. In a directed graph, traversal from node
i to node j can be accomplished over the edge G[i, j], but not the edge
G[j, i].  In a non-directed graph, traversal from node i to node j can be
accomplished over either G[i, j] or G[j, i].  If both edges are not null,
and the two have unequal weights, then the smaller of the two is used.
Note that a symmetric matrix will represent an undirected graph, regardless
of whether the 'directed' keyword is set to True or False.  In this case,
using ``directed=True`` generally leads to more efficient computation.

The routines in this module accept as input either scipy.sparse representations
(csr, csc, or lil format), masked representations, or dense representations
with non-edges indicated by zeros, infinities, and NaN entries.
"""

from __future__ import division, print_function, absolute_import

__docformat__ = "restructuredtext en"

__all__ = ['cs_graph_components',
           'connected_components',
           'laplacian',
           'shortest_path',
           'floyd_warshall',
           'dijkstra',
           'bellman_ford',
           'johnson',
           'breadth_first_order',
           'depth_first_order',
           'breadth_first_tree',
           'depth_first_tree',
           'minimum_spanning_tree',
           'reverse_cuthill_mckee',
           'maximum_bipartite_matching',
           'structural_rank',
           'construct_dist_matrix',
           'reconstruct_path',
           'csgraph_masked_from_dense',
           'csgraph_from_dense',
           'csgraph_from_masked',
           'csgraph_to_dense',
           'csgraph_to_masked',
           'NegativeCycleError']

from ._components import cs_graph_components
from ._laplacian import laplacian
from ._shortest_path import shortest_path, floyd_warshall, dijkstra,\
    bellman_ford, johnson, NegativeCycleError
from ._traversal import breadth_first_order, depth_first_order, \
    breadth_first_tree, depth_first_tree, connected_components
from ._min_spanning_tree import minimum_spanning_tree
from ._reordering import reverse_cuthill_mckee, maximum_bipartite_matching, \
    structural_rank
from ._tools import construct_dist_matrix, reconstruct_path,\
    csgraph_from_dense, csgraph_to_dense, csgraph_masked_from_dense,\
    csgraph_from_masked, csgraph_to_masked

from numpy import deprecate as _deprecate
cs_graph_components = _deprecate(cs_graph_components,
                                 message=("In the future, use "
                                          "csgraph.connected_components. Note "
                                          "that this new function has a "
                                          "slightly different interface: see "
                                          "the docstring for more "
                                          "information."))

from numpy.testing import Tester
test = Tester().test


text:
import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
import { NavigationActions, StackActions } from 'react-navigation';

import { Page, Button, TextInput, SecondaryFlatButton } from 'components';
import theme from 'theme';
import I18n from 'lib/i18n';

type Props = {
  navigation: any,
};

class Login extends Component<void, Props, void> {
  _goToHomePage() {
    // @see https://github.com/react-community/react-navigation/issues/1127
    const resetAction = StackActions.reset({
      index: 0,
      key: null,
      actions: [NavigationActions.navigate({ routeName: 'dashboard' })],
    });
    this.props.navigation.dispatch(resetAction);
  }

  render() {
    return (
      <Page backgroundImage={theme.images.landing} style={styles.page}>
        <View>
          <TextInput type="email" placeholder={I18n.t('user.form.email')} />
          <TextInput
            type="password"
            placeholder={I18n.t('user.form.password')}
          />

          <Button
            onPress={() => this._goToHomePage()}
            text={I18n.t('login.login')}
          />
          <SecondaryFlatButton
            onPress={() => this.props.navigation.navigate('signup')}
            text={I18n.t('login.signup')}
          />
        </View>
      </Page>
    );
  }
}

const styles = StyleSheet.create({
  page: {
    paddingTop: 50,
  },
});

export default Login;


text:
package com.navercorp.pinpoint.web.controller;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.navercorp.pinpoint.web.alarm.CheckerCategory;
import com.navercorp.pinpoint.web.alarm.vo.Rule;
import com.navercorp.pinpoint.web.service.AlarmService;

/**
 * @author minwoo.jung
 */
@Controller
@RequestMapping(value="/alarmRule")
public class AlarmController {
    public final static String USER_GROUP_ID = "userGroupId";

    @Autowired
    AlarmService alarmService;

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> insertRule(@RequestBody Rule rule) {
        Map<String, String> result = new HashMap<String, String>();

        if (StringUtils.isEmpty(rule.getApplicationId()) || StringUtils.isEmpty(rule.getCheckerName()) || StringUtils.isEmpty(rule.getUserGroupId()) || StringUtils.isEmpty(rule.getThreshold())) {
            result.put("errorCode", "500");
            result.put("errorMessage", "there is not applicationId/checkerName/userGroupId/threashold to insert alarm rule");
            return result;
        }

        String ruleId = alarmService.insertRule(rule);

        result.put("result", "SUCCESS");
        result.put("ruleId", ruleId);
        return result;
    }

    @RequestMapping(method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String, String> deleteRule(@RequestBody Rule rule) {
        if (StringUtils.isEmpty(rule.getRuleId())) {
            Map<String, String> result = new HashMap<String, String>();
            result.put("errorCode", "500");
            result.put("errorMessage", "there is not ruleId to delete alarm rule");
            return result;
        }

        alarmService.deleteRule(rule);

        Map<String, String> result = new HashMap<String, String>();
        result.put("result", "SUCCESS");
        return result;
    }

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public Object getRule(@RequestParam(USER_GROUP_ID) String userGroupId) {
        if (StringUtils.isEmpty(userGroupId)) {
            Map<String, String> result = new HashMap<String, String>();
            result.put("errorCode", "500");
            result.put("errorMessage", "there is not userGroupId to get alarm rule");
            return result;
        }

        return alarmService.selectRuleByUserGroupId(userGroupId);
    }

    @RequestMapping(method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, String> updateRule(@RequestBody Rule rule) {
        Map<String, String> result = new HashMap<String, String>();

        if (StringUtils.isEmpty(rule.getRuleId()) || StringUtils.isEmpty(rule.getApplicationId()) || StringUtils.isEmpty(rule.getCheckerName()) || StringUtils.isEmpty(rule.getUserGroupId())) {
            result.put("errorCode", "500");
            result.put("errorMessage", "there is not ruleId/userGroupId/applicationid/checkerName to get alarm rule");
            return result;
        }

        alarmService.updateRule(rule);

        result.put("result", "SUCCESS");
        return result;
    }

    @RequestMapping(value = "/checker", method = RequestMethod.GET)
    @ResponseBody
    public List<String> getCheckerName() {
        return CheckerCategory.getNames();
    }

}


text:
package com.thoughtworks.go.plugin.access.scm;

import com.thoughtworks.go.plugin.access.common.PluginInfoBuilder;
import com.thoughtworks.go.plugin.api.config.Configuration;
import com.thoughtworks.go.plugin.api.config.Property;
import com.thoughtworks.go.plugin.domain.common.*;
import com.thoughtworks.go.plugin.domain.scm.SCMPluginInfo;
import com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

import static java.lang.String.format;

@Component
public class SCMPluginInfoBuilder implements PluginInfoBuilder<SCMPluginInfo> {

    private SCMExtension extension;

    @Autowired
    public SCMPluginInfoBuilder(SCMExtension extension) {
        this.extension = extension;
    }

    @Override
    public SCMPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) {
        SCMPropertyConfiguration scmConfiguration = extension.getSCMConfiguration(descriptor.id());
        SCMView scmView = extension.getSCMView(descriptor.id());
        PluggableInstanceSettings pluginSettingsAndView = getPluginSettingsAndView(descriptor, extension);
        if (scmConfiguration == null) {
            throw new RuntimeException(format("Plugin[%s] returned null scm configuration", descriptor.id()));
        }

        if (scmView == null) {
            throw new RuntimeException(format("Plugin[%s] returned null scm view", descriptor.id()));
        }

        PluggableInstanceSettings scmSettings = new PluggableInstanceSettings(scmPluginConfigurations(scmConfiguration), new PluginView(scmView.template()));
        return new SCMPluginInfo(descriptor, scmView.displayValue(), scmSettings, pluginSettingsAndView);
    }

    private List<PluginConfiguration> scmPluginConfigurations(Configuration config) {
        ArrayList<PluginConfiguration> pluginConfigurations = new ArrayList<>();

        for (Property property : config.list()) {
            Metadata metadata = new MetadataWithPartOfIdentity(property.getOption(Property.REQUIRED), property.getOption(Property.SECURE), property.getOption(Property.PART_OF_IDENTITY));
            pluginConfigurations.add(new PluginConfiguration(property.getKey(), metadata));
        }
        return pluginConfigurations;
    }

}


text:
import time
import oauth2

# These keys can be obtained from creating a new app at
# https://dev.twitter.com/apps
# ACCESS_KEY is now shown as ACCESS_TOKEN on Twitter's page
# and ACCESS_SECRET as ACCESS_TOKEN_SECRET
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_KEY = ''
ACCESS_SECRET = ''

def oauth(url):

	CONSUMER = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET)
	access_token = oauth2.Token(key=ACCESS_KEY, secret=ACCESS_SECRET)

	params = {
		'oauth_version': "1.0",
		'oauth_nonce': oauth2.generate_nonce(),
		'oauth_timestamp': int(time.time()),
		'oauth_token': access_token.key,
		'oauth_consumer_key': CONSUMER.key
	}

	req = oauth2.Request(
		method="GET", url=url, parameters=params, is_form_encoded=True)

	req.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), CONSUMER, access_token)
	return req.to_header()['Authorization'].encode('utf-8')


text:
<?php

/**
 * Test: Operation.
 *
 * @author     Petr Bugyík
 * @package    Grido\Tests
 */

namespace Grido\Tests;

require_once __DIR__ . '/../bootstrap.php';

use Tester\Assert,
    Grido\Grid,
    Grido\Components\Operation;

class OperationTest extends \Tester\TestCase
{
    function testSetConfirm()
    {
        Helper::grid(function(Grid $grid) {
            $grid->setModel([]);
            $grid->addColumnText('column', 'Column');
            $grid->setOperation(['edit' => 'Edit', 'delete' => 'Delete'], function() {})
                ->setConfirm('delete', 'Are you sure?');
            $grid->render();
        })->run();

        $formControl = Helper::$grid['form'][Operation::ID][Operation::ID];
        Assert::same($formControl->controlPrototype->getAttribute('data-grido-confirm-delete'), 'Are you sure?');
    }

    /**********************************************************************************************/

    function testGetPrimaryKey()
    {
        $grid = new Grid;
        $operation = $grid->setOperation([], []);
        Assert::same($grid->primaryKey, $operation->primaryKey);

        $primaryKey = 'xx';
        $operation->setPrimaryKey($primaryKey);
        Assert::same($primaryKey, $operation->primaryKey);
    }

    /**********************************************************************************************/

    function testHandleOperations()
    {
        $definition = function(Grid $grid, $strictMode = TRUE) {
            $grid->setStrictMode($strictMode);
            $grid->setModel([
                ['id' => 1, 'a' => 'A1', 'b' => 'B1'],
                ['id' => 2, 'a' => 'A2', 'b' => 'B2'],
                ['id' => 3, 'a' => 'A3', 'b' => 'B3'],
                ['id' => 4, 'a' => 'A4', 'b' => 'B4'],
                ['id' => 5, 'a' => 'A5', 'b' => 'B5'],
            ]);
            $grid->addColumnText('a', 'A');
            $grid->addColumnText('b', 'B');
            $grid->setOperation(['edit' => 'Edit', 'del' => 'Del'], function($operation, $id) {
                Assert::same('edit', $operation);
                Assert::same(['2','4'], $id);
            });
        };
        Helper::grid(function(Grid $grid) use ($definition) {
            $definition($grid);
        });

        $params = [
            'do' => 'grid-form-submit',
            'count' => 10,
            Grid::BUTTONS => [Operation::ID => 'OK'],
            Operation::ID => [
                Operation::ID => 'edit',
                '2' => 'on',
                '4' => 'on',
                '9' => 'on'
        ]];

        Helper::request($params);

        $fakeParams = $params;
        $fakeParams[Operation::ID][Operation::ID] = 'fake';

        Assert::error(function() use ($fakeParams) {
            Helper::request($fakeParams);
        }, E_USER_NOTICE, "Operation with name 'fake' does not exist.");

        Helper::grid(function(Grid $grid) use ($definition) {
            $definition($grid, FALSE);
        })->run($fakeParams);
    }

    /**********************************************************************************************/

    function testHasOperations()
    {
        $grid = new Grid;
        Assert::false($grid->hasOperation());

        $grid->setOperation([], []);
        Assert::false($grid->hasOperation());
        Assert::true($grid->hasOperation(FALSE));
    }

    function testSetOperations()
    {
        $grid = new Grid;
        $operations = ['print' => 'Print', 'delete' => 'Delete'];
        $onSubmit = function() {};
        $grid->setOperation($operations, $onSubmit);
        $component = $grid->getOperation();
        Assert::type('\Grido\Components\Operation', $component);
        $componentId = \Grido\Components\Operation::ID;
        Assert::same($operations, $grid['form'][$componentId][$componentId]->items);
        Assert::same($component->onSubmit, [$onSubmit]);

        // getter
        $grid = new Grid;
        Assert::exception(function() use ($grid) {
            $grid->getOperation();
        }, 'Nette\InvalidArgumentException');

        Assert::null($grid->getOperation(FALSE));
    }
}

run(__FILE__);


text:
----------------------------------------------------------------
-- [action_version_map] Table
--

Create or replace FUNCTION Insertaction_version_map(v_action_type INTEGER,
	v_cluster_minimal_version VARCHAR(40),
	v_storage_pool_minimal_version VARCHAR(40))
RETURNS VOID
   AS $procedure$
BEGIN
INSERT INTO action_version_map(action_type, cluster_minimal_version, storage_pool_minimal_version)
	VALUES(v_action_type, v_cluster_minimal_version, v_storage_pool_minimal_version);
END; $procedure$
LANGUAGE plpgsql;

Create or replace FUNCTION Deleteaction_version_map(v_action_type INTEGER)
RETURNS VOID
   AS $procedure$
BEGIN

   DELETE FROM action_version_map
   WHERE action_type = v_action_type;

END; $procedure$
LANGUAGE plpgsql;

Create or replace FUNCTION GetAllFromaction_version_map() RETURNS SETOF action_version_map
   AS $procedure$
BEGIN
   RETURN QUERY SELECT *
   FROM action_version_map;

END; $procedure$
LANGUAGE plpgsql;

Create or replace FUNCTION Getaction_version_mapByaction_type(v_action_type INTEGER) RETURNS SETOF action_version_map
   AS $procedure$
BEGIN
   RETURN QUERY SELECT *
   FROM action_version_map
   WHERE action_type = v_action_type;

END; $procedure$
LANGUAGE plpgsql;


text:
from sochi.data.db.base.followerObj import followerObj
import copy

class ExampleFollowerObj(followerObj):
    def __init__(self):
        followerObj.__init__(self)

    def __repr__(self):
        result = "ExampleFollowerObj():\n\t"
        result = result+"rid: %s\n\t"%(str(self.rid))
        result = result+"user: "+self.user.encode('utf-8')+"\n\t"
        result = result+"follower: "+self.follower.encode('utf-8')+"\n\t"
        result = result+"user_id: %s\n\t"%(str(self.user_id))
        result = result+"follower_id: %s"%(str(self.follower_id))
        return result


text:
package org.springframework.social.twitter.api;

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

/**
 * An enum to facilitate the use of the rate_limit_status endpoint by enumerating all of the resource
 * families that can be searched via the API
 * @author Jeremy Appel
 */
public enum ResourceFamily {

	ACCOUNT("account"),
	APPLICATION("application"),
	BLOCKS("blocks"),
	DIRECT_MESSAGES("direct_messages"),
	FOLLOWERS("followers"),
	FRIENDS("friends"),
	FRIENDSHIPS("friendships"),
	GEO("geo"),
	HELP("help"),
	LISTS("lists"),
	SAVED_SEARCHES("saved_searches"),
	SEARCH("search"),
	STATUSES("statuses"),
	TRENDS("trends"),
	USERS("users");

	private final String name;
	private static final Map<String, ResourceFamily> stringToEnum =  new HashMap<String, ResourceFamily>();

	static {
		for (ResourceFamily resource : values())
			stringToEnum.put(resource.toString(), resource);
	}

	ResourceFamily(String name) {
		this.name = name;
	}

	@Override
	public String toString(){
		return name;
	}

	public static ResourceFamily getResourceFamily(String name) {
		return stringToEnum.get(name);
	}

}


text:
import os
os.system('python runTrainer.py --agent=KerasNAFAgent --env=Motionv0Env --train-for=10000000 --test-for=0 --random-initial-position --gui --save-file=checkpoints/KerasNAF-Motionv0-$(date +%y%m%d%H%M%S).h5')


text:
@(formLogin: Form[Application.Login])

        @helper.form(routes.Application.authenticate) {

Efetue o Login para ter acesso ao Corpo Docente

            @if(formLogin.hasGlobalErrors) {

                    @formLogin.globalError.message

            }

            @if(flash.contains("success")) {

                    @flash.get("success")

            }

                <input type="email" name="email" placeholder="Email" value="@formLogin("email").value">

                <input type="password" name="password" placeholder="Senha">

               	<input type="submit" value="Login" class="btn btn-danger">

               	 Cadastrar

        }


text:
<?php
use Mouf\Doctrine\ORM\Admin\Controllers\EntityManagerController;

/* @var $this EntityManagerController */
?>

Configure your Entity Manager

<?php if (!$this->autoloadDetected) {
    ?>

Warning! Could not detect the autoload section of your composer.json file.
Unless you are developing your own autoload system, you should configure composer.json to define a source directory and a root namespace using PSR-0.

<?php
} ?>

<form action="do_generate_daos" class="form-horizontal">
	<input type="hidden" id="selfedit" name="selfedit" value="<?php echo plainstring_to_htmlprotected($this->selfedit) ?>" />
	<input type="hidden" id="instanceName" name="instanceName" value="<?php echo plainstring_to_htmlprotected($this->instanceName); ?>" />
	<input type="hidden" id="psrMode" name="psrMode" value="<?php echo plainstring_to_htmlprotected($this->psrMode); ?>" />
	<input type="hidden" id="installMode" name="installMode" value="<?php echo plainstring_to_htmlprotected($this->installMode); ?>" />

		Entities Namespace:

			<input type="text" id="entitiesNamespace" name="entitiesNamespace" value="<?php echo plainstring_to_htmlprotected($this->entitiesNamespace) ?>" />
			The namespace for the entities to be generated

		Proxy Namespace:

			<input type="text" id="proxyNamespace" name="proxyNamespace" value="<?php echo plainstring_to_htmlprotected($this->proxyNamespace) ?>" />
			The namespace for the Proxies

		DAO Namespace:

			<input type="text" id="daoNamespace" name="daoNamespace" value="<?php echo plainstring_to_htmlprotected($this->daoNamespace) ?>" />
			The namespace for the DAOs

			<button name="action" value="install" type="submit" class="btn btn-danger">Generate DAOs ></button>

</form>


text:
import operator
import re

from functools import partial

from ..cache import Cache
from ..exceptions import PluginError, NoStreamsError
from ..options import Options

QUALITY_WEIGTHS_EXTRA = {
    "other": {
        "live": 1080,
    },
    "tv": {
        "hd": 1080,
        "sd": 576,
    },
    "quality": {
        "ehq": 720,
        "hq":  576,
        "sq":  360,
    },
}

FILTER_OPERATORS = {
    "<": operator.lt,
    "<=": operator.le,
    ">": operator.gt,
    ">=": operator.ge,
}

def stream_weight(stream):
    for group, weights in QUALITY_WEIGTHS_EXTRA.items():
        if stream in weights:
            return weights[stream], group

    match = re.match("^(\d+)([k]|[p])?(\d*)([\+])?$", stream)

    if match:
        if match.group(2) == "k":
            bitrate = int(match.group(1))

            # FIXME: This is a crude attempt at making a bitrate's
            # weight end up similar to the weight of a resolution.
            # Someone who knows math, please fix.
            weight = bitrate / 2.8

            return weight, "bitrate"

        elif match.group(2) == "p":
            weight = int(match.group(1))

            if match.group(3):
                weight += int(match.group(3))

            if match.group(4) == "+":
                weight += 1

            return weight, "pixels"

    return 0, "none"

def iterate_streams(streams):
    for name, stream in streams:
        if isinstance(stream, list):
            for sub_stream in stream:
                yield (name, sub_stream)
        else:
            yield (name, stream)

def stream_type_priority(stream_types, stream):
    stream_type = type(stream[1]).shortname()

    try:
        prio = stream_types.index(stream_type)
    except ValueError:
        prio = 99

    return prio

def stream_sorting_filter(expr, stream_weight):
    match = re.match(r"(?P<op><=|>=|<|>)?(?P<value>[\w\+]+)", expr)

    if not match:
        raise PluginError("Invalid filter expression: {0}".format(expr))

    op, value = match.group("op", "value")
    op = FILTER_OPERATORS.get(op, operator.eq)
    filter_weight, filter_group = stream_weight(value)

    def func(quality):
        weight, group = stream_weight(quality)

        if group == filter_group:
            return not op(weight, filter_weight)

        return True

    return func

class Plugin(object):
    """A plugin can retrieve stream information from the URL specified.

    :param url: URL that the plugin will operate on
    """

    cache = None
    logger = None
    module = "unknown"
    options = Options()
    session = None

    @classmethod
    def bind(cls, session, module):
        cls.cache = Cache(filename="plugin-cache.json",
                          key_prefix=module)
        cls.logger = session.logger.new_module("plugin." + module)
        cls.module = module
        cls.session = session

    def __init__(self, url):
        self.url = url

    @classmethod
    def can_handle_url(cls, url):
        raise NotImplementedError

    @classmethod
    def set_option(cls, key, value):
        cls.options.set(key, value)

    @classmethod
    def get_option(cls, key):
        return cls.options.get(key)

    @classmethod
    def stream_weight(cls, stream):
        return stream_weight(stream)

    @classmethod
    def default_stream_types(cls, streams):
        stream_types = ["rtmp", "hls", "hds", "http"]

        for name, stream in iterate_streams(streams):
            stream_type = type(stream).shortname()

            if stream_type not in stream_types:
                stream_types.append(stream_type)

        return stream_types

    @classmethod
    def broken(cls, issue=None):
        def func(*args, **kwargs):
            msg = (
                "This plugin has been marked as broken. This is likely due to "
                "changes to the service preventing a working implementation. "
            )

            if issue:
                msg += "More info: https://github.com/streamlink/streamlink/issues/{0}".format(issue)

            raise PluginError(msg)

        def decorator(*args, **kwargs):
            return func

        return decorator

    def streams(self, stream_types=None, sorting_excludes=None):
        """Attempts to extract available streams.

        Returns a :class:`dict` containing the streams, where the key is
        the name of the stream, most commonly the quality and the value
        is a :class:`Stream` object.

        The result can contain the synonyms **best** and **worst** which
        points to the streams which are likely to be of highest and
        lowest quality respectively.

        If multiple streams with the same name are found, the order of
        streams specified in *stream_types* will determine which stream
        gets to keep the name while the rest will be renamed to
        "<name>_<stream type>".

        The synonyms can be fine tuned with the *sorting_excludes*
        parameter. This can be either of these types:

            - A list of filter expressions in the format
              *[operator]<value>*. For example the filter ">480p" will
              exclude streams ranked higher than "480p" from the list
              used in the synonyms ranking. Valid operators are >, >=, <
              and <=. If no operator is specified then equality will be
              tested.

            - A function that is passed to filter() with a list of
              stream names as input.

        :param stream_types: A list of stream types to return.
        :param sorting_excludes: Specify which streams to exclude from
                                 the best/worst synonyms.

        .. versionchanged:: 1.4.2
           Added *priority* parameter.

        .. versionchanged:: 1.5.0
           Renamed *priority* to *stream_types* and changed behaviour
           slightly.

        .. versionchanged:: 1.5.0
           Added *sorting_excludes* parameter.

        .. versionchanged:: 1.6.0
           *sorting_excludes* can now be a list of filter expressions
           or a function that is passed to filter().

        """

        try:
            ostreams = self._get_streams()
            if isinstance(ostreams, dict):
                ostreams = ostreams.items()

            # Flatten the iterator to a list so we can reuse it.
            if ostreams:
                ostreams = list(ostreams)
        except NoStreamsError:
            return {}
        except (IOError, OSError, ValueError) as err:
            raise PluginError(err)

        if not ostreams:
            return {}

        if stream_types is None:
            stream_types = self.default_stream_types(ostreams)

        # Add streams depending on stream type and priorities
        sorted_streams = sorted(iterate_streams(ostreams),
                                key=partial(stream_type_priority,
                                            stream_types))

        streams = {}
        for name, stream in sorted_streams:
            stream_type = type(stream).shortname()

            if stream_type not in stream_types:
                continue

            existing = streams.get(name)
            if existing:
                existing_stream_type = type(existing).shortname()
                if existing_stream_type != stream_type:
                    name = "{0}_{1}".format(name, stream_type)

                if name in streams:
                    name = "{0}_alt".format(name)
                    num_alts = len(list(filter(lambda n: n.startswith(name), streams.keys())))

                    # We shouldn't need more than 2 alt streams
                    if num_alts >= 2:
                        continue
                    elif num_alts > 0:
                        name = "{0}{1}".format(name, num_alts + 1)

            # Validate stream name and discard the stream if it's bad.
            match = re.match("([A-z0-9_+]+)", name)
            if match:
                name = match.group(1)
            else:
                self.logger.debug("The stream '{0}' has been ignored "
                                  "since it is badly named.", name)
                continue

            # Force lowercase name and replace space with underscore.
            streams[name.lower()] = stream

        # Create the best/worst synonmys
        stream_weight_only = lambda s: (self.stream_weight(s)[0] or
                                        (len(streams) == 1 and 1))
        stream_names = filter(stream_weight_only, streams.keys())
        sorted_streams = sorted(stream_names, key=stream_weight_only)

        if isinstance(sorting_excludes, list):
            for expr in sorting_excludes:
                filter_func = stream_sorting_filter(expr, self.stream_weight)
                sorted_streams = list(filter(filter_func, sorted_streams))
        elif callable(sorting_excludes):
            sorted_streams = list(filter(sorting_excludes, sorted_streams))

        if len(sorted_streams) > 0:
            best = sorted_streams[-1]
            worst = sorted_streams[0]
            streams["best"] = streams[best]
            streams["worst"] = streams[worst]

        return streams

    def get_streams(self, *args, **kwargs):
        """Deprecated since version 1.9.0.

        Has been renamed to :func:`Plugin.streams`, this is an alias
        for backwards compatibility.
        """

        return self.streams(*args, **kwargs)

    def _get_streams(self):
        raise NotImplementedError

__all__ = ["Plugin"]


text:
#ifndef _mitkContourModelSubDivisionFilter_h__
#define _mitkContourModelSubDivisionFilter_h__

#include "mitkCommon.h"
#include "ContourModelExports.h"
#include "mitkContourModel.h"
#include "mitkContourModelSource.h"

namespace mitk {

  /**
  *
  * \brief This filter interpolates a subdivision curve between control points of the contour.
  * For inserting subpoints Dyn-Levin-Gregory (DLG) interpolation scheme is used.
  * Interpolating a cruve subdivision is done by:
  * F2i = Ci
  * F2i+1 = -1/16Ci-1 + 9/16Ci + 9/16Ci+1 - 1/16Ci+2
  *
  * The number of interpolation iterations can be set via SetNumberOfIterations(int) which are 4 by dafault.
  *
  * \ingroup ContourModelFilters
  * \ingroup Process
  */
  class ContourModel_EXPORT ContourModelSubDivisionFilter : public ContourModelSource
  {

  public:

    mitkClassMacro(ContourModelSubDivisionFilter, ContourModelSource);
    itkNewMacro(Self);

    typedef ContourModel OutputType;
    typedef OutputType::Pointer OutputTypePointer;
    typedef mitk::ContourModel InputType;

    /**
    * \brief Set the number of iterations for inserting new interpolated control points.
    *
    */
    void SetNumberOfIterations( int iterations)
    {
      this->m_InterpolationIterations = iterations;
    }

    virtual void SetInput( const InputType *input);

    virtual void SetInput( unsigned int idx, const InputType * input);

    const InputType* GetInput(void);

    const InputType* GetInput(unsigned int idx);

  protected:
    ContourModelSubDivisionFilter();

    virtual ~ContourModelSubDivisionFilter();

    void GenerateOutputInformation() {};

    void GenerateData();

    int m_InterpolationIterations;
  };

}

#endif


text:
package io.tilt.minka.core.monitor;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import io.tilt.minka.api.Config;
import io.tilt.minka.core.task.LeaderAware;
import io.tilt.minka.core.task.Scheduler;
import io.tilt.minka.core.task.Scheduler.Agent;
import io.tilt.minka.core.task.Scheduler.Frequency;
import io.tilt.minka.core.task.Scheduler.PriorityLock;
import io.tilt.minka.core.task.Semaphore.Action;

/**
 * Read only views built at request about the system state
 * JSON format.
 *
 * @author Cristian Gonzalez
 * @since Nov 6, 2016
 */
public class SystemStateMonitor {

	private final DistroJSONBuilder distro;
	private final FollowerJSONBuilder follower;
	private final CrossJSONBuilder cross;
	private final SchemeJSONBuilder scheme;
	private final LeaderAware leaderAware;
	private final Config config;

	private final Agent coredumper;

	static final ObjectMapper mapper;
	static {
		mapper = new ObjectMapper();
		mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
		mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
		//mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
		mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
		mapper.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, false);
		mapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, false);
		mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		mapper.configure(Feature.WRITE_NUMBERS_AS_STRINGS, true);
	}

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

	public SystemStateMonitor(
			final Config config,
			final DistroJSONBuilder leader,
			final FollowerJSONBuilder follower,
			final CrossJSONBuilder cross,
			final SchemeJSONBuilder scheme,
			final LeaderAware leaderAware,
			final Scheduler scheduler) {
		super();
		this.config = config;
		this.distro = leader;
		this.follower = follower;
		this.cross = cross;
		this.leaderAware = leaderAware;
		this.scheme = scheme;
		this.coredumper = createStateMonitor(scheduler);

		if (config.getBootstrap().isEnableCoreDump()) {
			scheduler.schedule(coredumper);
		}

	}

	static String toJson(final Object o) {
		try {
			return mapper.writeValueAsString(o);
		} catch (JsonProcessingException e) {
			return "";
		}
	}

	public Agent createStateMonitor(final Scheduler scheduler) {
		return scheduler
				.getAgentFactory().create(
						Action.BOOTSTRAP_COREDUMP,
						PriorityLock.HIGH_ISOLATED,
						Frequency.PERIODIC,
						() -> stateMonitor())
				.every(config.beatToMs(config.getBootstrap().getCoreDumpFrequency()))
				.build();
	}

	private boolean saveOnDiff(final String key, final Instant now, final String value) {
		boolean ret = false;
		final String last = lastJsons.get(key);
		if (last==null || !last.contentEquals(value)) {
			lastJsons.put(key, value);
			final StringBuilder filepath = new StringBuilder()
					.append(config.getBootstrap().getCoreDumpFilepath())
					.append("/minka-")
					.append(key)
					.append("-")
					.append(config.getBootstrap().getServerTag());
			if (!config.getBootstrap().isCoreDumpOverwrite()) {
				filepath.append("-").append(now.toString());
			}
			filepath.append(".json");
			try {
				FileUtils.writeStringToFile(new File(filepath.toString()), value, Charset.defaultCharset());
			} catch (IOException e) {
			}
			ret = true;
		}
		return ret;
	}

	protected void stateMonitor() {
		final Instant now = Instant.now();
		saveOnDiff("config", now, config.toJson());
		saveOnDiff("schedule", now, cross.scheduleToJson(false));
		saveOnDiff("shards", now, distro.shardsToJson());
		saveOnDiff("broker", now, cross.brokerToJson());
		saveOnDiff("partition", now, follower.partitionToJson(false));
		saveOnDiff("beats", now, follower.beatsToJson());

		if (leaderAware.imLeader()) {
			saveOnDiff("plans", now, distro.plansToJson(true));
			saveOnDiff("distro", now, distro.distributionToJson());
			saveOnDiff("scheme", now, scheme.schemeToJson(true));
			saveOnDiff("pallets", now, distro.palletsToJson());
		}
	}

}


text:
START_ATF_NAMESPACE
    struct _UNIVERSAL_NAME_INFOW
    {
        wchar_t *lpUniversalName;
    };
END_ATF_NAMESPACE


text:
Spike running a Kubernetes cluster on CoreOS on AWS.

## Using

1. First setup VPC and security groups using `cluster-vpc.template`.
2. Setup Kubernetes cluster using `kubernetes-cluster.template`.

## Versions

* CoreOS version: 660
* Kubernetes version: 0.15.0

## Demo

Will show a complete pipeline from developer's laptop, git push, BuildKite, ending up in a rolling update in Kubernetes.

## References

### Paper on Borg

Kubernetes incorporated many lessons from running Borg in production at Google scale for over a decade - paper.

### Managing CoreOS fleet

CoreOS released a

### Pretty UI for Kubernetes

There is [Kismatic](http://kismatic.io/) and [Tectonic](https://tectonic.com/).

### Visualise your logs.

There is ElasticSearch and Kibana.

### Architecting on AWS VPC

One cluster per AZ, load balance the Kubernetes master. As explained [here](https://github.com/GoogleCloudPlatform/kubernetes/issues/3604).


text:
package validate

import (
	"unicode"

	"github.com/fcavani/e"
	"github.com/fcavani/text"
	uni "github.com/fcavani/unicode"
)

func CheckObjectName(name string) error {
	for _, v := range name {
		if !uni.IsLetter(v) && !unicode.IsDigit(v) && v != '-' && v != '_' && v != '*' && v != '{' && v != '}' && v != '/' && v != '.' && v != '[' && v != ']' {
			return e.Push(e.New(text.ErrInvCharacter), e.New("the character '%v' in object name is invalid", string([]byte{byte(v)})))
		}
	}
	return nil
}

func CheckSession(name string) error {
	for _, v := range name {
		if !uni.IsLetter(v) && !unicode.IsDigit(v) && v != '-' {
			return e.Push(e.New(text.ErrInvCharacter), e.New("the character '%v' in session string is invalid", string([]byte{byte(v)})))
		}
	}
	return nil
}

func CheckInstanceName(name string) error {
	for _, v := range name {
		if !uni.IsLetter(v) && !unicode.IsDigit(v) && v != '-' && v != '_' {
			return e.Push(e.New(text.ErrInvCharacter), e.New("the character '%v' in instance name is invalid", string([]byte{byte(v)})))
		}
	}
	return nil
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. Mag. (Tokyo) 27:125. 1913

#### Original name
null

### Remarks
null


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

<title>Uses of Class View.InstructionView</title>
<meta name="date" content="2016-09-19">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
View.InstructionView

Packages that use InstructionView

Package
Description

View

Uses of InstructionView in View

Methods in View that return InstructionView

Modifier and Type
Method and Description

static InstructionView
InstructionView.getInstance()

get instance of Instruction view this is a singleton

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
function I = get_item_struct(o, item)
% get whole item structure, including parameters
% FORMAT I = get_item_struct(o, item)
%
% This is used internally, and might be useful for debugging
%
% o       - object
% item    - item name
%
% Returns
% I       - item structure, with data in field 'data' and/or specified in
%           field 'filename'
%
% $Id$

if ~item_exists(o, item)
  error('Item does not exist');
end
I = getfield(o.items, item);


text:
<?php

namespace DCarbone\PHPFHIRGenerated\STU3\PHPFHIRTests\FHIRCodePrimitive;

use PHPUnit\Framework\TestCase;
use DCarbone\PHPFHIRGenerated\STU3\FHIRCodePrimitive\FHIRUDIEntryTypeList;

/**
 * Class FHIRUDIEntryTypeListTest
 * @package \DCarbone\PHPFHIRGenerated\STU3\PHPFHIRTests\FHIRCodePrimitive
 */
class FHIRUDIEntryTypeListTest extends TestCase
{
    public function testCanConstructTypeNoArgs()
    {
        $type = new FHIRUDIEntryTypeList();
        $this->assertInstanceOf('\DCarbone\PHPFHIRGenerated\STU3\FHIRCodePrimitive\FHIRUDIEntryTypeList', $type);
    }
}


text:
package com.example.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/*
 * ´Ó·þÎñÆ÷¶Ë»ñÈ¡Ê¡ÊÐÏصÄÊý¾Ý
 *
 */
public class HttpUtil {

	public static void sendHttpRequest(final String address,
			final HttpCallbackListener listener) {

		new Thread() {
			public void run() {
				HttpURLConnection connection = null;

				try {
					URL url = new URL(address);

					connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(8000);
					connection.setReadTimeout(8000);
					InputStream in = connection.getInputStream();
					BufferedReader br = new BufferedReader(
							new InputStreamReader(in));
					String len;
					StringBuilder sbBuilder = new StringBuilder();
					while ((len = br.readLine()) != null) {
						sbBuilder.append(len);
					}
					if (listener != null) {
						/*
						 * »Øµ÷onfinish
						 */
						listener.onFinish(sbBuilder.toString());
					}

				} catch (IOException e) {
					/*
					 * »Øµ÷onerror
					 */
					if (listener != null) {
						listener.onError(e);
					}

				} finally {

					if (connection != null) {
						connection.disconnect();
					}
				}
			};
		}.start();

	}

}


text:
import React from 'react';
import { mount } from 'enzyme';
import { spy } from 'sinon';

import {
    expect,
    it,
} from '../common/test-base';

import {
    GoogleMapProvider,
    // __RewireAPI__ as RewireAPI,
} from '../../main/map';
import contextTypes from '../../main/map/contextTypes';

describe('GoogleMapProvider', () => {
    class Child extends React.Component {
        render() {
            return null;
        }
    }

    Child.contextTypes = contextTypes;

    const wrapper = mount(
        <GoogleMapProvider>
            <Child />
        </GoogleMapProvider>
    );

    context('While render GoogleMapProvider:', () => {
        it('should have "children" props', () => {
            expect(wrapper.props().children).to.be.an('object');
        });
    });

    it('should have "children" props', () => {
        it('calls componentDidMount', () => {
            spy(GoogleMapProvider.prototype, 'componentDidMount');
            mount(<GoogleMapProvider />);
            expect(GoogleMapProvider.prototype.componentDidMount).to.have.property('callCount', 1);
            GoogleMapProvider.prototype.componentDidMount.restore();
        });
    });
});